Writing Suricata Rules: Understanding the Basic Rule Format

Crafting Effective Suricata Rules for Network Security

Even the smartest security tools are only as powerful as the experts who use them. This is particularly true in network security analysis, where the power of a tool like Suricata is directly tied to the quality and accuracy of its configuration.

Suricata stands as a versatile open-source engine, operating as an Intrusion Detection System (IDS), Intrusion Prevention System (IPS), and Network Security Monitoring (NSM) platform. While its potential to identify and block malicious network activity is significant, its actual effectiveness hinges on the strength of the rules that guide it. Poorly designed rules can lead to overlooked threats or an overwhelming number of false alarms, diminishing the system’s value.

This exploration delves into the fundamental principles of creating robust Suricata rules. We will dissect their essential components—actions, headers, and options—to understand how each element contributes to a rule’s functionality and its overall impact on safeguarding networks.

Tailoring Security: Transforming Organizational Uniqueness into Defensive Advantages

Each organization operates with its own specific rhythms, common practices, and technological configurations. These inherent details, if properly leveraged, can dramatically improve the precision and efficacy of Suricata rules. Rather than dismissing these unique characteristics as irregularities, they should be recognized as valuable intelligence sources. By integrating these organizational distinctions into your rule-creation process, you elevate the challenge for attackers from overcoming standard protections to navigating the intricacies of your company’s specific environment.

Consider these practical methods for embedding organizational context into your Suricata rules:

  • Baseline Activity Hours: If your company functions within established operational hours—for example, concluding work by 7:00 PM and restricting off-hours remote connections—implement rules that flag connections made outside these defined periods. An unexpected login or outbound communication attempt late in the evening could signify a compromised device or an unauthorized access effort, focusing attention precisely where needed.
  • Consistent Software Environments: Organizations that enforce the use of particular software—such as a designated web browser across all workstations—can monitor for deviations from this norm. Suricata rules can be configured to alert on network traffic originating from unauthorized browsers or applications, indicating either a breach of policy or potential malicious activity (like malware using its own HTTP client).
  • IP Address Allocation by Function: Segmenting internal network ranges based on server roles allows for more focused monitoring. For example:
    • All database servers are confined to the 192.168.0.0/24 subnet.
    • Web servers utilize the 192.168.1.0/24 subnet.
    • Printers and IoT devices adhere to a separate addressing plan. With such a structure, rules can be developed to detect improbable actions, like a database server initiating outbound connections (particularly to the internet) or printers trying to access sensitive internal systems.
  • Expected Communication Pathways: Examine normal interaction patterns, such as how users share files or the typical directionality of print jobs. Attempts by client workstations to establish direct connections with each other—especially if such access is generally prohibited—should trigger scrutiny. Even if firewalls ultimately block the connection, the attempt itself is a crucial piece of intelligence worth capturing.
  • Customized Ports and Protocols: If your infrastructure redirects standard protocols (for instance, running internal HTTP on a port different from 80 or 443), then any traffic utilizing the default ports should be viewed with suspicion. Crafting Suricata rules that identify the use of non-standard ports—or, conversely, the unexpected use of well-known ports—helps to highlight anomalous communications that could otherwise be overlooked.

In summary, the more your Suricata rules are customized to reflect your organization’s true operational context, the more acute their detection capabilities will become. By incorporating these specific nuances, you compel potential intruders to acquire an intimate familiarity with your environment—a significant barrier that often deters all but the most persistent cyber threats.

Deconstructing Suricata Rule Structure: Actions, Headers, and Options

A Suricata rule is built upon three key elements: the action, the header, and the options. Each of these plays a vital role in defining how network traffic is evaluated and how the system responds to what it observes.

Prioritizing Fundamental Flaws Instead of Individual Exploits

When crafting impactful Suricata rules, it is vital to concentrate on the core vulnerability rather than trying to detect a singular exploit. This methodology offers significant long-term advantages:

  • Exploits Evolve Rapidly: Malicious actors continuously devise new exploits for existing vulnerabilities, frequently modifying patterns or data payloads to bypass signature-based detection. Rules designed to identify only one exploit iteration can swiftly lose their effectiveness as attackers adapt their methods.
  • Enduring Defense: By developing rules that identify the improper use or manipulation of a protocol, data field, or system function—as opposed to the unique signature of a specific exploit—you enhance your capability to detect both current and emerging attack vectors. This might involve monitoring for abnormal input sizes, breaches of protocol standards, or improperly structured requests that indicate more profound issues.
  • Minimizing Missed Detections: Attacker toolsets can readily change non-critical elements, like buffer padding characters, thereby evading overly precise signatures. However, a rule centered on the actual underlying weakness is considerably more challenging to bypass without addressing the targeted flaw itself.

