Commit Graph

6512 Commits (2e78bf0ba81bcb8cebc25bd49f717daf301d8658)

Author SHA1 Message Date
Eric Leblond 5f84b55d98 af-packet: AFPWalkBlock error handling
Error handling was not done. The implementation is making the
choice to consider we must detroy the socket in case of parsing
error. The same was done for tpacket_v2.
10 years ago
Eric Leblond b797fd926c af-packet: continuing cleaning and hole hunting
Suppress useless fields in AFPThreadVars. This patch also get rid
of bytes counter as it was only used to display a message at exit.
Information on livedev and on packet counters are enough.
10 years ago
Eric Leblond 9500d12c9f af-packet: cleaning and hole hunting
Reorder fields in AFPThreadVars and suppress some that were not
used elsewhere than in the initialization.
10 years ago
Eric Leblond bae1b03cf5 af-packet: tpacket_v3 implementation
This patch adds a basic implementation of AF_PACKET tpacket v3. It
is basic in the way it is only working for 'workers' runnning mode.
If not in 'workers' mode there is a fallback to tpacket_v2. Feature
is activated via tpacket-v3 option in the af-packet section of
Suricata YAML.
10 years ago
Eric Leblond d094039600 af-packet: remove useless code
No need for cooked header in the case of mmap capture.
10 years ago
Eric Leblond 27adbfa868 af-packet: micro optimization 10 years ago
Eric Leblond 5f400785c8 af-packet: avoid test for each packet 10 years ago
Justin Viiret f77bc5195c spm: handle null ptrs in destroy funcs gracefully
This will handle minimal DetectEngineCtx structures (used in delayed
detect mode) safely, since they don't get SPM global contexts allocated.

Also added BUG_ON checks for valid spm_table entries.
10 years ago
Victor Julien e43ce0a9ec file: switch to streaming buffer API
Make the file storage use the streaming buffer API.

As the individual file chunks were not needed by themselves, this
approach uses a chunkless implementation.
10 years ago
Victor Julien e836a750c8 http: improve body inspection
Enforce inspect window also in IDS mode. Try always to get at least
'inspect win' worth of data. In case there is more new data, take
some of the old data as well to make sure there is always some overlap.

This unifies IDS and IPS modes, the only difference left is the start
of inspection. IDS waits until min_size is available, IPS starts right
away.
10 years ago
Victor Julien feafc838db http: make htpstate cfg ptr const 10 years ago
Victor Julien 24a2f51569 http: move body settings into per dir struct 10 years ago
Victor Julien 6fb808fc1a http: add per direction config for body parsing
The HTPCfgDir structure is meant to contain config for per direction
body parsing parameters.

This patch stores the streaming API config.
10 years ago
Victor Julien 46e55f1e34 http body handling: use streaming buffer API
Convert HTTP body handling to use the Streaming Buffer API. This means
the HtpBodyChunks no longer maintain their own data segments, but
instead add their data to the StreamingBuffer instance in the HtpBody
structure.

In case the HtpBodyChunk needs to access it's data it can do so still
through the Streaming Buffer API.

Updates & simplifies the various users of the reassembled bodies:
multipart parsing and the detection engine.
10 years ago
Victor Julien 81b2984c4e streaming: buffer API
Add a new API to store data from streaming sources, like HTTP body
processing or TCP data.

Currently most of the code uses a pattern of list of data chunks
(e.g. TcpSegment) that is reassembled into a large buffer on-demand.

The Streaming Buffer API changes the logic to store the data in
reassembled form from the start, with the segments/chunks pointing
to the reassembled data.

The main buffer storing the data slides forward, automatically or
manually. The *NoTrack calls allows for a segmentless mode of
operation.

This approach has two main advantages:

1. accessing the reassembled data is virtually cost-free
2. reduction of allocations and memory management
10 years ago
Victor Julien 78ecfe8780 autofp: update queue handlers
Now that the flow lookup is done in the worker threads the flow
queue handlers running after the capture thread(s) no longer have
access to the flow. This limits the options of how flow balancing
can be done.

This patch removes all code that is now useless. The only 2 methods
that still make sense are 'hash' and 'ippair'.
10 years ago
Victor Julien 61ce05e7ed flow: remove dead code 10 years ago
Victor Julien 52d500c670 flowworker: initial support
Initial version of the 'FlowWorker' thread module. This module
combines Flow handling, TCP handling, App layer handling and
Detection in a single module. It does all flow related processing
under a single flow lock.
10 years ago
Victor Julien 408948815f detect: simplify flow locking
To simplify locking, move all locking out of the individual detect
code. Instead at the start of detection lock the flow, and at the
end of detection unlock it.

The lua code can be called without a lock still (from the output
code paths), so still pass around a lock hint to take care of this.
10 years ago
Victor Julien 6f560144c1 time: improve offline time handling
When we run on live traffic, time handling is simple. Packets have a
timestamp set by the capture method. Management threads can simply
use 'gettimeofday' to know the current time. There should never be
any serious gap between the two or major differnces between the
threads.

In offline mode, things are dramatically different. Here we try to keep
the time from the pcap, which means that if the packets are recorded in
2011 the log output should also reflect this. Multiple issues:

 1. merged pcaps might have huge time jumps or time going backward
 2. slowly recorded pcaps may be processed much faster than their
    'realtime'
 3. management threads need a concept of what the 'current' time is for
    enforcing timeouts
 4. due to (1) individual threads may have very different views on what
    the current time is. E.g. T1 processed packet 1 with TS X, while T2
    at the very same time processes packet 2 with TS X+100000s.

The changes in flow handling make the problems worse. The capture thread
no longer handles the flow lookup, while it did set the global 'time'.
This meant that a thread may be working on Packet 1 with TS 1, while the
capture thread already saw packet 2 with TS 10000. Management threads
would take TS 10000 as the 'current time', considering a flow created by
the first thread as timed out immediately.

This was less of a problem before the flow changes as the capture thread
would also create a flow reference for a packet, meaning the flow
couldn't time out as easily. Packets in the queues between capture
thread and workers would all hold such references.

The patch updates the time handling to be as follows.

In offline mode we keep the timestamp per thread. If a management thread
needs current time, it will get the minimum of the threads' values. This
is to avoid the problem that T2s time value might already trigger a flow
timeout as the flow lastts + 100000s is almost certainly meaning the
flow would be considered timed out.
10 years ago
Victor Julien 2f0e0f17db flow: move flow handling into worker threads
Instead of handling the packet update during flow lookup, handle
it in the stream/detect threads. This lowers the load of the
capture thread(s) in autofp mode.

The decoders now set a flag in the packet if the packet needs a
flow lookup. Then the workers will take care of this. The decoders
also already calculate the raw flow hash value. This is so that
this value can be used in flow balancing in autofp.

Because the flow lookup/creation is now done in the worker threads,
the flow balancing can no longer use the flow. It's not yet
available. Autofp load balancing uses raw hash values instead.

In the same line, move UDP AppLayer out of the DecodeUDP module,
and also into the stream/detect threads.

Handle TCP session reuse inside the flow engine itself. If a looked up
flow matches the packet, but is a TCP stream starter, check if the
ssn needs to be reused. If that is the case handle it within the
lookup function. Simplies the locking and removes potential race
conditions.
10 years ago
Victor Julien ae7aae81dc flow: get flow reference during lookup
Update Flow lookup functions to get a flow reference during lookup.

This reference is set under the FlowBucket lock.

This paves the way to not getting a flow lock during lookups.
10 years ago
Victor Julien a81766c046 detect: split detect entry into flow/noflow
This is a preparation for flow locking updates.
10 years ago
Mats Klepsland a13df67864 detect: add (mpm) keyword for tls_sni
Match on server name indication (SNI) extension in TLS using tls_sni
keyword, e.g:

alert tls any any -> any any (msg:"SNI test"; tls_sni;
        content:"example.com"; sid:12345;)
10 years ago
Jason Ish 3da79610af typo: SURCATA -> SURICATA 10 years ago
Victor Julien b77d307272 ipv6: simplify ext hdr parsing 10 years ago
Victor Julien abb0a31aed defrag: work around packet creation issues
Defrag tests set up packets but don't call Decode on them. Work
around failing IPv6 tests.
10 years ago
Victor Julien 68c7fae79f ipv6: simplify ext hdr parsing and storage
This reduces size of the IPV6ExtHdr structure part of every packet
significantly.

Clean up macro's in the ipv6 header.
10 years ago
Victor Julien 64405ae194 detect-ipopts: optimize matching 10 years ago
Victor Julien 3ab7dfd988 detect-ipopts: cleanup 10 years ago
Victor Julien 6ea0db2f60 ipv4: removed unused variables 10 years ago
Victor Julien 8c37906cf9 ipv4: store ipopts as flags, not bools 10 years ago
Victor Julien be5a5df1f7 ipv4: shrink per packet ipopts storage 10 years ago
Justin Viiret 91011b30a6 spm: add "spm-algo: auto" setting
This will default to Hyperscan when Suricata is built with Hyperscan
support. Otherwise, Boyer-Moore is used by default.
10 years ago
Justin Viiret 6a6d019245 spm: add Hyperscan implementation 10 years ago
Justin Viiret cce2d114e8 spm: add and use new SPM API
This new API allows for different SPM implementations, using a function
pointer table like that used for MPM.

This change also switches over the paths that make use of
DetectContentData (which previously used BoyerMoore directly) to the new
API.
10 years ago
Justin Viiret ce408c4d10 spm: add SinglePatternMatchDefaultMatcher
Allows selecting SPM algorithm with the 'spm-algo' value in the YAML
config file.
10 years ago
Victor Julien d84dc02bd7 tcp sack: improve tests 10 years ago
Victor Julien fbf0a7aa45 detect app-layer-event: fix tests 10 years ago
Victor Julien 80716f860e app-layer: test fixes 10 years ago
Victor Julien 90414472ed thread storage: fix memset 0 after realloc
Thread storage expansion would not properly memset 0 the new part
of the memory.
10 years ago
Mats Klepsland 45342078e4 tlsstore: fix memleak
Bug #1771.

Direct leak of 1834 byte(s) in 1 object(s) allocated from:
    #0 0x4e2e65 in realloc ??:?
    #1 0xcec27b in LogTlsLogPem /home/mats/suricata/src/log-tlsstore.c:130
    #2 0xcea4f5 in LogTlsStoreLogger /home/mats/suricata/src/log-tlsstore.c:303
    #3 0xd8b99c in OutputPacketLog /home/mats/suricata/src/output-packet.c:104
10 years ago
Mats Klepsland ed33f5f148 tlsstore: use TxLogger 10 years ago
Mats Klepsland 77cc03505b output: add new tx logger to log at certain condition
Some loggers needs certain conditions to be met before logging.
This enables us to use conditions on the tx logger.
10 years ago
Mats Klepsland 663273a31e tls: change flag checking in SSLParserTest23
Change flag checking in SSLParserTest23 to check each flag individually
to enable adding more flags without the test failing.
10 years ago
Mats Klepsland 47a4daeeb8 output: allow more than one TLS logger 10 years ago
Mats Klepsland e9074bc829 jsontls: use TxLogger 10 years ago
Mats Klepsland c6a61e009b tlslog: use TxLogger 10 years ago
Mats Klepsland 88bf866381 output-lua: use LuaTxLogger for TLS 10 years ago
Mats Klepsland fa6257b66a output: add new logger to log at specified state
Sometimes we want to log when we reach a specified state instead of
waiting for the session to end. E.g for TLS we want to log as soon
as the handshake is done.

To do this, a new logger is added, where it is possible to specify
a custom "ProgressCompletionStatus".
10 years ago
Mats Klepsland 4166ec3064 template: register logger functions 10 years ago
Mats Klepsland 593f81527a modbus: register logger functions 10 years ago
Mats Klepsland c52fe9a5fa http: register logger functions 10 years ago
Mats Klepsland d484812d05 smtp: register logger functions 10 years ago
Mats Klepsland dacb860d24 dns: register logger functions 10 years ago
Mats Klepsland 1f98915ebe tls: register logger functions 10 years ago
Mats Klepsland f3599323e4 tx: add functions for logging
Add function AppLayerParserRegisterLoggerFuncs for registering
a callback function for checking if a specific logger has logged
a transaction, and a callback function for specifying that it has.

Also add functions AppLayerParserGetTxLogged and
AppLayerParserSetTxLogged to invoke these callback functions.
10 years ago
Mats Klepsland c4b918b6c4 tx: do not store ProgressCompletionStatus per ipproto
Change AppLayerParserRegisterGetStateProgressCompletionStatus to
only store one ProgressCompletionStatus callback function for each
alproto, instead of storing one for each ipproto.

This enables us to use AppLayerParserGetStateProgressCompletionStatus
in functions where we do not know the ipproto used.
10 years ago
Mats Klepsland e4f03b18ba tls: make TX aware 10 years ago
Mats Klepsland a422ae9f3c tls-sni: fix alignment issues 10 years ago
Victor Julien 8dc477f85a sources: fix netmap compilation and pcap setup 10 years ago
Victor Julien be714a2f02 flow queue handler: use int16_t
Use int16_t instead of int to store the autofp queue id. We should
not easily get to 32k threads so 2 bytes per flow is sufficient.
10 years ago
Victor Julien ba64069b35 flow: remove unused debug code 10 years ago
Victor Julien 2c7cd1c22a flowint: redo tests 10 years ago
Victor Julien 3a36dea358 detect: add missing sigorder case 10 years ago
DIALLO David 271bd04539 modbus: fix AddressSanitizer error (segmentation fault)
In case of Mask Write register or Write single register request with
no data (malformed packet), app-layer-modbus checks response content
(data) with the none stored request content. That causes the segmentation
fault.

Before accessing to request content, app-layer-modbus checks now if
content has been previously stored. 4 unitests have been adding, 2 of them
to test the management of Mask Write register and Write single register requests,
and the 2 others to check invalid Mask Write register and Write single register
requests.
10 years ago
Victor Julien 79c1904ab2 ipv6: fix alignment issue in address to string code 10 years ago
Victor Julien 3979cb0e57 ac-ks: fix integer handling issue 10 years ago
Victor Julien 8db7b70e93 unittests: don't call memcpy on NULL-ptr 10 years ago
Victor Julien 4875040dca pcre: initialize var before use 10 years ago
Victor Julien e13f956100 yaml: minor cleanup 10 years ago
Victor Julien 542492d6c2 yaml: initialize var to prevent uninitialized read 10 years ago
Victor Julien d79208d93b tcp sack: fix alignment issues 10 years ago
Victor Julien 055f8bea10 smb: improve integer handling 10 years ago
Victor Julien ed5a01e8dd dcerpc: improve integer handling 10 years ago
Victor Julien 9235dd498f detect port: fix integer handling in hashing 10 years ago
Victor Julien 001e87310d decode: don't call memcpy on NULL-ptr on pseudo packets 10 years ago
Victor Julien 35d081a797 ippair: fix alignment issues 10 years ago
Victor Julien 31b632a17d host: fix alignment issues 10 years ago
Victor Julien b112af817d flow: fix alignment issues 10 years ago
Victor Julien 76c8c077c5 tcp: fix alignment issues with tcp timestamps 10 years ago
Victor Julien c64815e4a8 decode-mime: don't call memcpy on NULL pointer 10 years ago
Jason Ish aa8e747e4d sources: allow interface definitions to be reordered
For af-packet, pf-ring, netmap, and pcap use a generic
lookup function to find the configuration node for an
interface.

The new lookup function does not depend on the ordering
of the items inside the device configuration.
10 years ago
Eric Leblond e29e9056cb config-test: fix memory leak detect by ASAN
NSS library was not deinit at exit resulting in memory leak. As
it is useless for a config test, the patch updates the code so it
is not initialized.

Patch also calls MagicDeinit to free memory used by libmagic.
10 years ago
maxtors bf551ace4e Use ConfValIsTrue for parseing util-logfile append value. 10 years ago
maxtors 3c15c1f8d5 Use ConfValIsTrue for parsing TILE PCIE logging append value. 10 years ago
maxtors a81796654f Use ConfValIs* for parsing pf-ring.checksum-checks. 10 years ago
maxtors 70b864d06b Use ConfValIs* for parsing pcap.checksum-checks. 10 years ago
maxtors b28ebae088 Use ConfValIs* for parsing netmap.checksum-checks. 10 years ago
maxtors d18e2f6e9a Use ConfValIs* for parsing af-packet.checksum-checks. 10 years ago
maxtors 3d4cdd1117 Use ConfValIs* for parseing mpipe.checksum-checks. 10 years ago
maxtors 524c627194 Use ConfValIs* for parsing pcap-file.checksum-checks. 10 years ago
Victor Julien c742a818d5 profiling: suppress inferior version of UtilCpuGetTicks warning 10 years ago
Victor Julien db4ec46f18 coverty: fix dead code warning 10 years ago
Jason Ish dd86ac07f7 smb: check that there is enough input data
Conditional was checking the word count, but indexing
much further into the input data.
10 years ago
maxtors 0e5bbe8564 Reordering of RRTYPE switch case for performance. 10 years ago
maxtors 387919e203 Added more DNS Resource Record Types. 10 years ago
maxtors 16e4c92b69 Changed "enabled" parsing to use ConfValIs(true|false) 10 years ago
maxtors 2b80da424b Update ASN1_MAX_FRAMES to reflect default in suricata.yaml.in 10 years ago
Victor Julien 9818557369 stats: fix stats.log ignoring null-values for threads 10 years ago
Victor Julien d9639fba60 cppcheck: fix harmless warnings
[src/detect-engine-loader.c:272]: (error) Buffer is accessed out of bounds.
[src/flow-manager.c:742]: (error) Buffer is accessed out of bounds.
[src/flow-manager.c:906]: (error) Buffer is accessed out of bounds.
10 years ago
Zachary Rasmor dbbca37a94 Remove free operation on thread name field.
Name field is now  a pre-allocated array - free is no longer necessary.
Fix issue leading to segfault during interface shortening in Single runmode.
10 years ago
Victor Julien 71018cd2ce runmodes: constify names 10 years ago
Zachary Rasmor f211fa48f4 Update unit test to account for 'name' type change. 10 years ago
Zachary Rasmor 68cfa009a0 Update thread creation and threads to use global thread names.
Thread name is now stored as a static string buffer,
string duplication and alloc/de-alloc is no longer required.
10 years ago
Zachary Rasmor 10d3d90f06 Change thread name from pointer to buffer. Remove pointer free. 10 years ago
Zachary Rasmor 885747218b Update shortening algorithm to account for addition of #. 10 years ago
Zachary Rasmor 8c8759c189 Add global threadnames.
Update thread naming convention to follow: W#01-eth0.
Add interface name where applicable, add #.
10 years ago
Zachary Rasmor f8a40dd906 Update pcap-file runmode to adhere to new thread standard. 10 years ago
Zachary Rasmor 41c768ce28 Update threads to use global thread names.
Update FlowManager/Recycler to use global name.
Also add # into thread number.
Update af-packet to use global threadnames.
Update pcap to use global threadnames.
Update pfring to use global threadnames.
Update erf-dag to use global threadnames.
Update nflog to use global threadnames.
Update netmap to use global threadnames.
Update napatech to use global threadnames.
10 years ago
Zachary Rasmor 1bfebae8c4 Update IPS thread names to new name standard. 10 years ago
Zachary Rasmor 19bc6c1f9f Update thread naming convention for all IDS modes.
- Change 'Detect' to 'W'
- Enforce 2 digit numbering in thread names with leading zero
- Add 01 after W for single mode: W01
10 years ago
maxtors a6adb5dbbf Changed naming of flowmanager/recycler.
- Changed FlowManagerThread to FM-
- Changed FlowRecyclerThread to FR-
- Changed use of strcasecmp to strncasecmp. This was used in the
  killing and disabling of FM/FR Threads.