In application, this involves transitioning from matching the specific characteristics of a known exploit to recognizing the indicative signs of a vulnerability being actively exploited. Such an approach ultimately yields rules that are more robust, flexible, and proficient in maintaining network security.


Action: Defining the System’s Response

The action dictates what Suricata should do when network traffic matches the criteria of a rule. The behavior of these actions varies depending on whether Suricata is operating in IDS or IPS mode:

Keyword

Behavior

alert

Commonly used in IDS mode, this action generates a log entry when traffic matches the rule but does not block the traffic.

pass

Allows matching traffic to proceed without further inspection or generating an alert.

drop

Available in IPS mode, this action immediately stops the processing of the matching traffic and discards the packet.

reject

Also for IPS mode, it discards the packet and sends a notification to the sender, typically a TCP reset or an ICMP unreachable message.

rejectsrc

Sends a notification only to the source of the traffic.

rejectdst

Sends a notification only to the destination of the traffic.

rejectboth

Sends notifications to both the source and the destination of the traffic.

Each action serves different security objectives, ranging from passive observation and logging to active intervention against potential threats.

The Headers

The header itself also has specific sections that further detail what the rule itself will apply to. Headers consist of protocols, IP addresses or IP ranges, source or destination ports, and the direction of traffic to which the rule should be applied.

 

writing suricata

 

Header: Specifying the Traffic for Inspection

The header identifies the specific type of network traffic that the rule should examine. It includes details such as the network protocol, IP addresses, port numbers, and the direction of the traffic flow:

By precisely defining the traffic characteristics in the header, you can target specific communication patterns and significantly reduce the occurrence of false positives.

Protocols

Suricata supports a wide range of network and application layer protocols, including TCP, UDP, HTTP, DNS, and SSH.

“Basic” Protocols

Application Protocols

tcp

http

ftp

Tls (ssl)

smb

dns

dcerpic

ssh

udp

smtp

imap

modbus(*)

dnp3(*)

enip(*)

nfs

ikev2

icmp

krb5

ntp

dhcp

rfb

rdp

snmp

tftp

ip

sip

http2

(*) protocols must be enabled in config file

It’s important to note that in addition to basic protocols, you can also use application protocols and industrial protocols (though some of the latter may need to be enabled in the config file as indicated in the table above).

IP Addresses

IP addresses can refer to single addresses, subnets, or the home/external net variable. Below are some examples:

    • Individual IP address: 1.2.3.4
    • CIDR Notation for network ranges: 192.168.0.0/24
    • Variables for defining network scopes: $HOME_NET, $EXTERNAL_NET
    • Support for negation (e.g., !192.168.1.5) and grouping (using []).

Type

Example

Single IP

1.2.3.4

CIDR Range

192.168.0.0/24

$HOME_NET

Defined home network in config

$EXTERNAL_NET

Defined external network in config

Negation Operator

!HOME_NET

Grouping Operator

[HOME_NET, 192.168.0.0/24]

Any IP

any


Header Section: Ports

The same logic can be applied when working with ports, which can also be provided as single ports, in groups, or negated. Examples below:

Type

Example

Single Port

80

Any Port

any

Port Range

100.102

Negation

!80

Grouping Operator

[100:120,!101]


As shown with the grouping operator example, you can get pretty detailed with the logic in these rules.

Monitoring Beyond Default Port Assignments

It’s not a given that every organization restricts its HTTP traffic to widely recognized ports such as 80, 443, or 8080. Some infrastructures, for reasons spanning from internal performance tuning to reliance on legacy applications, may run essential services on non-standard or what could be termed “uncommon” ports.

What makes this significant? Adversaries understand that defensive measures are heavily weighted towards overseeing traditional service ports. As a result, they might aim for lesser-used ports or try to obscure harmful activity in unexpected network locations. By the same token, legitimate communications on these distinct or atypical ports might be officially sanctioned, yet they could also betray unexpected or unauthorized actions.