10 years ago
maxtors a17ac21077 Reworked how shortening should be performed.
The shortening of the interfacenames is now dependent on the
size of the destination buffer, so that this can be easily
changed in the future. The process uses snprintf and strlcat.

Also changed the buffer sizes in the util-runmodes to 12
so that they can hold 11 chars + null terminator.
10 years ago
maxtors 88a6e79607 Fixed string copy and cat functions and made shortening safer.
Changed out strcpy, strncpy to strlcat and strlcpy. Also added
checks to see if the shortening did work or if it would fail in
advance. Fixed code in util-device and util-runmodes.
10 years ago
maxtors 10d1450e49 Added shortening of listening interface in util-runmodes
Added function LiveSafeDeviceName in util-device that shortens an
NIC device name if the name is over a given length and turns
it in to Ex: longi...eeth1
10 years ago
Eric Leblond 63937cd903 detect-msg: fix option parsing
Code removing the space before the double quote at msg option start
was not working correctly for option starting with a space.
10 years ago
Victor Julien 7f700a137c smtp: fix test 10 years ago
Victor Julien c4a9580fce detect file: improve multi file handling
When multiple files were in a tx, the first one(s) closed/complete
and a new open one as well, a match in the former could lead to not
inspecting the latter.

This patch adds a workaround for this case, by allowing the file
inspection code to return a special code for 'match, but more files
available in tx'.

The stateful detection engine will then not make this match final for
the tx. It relies on the file pruning to kick in to make sure the
already complete files are removed from the tx before the next time
the detection engine is called on the tx.
10 years ago
Victor Julien 8cd4405c21 detect file: cleanups 10 years ago
Victor Julien ea0067add8 debug: add various detect engine debug statements 10 years ago
Victor Julien 83e0529b2b http: flag destate about new files
The stateful detection engine needs some assistance when inspecting
transactions with multiple files. This patch flags the detect state
(if any) about the availability of new files in http. For http it
should only apply to multipart bodies although the flag is set for
all files.
10 years ago
Victor Julien aa4ad9d25b smtp: flag detect state that new files are available
The stateful detection engine needs some assistance when inspecting
transactions with multiple files. This patch flags the detect state
(if any) about the availability of new files in smtp.
10 years ago
Victor Julien 807fe4ac9f detect state: fix issues with multiple files per tx
Make sure multiple files in a single tx are inspected correctly. This
requires resetting part of the stored state on new files.
10 years ago
Victor Julien 19d112ba07 smtp/mime: allow unquoted name/filename fields
Don't enforce that name/filename fields are quoted.

Reported-By: Blair Steven
10 years ago
Victor Julien 5c514c904f smtp: fix file logging and matching
When no rules with 'file content' keywords like filemd5 or filestore
were used, and non of the file outputs would force 'output' like
'force-md5' and 'force-magic', the file would not be tracked at all.

This meant that logging wouldn't work and neither would filename and
fileext inspection.

This patch removes the tracking bypass from the SMTP code and leaves
decisions to the file API.
10 years ago
maxtors 9d3fd82849 Removed duplicate include statements. 10 years ago
maxtors 06d74b5775 Module specific error code for init ctx error. 10 years ago
maxtors 69863f7b1c Corrected and unified debugmessages for init data errors in *ThreadInit. 10 years ago
maxtors 7f2f7cc48d Added parsing and utilization of yaml defined payload buffer value. 10 years ago
Victor Julien 554080cced lua: print lua script func/line/file in SCLog* funcs
Instead of printing the func/line/file of the C code SCLog* wrappers,
print them from inside the lua script. They are not always available.
10 years ago
Victor Julien 1c8775b340 QA: --afl-rules for faster rule fuzzing 10 years ago
Victor Julien c3efc4e072 pcap: small cleanups 10 years ago
Victor Julien 3f16ebe476 dns: don't read uninitialized memory in name parsing
AFL+ASAN found that with certain input we used an uninitialized byte
in the length calculation. Probably harmless as the length was still
validated afterwards.
10 years ago
Victor Julien c4575d1419 stream-tcp: improve test function cleanup 10 years ago
Victor Julien 3aea0bd4f3 stream-tcp: introduce stream cleanup function 10 years ago
Victor Julien 93fa291922 stream-tcp: unify ssn clean up functions
There were 2 separate function doing ssn cleanup. To prevent issues
common with code duplication, unify them.
10 years ago
Victor Julien 9b08cdae74 capture: only check for faster methods on -i
Also, since we now default to AF_PACKET for -i if available, only check
for PF_RING and NETMAP.
10 years ago
Victor Julien 053b96458f commandline: add -i arg check 10 years ago
Victor Julien f8852f4415 commandline: use afpacket for -i if available 10 years ago
Victor Julien a3a7d9b299 pcap: unify -i and --pcap parsing 10 years ago
Victor Julien b50111a5a7 commandline: move afpacket parsing into util func 10 years ago
Victor Julien 1fe09a38e0 commandline: move pcap parsing into util func 10 years ago
Victor Julien 7ac7f9cd55 instance: add progname as ptr to argv[0] 10 years ago
Mats Klepsland 45d87d66c0 afl: add support for AFL PERSISTANT_MODE
Add support for AFL PERSISTANT_MODE when Suricata is compiled with
a supported compiler (only afl-clang-fast for now).

This gives a ~10x performance boost when fuzzing.
10 years ago
Mats Klepsland 8111eb934f QA: add --afl-der=<file>
Expose SSL/TLS certificate decoding (DER) to commandline
using --afl-der=<file>.
10 years ago
Victor Julien d165906397 QA: add --afl-decoder-ppp=<file> 10 years ago
Victor Julien bdaba1d815 QA: expose Mime decoding API to commandline using --afl-mime=<file> 10 years ago
Victor Julien 077ac81688 QA: direct access from commandline to AppLayer API
This patch introduces a new set of commandline options meant for
assisting in fuzz testing the app layer implementations.

Per protocol, 2 commandline options are added:

--afl-http-request=<filename>
--afl-http=<filename>

In the former case, the contents of the file are passed directly to
the HTTP parser as request data.

In the latter case, the data is devided between request and responses.
First 64 bytes are request, then next 64 are response, next 64 are
request, etc, etc.
10 years ago
Victor Julien ca81c33e14 afl: add --enable-afl configure option 10 years ago
Victor Julien 09242fb4a8 afl: optionally exit right after afl single runmode
Exit right away if afl.exit_after_pcap is set to true. Safes time
as fuzzing the shutdown code may not be as interesting.
10 years ago
Victor Julien d461837511 afl: add --afl-parse-rules to return 0 on any rule
When fuzzing, AFL will create lots of malformed rules. We don't want
to error out on those. As we're fuzzing the parser any non-crash
should return 0. Crashes (ASAN or not) will return a non-0 code.
10 years ago
Victor Julien e824a8be76 afl: special 'single' runmode
To avoid threading, this 'single' mode doesn't run in it's own thread
but instead runs in the main thread.
10 years ago
Victor Julien a42251d459 afl: add define to disable mgt threads
The inherent non-deterministic nature of the management threads
creates variable test cases.
10 years ago
Victor Julien b2695600ba afl: add define to disable rand_r use
The randomness affects AFL. It creates variable test cases, which
we need to avoid.
10 years ago
Victor Julien 4c1c13d110 detect reload: improve signal logic 10 years ago
Victor Julien c0294521dd startup: move more into PostConfLoadedSetup 10 years ago
Victor Julien 0ab83288ac startup: move RunUnittests to StartInternalRunMode 10 years ago
Victor Julien e67ae0f174 detect keywords: use parse regex util func 10 years ago
Victor Julien 4a2e816bea detect parser: add parse regex util function
Add regex setup and free util functions. Keywords often use a regex
to parse rule input. Introduce a common function to do this setup.

Also create a list of registered regexes to free at engine shutdown.
10 years ago
Victor Julien 167d94efff dns: improve handling of tx pick up on response 10 years ago
Mats Klepsland c2f0f82bb4 util-decode-der: fix hang detected by AFL
Fix hang that occurs when child->length is zero, resulting in an
endless loop.
10 years ago
Mats Klepsland 18f88a6344 util-decode-der-get: code cleanup 10 years ago
Mats Klepsland a985b450e3 util-decode-der: code cleanup 10 years ago
Mats Klepsland e117461d4b app-layer-ssl: code cleanup 10 years ago
Mats Klepsland 550823455e app-layer-tls-handshake: code cleanup 10 years ago
Mats Klepsland 434b09563a app-layer-tls-handshake: remove duplicate include 10 years ago
Alexander Gozman 365015c2d5 Support sending rejects via libnet when running under non-root.
Since version 1.1.6 libnet handles capabilities correctly.
So changing libnet's version checking a little bit should do the trick.
10 years ago
Jason Ish 52f6d21463 flowbits: use some of the new test macros 10 years ago
Jason Ish da1dec6d65 counters: use some of the new macros in tests 10 years ago
Jason Ish d7d05b007c conf: use new testing macros
Also don't bother with cleanup on failure.
10 years ago
Jason Ish 13cf2f829e testing: new test macros, new testing documentation group.
Unit testing support macros for failing on expressions,
as well as passing tests on expressions.

If fatal unittests are enabled BUG_ON will be triggered for
an assertion providing the line number of the failure, otherwise
the test will simply fail.

Moved the fatal flag to a global var instead of a configuration
parameter for ease of access from a macro.
10 years ago
Jason Ish 796dd5223b tests: no longer necessary to provide successful return code
1 pass, 0 is fail.
10 years ago
Jason Ish 52983bf314 tests: convert all test to return 0 on failure, 1 on success 10 years ago
Victor Julien 38f67d88ea tcp: reduce TCP options storage in packets
Until now, the TCP options would all be stored in the Packet structure.
The commonly used ones (wscale, ts, sack, sackok and mss*) then had a
pointer to the position in the option array. Overall this option array
was large. About 360 bytes on 64bit systems. Since no part of the engine
would every access this array other than through the common short cuts,
this was actually just wasteful.

This patch changes the approach. It stores just the common ones in the
packet. The rest is gone. This shrinks the packet structure with almost
300 bytes.