With Suricata, you have the capability—and should make it a practice—to adapt your rules for close monitoring of these uncommon ports. Consider these examples:

  • Establish signatures to generate alerts upon detecting any unanticipated traffic towards sensitive ports that are known to operate outside the customary range.
  • Flag any HTTP communications that manifest outside of the ports allocated for your company’s specific applications, even if internal guidelines classify those ports as “safe.”
  • Utilize grouping and negation logic in your port definitions to isolate ports not usually involved in your day-to-day web or mail traffic flows.

This targeted methodology helps uncover activities like internal network reconnaissance, illicit tunneling, or configuration changes that might easily go unnoticed by conventional port-based surveillance.

 

Direction Operators

Finally, the header will indicate the directionality of the traffic it applies to, which can be unidirectional or bidirectional. 

    • Unidirectional traffic flow (source to destination): ->
    • Bidirectional traffic flow: <>

Type

Example

->

Unidirectional Match

<->

Bidirectional Match

By precisely defining the traffic characteristics in the header, you can target specific communication patterns and significantly reduce the occurrence of false positives.

The Rule Options


This is where the rule’s edge gets honed into a blade. Options can include metadata, specific identifiable bytes, and everything in between. There are some important things to keep in mind:

  • Rule options are always contained in parentheses
  • The options may be binary or key/value pairs
  • [this one is critical] Rule option order matters
  • Keywords vary by supported protocol


Each of the key value pairs is either going to be metadata or it will define matching action. Let’s see what this looks like in a specific Suricata rule:

Keyword

Value

Description

msg

“ET TROJAN Likely Bot Nick in IRC (USA +..)”

Text information sent when alert fires

flow

established,to_server;

Match on established connections to the server

flowbits

isset,is_proto_irc

Only run rule when is_proto_irc bit is set to true

content

“NICK “

Content for the signature to match

pcre

“/NICK . *USA.*[0-0]{3,}/i”

Perl compatible regular expression to match packet body against

reference

url,doc.emergingthreats.net/2008124

Reference source to learn more when alert fires

classtype

trojan-activity

Signature classification metadata

sid

2008124

Signature ID metadata

rev

2

Signature revision metadata

Options: Defining Detailed Matching Criteria and Metadata

Options provide the granular detail and context for Suricata rules. Enclosed in parentheses following the header, they allow for:

  • Adding Descriptive Information:
    msg:"Detected suspicious URL access";
  • Tracking Network Sessions:
    flow:established,to_server;
  • Setting and Checking Session State:
    flowbits:set,suspicious_behavior;
    flowbits:isset,suspicious_behavior;
  • Matching Specific Content within Packets:
    content:"/login"; http_uri;
  • Utilizing Regular Expressions for Pattern Matching:
    pcre:"/\bselect.+from\b/i";
  • Including External References:
    reference:url,www.example.com;

Each option keyword adds a layer of sophistication to the detection logic, enabling the creation of highly specific and context-aware security rules.

Going Beyond the Basics

There’s a lot more to learn about Suricata rules. Options don’t stop at plain text matches: you can harness RegEx parsing for powerful pattern detection, employ protocol-specific parsing (such as uricontent for HTTP), or even look for binary (non-textual) data with byte and hex value matching. This flexibility means you’re equipped to detect everything from suspicious SQL statements to encoded payloads hiding in HTTP traffic.

If you’re aiming for more advanced threat detection, consider combining multiple options and protocols. The Suricata rule language supports layer 7 protocol keywords, lets you parse application-specific content, and even supports industrial protocols (once enabled in the config). Whether you’re matching on IRC nicknames, examining byte sequences, or parsing DNS queries, you’ll find the options section is your primary toolkit for crafting sophisticated detection logic.

On a more practical level, signature IDs and signature revisions are important for version control and tracking. In addition to this article, you can dig a little deeper into writing Suricata rules in this previous Tech Talk Tuesday video from our CEO & Founder, Dan Gunter: Writing Suricata Rules: Understanding The Basic Rule Format. 

Here’s a rephrased version of the provided text, broken down by section, aiming to avoid plagiarism while retaining the core meaning:

Harnessing Organizational Understanding for Bespoke Detection

While the technical capabilities of Suricata rules offer considerable adaptability, their true power emerges when this technical skill is fused with an intimate understanding of your organization’s unique characteristics. Utilizing your company’s distinct operational habits and internal structures can elevate generic detection mechanisms into a finely tuned, customized defense.

Let’s explore several methods to convert routine operational knowledge into effective security indicators:

  • Awareness of Operational Hours: If your organization’s typical workday concludes by 7:00 PM and remote access is not permitted, any network connections originating from the office environment after these hours should warrant immediate investigation. Developing Suricata rules to monitor network traffic outside of established business hours provides a straightforward yet remarkably potent initial layer of scrutiny. Attackers unfamiliar with your specific schedule are likely to trigger these alerts.
  • Enforcement of Standardized Browser Use: Imagine your IT department mandates the Brave browser across the organization and actively restricts access to Internet Explorer and Edge. A Suricata rule designed to trigger an alert upon detecting connections from unapproved browsers (identified via user-agent data) can highlight unauthorized or compromised processes that deviate from your established software baseline.
  • Role-Based IP Address Segmentation: Allocating distinct subnets for various server categories—for instance, positioning databases within 192.168.0.0/24 and web servers in 192.168.1.0/24—enables the creation of rules that detect anomalous traffic patterns. For example, if a database server unexpectedly communicates with a server outside its designated communication pathways, it signals a potential issue. Similarly, observing a printer attempting to establish direct communication with a domain controller is an event that demands further examination.
  • Monitoring Client-to-Client Interactions: Despite internal network hardening through firewalls, resourceful attackers may find alternative pathways. In most organizational settings, direct communication between client machines is unnecessary and discouraged. By implementing rules that identify any east-west traffic between user endpoints, you can uncover potential lateral movement or policy breaches before significant harm occurs.

In each of these instances, your comprehensive knowledge of your environment’s expected behavior empowers you to develop rules that can isolate specific threats rather than just sifting through general network noise. Capitalize on your organization’s collective experience and daily operational cadences; the combination of automation and contextual awareness fosters a defense-in-depth strategy.

Developing Robust Buffer Overflow Detection Methods

Ineffectively designed detection rules frequently err by focusing on a specific exploit rather than the fundamental vulnerability. Consider, for instance, earlier strategies for buffer overflow detection. Many rules were configured to simply identify long sequences of identical characters—such as numerous “A”s—within HTTP traffic. While this might detect a rudimentary exploit or an unsophisticated attempt, its overall effectiveness is limited, akin to securing the main entrance while leaving other access points vulnerable. Adversaries rapidly adapted to bypass such signatures by diversifying payload structures, employing different characters, or encoding their malicious inputs.

Here’s an illustration of a less effective rule: Weak Rule Example: Scanning for a predetermined string like content:"AAAAAAAAAAAAAA" and generating a generic alert. Attackers can easily circumvent this by changing their input to “BBBBBBBBBB,” rendering the rule ineffective.

To genuinely enhance your detection capabilities, it is far more productive to concentrate on the indicators of vulnerability exploitation itself—particularly, abnormal or improperly formatted input lengths or field values that are incongruous with protocol or application norms. The objective is to identify the effects of exploitation rather than the specific, often transient, methods used.

So, what characterizes a more intelligent rule strategy? Effective Rule Example: Inspecting payload size, unexpected data formats, or anomalous request constructions that violate standard protocol grammar (e.g., an authentication username field suddenly expanding to hundreds of bytes). Regular expressions or “byte_test” operators can assist in enforcing such validation, making your detection signature more resistant to simple character alterations.

In essence: pursue the predictable anomalies resulting from exploitation, not the ephemeral variants of shellcode or buffer-filling techniques. Rules that generalize to address the underlying flaw demonstrate greater longevity and resilience against the constantly evolving offensive toolkit.

Honeytokens: Employing Deception as a Defensive Tactic

Honeytokens represent an ingenious defensive maneuver—the cybersecurity parallel to marking valuable items with invisible ink to see who attempts to pilfer them. Unlike conventional security measures, honeytokens are fabricated credentials, spurious records, or decoy data deliberately placed within your environment. Their sole purpose is to serve as tripwires: if any entity interacts with them, it signals a potential security breach.