* even though mss wasn't actually used
10 years ago
Torgeir Natvig 7ef8558e79 lua_close() segfaults on null pointers 10 years ago
Victor Julien d085362e61 detect: fix error handling in mpm setup
*** CID 1358124:  Null pointer dereferences  (REVERSE_INULL)
/src/detect-engine-mpm.c: 940 in MpmStoreSetup()
934                     PopulateMpmHelperAddPatternToPktCtx(ms->mpm_ctx,
935                             cd, s, 0, (cd->flags & DETECT_CONTENT_FAST_PATTERN_CHOP));
936                 }
937             }
938         }
939
>>>     CID 1358124:  Null pointer dereferences  (REVERSE_INULL)
>>>     Null-checking "ms->mpm_ctx" suggests that it may be null, but it has already been dereferenced on all paths leading to the check.
940         if (ms->mpm_ctx != NULL) {
941             if (ms->mpm_ctx->pattern_cnt == 0) {
942                 MpmFactoryReClaimMpmCtx(de_ctx, ms->mpm_ctx);
943                 ms->mpm_ctx = NULL;
944             } else {
945                 if (ms->sgh_mpm_context == MPM_CTX_FACTORY_UNIQUE_CONTEXT) {
10 years ago
Victor Julien dc008206e3 detect: fix scan-build warning
detect-engine-siggroup.c:700:38: warning: Call to 'malloc' has an allocation size of 0 bytes
    sgh->non_mpm_other_store_array = SCMalloc(non_mpm * sizeof(SignatureNonMpmStore));
                                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
./util-mem.h:177:14: note: expanded from macro 'SCMalloc'
    ptrmem = malloc((a)); \
             ^~~~~~~~~~~
1 warning generated.
10 years ago
Victor Julien 2ee3e726a9 detect: don't set unused variable
detect.c:3801:13: warning: Value stored to 'tmplist2_tail' is never read
            tmplist2_tail = joingr;
            ^               ~~~~~~
detect.c:3804:13: warning: Value stored to 'tmplist2_tail' is never read
            tmplist2_tail = joingr;
            ^               ~~~~~~
2 warnings generated.
10 years ago
Victor Julien 9b6e292a28 mpm: remove unused max pattern len field 10 years ago
Victor Julien f1ee125810 detect-flowvar: shrink mem structure by 8 bytes 10 years ago
Victor Julien e2789a87c2 detect: shrink IPOnlyCIDRItem with 8 bytes 10 years ago
Victor Julien adc453eec6 detect-port: improve comment about sgh pointer 10 years ago
Victor Julien ef6f347f84 detect-address: remove sgh pointer as it's unused 10 years ago
Victor Julien d5c6d08bc8 detect-port: remove debug mem counters 10 years ago
Victor Julien 9bd8197009 detect-address: remove debug mem counters 10 years ago
Victor Julien e0111fbb90 detect grouping: remove debug mem counters 10 years ago
Victor Julien 5f676167a3 detect grouping: make json dump configurable
Make the rule grouping dump to rule_group.json configurable.

detect:
  profiling:
    grouping:
      dump-to-disk: false
      include-rules: false      # very verbose
      include-mpm-stats: false
10 years ago
Victor Julien d6ba01b1b7 detect: make port whitelisting configurable
Make the port grouping whitelisting configurable. A whitelisted port
ends up in it's own port group.

detect:
  grouping:
    tcp-whitelist: 80, 443
    udp-whitelist: 53, 5060

No portranges are allowed at this point.
10 years ago
Victor Julien 5b1d75f0bd detect: suppress output 10 years ago
Victor Julien 725d6c3739 yaml: convert detect-engine to just detect
Instead of detect-engine which used a list for no good reason, use a
simple map now.

detect:
  profile: medium
  custom-values:
    toclient-groups: 3
    toserver-groups: 25
  sgh-mpm-context: auto
  inspection-recursion-limit: 3000
  # If set to yes, the loading of signatures will be made after the capture
  # is started. This will limit the downtime in IPS mode.
  #delayed-detect: yes
10 years ago
Victor Julien ac2c206359 mpm: clean up builtin mpm setup, enable single/full 10 years ago
Victor Julien 1dd135d512 mpm: always cleanup factory 10 years ago
Victor Julien 6ef27c9f92 mpm: allow app buffer shared/unique
Allow setting of shared or unique setting per app buffer type:
e.g. detect.mpm.http_uri.shared=true
10 years ago
Victor Julien 79a96b2b90 mpm: refactor 'single' setup handling 10 years ago
Victor Julien 157ca89dd7 mpm: remove useless flag from factory 10 years ago
Victor Julien fdd05e8fb4 mpm: remove unused app proto factory 10 years ago
Victor Julien 4e91f6b1e6 mpm: in factory register, consider name const 10 years ago
Victor Julien 2b84387ea4 detect: work around cocci limitation 10 years ago
Victor Julien 0311f01b97 rule grouping: speed up port based grouping
Create a hash table of unique DetectPort objects before trying to
create a unique list of these objects. This safes a lot of cycles
in the creation of the list.
10 years ago
Victor Julien a2223bb066 mpm: consify packet/stream search 10 years ago
Victor Julien 87f3adbe4c detect/mpm: unify packet/stream mpm_ctx pointers
SGH's for tcp and udp are now always only per proto and per direction.
This means we can simply reuse the packet and stream mpm pointers.

The SGH's for the other protocols already used a directionless catch
all mpm pointer.
10 years ago
Victor Julien 30755265ee http_raw_header: improve mpm progress handling 10 years ago
Victor Julien af3bf3dc7a detect: optimize sgh layout 10 years ago
Victor Julien de273d88cc detect: remove unused content minlen tracking 10 years ago
Victor Julien e43c4f3ea2 mpm: optimize calls
For all mpm wrapper functions, check minlen vs the input buffer to see
if we can bypass the mpm search.

Next to this, make all the function inline. Also constify the input and
do other minor cleanups.
10 years ago
Victor Julien 5857660568 http_uri: mpm cleanup. Use mpm_ctx's minlen 10 years ago
Victor Julien 6bb2b001a3 mpm: cleanup: move mpm funcs into buffer specific files 10 years ago
Victor Julien e57e7d1b96 mpm: cleanup, remove unused structs and prototypes 10 years ago
Victor Julien eb19fc4c7b mpm: remove unused structure 10 years ago
Victor Julien caea596ce5 profiling: output post-prefilter matches
Dump a json record containing all sigs that need to be inspected after
prefilter. Part of profiling. Only dump if threshold is met, which is
currently set by:

 --set detect.profiling.inspect-logging-threshold=200

A file called packet_inspected_rules.json is created in the default
log dir.
10 years ago
Victor Julien 92c571b26d detect: move sm_list to string funcs to parser code 10 years ago
Victor Julien 722e2dbf7c profiling: initial rulegroup tracking
Per rule group tracking of checks, use of lists, mpm matches,
post filter counts.

Logs SGH id so it can be compared with the rule_group.json output.

Implemented both in a human readable text format and a JSON format.
10 years ago
Victor Julien e310a033be detect: assign id to sgh 10 years ago
Victor Julien c880b79f45 detect: shrink sgh
Turn list of mpm_ctx pointers into a union so that we don't waste
space. The sgh's for tcp and udp are in one direction only, so the
ts and tc ones are now in the union.
10 years ago
Victor Julien c804102a9a detect: move app_mpms array to init data 10 years ago
Victor Julien 9b3d4f7e24 mpm: unify & localize mpm pattern (id) handling
So far, the patterns as passed to the mpm's would use global id's that
were shared among all buffers, directions. This would lead to a fairly
large pattern id space. As the mpm algo's use the pattern id's to
prevent duplicate matching through a pattern id based bitarray,
shrinking this space will optimize performance.

This patch implements this. It sets a flag before adding the pattern
to the mpm ctx, instructing the mpm to ignore the provided pid and
handle pids management itself. This leads to a shrinking of the
bitarray size.

This is made possible by the previous work that removes the pid logic
from the code.

Next to this, this patch moves the pattern setup stage to common util
functions. This avoids code duplication.

Update ac, ac-bs and ac-ks to use this.
10 years ago
Victor Julien ba9d43cce5 mpm: improve negated mpm
The idea is: if mpm is negated, it's both on mpm and nonmpm sid lists
and we can kick it out in that case during the merge sort.

It only works for patterns that are 'independent'. This means that the
rule doesn't need to only match if the negated mpm pattern is limited
to the first 10 bytes for example.

Or more generally, an negated mpm pattern that has depth, offset,
distance or within settings can't be handled this way. These patterns
are not added to the mpm at all, but just to to non-mpm list. This
makes sense as they will *always* need manual inspection.

Similarly, a pattern that is 'chopped' always needs validation. This
is because in this case we only inspect a part of the final pattern.
10 years ago
Victor Julien 9e71ef4c3b detect: remove signature pattern id reference 10 years ago
Victor Julien 46734ec41b mpm: remove unused pmq merge function 10 years ago
Victor Julien c1ad08d11e detect: remove stream pmq array 10 years ago
Victor Julien 4e8e591715 detect mpm: mpm store cleanup
Move all rule modification to the fast_pattern assigment.
10 years ago
Victor Julien c87fcb29ff detect mpm: fast_pattern assignment cleanup 10 years ago
Victor Julien 7c94077892 detect mpm: remove unused mpm flags 10 years ago
Victor Julien a7d126738a detect address: remove unused features 10 years ago
Victor Julien cbf80de6fe detect-port: cleanup 10 years ago
Victor Julien a96fa0fc2f detect: remove unused dport sgh hash 10 years ago
Victor Julien e6248b0dbe detect: clean up sgh's at detect engine free 10 years ago
Victor Julien 1f7e33a4b0 detect: remove unused flag 10 years ago
Victor Julien e8c9598035 detect sgh: remove unused field 10 years ago
Victor Julien 2ab20d0b9b detect: free lookup structures 10 years ago
Victor Julien 4ba1ac55f0 detect: output sgh stats
Output stats for the rule groups into a json format.
10 years ago
Victor Julien 810d2d3ec6 detect: add list id to string funcs 10 years ago
Victor Julien fa885e1d85 mpm: remove pattern id logic 10 years ago
Victor Julien 69d38a3222 mpm: ac-bs use internal pattern id tracking 10 years ago
Victor Julien 4edb03ab9d mpm: ac use internal pattern id tracking 10 years ago
Victor Julien cd8283bb72 smtp: use rule_id mpm support instead of pattern id 10 years ago
Victor Julien b2fcb17859 proto detect: in mpm switch to rule id
Use the rule id API instead of pattern id API.
10 years ago
Victor Julien a34be23002 detect: simplify negated mpm handling 10 years ago
Victor Julien b84d6d402f detect grouping: multiple whitelist conditions
Instead of the binary yes/no whitelisting used so far, use different
values for different sorts of whitelist reasons. The port list will
be sorted by whitelist value first, then by rule count.

The goal is to whitelist groups that have weak sigs:

 - 1 byte pattern groups

 - SYN sigs

    Rules that check for SYN packets are mostly scan detection rules.
    They will be checked often as SYN packets are very common.

    e.g. alert tcp any any -> any 22 (flags:S,12; sid:123;)

    This patch adds whitelisting for SYN-sigs, so that the sigs end up
    in as unique groups as possible.

 - negated mpm sigs

    Currently negated mpm sigs are inspected often, so they are quite
    expensive. For this reason, try to whitelist them.

These values are set during 'stage 1', rule preprocessing.
10 years ago
Victor Julien 3c184c19cd detect grouping: port based group whitelisting
Whitelist some ports in grouping to make sure they get their own group.
10 years ago
Victor Julien 5772f526dc detect grouping: warn on and fix up bad sigs
Only inspect directionless SYN scan sigs toserver. Issue a warning for
those rules.
10 years ago
Victor Julien 2ce03fbabb detect: split non-mpm list into syn/nosyn
Since SYN inspecting rules are expensive, this patch splits the
'non-mpm' list (i.e. the rules that are always considered) into
a 'syn' and 'non-syn' list. The SYN list is only inspected if the
packet has the SYN flag set, otherwise the non-syn list is used.

The syn-list contains _all_ rules. The non-syn list contains all
minus the rules requiring the SYN bit in a packet.
10 years ago
Victor Julien e48d745ed7 mpm: constify search func args 10 years ago
Victor Julien 26517b8b61 detect: mpm store frees mpm_ctx' it owns 10 years ago
Victor Julien 102a82fc7b detect: use mpm store for app layer mpms
Rework app-layer mpm setup and registration to make this possible.
10 years ago
Victor Julien fac2cc0560 detect: mpm deduplication
Create hash for mpm's that we can reuse. Have packet/stream mpms
use this.
10 years ago
Victor Julien f0ba00e51d detect: remove old unused code 10 years ago
Victor Julien 10b049304f detect: set new defaults for grouping 10 years ago
Victor Julien 2ee9bf2aef detect: rename groupings vars 10 years ago
Victor Julien 1f70ccfc23 detect: remove unused grouping settings 10 years ago
Victor Julien ae80ed5964 detect: make port grouping use config limits 10 years ago
Victor Julien df529b13ce detect: change port grouping
Update port grouping logic. Previously it would create one consistent
list w/o overlap. It largely still does this, except for the 'catch
all' port group at the end of the list. This port group contains all
the sigs that didn't fit into the other groups.
10 years ago
Victor Julien a392812302 detect: sort/group port sigs 10 years ago
Victor Julien e570b10abe detect: display unique sgh count 10 years ago
Victor Julien eda9552e95 detect: group proto sghs 10 years ago
Victor Julien d82df4eb8b detect-mpm: make sgh setup proto aware
Allow multi-proto, multi-direction sgh's.
10 years ago
Victor Julien 4223ce9aba detect: remove obsolete grouping code 10 years ago
Victor Julien 9ae4cb9e02 detect: debug output 10 years ago
Victor Julien fd5a06017d detect: per port and proto rule grouping
Replace tree based approach for rule grouping with a per port (tcp/udp)
and per protocol approach.

Grouping now looks like:

               +----+
               |icmp+--->
               +----+
               |gre +--->
               +----+
               |esp +--->
               +----+
          other|... |
        +----->-----+
        |      |N   +--->
        |      +----+
        |
        | tcp  +----+   +----+
        +----->+ 80 +-->+ 139+-->
        |      +----+   +----+
        |
        | udp  +----+   +----+
    +---+----->+ 53 +-->+ 135+-->
    |          +----+   +----+
    |toserver
+--->
    |toclient
    |
    +--->

So the first 'split' in the rules is the direction: toserver or toclient.
Rules that don't have a direction, are in both branches.

Then the split is between tcp/udp and the other protocols. For tcp and
udp port lists are used. For the other protocols, grouping is simply per
protocol.

The ports used are the destination ports for toserver sigs and source
ports for toclient sigs.
10 years ago
Victor Julien 27e63a1e11 detect: track direction and ipproto of sgh
Each SGH has a unique ipproto and direction.
10 years ago
Victor Julien e75a93b125 detect: pass ipproto to rule grouping funcs 10 years ago
Victor Julien c71c991669 detect: delay sgh cleanup 10 years ago
Victor Julien bb662a65f8 detect: delay sgh mpm setup 10 years ago
Victor Julien 18dd54dfa7 Start rule inspect with mask check 10 years ago
Victor Julien bfe49b60f7 rule analyzer: add no/both direction warning 10 years ago
Victor Julien b7d81fc3b0 detect: SYN flags
Add funcs to see if a rule needs a SYN flag in the packet.
10 years ago
Victor Julien f720dfd21e detect: validate http_method pattern
Leading and trailing spaces and tabs are invalid as these are not part
of the buffer as returned by libhtp.
10 years ago
Victor Julien 66b3dba676 detect: remove dead code 10 years ago
Victor Julien b3dcdb10be detect mpm: remove dead code 10 years ago
Victor Julien 14d9ce7b2e detect/mpm: remove unused max_id param from API 10 years ago
Victor Julien 0d3f671b55 detect: constify mpm/detect funcs 10 years ago
Victor Julien 4f8e1f59a6 mpm: remove obsolete mpm algos
Remove: ac-gfbs, wumanber, b2g, b3g.
10 years ago
Victor Julien 262abbb49f mpm: fix ac-ks compilation on cygwin 10 years ago
Victor Julien 58e533858b detect mpm: ac-tile/ac-ks default to single
Use sgh-mpm-context single is it is set to 'auto' when ac-ks is used.
10 years ago
Victor Julien 0987fd16dc ac-ks: 32bit fixes 10 years ago
Victor Julien 9c2e374a3d ac-ks: fix mem leaks 10 years ago
Victor Julien 887ddf1ed8 mpm: introduce ac-ks
Introduce 'ac-ks' or the Kenneth Steele AC implementation. It's
actually 'ac-tile' written by Ken for the Tilera platform. This
patch adds support for it on other architectures as well.

Enable ac-tile for other archs as 'ac-ks'.

Fix a bunch of OOB reads in the loops that triggered ASAN.
10 years ago
Victor Julien 3781b00dbc Open Suricata 3.1 development branch 10 years ago
Mats Klepsland f9ac42b36f util-decode-der: fix NULL dereference bug
Make sure that the length is not longer than the size of the buffer
provided.
10 years ago
Mats Klepsland c0dd911591 util-decode-der: fix heap-buffer-overflow 10 years ago
Mats Klepsland d07c495ed1 app-layer-tls-handshake: fix heap-buffer overflow
Fix heap-buffer overflow that occurs when we are given repeatedly
certificates with the length of zero.
10 years ago
Victor Julien ba035e601e hyperscan: fix minor coverity warning 1358023
*** CID 1358023:  Null pointer dereferences  (REVERSE_INULL)
/src/util-mpm-hs.c: 860 in SCHSDestroyThreadCtx()
854         if (thr_ctx->scratch != NULL) {
855             hs_free_scratch(thr_ctx->scratch);
856             mpm_thread_ctx->memory_cnt--;
857             mpm_thread_ctx->memory_size -= thr_ctx->scratch_size;
858         }
859
>>>     CID 1358023:  Null pointer dereferences  (REVERSE_INULL)
>>>     Null-checking "mpm_thread_ctx->ctx" suggests that it may be null, but it has already been dereferenced on all paths leading to the check.
860         if (mpm_thread_ctx->ctx != NULL) {
861             SCFree(mpm_thread_ctx->ctx);
862             mpm_thread_ctx->ctx = NULL;
863             mpm_thread_ctx->memory_cnt--;
864             mpm_thread_ctx->memory_size -= sizeof(SCHSThreadCtx);
865         }
10 years ago
Victor Julien 2ccf028eac hyperscan: fix minor coverity warning 1358024
*** CID 1358024:  Null pointer dereferences  (REVERSE_INULL)
/src/util-mpm-hs.c: 1043 in SCHSPrintInfo()
1037         printf("  SCHSPattern    %" PRIuMAX "\n", (uintmax_t)sizeof(SCHSPattern));
1038         printf("Unique Patterns: %" PRIu32 "\n", mpm_ctx->pattern_cnt);
1039         printf("Smallest:        %" PRIu32 "\n", mpm_ctx->minlen);
1040         printf("Largest:         %" PRIu32 "\n", mpm_ctx->maxlen);
1041         printf("\n");
1042
>>>     CID 1358024:  Null pointer dereferences  (REVERSE_INULL)
>>>     Null-checking "ctx" suggests that it may be null, but it has already been dereferenced on all paths leading to the check.
1043         if (ctx) {
1044             char *db_info = NULL;
1045             if (hs_database_info(pd->hs_db, &db_info) == HS_SUCCESS) {
1046                 printf("HS Database Info: %s\n", db_info);
1047                 SCFree(db_info);
1048             }
10 years ago
browner87 070a35fd3b source-pcap-file: fix stats not being reset
Fix for redmine #1737. Clears stats between each scanned PCAP instead of just 
on load in Unix socket mode.
10 years ago
browner87 d05883af9b Fix for redmine bug 1737
PCAP stats not reset between files in Unix socket mode. Added a memset to the Global Init function to clear these stats.
10 years ago
Jason Ish 06dcaec335 byte-extract: for string, default to base "dec" if not provided
For Snort compatibility, as Snort defaults to "dec" if not provided.

Fixed issue 1697:
https://redmine.openinfosecfoundation.org/issues/1697
10 years ago
Victor Julien ffb5498228 detect: fix potential deadlock during reload
If interrupted during the BreakLoop stage during reload, a deadlock
could happen.
10 years ago
Victor Julien f836256e20 detect: fix small mem leak on duplicate sigs
Direct leak of 80 byte(s) in 5 object(s) allocated from:
    #0 0x4c673b in __interceptor_malloc (/home/victor/dev/suricata/src/suricata+0x4c673b)
    #1 0xb7a425 in DetectEngineSignatureIsDuplicate /home/victor/dev/suricata/src/detect-parse.c:1715:10
    #2 0xb79390 in DetectEngineAppendSig /home/victor/dev/suricata/src/detect-parse.c:1836:19
    #3 0x86fe56 in DetectLoadSigFile /home/victor/dev/suricata/src/detect.c:357:15
    #4 0x815fee in ProcessSigFiles /home/victor/dev/suricata/src/detect.c:419:13
    #5 0x8139a8 in SigLoadSignatures /home/victor/dev/suricata/src/detect.c:499:15
    #6 0xfe435d in LoadSignatures /home/victor/dev/suricata/src/suricata.c:1979:9
    #7 0xfcd87e in main /home/victor/dev/suricata/src/suricata.c:2345:17
    #8 0x7fb66bf7cec4 in __libc_start_main /build/eglibc-3GlaMS/eglibc-2.19/csu/libc-start.c:287
10 years ago
Justin Viiret 13b87f5aff mpm: add Hyperscan integration
This adds an MPM implementation that uses the Hyperscan regex engine
library from Intel, accessible as the "hs" mpm-algo.
10 years ago
Justin Viiret c37195c95f mpm: pass offset, depth args to add functions
MpmAddPatternCI and MpmAddPatternCS had arguments for offset and depth,
but these were not being passed in by the caller.
10 years ago
Justin Viiret c8e01a3d62 util-hash-lookup3: Add hashlittle_safe() variant
By default, hashlittle() will read off the end of the key, up to the
next four-byte boundary, although the data beyond the end of the key
doesn't affect the hash. This read causes uninitialized read warnings
from Valgrind and Address Sanitizer.

Here we add hashlittle_safe(), which avoids reading off the end of the
buffer (using the code inside the VALGRIND-guarded block in the original
hashlittle() implementation).
10 years ago
Victor Julien 30410e6900 capture: warn -i user if faster options are available
If af-packet, netmap or pfring are available, users should use those
for best performance.
10 years ago
Victor Julien cae3ce9e1c netmap: implement capture inject packet flag 10 years ago
Victor Julien 11099cfa42 detect reload: generic packet injection for capture
Capture methods that are non blocking will still not generate packets
that go through the system if there is no traffic. Some maintenance
tasks, like rule reloads rely on packets to complete.

This patch introduces a new thread flag, THV_CAPTURE_INJECT_PKT, that
instructs the capture thread to create a fake packet.

The capture implementations can call the TmThreadsCaptureInjectPacket
utility function either with the packet they already got from the pool
or without a packet. In this case the util func will get it's own
packet.

Implementations for pcap, AF_PACKET and PF_RING.
10 years ago
Victor Julien eafd212661 detect reload: call 'breakloop' on capture method
Split wait loop into three steps:
- first insert pseudo packets
- 2nd nudge all capture threads to break out of their loop
- third, wait for the detection thread contexts to be used

Interupt capture more than once if needed

Move packet injection into util func
10 years ago
Victor Julien dd98bc353e signals: cleanup signal handling
Simplify handling of USR2 signal. The SCLogInfo usage could lead to
dead locks as the SCLog API can do many complicated things including
memory allocations, syslog calls, libjansson message construction.

If an existing malloc call was interupted, it could lead to the
following dead lock:

 0  __lll_lock_wait_private () at ../nptl/sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:97
 1  0x0000003140c7d2df in _L_lock_10176 () from /lib64/libc.so.6
 2  0x0000003140c7ab83 in __libc_malloc (bytes=211543457408) at malloc.c:3655
 3  0x0000003140c80ec2 in __strdup (s=0x259ca40 "[%i] %t - (%f:%l) <%d> (%n) -- ") at strdup.c:43
 4  0x000000000059dd4a in SCLogMessageGetBuffer (tval=0x7fff52b47360, color=1, type=SC_LOG_OP_TYPE_REGULAR, buffer=0x7fff52b47370 "", buffer_size=2048,
    log_format=0x259ca40 "[%i] %t - (%f:%l) <%d> (%n) -- ", log_level=SC_LOG_INFO, file=0x63dd00 "suricata.c", line=287, function=0x640f50 "SignalHandlerSigusr2StartingUp", error_code=SC_OK,
    message=0x7fff52b47bb0 "Live rule reload only possible after engine completely started.") at util-debug.c:307
 5  0x000000000059e940 in SCLogMessage (log_level=SC_LOG_INFO, file=0x63dd00 "suricata.c", line=287, function=0x640f50 "SignalHandlerSigusr2StartingUp", error_code=SC_OK,
    message=0x7fff52b47bb0 "Live rule reload only possible after engine completely started.") at util-debug.c:549
 6  0x000000000057e374 in SignalHandlerSigusr2StartingUp (sig=12) at suricata.c:287
 7  <signal handler called>
 8  _int_malloc (av=0x3140f8fe80, bytes=<value optimized out>) at malloc.c:4751
 9  0x0000003140c7ab1c in __libc_malloc (bytes=296) at malloc.c:3657
 10 0x0000000000504d55 in FlowAlloc () at flow-util.c:60
 11 0x00000000004fd909 in FlowInitConfig (quiet=0 '\000') at flow.c:454
 12 0x0000000000584c8e in main (argc=6, argv=0x7fff52b4a3b8) at suricata.c:2300

This patch simply sets a variable and lets the main loop act on that.
10 years ago
Victor Julien f78e990915 signals: handle INT/TERM signals in the main loop 10 years ago
Victor Julien dc7d0c736b pfring: use likely for fast path 10 years ago
Victor Julien 9c5ee76455 tcp: fix unlikely NULL-ptr dereference
If a TCP packet could not get a flow (flow engine out of flows/memory)
and there were *only* TCP inspecting rules with the direction
explicitly set to 'to_server', a NULL pointer deref could happen.

PacketPatternSearchWithStreamCtx would fall through to the 'to_client'
case which was not initialized.
10 years ago
Victor Julien f005310ddf detect: add corner case mpm test 10 years ago
Victor Julien a866d5d915 tx logging: fix potential missed logging issue
Wrong scope of proto_logged variable could potentially lead to
incrementing logged tx id w/o actually being logged.

Reported-By: Jason Ish
10 years ago
Victor Julien 400fa5b9e5 stats-log: fix layout issue due to decoder stats 10 years ago
Victor Julien 1e0b5eb529 autofp: print packet scheduler info only on autofp
To avoid confusion about what runmode is active, only print autofp
related scheduler information if autofp is the actual runmode.
10 years ago
cdwakelin 2e9279dd42 autofp: add "ippair" scheduler
Add "ippair" autofp scheduler to split traffic based on source and
destination IP only (not ports).

- This is useful when using the "xbits" feature to track events
  that occur between the same hosts but not necessarily the same
  flow (such as exploit kit landings/expoits/payloads)
- The disadvantage is that traffic may be balanced very unevenly
  between threads if some host pairs are much more frequently seen
  than others, so it may be only practicable for sandbox or pcap
  analysis
- not tested for IPv6

See https://redmine.openinfosecfoundation.org/issues/1661
10 years ago
Jason Ish 8edbc20a07 flow: record the flow hash for use as the output flow id
Provides a consistent hash for a flow, as well as a better
distribution than using a memory address.
10 years ago
Eric Leblond 1b1cde6837 output-json-email: fix memleak
This patch fixes some error handling in code generating JSON output for
email event.

This fixes:

Indirect leak of 128 byte(s) in 1 object(s) allocated from:
    #0 0x50c142 in malloc (/home/eric/git/oisf/src/.libs/lt-suricata+0x50c142)
    #1 0x7ff92394771c  (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x371c)
    #2 0x1bd3309 in JsonEmailLogJson /home/eric/git/oisf/src/output-json-email-common.c:376:19
    #3 0x1bfe774 in JsonSmtpLogger /home/eric/git/oisf/src/output-json-smtp.c:103:9
    #4 0x1c378ff in OutputTxLog /home/eric/git/oisf/src/output-tx.c:165:17
    #5 0x1f94ef3 in TmThreadsSlotVarRun /home/eric/git/oisf/src/tm-threads.c:134:17
    #6 0x1d33478 in TmThreadsSlotProcessPkt /home/eric/git/oisf/src/./tm-threads.h:150:9
    #7 0x1d32dd4 in PcapFileCallbackLoop /home/eric/git/oisf/src/source-pcap-file.c:184:9
    #8 0x7ff924199013  (/usr/lib/x86_64-linux-gnu/libpcap.so.0.8+0x1f013)

Indirect leak of 96 byte(s) in 3 object(s) allocated from:
    #0 0x50c142 in malloc (/home/eric/git/oisf/src/.libs/lt-suricata+0x50c142)
    #1 0x7ff92394bc7b  (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x7c7b)

Indirect leak of 82 byte(s) in 3 object(s) allocated from:
    #0 0x50c142 in malloc (/home/eric/git/oisf/src/.libs/lt-suricata+0x50c142)
    #1 0x7ff923949924  (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x5924)

Indirect leak of 72 byte(s) in 1 object(s) allocated from:
    #0 0x50c142 in malloc (/home/eric/git/oisf/src/.libs/lt-suricata+0x50c142)
    #1 0x7ff92394bcda in json_object (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x7cda)
    #2 0x1bd3309 in JsonEmailLogJson /home/eric/git/oisf/src/output-json-email-common.c:376:19
    #3 0x1bfe774 in JsonSmtpLogger /home/eric/git/oisf/src/output-json-smtp.c:103:9
    #4 0x1c378ff in OutputTxLog /home/eric/git/oisf/src/output-tx.c:165:17
    #5 0x1f94ef3 in TmThreadsSlotVarRun /home/eric/git/oisf/src/tm-threads.c:134:17
    #6 0x1d33478 in TmThreadsSlotProcessPkt /home/eric/git/oisf/src/./tm-threads.h:150:9
    #7 0x1d32dd4 in PcapFileCallbackLoop /home/eric/git/oisf/src/source-pcap-file.c:184:9
    #8 0x7ff924199013  (/usr/lib/x86_64-linux-gnu/libpcap.so.0.8+0x1f013)

Indirect leak of 64 byte(s) in 1 object(s) allocated from:
    #0 0x50c142 in malloc (/home/eric/git/oisf/src/.libs/lt-suricata+0x50c142)
    #1 0x7ff92394bf5a in json_array (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x7f5a)
    #2 0x1bd04b5 in JsonEmailLogJsonData /home/eric/git/oisf/src/output-json-email-common.c:296:27
    #3 0x1bd3309 in JsonEmailLogJson /home/eric/git/oisf/src/output-json-email-common.c:376:19
    #4 0x1bfe774 in JsonSmtpLogger /home/eric/git/oisf/src/output-json-smtp.c:103:9
    #5 0x1c378ff in OutputTxLog /home/eric/git/oisf/src/output-tx.c:165:17
    #6 0x1f94ef3 in TmThreadsSlotVarRun /home/eric/git/oisf/src/tm-threads.c:134:17
    #7 0x1d33478 in TmThreadsSlotProcessPkt /home/eric/git/oisf/src/./tm-threads.h:150:9
    #8 0x1d32dd4 in PcapFileCallbackLoop /home/eric/git/oisf/src/source-pcap-file.c:184:9
    #9 0x7ff924199013  (/usr/lib/x86_64-linux-gnu/libpcap.so.0.8+0x1f013)

Indirect leak of 48 byte(s) in 1 object(s) allocated from:
    #0 0x50c142 in malloc (/home/eric/git/oisf/src/.libs/lt-suricata+0x50c142)
    #1 0x7ff92394bf2a in json_array (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x7f2a)
    #2 0x1bd04b5 in JsonEmailLogJsonData /home/eric/git/oisf/src/output-json-email-common.c:296:27
    #3 0x1bd3309 in JsonEmailLogJson /home/eric/git/oisf/src/output-json-email-common.c:376:19
    #4 0x1bfe774 in JsonSmtpLogger /home/eric/git/oisf/src/output-json-smtp.c:103:9
    #5 0x1c378ff in OutputTxLog /home/eric/git/oisf/src/output-tx.c:165:17
    #6 0x1f94ef3 in TmThreadsSlotVarRun /home/eric/git/oisf/src/tm-threads.c:134:17
    #7 0x1d33478 in TmThreadsSlotProcessPkt /home/eric/git/oisf/src/./tm-threads.h:150:9
    #8 0x1d32dd4 in PcapFileCallbackLoop /home/eric/git/oisf/src/source-pcap-file.c:184:9
    #9 0x7ff924199013  (/usr/lib/x86_64-linux-gnu/libpcap.so.0.8+0x1f013)
10 years ago
Eric Leblond a05cdbdf28 output-json-email: fix memleak
This possibly fix:

ndirect leak of 64 byte(s) in 1 object(s) allocated from:
    #0 0x4c264b in malloc (/home/victor/qa/buildbot/donkey/z600fuzz/Private/src/.libs/lt-suricata+0x4c264b)
    #1 0x7fb09c1e8aaa in json_array (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x6aaa)
    #2 0xd67553 in JsonEmailLogJsonData /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/output-json-email-common.c:290:27
    #3 0xd6a272 in JsonEmailLogJson /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/output-json-email-common.c:370:19
    #4 0xd956b9 in JsonSmtpLogger /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/output-json-smtp.c:103:9
    #5 0xdcedac in OutputTxLog /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/output-tx.c:165:17
    #6 0xff6669 in TmThreadsSlotVarRun /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/tm-threads.c:132:17
    #7 0xffecc1 in TmThreadsSlotVar /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/tm-threads.c:474:17
    #8 0x7fb09bfcc181 in start_thread /build/eglibc-3GlaMS/eglibc-2.19/nptl/pthread_create.c:312
10 years ago
Eric Leblond 9dec6d933f output-json-email: fix memleak in error path
In JsonEmailLogJsonData function, an invalid state was leading to
early exit without a proper freeing of resources.

This should fix:

Indirect leak of 72 byte(s) in 1 object(s) allocated from:
    #0 0x4c264b in malloc (/home/victor/qa/buildbot/donkey/z600fuzz/Private/src/.libs/lt-suricata+0x4c264b)
    #1 0x7fb09c1e886a in json_object (/usr/lib/x86_64-linux-gnu/libjansson.so.4+0x686a)
    #2 0xd6a272 in JsonEmailLogJson /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/output-json-email-common.c:370:19
    #3 0xd956b9 in JsonSmtpLogger /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/output-json-smtp.c:103:9
    #4 0xdcedac in OutputTxLog /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/output-tx.c:165:17
    #5 0xff6669 in TmThreadsSlotVarRun /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/tm-threads.c:132:17
    #6 0xffecc1 in TmThreadsSlotVar /home/victor/qa/buildbot/donkey/z600fuzz/Private/src/tm-threads.c:474:17
    #7 0x7fb09bfcc181 in start_thread /build/eglibc-3GlaMS/eglibc-2.19/nptl/pthread_create.c:312
10 years ago
Eric Leblond 92ad63abb7 output-json-email: fix error code
Returning early if first function call fail could avoid some issue.
10 years ago
JonZeolla b5972eeea2 Fix typos in an error message
Fix two minor typos in a SC_ERR_INVALID_ARGUMENT error message.
10 years ago
gureedo e4443fac53 netmap: fix issue 1717
Use packet pool only without packet allocation.
Wait for N packets available in packet pool before netmap ring fetching.
10 years ago
gureedo 02d4e729c4 netmap: fix log typo 10 years ago
gureedo f891aadefc netmap: remove workers zero copy mode restriction between interfaces
Rationale: https://github.com/luigirizzo/netmap/issues/126
10 years ago
Mats Klepsland eb39487f48 app-layer-ssl: fix out of bounds memory read
Added several checks to avoid out of bounds memory read caused
by malformed traffic.
10 years ago
Victor Julien ef4c717052 ip parsing: fix cppcheck negative shift warning
[src/util-ip.c:104]: (error) Shifting a negative value is undefined behaviour
[src/util-radix-tree.c:1160]: (error) Shifting a negative value is undefined behaviour
[src/util-radix-tree.c:1357]: (error) Shifting a negative value is undefined behaviour
[src/util-radix-tree.c:1380]: (error) Shifting a negative value is undefined behaviour
[src/util-radix-tree.c:1438]: (error) Shifting a negative value is undefined behaviour
10 years ago
Victor Julien a70ff19911 stats: fix unix socket crash
Reset counters_global_id at ctx destruction. In the unix socket
runmode the lack of this reset would cause the id's to increase with
each pcap, leading to an ever larger stats array.
10 years ago
Jason Ish 3c3fe4b47d detect: denote the max detection list; fix issue 1674.
Denotes the max detection list so that rule validation can
allow post-detection lists to come after base64_data, but
disallow detection lists to come after it.
10 years ago
Victor Julien 9afaf14ba4 smtp: use detection file tracking
As SMTP file_data detection uses the file API, the file's inspect
tracker should be considered when pruning files.

This patch sets the FILE_USE_DETECT flag on files tracked by smtp.

It also adds logic to move inspected tracker ahead if detection
doesn't do it, like when no rules are matching or detection engine
is disabled.
10 years ago
Victor Julien 77358a4113 file: optionally use detect tracking in pruning
When the file API is used to do content inspection (currently only
smtp does this), the detection should be considered while pruning
the file chunks.

This patch introduces a new flag for the file API: FILE_USE_DETECT

When it is used, 'FilePrune' will not remove chunks that are (partly)
beyond the File::content_inspected tracker.

When using this flag, it's important to realize that when the detect
engine is disabled or rules are not matching, content_inspected
might not get updated.
10 years ago
Victor Julien 5aee386fa9 smtp: add file_data debug code 10 years ago
Victor Julien c19412243a file logging: fix bad end of file check
File storage could end file storing when the logger was invoked
while no new data chunks were available.
10 years ago
Victor Julien 4526aed2b1 smtp: fix config parsing and config defaults 10 years ago
Victor Julien 32bf68aef8 smtp: consider file state in file_data inspection limits 10 years ago
Victor Julien 4783d5107f pfring: strip prio from vlan id 10 years ago
Victor Julien 01a8cc4ec9 afpacket: strip prio from vlan id 10 years ago
Victor Julien 8394b38941 cppcheck: work around snprintf warning
Cppcheck 1.72 gives a warning on the following code pattern:

    char blah[32] = "";
    snprintf(blah, sizeof(blah), "something");

The warning is:

    (error) Buffer is accessed out of bounds.

While this appears to be a FP, in most cases the initialization to ""
was unnecessary as the snprintf statement immediately follows the
variable declaration.
10 years ago
Mats Klepsland 7602f650b1 app-layer-ssl: fix memleak
Avoid that the SNI extension code is executed twice sometimes, causing
memory leaks.
10 years ago
Victor Julien f17ef5e46b daemon: suppress coverity resource leak warning (CID 400725) 10 years ago
Victor Julien ed93e9394d coverity: suppress CID 1038112 10 years ago
Victor Julien 444c4b546e htp: optimize multipart parsing
Store boundary in a single stack buffer instead of 2 heap allocated
buffers.
10 years ago
Victor Julien 665cafbe3b htp: fix boundry error handling (CID 1153934) 10 years ago
Victor Julien bfc4be230c htp: fix dead code warning (CID 1153933) 10 years ago
Victor Julien b4912f3bf9 unified2: fix unused value warning (CID 1247404) 10 years ago
Victor Julien a46c4da338 lua: fix unlikely null-deref during setup (CID 1351209) 10 years ago
Victor Julien c858bfea4a base64_decode: fix potential keyword parsing issue (CID 1340064) 10 years ago
Victor Julien 2a7f068438 ioctl: fix NULL check after dereference (CID 1204326) 10 years ago
Victor Julien dff9f65ce7 lua: fix minor coverity issues
Remove checks that can never be false. CID 1232076, 1312012
10 years ago
Victor Julien 339f066533 afpacket: suppress harmless Coverity warning (1192960) 10 years ago
Victor Julien e91b9bf22b Fix compilation on systems with Musl 10 years ago
Victor Julien c91546022d smtp: clean up thread local memory 10 years ago
Victor Julien 12d7c86efc stream-tcp: improve function doc 10 years ago
Victor Julien 81878c1998 Add global MAX macro. 10 years ago
Maurizio Abba 44a7c12ad0 decode-events: counters for decode events errors
We want to add counters in order to track the number of times we hit a
decode event. A decode event is related to an error in the protocol
decoding over a certain packet.

This patch fist modifies the decode-event list, reordering it in order
to separate single packet events from stream-related events and adding
the prefix "decoder" to decode events.
The counters are created during the decode setup and the relative event
counter is increased every time a packet with the flag PKT_IS_INVALID is
finalized in the decode phase
10 years ago
Eric Leblond b7bf299e3b af-packet: don't check GRO LRO on non ethernet
This way we avoid an error message when sniffing on a non Ethernet
device.
10 years ago
Eric Leblond 11eb1d7c1d af-packet: handle raw link
If no link layer header is reported then it is a raw header.
10 years ago
Eric Leblond 994bc15c2a af-packet: disable most code when not built in
When af-packet is not build we can avoid to build a large amount
of code.
10 years ago
Victor Julien e4059fb541 stream: fix stream.inline default
If stream.inline setting was missing it would default to IDS.

This patch changes the default to 'auto', meaning that in IPS mode
the stream engine also uses IPS mode and in IDS mode it's still in
IDS mode.

Bug #1570
10 years ago
Victor Julien bda9869af7 dns: turn debug BUG_ON's into events 10 years ago
Victor Julien c0b16fa2bb detect: allow for more than 64k mpm rules 10 years ago