A common tactic involves renaming the legitimate administrator account and establishing a counterfeit “Administrator” account that should never experience legitimate usage. With Suricata, you can implement rules to monitor any activity associated with this decoy account—such as attempted authentications, email transmissions, or the use of its credentials anywhere on your network. If Suricata detects such activity, it is highly probable that it is not a recognized system administrator performing routine tasks.

Beyond login credentials, the application of honeytokens is highly scalable. Consider distributing counterfeit credit card numbers, fabricated user profiles, or imitation proprietary documents within your databases. Subsequently, customize your Suricata rules to detect these unique data markers in network traffic. If even a fragment of this decoy data is observed exiting your network perimeter, you possess actionable intelligence indicating suspicious activity.

By incorporating honeytoken detection into your security framework, you gain early warning indicators—often identifying attackers before they can inflict substantial damage.


Hitting a Higher Gear on Mastery of Suricata Rules

Although the main structure of a Suricata rule is simple, writing Suricata rules can initially feel complicated. This is especially true when one begins to truly leverage the key values; writing these rules can become quite complex. The best way to gain mastery of Suricata rules is to be curious.

Download some sample PCAP files and really play around with the rules to see what you’re able to find (You’ll find some sample PCAP files here: https://github.com/automayt/ICS-pcap). 


Really dive into the different protocols and their keywords, and examine the impacts of utilizing Suricata’s ability to be very generalized or specific. And if you ever have questions or need someone to do some additional threat hunting, triage, or incident response, we’re just a
Contact Us form away. 

Using Deception: Fake Accounts and Records as Detection Tools

Let’s talk about one of the sneakier—yet highly effective—tools in the network security arsenal: honeytokens. Just as attackers thrive on trickery, defenders can turn the tables by setting up enticing decoys throughout their environment. Consider tweaking default accounts on your systems. For example, instead of relying on the standard administrator account, you might rename it to something innocuous and create a decoy account named “Administrator.” This bogus account isn’t actually used for legitimate activity, but it becomes a perfect bait. Creating a Suricata rule to watch for any authentication attempts or traffic involving this account means any use on the network instantly raises a red flag, catching unwelcome guests in the act—long before they realize they’ve been spotted.

The same strategy applies beyond user accounts. Inject fake user records, customers, products, or even phony credit card details into your databases. By crafting Suricata rules to look for these planted tokens traversing your network, you create high-fidelity tripwires: legitimate users won’t interact with these fakes, so any sign of them in network traffic is a surefire sign of malicious probing or data exfiltration attempts.

These simple additions deliver an outsized punch to your defense—not by making things more complicated, but by giving attackers enough rope to expose themselves, all while your genuine assets stay protected behind the curtain.

Conclusion

Developing mastery in crafting Suricata rules goes beyond mere technical proficiency; it necessitates strategic thinking and a thorough grasp of typical and anomalous network behavior. When thoughtfully constructed, these rules serve as a formidable line of defense, capable of identifying and mitigating intricate cyber threats. This guide lays the groundwork for creating rules that not only detect malicious activity but also do so with accuracy and clarity, aligning with both operational security objectives and the ever-evolving landscape of cyber threats.

Frequently Asked Questions

What are the primary applications of Suricata? Suricata is primarily used as an Intrusion Detection System (IDS), Intrusion Prevention System (IPS), and Network Security Monitoring (NSM) tool to observe and secure network traffic.

Can Suricata function as a replacement for a traditional firewall? No. While Suricata offers detection and prevention capabilities, it operates at a different layer and complements rather than substitutes the fundamental access control functions of a firewall.

What are effective strategies for minimizing false positives in Suricata alerts? Minimizing false positives involves crafting precise rule headers to target specific traffic patterns and utilizing flow and context-aware options to refine the matching criteria.

Does Suricata offer support for industrial control system protocols? Yes, with appropriate configuration and rule sets, Suricata can be used to monitor and analyze industrial protocols such as Modbus and DNP3.

Is Suricata capable of detecting threats within encrypted network traffic? Suricata can analyze certain metadata and behavioral patterns associated with encrypted traffic. However, deep packet inspection of encrypted content typically requires TLS decryption or the use of indirect detection techniques based on observable characteristics.

See how Insane Cyber transforms security

Our products are designed to work with
you and keep your network protected.