Commit Graph

5514 Commits (def2b58725e6876abecceccecb096ba005eb34bc)

Author SHA1 Message Date
Victor Julien bc2c7f462e stats api: call thread deinit API functions
Thread deinit funcs weren't called. This meant the lua scripts 'deinit'
functions weren't called either.
11 years ago
gureedo 10104066e1 netmap support 11 years ago
Victor Julien cbe934267e file: register filedata log before file log
This way the file log can log the 'stored' info that the filedata
log sets.
11 years ago
Victor Julien c58b2b4b18 file: improve file pruning
Check if file has been logged/stored before considering it 'done'.
11 years ago
Victor Julien e58fd3cc6e runmodes: add funcs to check if file loggers enabled
Add functions to check if file/filedata loggers are enabled.
11 years ago
Victor Julien fbe6dac1ae file: optimize file pruning
FilePrune would clear the files, but not free them and remove them
from the list. This lead to ever growing lists in some cases.
Especially in HTTP sessions with many transactions, this could slow
us down.
11 years ago
Victor Julien 5251ea9ff5 flow: lockless flow manager checks
Until this point, the flow manager would check for timed out flows
by walking the flow hash, locking first the hash row and then each
individual flow to get it's state and timestamp. To not be too
intrusive trylocks were used so that a busy flow wouldn't cause the
flow manager to wait for a long time while holding the hash row lock.

Building on the changes in handling of the flow state and lastts
fields, this patch changes the flow managers behavior.

It can now get a flows state atomically and the lastts can be safely
read while holding just the flow hash row lock. This allows the flow
manager to do the basic time out check much more cheaply:

1. it doesn't have to wait for getting a lock
2. it doesn't interupt the packet path

As a consequence the trylock is now also gone. A flow that returns
'true' on timeout is pretty much certainly not going to be busy so
we can safely lock it unconditionally. This also means the flow
manager now walks the entire row unconditionally and is guaranteed
to inspect each flow in the row.

To make sure the functions called before the flow lock don't
accidentally change the flow (which would require a lock) the args
to these flows are changed to const pointers.
11 years ago
Victor Julien 5587372ce1 flow: modify lastts update logic
In the lastts timeval struct field in the flow the timestamp of the
last packet to update is recorded. This allows for tracking the timeout
of the flow. So far, this value was updated under the flow lock and also
read under the flow lock.

This patch moves the updating of this field to the FlowGetFlowFromHash
function, where it updated at the point where both the Flow and the
Flow Hash Row lock are held. This guarantees that the field is only
updated when both locks are held.

This makes reading the field safe when either lock is held, which is the
purpose of this patch.

The flow manager, while holding the flow hash row lock, can now safely
read the lastts value. This allows it to do the flow timeout check
without actually locking the flow.
11 years ago
Victor Julien a0732d3db2 flow: change flow state logic
A flow has 3 states: NEW, ESTABLISHED and CLOSED.

For all protocols except TCP, a flow is in state NEW as long as just one
side of the conversation has been seen. When both sides have been
observed the state is moved to ESTABLISHED.

TCP has a different logic, controlled by the stream engine. Here the TCP
state is leading.

Until now, when parts of the engine needed to know the flow state, it
would invoke a per protocol callback 'GetProtoState'. For TCP this would
return the state based on the TcpSession.

This patch changes this logic. It introduces an atomic variable in the
flow 'flow_state'. It defaults to NEW and is set to ESTABLISHED for non-
TCP protocols when we've seen both sides of the conversation.

For TCP, the state is updated from the TCP engine directly.

The goal is to allow for access to the state without holding the Flow's
main mutex lock. This will later allow the Flow Manager(s) to evaluate
the Flow w/o interupting it.
11 years ago
Victor Julien 9327b08ab1 tcp: add stream.reassembly.zero-copy-size option
The option sets in bytes the value at which segment data is passed to
the app layer API directly. Data sizes equal to and higher than the
value set are passed on directly.

Default is 128.
11 years ago
Victor Julien 37b56dca55 tcp: add debug stats about reassembly fast paths
Only shown if --enable-debug is passed to configure.
11 years ago
Victor Julien 2bba5eb704 tcp: zero copy fast path in app-layer reassembly
Create 2 'fast paths' for app layer reassembly. Both are about reducing
copying. In the cases described below, we pass the segment's data
directly to the app layer API, instead of first copying it into a buffer
than we then pass. This safes a copy.

The first is for the case when we have just one single segment that was
just ack'd. As we know that we won't use any other segment this round,
we can just use the segment data.

The second case is more aggressive. When the segment meets a certain
size limit (currently hardcoded at 128 bytes), we pass it to the
app-layer API directly. Thus invoking the app-layer somewhat more often
to safe some copies.
11 years ago
Victor Julien 8c1bc7cfb6 stream: move raw stream gap handling into util func 11 years ago
Victor Julien 6ca9c8eb32 stream: move raw reassembly into util func 11 years ago
Victor Julien ff2fecf590 stream: remove StreamTcpReassembleInlineAppLayer
Function is now unused.
11 years ago
Victor Julien 97908bcd2d stream: unify inline and non-inline applayer assembly
Unifiy inline and non-inline app layer stream reassembly to aid
maintainability of the code.
11 years ago
Victor Julien e1d134b027 stream: remove STREAM_SET_FLAGS
Use the unified StreamGetAppLayerFlags instead.
11 years ago
Victor Julien 29d2483efb stream: update inline tests
Make sure inline tests set the stream_inline flag.
11 years ago
Victor Julien e4cb8715de stream: replace STREAM_SET_INLINE_FLAGS macro
Replace it by a generic function StreamGetAppLayerFlags, that can
be used both by inline and non-inline.
11 years ago
Victor Julien ed791a562e stream: track data sent to app-layer 11 years ago
Victor Julien e494336453 stream: move reassembly loop into util funcs
Move IDS per segment reassembly and gap handling into utility functions.
11 years ago
Victor Julien 5b6f8bda1d detect: fix small memory leaks
Fix small memory leaks in option parsing. Move away from
pcre_get_substring in favor of pcre_copy_substring.

Related to #1046.
11 years ago
Victor Julien 5a8094136c Clean up Conf API memory on shutdown. 11 years ago
Victor Julien 04e49cea89 Fix live reload detect counter setup
When profiling was compiled in the detect counters were not setup
properly after a reload.
11 years ago
Victor Julien 844065bf58 conf api: use const pointers where possible
Use const pointers where possible in the Conf API.
11 years ago
Victor Julien ddce14360d Cosmetic fixes to main() 11 years ago
Victor Julien a3de4ecd97 Suppress debug statements 11 years ago
Victor Julien a8c16405fb detect: properly size det_ctx::non_mpm_id_array
Track which sgh has the higest non-mpm sig count and use that value
to size the det_ctx::non_mpm_id_array array.
11 years ago
Victor Julien 62751c8017 Fix live reload detect thread ctx setup
Code failed to setup non_mpm_id_array in case of a live reload.
11 years ago
Victor Julien 4e98a3e530 AC: fix memory leak 11 years ago
Victor Julien f88405c650 geoip: adapt to 'const' pointer passing 11 years ago
Victor Julien f1f5428faa detect: expand mask checking
Change mask to u16, and add checks for various protocol states
that need to be present for a rule to be considered.
11 years ago
Victor Julien ca59eabca3 detect: introduce DetectPrefilterBuildNonMpmList
Move building of non-mpm list into a separate function, that is inlined
for performance reasons.
11 years ago
Victor Julien cc4f7a4b96 detect: add profiling for non-mpm list build & filter 11 years ago
Victor Julien 4c10635dc1 detect: optimize non-mpm mask checking
Store id and mask in a single array of type SignatureNonMpmStore so
that both are loaded into the same cache line.
11 years ago
Victor Julien b5a3127151 detect: add mask check prefilter for non mpm list
Add mask array for non_mpm sigs, so that we can exclude many sigs before
we merge sort.

Shows 50% less non mpm sigs inspected on average.
11 years ago
Ken Steele 904441327c Conditionalize SigMatch performance counters.
Only include the counters when PROFILING.
11 years ago
Victor Julien 30b7fdcb49 Detect perf counters 11 years ago
Victor Julien ef6875d583 detect: Disable unused SignatureHeader code 11 years ago
Ken Steele 65af1f1c5e Remove sgh->mask_array
Not needed by new MPM opt.
11 years ago
Ken Steele 4bd280f196 Indentation clean up 11 years ago
Ken Steele 403b5a4645 Further optimize merging mpm and non-mpm rule ID lists.
When reaching the end of either list, merging is no longer required,
simply walk down the other list.

If the non-MPM list can't have duplicates, it would be worth removing
the duplicate check for the non-MPM list when it is the only non-empty list
remaining.
11 years ago
Ken Steele 86f4c6c47b Custom Quick Sort for Signature IDs
Use an in place Quick Sort instead of qsort(), which does merge sort and
calls memcpy().

Improves performance on my tests.
11 years ago
Ken Steele 736ac6a459 Use SigIntId as the type for storing signature IDs (Internal)
Previously using uint32_t, but SigIntId is currently uint16_t, so arrays
will take less memory.
11 years ago
Ken Steele d01d3324fc Increase max pattern ID allowed in MPM AC-tile to 28-bits 11 years ago
Victor Julien 6717c356e3 Clean up sm_array memory at SigFree 11 years ago
Ken Steele 1874784c10 Create optimized sig_arrays from sig_lists
Create a copy of the SigMatch data in the sig_lists linked-lists and store
it in an array for faster access and not next and previous pointers. The
array is then used when calling the Match() functions.

Gives a 7.7% speed up on one test.
11 years ago
Ken Steele 923a77e952 Change Match() function to take const SigMatchCtx*
The Match functions don't need a pointer to the SigMatch object, just the
context pointer contained inside, so pass the Context to the Match function
rather than the SigMatch object. This allows for further optimization.

Change SigMatch->ctx to have type SigMatchCtx* rather than void* for better
type checking. This requires adding type casts when using or assigning it.

The SigMatch contex should not be changed by the Match() funciton, so pass it
as a const SigMatchCtx*.
11 years ago
Ken Steele 900def5caf Create Specialized SCMemcmpNZ() when the length can't be zero. 11 years ago
Ken Steele 7835070385 Replace memcpy() in MpmAddSids with copy loop
For the short size of most sids lists, a straight copy loop is faster.
11 years ago
Ken Steele 83ed01a279 Fix compiler warnings in ac-tile.
Signed vs unsigned comparisons.
11 years ago
Ken Steele 1c76fa50b1 Prefetch the next signature pointer
Read one signature pointer ahead to prefetch the value.
Use a variable, sflags, for s->flags, since it is used many times and the
compiles doesn't know that the signatures structure doesn't change, so it
will reload s->flags.
11 years ago
Ken Steele fa51118dfe Move type first in SigMatch array since it is used more often. 11 years ago
Ken Steele 7a2095d851 In AC-Tile, convert from using pids for indexing to pattern index
Use an MPM specific pattern index, which is simply an index starting
at zero and incremented for each pattern added to the MPM, rather than
the externally provided Pattern ID (pid), since that can be much
larger than the number of patterns. The Pattern ID is shared across at
MPMs. For example, an MPM with one pattern with pid=8000 would result
in a max_pid of 8000, so the pid_pat_list would have 8000 entries.

The pid_pat_list[] is replaced by a array of pattern indexes. The PID is
moved to the SCACTilePatternList as a single value. The PatternList is
also indexed by the Pattern Index.

max_pat_id is no longer needed and mpm_ctx->pattern_cnt is used instead.

The local bitarray is then also indexed by pattern index instead of PID, making
it much smaller. The local bit array sets a bit for each pattern found
for this MPM. It is only kept during one MPM search (stack allocated).

One note, the local bit array is checked first and if the pattern has already
been found, it will stop checking, but count a match. This could result in
over counting matches of case-sensitve matches, since following case-insensitive
matches will also be counted. For example, finding "Foo" in "foo Foo foo" would
report finding "Foo" 2 times, mis-counting the third word as "Foo".
11 years ago
Ken Steele 77269fbb2c Fix missing use of MpmAddPid()
Found by Victor using ASAN. One place was not checking to resize the
pid array before adding a new PID.
11 years ago
Ken Steele eaac9c8d93 fix check in PmqMerge 11 years ago
Ken Steele 1c03eb56d0 Fix bug in MPM rule array handling
In PmqMerge() use MpmAddSids() instead of blindly copying the src
rule list onto the end of the dst rule list, since there might not
be enough room in the dst list. MpmAddSids() will resize the dst array
if needed.

Also add code to MpmAddSids() MpmAddPid() to better handle the case
that realloc fails to get more space. It first tries 2x the needed
space, but if that fails, it tries for just 1x. If that fails resize
returns 0. For MpmAddPid(), if resize fails, the new pid is lost. For
MpmAddSids(), as many SIDs as will fit are added, but some will be
lost.
11 years ago
Ken Steele ab8b1158b0 Dynamically resize pattern id array as needed
Rather than creating the array of size maxpatid, dynamically resize as needed.
This also handles the case where duplicate pid are added to the array.

Also fix error in bitarray allocation (local version) to always use bitarray_size.
11 years ago
Ken Steele 104a903478 Dynamically resize pmq->rule_id_array
Rather than statically allocate 64K entries in every rule_id_array,
increase the size only when needed. Created a new function MpmAddSids()
to check the size before adding the new sids. If the array is not large
enough, it calls MpmAddSidsResize() that calls realloc and does error
checking. If the realloc fails, it prints an error and drops the new sids
on the floor, which seems better than exiting Suricata.

The size is increased to (current_size + new_count) * 2. This handles the
case where new_count > current_size, which would not be handled by simply
using current_size * 2. It should also be faster than simply reallocing to
current_size + new_count, which would then require another realloc for each
new addition.
11 years ago
Ken Steele d31db4ed1c Fix clang warning
Clang doesn't seem to like defining a function within a function.
11 years ago
Ken Steele 23d2a1c422 Optimize DetectPrefilterMergeSort
Fixup rebase changes to remove debug code
11 years ago
Ken Steele f83022d818 Implement MPM opt for ac-bs and ac-gfbs
Copies sids changes from ac.
11 years ago
Ken Steele d03f124445 Implement MPM opt for b2g, b3g, wumanber
Found problems in b2gm and b2gc, so those are removed.
11 years ago
Ken Steele edaefe5af2 Fix AC-tile for new pattern ID array. 11 years ago
Victor Julien 29074af9a6 AC: use local bit array
Use a local pattern bit array to making sure we don't match more than
once, in addition to the pmq bitarray that is still used for results
validation higher up in the rule matching process.

Why: pmq->pattern_id_bitarray is currently sometimes used in a
'stateful' way, meaning that for a single packet we run multiple
MPM's on the same pmq w/o resetting it.

The new bitarray is used to determine wherther we need to append the
patterns associated 'sids' list to the pmq rule_id_array.

It has been observed that MPM1 matches for PAT1, and MPM2 matches for
PAT1 as well. However, in MPM1 PAT1 doesn't have the same sids list.
In this case MPM2 would not add it's sids to the list, leading to missed
detection.
11 years ago
Victor Julien 7876277119 detect: move checks from prefilter to rule detect
Move the prefilter checks to the main detect loop.
11 years ago
Victor Julien d1d895a884 Replace build match array with new filter logic
Use MPM and non-MPM lists to build our match array. Both lists are
sorted, and are merged and sorted into the match array.

This disables the old match array building code and thus also bypasses
the mask checking.
11 years ago
Victor Julien 1f57e25c03 detect: Add negated MPM to non-MPM array
Treat negated MPM sigs as if non-MPM, so we consider them always.

As MPM results and non-MPM rules lists are now merged and considered
for further inspection, rules that need to be considerd when a pattern
is absent are caught in the middle.

As a HACK/workaround this patch adds them to the non-MPM list. This
causes them to be inspected each time.
11 years ago
Victor Julien f5df526f9b Detect: create per sgh non-MPM rule array
Array of rule id's that are not using MPM prefiltering. These will be
merged with the MPM results array. Together these should lead to a
list of all the rules that can possibly match.
11 years ago
Victor Julien e49d0a5924 MPM: build sid list from MPM matches
Pmq add rule list: Array of uint32_t's to store (internal) sids from the MPM.

AC: store sids in the pattern list, append to Pmq::rule_id_array on match.

Detect: sort rule_id_array after it was set up by the MPM. Rule id's
(Signature::num) are ordered, and the rule's with the lowest id are to
be inspected first. As the MPM doesn't fill the array in order, but instead
'randomly' we need this sort step to assure proper inspection order.
11 years ago
Ken Steele b96645ded2 Create a wrapper around DetectFlowvarProcessList() to check for empty list
Creates an inline wrapper to check for flowvarlist == NULL before calling
DetectFlowvarProcessList() to remove the overhead of checking since the
list is usually empty.
11 years ago
Ken Steele 5008d0a58b Remove the b2gm and b2gc MPMs
These MPMs have code that looks like it won't work and updating them to
for the new MPM optimization wasn't working.
11 years ago
Victor Julien 227a7de351 Global define of MIN
Some OS' provide it automatically, so make sure we define it
conditionally in one place.
11 years ago
Victor Julien bcfd61416f Fix a fix: defrag OOM condition
** CID 1257764:  Dereference after null check  (FORWARD_NULL)
/src/defrag.c: 291 in Defrag4Reassemble()

** CID 1257763:  Dereference after null check  (FORWARD_NULL)
/src/defrag.c: 409 in Defrag6Reassemble()

In the error case 'rp' can be both NULL or non-NULL.
11 years ago
Victor Julien 43a1007788 detect: add test for memcmp issue 11 years ago
Victor Julien 0d910bed1d Add test for memcmp issue. 11 years ago
Victor Julien 17dfd59bc3 memcmp: compare the first byte as well
MemcmpLowercase would not compare the first byte of both input buffers
leading to two non-identical buffers to be considered the same.

Affects SSE_4_1 and SSE_4_2 implementations of SCMemcmpLowercase, as well
as the non-SIMD implementation. SSE_3 and Tile version are not affected.
11 years ago
Victor Julien c51ce4d2c0 Fix OS X 10.10 unittest failure
Work around OS X 10.10 Yosemite returning EDEADLK on a rwlock wrlocked
then tested by wrtrylock. All other OS' (and versions of OS X that I
tested) seem to return EBUSY instead.
11 years ago
Victor Julien baa55ba239 Fix Tilera compilation
Use proper initializer for a static mutex declaration.

Credits: Ken Steele
11 years ago
Victor Julien 8e946b92b7 Fix compilation on OS X Yosemite
Due to our unconditional declaration of the strlcat and strlcpy
functions, compilation failed on OS X Yosemite.

Bug #1192
11 years ago
Victor Julien 485f34134e unix socket: support profiling 11 years ago
Victor Julien f32d79dfe0 smtp: fix tx handling
Fix issue where SMTPStateGetTxCnt would return the actual active tx'.

The 'GetCnt' API call is not named correctly. It should be 'GetMaxId',
as this is actually the expected behavior.
11 years ago
Victor Julien 105b4340c2 thread local storage: add to build-info 11 years ago
Victor Julien 623c2e78fd packet pool: make pending pool use more robust
Don't leave pointers dangling.
11 years ago
Victor Julien 6e174128c8 packet pool: memory fixes for non-TLS
If the posix TLS implementation is used, the packet pool is memset to
0 before use.

Also use proper 'free' function.
11 years ago
Victor Julien 2745cd2ce9 packet pool: fix wrong free call 11 years ago
Eric Leblond ff8dae3b75 app-layer: fix 'detection-only' keyword
If we follow the description in the yaml file, we should disable
parsing if 'detection-only' keyword is used.
11 years ago
Eric Leblond 969abc2ccd output-json: fix duplicate logging
This patches is fixing a issue in the OutputJSONBuffer function. It
was writing to file the content of the buffer starting from the start
to the final offset. But as the writing is done for each JSON string
we are duplicating the previous events if we are reusing the same
buffer.

Duplication was for example triggered when we have multiple alerts
attached to a packet. In the case of two alerts, the first one was
logged twice more as the second one.
11 years ago
Victor Julien dc5e2a515c stream: improve inline mode GAP handling
Don't conclude a GAP is 'final' until the missing data is ack'd.

Further, cleanup and unify more with the non-inline code.
11 years ago
Victor Julien b69ca16553 stream: move utility functions
This way they can be used by the *Inline* functions as well.
11 years ago
Victor Julien a095694945 host: register unittests
Host unittests were not registered so they wouldn't run.
11 years ago
Victor Julien 60b50e1ca5 packet-pool: free pending packets 11 years ago
Victor Julien 8b2dd81628 stats: stats threads don't need packet pools 11 years ago
Victor Julien ffd2248459 flow manager: destroy packet pool on close 11 years ago
Victor Julien c4e1324690 flow-timeout: use packet pool
Use packet pool for pseudo packets on flow timeout. Wait for a packet
if necessary.

For shutdown, alloc a new pool as the 'main()' thread calls this.
11 years ago
Victor Julien cef609bb73 threading: lock TmThreadKillThreadsFamily 11 years ago
Victor Julien 3499d682c4 flow timeout: cleanups
Rename FlowForceReassemblyForFlowV2 to just FlowForceReassemblyForFlow
as there is no V1.
11 years ago
Victor Julien 6e69b51123 flow timeout: cleanup
Remove now unused old flow timeout code.
11 years ago
Victor Julien de4bda14e6 stream: handle flow timeout stream end packets
Handle flow timeout packets in the stream engine. Previously the flow
timeout code would call reassembly code directly.
11 years ago
Victor Julien 0ffaad66eb flow-time: disable remainder of the old timeout code
Disable registration code that was looking for threadvars
and slots as timeout handling is now done in a live engine.
11 years ago
Victor Julien 8e86f387a6 flow-time: use live threads at shutdown
Update pktacq loop to process flow timeouts in a running engine.

Add a new step to the shutdown phase of packet acquisition loop
threads (pktacqloop).

The shutdown code lets the pktacqloop break out of it's packet
acquisition loop. The thread then enters a flow timeout loop, where
it processes packets from it's tv->stream_pq queue until it's
empty _and_ the KILL flag is set.

Make sure receive threads are done before moving on to flow hash
cleanup (recycle all). Without this the flow recycler could start
it's unconditional hash clean up while detect threads are still
running on the flows.

Update unix socket to match live modes.
11 years ago
Victor Julien c6ec92d9b1 flow-timeout: use live threads
Use live threads. Disable old timeout code.
11 years ago
Victor Julien 48eccf7d91 Assign thread_id to flow on first packet stream engine 11 years ago
Victor Julien 8c51b23e94 Thread registration: id's start at 1
Start thread id's at 1, so that in flow's we can use 0 to indicate
a thread id hasn't been set in it yet.
11 years ago
Victor Julien 7f80516563 Introduce Flow timeout injection api
Add function TmThreadsInjectPacketById that is to be used to inject flow
timeout packets into the threads stream_pq queue.

TmThreadsInjectPacketById will also wake up listening threads if
applicable.

Packets are passed all packets together in an NULL terminated array
to reduce locking overhead.
11 years ago
Victor Julien 51a782fd8c Define FlowThreadId and add it to the flow
16 bits id should be enough for threads for a while.
11 years ago
Victor Julien a260cba32b Give easy access for thread stream packet queue
Access it from ThreadVars. This allows for easy injection of packets
into the stream engine.
11 years ago
Victor Julien 489ee20560 Thread Registration API for ID's
Create thread registration and unregistration API for assigning unique
thread id's.

Threadvars is static even if a thread restarts, so we can do the
registration before the threads start.

A thread is unregistered when the ThreadVars are freed.
11 years ago
Duarte Silva e586644c25 Fix and improvements
- Added/removed missing/superfluous util-memrchr.h include
- Improved the extraction of a IP from the XFF chain of IPs
11 years ago
Duarte Silva 68f43ffffb Implemented the diferent behaviour depending on the proxy deployment
- In forward deployment mode the first IP will be returned
- In reverse deployment mode the last IP will be retuned
11 years ago
Duarte Silva 496200dd08 Prepared everything for the proxy deployment configuration
- Added the suricata.yaml configurations and updated the comments
- Renamed the field in the configuration structure to something generic
- Added two new constants and the warning codes
11 years ago
Duarte Silva 4e04cd2d1b Adding XFF support to EVE alert output
- Created app-layer-htp-xff.c and app-layer-htp-xff.h
- Added entries in the Makefile.am
- Added the necessary configuration options to EVE alert section
- Updated Unified2 XFF configuration comments and removed unnecessary whitespace
- Created a generic function to parse the configuration
- Release the flow locks sooner and remove debug logging
- Added XFF support to EVE alert output
11 years ago
DIALLO David 0bdf494b54 fix Cygwin build fails: array subscript has type char 11 years ago
DIALLO David bfc871ce85 Update AppLayerProtoDetectPrintProbingParsers with Modbus protocol 11 years ago
DIALLO David 83d9834e77 fix CID 1257762: Logically dead code(DEADCODE) 11 years ago
Victor Julien 84e8217fd8 unix-socket: allow socked in custom locations
Allow the socket to be set in any location. This allows for easy
setting up of a socket as a non-root user.
11 years ago
Victor Julien b978730486 unix-socket: fix restart/shutdown cycle
When cleaning up after a pcap was processed, the stats api was cleaned
up before the stats threads were killed, leading to a BUG_ON triggering.
11 years ago
Ken Steele 3f3481e4d2 Fix indentation 11 years ago
Ken Steele 3f86c5a83f Fix memory leak in ac-tile
Incorrectly reallocing the goto table after it was freed by calling
SCACTileReallocState() when really only want to realloc the output table.
This was causing a large goto table to be allocated and never used or
freed.
11 years ago
Ken Steele b9e20ab4b8 Clean up memory leaks in ac-tile code
Free some memory at exit that was not getting freed.

Change pid_pat_list to store copy of case-strings in the same block
of memory as the array of pointers.
11 years ago
Ken Steele 1faa94c314 Make bad copy-mode be an error in runmode-tile. 11 years ago
Victor Julien c779065d35 Bug 1329: error out on invalid rule protocol
Due to a logic error in AppLayerProtoDetectGetProtoByName invalid
protocols would not be detected as such. Instead of ALPROTO_UNKNOWN
ALPROTO_MAX was returned.

Bug #1329
11 years ago
Eric Leblond 9f22c878e8 unix-manager: fix cppcheck errors
This patch fixes the following errors:
 [src/unix-manager.c:306]: (error) Memory pointed to by 'client' is freed twice.
 [src/unix-manager.c:313]: (error) Memory pointed to by 'client' is freed twice.
 [src/unix-manager.c:323]: (error) Memory pointed to by 'client' is freed twice.
 [src/unix-manager.c:334]: (error) Memory pointed to by 'client' is freed twice.

Unix manager was treating the packet after closing the socket if message was
too long.
11 years ago
Victor Julien 096b85ab68 stream: don't send EOF to AppLayer too soon
Sending EOF too soon results in the AppLayer cleaning up prematurely.
11 years ago
Victor Julien 0bb2b15491 ipv6: check for MLD messages with HL not 1
MLD messages should have a hop limit of 1 only. All others are invalid.

Written at MLD talk of Enno Rey, Antonios Atlasis & Jayson Salazar during
Deepsec 2014.
11 years ago
Ken Steele 68e6c4e94b Correct flow memory usage bookkeeping error
Fix bug 1321 where flow_memuse was incremented more on allocation than
free.
11 years ago
Victor Julien d951de2f19 Bug 977: -T / --init-errors-fatal to process all rules
Have -T / --init-errors-fatal process all rules so that it's easier
to debug problems in ruleset. Otherwise it can be a lengthy fix, test
error cycle if multiple rules have issues.

Convert empty rulefile error into a warning.

Bug #977
11 years ago
Victor Julien e951afb911 afpacket: only check offloading once per iface
Instead of once per thread per iface.
11 years ago
Victor Julien fa10811585 ioctl: make all string args const pointers 11 years ago
Victor Julien c3c144d504 http: don't crash when normalizing uri on low memory 11 years ago
Victor Julien f8f2ff49de defrag: don't crash when out of memory
Handle memory allocation errors in defrag better. Could lead to
crashes if malloc errors happened.
11 years ago
Eric Leblond 56373e5b34 af-packet: no more threads than RSS queues
If we manage to read the number of RSS queues from an interface,
this means that the optimal number of capture threads is equal
to the minimum of this number and of the number of cores on the
system.

This patch implements this logic thanks to the newly introduced
function GetIfaceRSSQueuesNum.
11 years ago
Eric Leblond 123c58af4b util-ioctl: add message in case of failure 11 years ago
Eric Leblond b4bb6e67ba util-ioctl: Add function to get number of RSS queues on iface
The number of RSS queues can be fetched via a standard ioctl which
is independant of hardware.
11 years ago
Victor Julien c174c9d779 af-packet: threads: auto, default to workers
Add a new default value for the 'threads:' setting in af-packet: "auto".
This will create as many capture threads as there are cores.

Default runmode of af-packet to workers.
11 years ago
Victor Julien 7b4987abc3 Runmode: handle value 'auto'
Auto now selects the default runmode for the capture method.
11 years ago
Victor Julien 234d18ab68 threading: remove '1slot' functions
No longer in use after the 'auto' runmode removal.

All runmodes now use either varslot or pktacqloop support.
11 years ago
Victor Julien 7025aabe75 Runmodes: remove 'auto' runmodes
Remove 'auto' runmodes from all capture methods. It wasn't reliable
enough, as it didn't enforce inspection order of packets.
11 years ago
Victor Julien 81c42f4916 log-stats: expand membuffer if necessary
Many threads could lead to a membuffer size requirement bigger than
64k. So use the expansion call to grow the buffer as needed.
11 years ago
Victor Julien 6277d2e0e4 MemBuffer: add expansion call
For some of the buffer users it's hard to predict how big the data
will be. In the stats.log case this depends on chosen runmode and
number of threads.

To deal with this case a 'MemBufferExpand' call is added. This realloc's
the buffer.
11 years ago
Victor Julien 75397ed750 stats: expose stats to Lua output
Register with type 'stats':

    function init (args)
        local needs = {}
        needs["type"] = "stats"
        return needs
    end

The stats are passed as an array of tables:

    { 1, { name=<name>, tmname=<tm_name>, value=<value>, pvalue=<pvalue>}}
    { 2, { name=<name>, tmname=<tm_name>, value=<value>, pvalue=<pvalue>}}
    etc

Name is the counter name (e.g. decoder.invalid), tm_name is the thread name
(e.g. AFPacketeth05), value is current value, and pvalue is the value of the
last time the script was invoked.
11 years ago
Victor Julien 5d95b08172 output streaming: cleanup at runmode destruction 11 years ago
Victor Julien 51a540c27e stats: disable stats if no loggers are enabled 11 years ago
Victor Julien 6252d24e0b stats: initialize after outputs
Initialize stats after outputs so that we can check if we need to
initialize the stats api at all.
11 years ago
Victor Julien a95c95f74c stats: introduce global config
As the stats api calls the loggers at a global interval, the global
interval should be configured globally.

 # global stats configuration
 stats:
   enabled: yes
   # The interval field (in seconds) controls at what interval
   # the loggers are invoked.
   interval: 8

If this config isn't found, the old config will be supported.
11 years ago
Victor Julien e98346b555 Introduce stats log API, convert existing output
Convert regular 'stats.log' output to this new API.

In addition to the current stats value, also give the last value. This
makes it easy to display the difference.
11 years ago
Victor Julien ee8da21e36 pcre: fix var capture for non relative matches
Var capture setup depended on the match being relative due to a logic
error.
11 years ago
Giuseppe Longo 1ad2a231fe pfring: fixes memleaks
This fixes some memory leaks
Bug #1184
11 years ago
Victor Julien 16941468ce lua: in streaming api, indicate open/close
The SCStreamingBuffer call now also returns two booleans:
    data, data_open, data_close = SCStreamingBuffer()

The first indicates this is the first data of this type for this
TCP session or HTTP transaction.

The second indicates this is the last data.

Ticket #1317.
11 years ago
Ken Steele 8dcd99209e Update copyright year in detect-flowbits files. 11 years ago
Ken Steele e6f83a586c DetectFlowintData - remove unused idx in TargetVar.
The idx inside TargetVar inside DetectFlowintData is never used, so remove
it.
11 years ago
Ken Steele c547d39152 Fix bug in DetectFlowintParse() - Assigning to both parts of a Union
sfd->target.value was always being set, even if the targettype was
not FLOWINT_TARGET_VAL. This would cause the tvar to be overwritten
with garbage data.
11 years ago
Ken Steele fa72082491 Don't write target.tvar.idx in DetectFlowintParse
Match functions should not be writing to the SigMatch context. So just use
a local variable instead.
11 years ago
Ken Steele 5cdb21ec34 Remove an unused define COUNTER_DETECT_ALERTS
The only place this exists in the code is when it is defined.
11 years ago
Ken Steele 18e2de320b Coding style cleanup in detect-modbus files. 11 years ago
Ken Steele ff41c1c452 Correct size increase in SigGroupHeadStore()
The code was increasing the size of the allocated memory by 16, but
only increasing the stored size by 10. Now uses one variable for both
places.
11 years ago
DIALLO David 55c5081240 Detect-engine: Add Modbus detection engine
Management of Modbus Tx

Based on DNS source code.

Signed-off-by: David DIALLO <diallo@et.esia.fr>
11 years ago
DIALLO David b3bf2f9939 Detect: Add Modbus keyword management
Add the modbus.function and subfunction) keywords for public function match in rules (Modbus layer).
Matching based on code function, and if necessary, sub-function code
or based on category (assigned, unassigned, public, user or reserved)
and negation is permitted.

Add the modbus.access keyword for read/write Modbus function match in rules (Modbus layer).
Matching based on access type (read or write),
and/or function type (discretes, coils, input or holding)
and, if necessary, read or write address access,
and, if necessary, value to write.
For address and value matching, "<", ">" and "<>" is permitted.

Based on TLS source code and file size source code (address and value matching).

Signed-off-by: David DIALLO <diallo@et.esia.fr>
11 years ago
DIALLO David 5a0409959f App-layer: Add Modbus protocol parser
Decode Modbus request and response messages, and extracts
MODBUS Application Protocol header and the code function.

In case of read/write function, extracts message contents
(read/write address, quantity, count, data to write).

Links request and response messages in a transaction according to
Transaction Identifier (transaction management based on DNS source code).

MODBUS Messaging on TCP/IP Implementation Guide V1.0b
(http://www.modbus.org/docs/Modbus_Messaging_Implementation_Guide_V1_0b.pdf)
MODBUS Application Protocol Specification V1.1b3
(http://www.modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf)

Based on DNS source code.

Signed-off-by: David DIALLO <diallo@et.esia.fr>
11 years ago
Christophe M 6c2ae469be Fix to output a JSON buffer to an Unix domain socket.
Create the JSON buffer and write to it like regular file.

Upper function SCConfLogOpenGeneric already handle it properly.

Closes issue #1246.
11 years ago
Victor Julien 27007cc7d5 Fix Coverity issue in SMTP output
** CID 1250327:  Uninitialized pointer read  (UNINIT)
/src/output-json-email-common.c: 117 in JsonEmailLogJson()
/src/output-json-email-common.c: 139 in JsonEmailLogJson()
11 years ago
Victor Julien 7c3b22da22 smtp: don't create a new tx for rset/quit
A tx is considered complete after the data command completed. However,
this would lead to RSET and QUIT commands setting up a new tx.

This patch simply adds a check that refuses to setup a new tx when these
commands are encountered after the data portion is complete.
11 years ago
Victor Julien f7c2c219cd filestore: fix crash if keyword setup fails
SigMatch would be added to list, then the alproto check failed, leading
to freeing of sm. But as it was still in the list, the list now contained
a dangling pointer.
11 years ago
Victor Julien 9d2a0c39e5 mime: fix output issues
When multiple email addresses were in the 'to' field, sometimes
they would be logged as "\r\n \"Name\" <email>".

The \r\n was added by GetFullValue in the mime decoder, for unknown
reasons. Disabling this seems to have no drawbacks.
11 years ago
Victor Julien ebd6737b65 mime: fix compiler warning 11 years ago
Victor Julien 20a175f315 mime: improve error checking 11 years ago
Victor Julien 5461294a52 smtp: fix SMTPParserTest14 on 32bit 11 years ago
Victor Julien 9d33131d37 smtp: improve ProcessDataChunk error checking 11 years ago
Victor Julien d209699a41 smtp: expand tx use
Instead of just using TX for mime decoding, it is now also used for
tracking decoder events.
11 years ago
Victor Julien d67289b60e output-filedata: close files even w/o data
If there is no data chunk but the file is closed/truncated anyway,
logging is still required.
11 years ago
Victor Julien 08b06bac3f smtp: register file truncate callback
Tag files as truncated from this callback so storing/logging displays
the correct info.
11 years ago
Victor Julien 2b9ef87527 smtp: convert logger to tx logger
Move from packet logger to tx logger.
11 years ago
Victor Julien d0357c6169 smtp: add file inspection engine
Fix file inspection engine.

TODO: test
11 years ago
Victor Julien 56b74c8b5b smtp: make TX aware
Store mime decoding context per transaction. For this the parser
creates a TX when the mime body decoding starts.
11 years ago
Victor Julien cb4440324e mime: redo PrintChars using PrintRawDataFp 11 years ago
Victor Julien f979e92f68 decode mime: refactor & cleanup
Partly to work around cppchecks:
[src/util-decode-mime.c:1085]: (error) Memory leak: url
11 years ago
Victor Julien 54df86658c mime: rename mime-decode.[ch] to util-decode-mime.[ch] 11 years ago
Victor Julien 6035470ffb mime: style updates 11 years ago
Victor Julien 595acf2dfc mime decode: reshuffle data structures to reduce structure sizes 11 years ago
Victor Julien 9a573c5704 output smtp: fix call 11 years ago
Victor Julien de44a5af94 decode mime: clean up includes 11 years ago
Victor Julien cd55b657c2 mime decode: improve MimeDecParseLineTest01 and MimeDecParseLineTest02 tests 11 years ago
Victor Julien dd4b506cc2 decode mime: fix scan-build issues 11 years ago
Victor Julien f91d52a0d2 mime decode: fix memory leak 11 years ago
Victor Julien bffceb7115 mime decode: remove unused url counter 11 years ago
Victor Julien d72f8c7de5 output smtp: clean up memory at shutdown 11 years ago
Victor Julien c712ab2299 Fix compiler warning 11 years ago
Victor Julien 106bbc78e1 mime: refactor buffer use
Turn all buffers into uint8_t (from char) and no longer use the
string functions like strncpy/strncasecmp on them.

Store url and field names as lowercase, and also search/compare
them as lowercase. This allows us to use SCMemcmp.
11 years ago
Tom DeCanio f55c94cb54 smtp-mime: preinitialize base64 decoder space
Preinit with zeros.
11 years ago
Tom DeCanio c279f07d2a mime-decode: clean up after MimeDecParseFullMsgTest01. 11 years ago
Tom DeCanio 4503ffeee9 mime-decode: fix minor memory leak if Mime parser initialization were to fail. 11 years ago
Tom DeCanio 1ab5f72fdd mime-decode: remove "comparison between signed and unsigned integer expressions"
warnings
11 years ago
Tom DeCanio e5c36952d6 app-layer-smtp: move old smtp-mime section in suricata.yaml into
app-layer-protocols.smtp.mine section and update code to accomodate.
11 years ago
Tom DeCanio 3e10ee4608 PR review comment. Use protocol to discern log type. 11 years ago
Tom DeCanio 746da75615 eve-log: catch and log URLs in basic text emails without mime encapsulation.
expand pointer walk protection.
11 years ago
Tom DeCanio 471967aafd mime-decode: don't scan attachment's data for URLs.
move event pointer lookup inside extract_urls and protect pointer walk.
11 years ago
Tom DeCanio 6467a5d563 app-layer-smtp: fix Test14.
Was running one byte past end of buffer.
Declare Unit Test 14's data as static.
11 years ago
Eric Leblond 260872ccd9 smtp layer: fix unittests
Synchronize test 14 with the new application layer API and improve
debug messages.
11 years ago
Tom DeCanio 31f8f5cf20 eve-log: SMTP JSON logger 11 years ago
Tom DeCanio 7850d896a8 smtp-mime: add server reply codes returned from outlook server 11 years ago
David Abarbanel c2dc686742 SMTP MIME Email Message decoder 11 years ago
Ken Steele a781fc5c2e Make suricata_ctl_flags be volatile
The global variable suricata_ctl_flags needs to volatile, otherwise the
compiler might not cause the variable to be read every time because it
doesn't know other threads might write the variable.

This was causing Suricata to not exit under some conditions.
11 years ago
Victor Julien 503cc3de69 stream/async: improve handling of syn/ack pickup
If we picked up the ssn with a syn/ack, we don't need to make more
assumptions about sack and wscale after that.
11 years ago
Victor Julien 1656148490 stream/async: fix session setup issues
For these 2 cases:

1. Missing SYN:
-> syn <= missing
<- syn/ack
-> ack
-> data

2. Missing SYN and 3whs ACK:
-> syn <= missing
<- syn/ack
-> ack <= missing
-> data

Fix session pickup. The next_win settings weren't correctly set, so that
packets were rejected.

Bug 1190.
11 years ago
Victor Julien b2e80a0f66 stream: improve tracking with pkt loss in async
If 3whs SYN/ACK and ACK are missing we can still pick up the session if
in async-oneside mode.

-> syn
<- syn/ack <= missing
-> ack     <= missing
-> data

Bug 1190.
11 years ago
Victor Julien 033409a042 iprep: cleanup ctx on shutdown
~~Dr.M~~ Error #1: LEAK 480 direct bytes 0x0aae7fc0-0x0aae81a0 + 0 indirect bytes
~~Dr.M~~ # 0 replace_malloc                    [/work/drmemory_package/common/alloc_replace.c:2373]
~~Dr.M~~ # 1 SRepInit                          [.../Suricata/src/reputation.c:594]
~~Dr.M~~ # 2 DetectEngineCtxInit               [.../src/detect-engine.c:844]
~~Dr.M~~ # 3 main                              [.../Suricata/src/suricata.c:2230]
11 years ago
Ken Steele b2b1239ddf Make AppLayerProfiling functions inline
The entire body of these functions are protected by ifdef PROFILING.
If the functions are inlined, then this check removes the need for the
function entirely.

Previously, the empty function was still called, even when not built
for profiling. The functions showed as being 0.25% of total CPU time
without being built for profiling.
11 years ago
Giuseppe Longo 2d43dae934 PF_RING: force cluster type if vlan is disabled
If vlan is disabled the cluster_flow mode will still take VLAN tags
into account due to using pf_ring's 6-tuple mode.
So this forces to use pf_ring's 5-tuple mode.

Bug #1292
11 years ago
Giuseppe Longo 395d5b7f61 iprep: add unit tests for cidr
Implements unit tests to test the new API
11 years ago
Giuseppe Longo 5499cb71b0 detect-iprep: extends cidr
Adds new API to check if an IP address is belong
to a netblock and gets the value.
11 years ago
Giuseppe Longo a1d8439b25 iprep: extends cidr support
Implements new API to expand the IP reputation
to netblocks with CIDR notation

A new object 'srepCIDRTree' is kept in the DetectionEngineCtx,
which contains two tree (one for ipv4 and one for ipv6)
where the reputation values are stored.
11 years ago
Eric Leblond 667b9a5220 lua: add export of dns.rrname
Add the capability for a lua script to ask for rrname in DNS query.
11 years ago
Eric Leblond 74ffa2b264 lua: move function to common utils
LuaStateNeedProto function can be used for any protocol so let's
move it out of the http file.
11 years ago
Victor Julien 4d66775a56 stream: improve bad window update detection
Ignore more valid ACKs in FIN shutdown phase.

Improve heuristic for window shrinking in case of packet loss.
11 years ago
Victor Julien a54f52278b stream: fix 'bad window update' false positive
ACK packets completing a valid FIN shutdown could be flagged as
'bad window update' if they would shrink the window.

This patch detects this case before doing the bad window update
check.
11 years ago
Tom DeCanio ce472d88be sanity check tcp SACK edges prior to recording. Attempt to avoid Cisco ASA
tcp randomization issue with it not properly writing sequence numbers in SACK.
11 years ago
Victor Julien 5834a1a619 stream: improve handling of 3whs packet loss
If the 3whs ACK and some data after this is lost, we would get stuck
in the 'SYN_RECV' state, where from there each packet might be
considered invalid.

This patch improves the handling of this case.
11 years ago
Victor Julien e7a909f4ae stream: fix ssh/ssl logging on tcp session reuse
TCP session reuse wouldn't unset FLOW_NO_APPLAYER_INSPECTION.
11 years ago
Victor Julien 59d12f334e ssh.softwareversion: allow more characters
The keyword would not allow matching on "OpenSSH_5.5p1 Debian-6+squeeze5"
as the + and space characters were not allowed.

This patch adds support for them.
11 years ago
Victor Julien a68e19d998 stream: add counter for failed pseudo setups
Stream pseudo packets are taken from the packet pool, which can be empty.
In this case a pseudo packet will not be created and processed.

This patch adds a counter "tcp.pseudo_failed" to track this.
11 years ago
Victor Julien e4c8084a75 stream: clean up pseudo packet counting
Increment the counter from StreamTcpPseudoPacketCreateStreamEndPacket.
11 years ago
Giuseppe Longo 8c09648ad0 pfring: removes old API and #ifdef chunks 11 years ago
Jason Ish 2d12209194 Use ENGINE_SET_INVALID_EVENT when the packet is too small for an
MPLS header, and when the payload type can not be determined.
11 years ago
Jason Ish 65f40cbeaa Don't default to ethernet, ethernet should be preceded by a pseudowire.
If the payload type can't be determined, raise an alert.
11 years ago
Jason Ish 348b0e0e9f Set decoder events for labels that shouldn't be seen on the wire.
Add unit tests to test for mpls decoder events.
11 years ago
Jason Ish 66a321ca2d Handle encapsulated ethernet without a PW by defaulting to ethernet
if a fall back.
11 years ago
Jason Ish 025342dc6c Handle explicitly IPv6 and IPv6 labels as well as encapsulated ethernet. 11 years ago
Jason Ish 3e3ab2dc9f Add MPLS counter.
Check length before decoding each label.
11 years ago
Jason Ish 7642489874 Basic MPLS decoder. 11 years ago
Anoop Saldanha b334b8a6e9 CUDA: Update the inspection engine to inform the cuda module that it
doesn't need the gpu results and to release the packet for the next run.

Previously the inspection engine wouldn't inform the cuda module, if it
didn't need the results.  As a consequence, when the packet is next taken
for re-use, and if the packet is still being processed by the cuda module,
the engine would wait till the cuda module frees the packet.

This commits updates this functionality to inform the cuda module to
release the packet for the afore-mentioned case.
11 years ago
Ken Steele 60c46170b0 Check replist is not NULL inline before doing any processing.
The replist is often NULL, so it is worth checking that case before making
the function call do perform work on the list.
11 years ago
Eric Leblond 9a36f7f633 detect-dce-opnum: add sanity check
Specifying the option dce_opnum without value was triggering a
segfault.
11 years ago
Victor Julien d44cb3f6fe pcap-log: add option to honor pass rules
Add option (disabled by default) to honor pass rules. This means that
when a pass rule matches in a flow, it's packets are no longer stored
by the pcap-log module.
11 years ago
Jason Ish a18e2ef402 Bug 1230: Check all SigMatch lists for a named byte_extract variable. 11 years ago
Jason Ish dc9d1ec867 Bug 1230: Simple test case demonstrating failure. 11 years ago
Ken Steele 38710697db Speed up SigMatchGetLastSMFromLists()
SigMatchGetLastSMFromLists() is finding the sm with the largest
index among all of the values returned from SigMatchGetLastSM() on
the set of (list and type) tuples passed as arguments.

The function was creating an array of the types, then creating an array
of the results of SigMatchGetLastSM(), sorting that list completely, then
only returning the first values from the list.

The new code, gets one set of arguments from the variable arguments, calls
SigMatchGetLastSM() and if the returned sm has a larger index, keeps that
as the last sm.
11 years ago
Victor Julien 9a5bf82ba5 tcp session reuse: reset detect state
Reset the detect state on TCP session reuse. We reset the app layer,
so we need to reset the stateful detection as well.
11 years ago
Victor Julien 0fff3c833e detect state: always lock de_state_m
Always lock the de_state_m on access, also at flow recycle or
cleanup.
11 years ago
Mats Klepsland 78c1af6b38 runmode-pfring: Fixed typo s/fron/from/ 11 years ago
Mats Klepsland a01b3339c7 runmode-pfring: Suppress errors when using DNA/ZC
PF_RING DNA/ZC don't use cluster-id and cluster-type. Therefore,
skip setting these values if DNA/ZC is being used.

Bug #1048
11 years ago
Victor Julien 944276b988 lua detect: expose stream payload
Allow a script to set the 'stream' buffer type. This will add the
script to the PMATCH list.

Example script:
alert tcp any any -> any any (content:"html"; lua:stream.lua; sid:1;)

    function init (args)
        local needs = {}
        needs["stream"] = tostring(true)
        return needs
    end

    -- return match via table
    function match(args)
        local result = {}

        b = tostring(args["stream"])
        o = tostring(args["offset"])

        bo = string.sub(b, o);
        print (bo)

        return result
    end

    return 0
11 years ago
Jason Ish 2e5292e229 Don't require an action-order configuration section. If not present,
use the defaults.
11 years ago
Victor Julien d9c523a332 filestore: fix parsing bug
Filestore keyword can have options or no options, and the parser
was enforcing the NOOPT flag too strictly.

Bug #1288
11 years ago
Victor Julien 4816dcc3d3 flow json log: add 'shutdown' as flow end reason
When engine shuts down all flows in the hash are logged out. They
may not have timed out yet. So they are forced. Log the reason to
be 'shutdown'.
11 years ago
Victor Julien bd1a193877 flow: fix flow logging at shutdown
Move all flows from the hash to the recycler at shutdown.

Bug #1260
11 years ago
Victor Julien 79f0da1df1 output-lua: set proper callbacks for HTTP
Enable the relevant HTTP callbacks.

Bug #1287
11 years ago
Victor Julien 4443da59b4 output-lua: add script-dir config param
Add 'scripts-dir' config directive that is prepended to the script
names to form a path. If ommited or empty, script are opened from
the CWD.
11 years ago
Victor Julien 04afcf2717 ssh: convert error message to debug statement
Don't print errors based on traffic issues.
11 years ago
Eric Leblond 0f61264d68 app-layer-ssh: fix banner parser
Carefully crafted SSH banner could result in parser error.

Signed-off-by: Eric Leblond <eric@regit.org>
11 years ago
Victor Julien 9fd96f531a ipv6: convert ext header pointers to const
To prevent accidental writes into the orignal packet buffer, use
const pointers for the extension header pointers used by IPv6. This
will cause compiler warnings in case of writes.
11 years ago
Victor Julien 5f4a23deb9 ipv6: RH extension header parsing issue
A logic error in the IPv6 Routing header parsing caused accidental
updating of the original packet buffer. The calculated extension
header lenght was set to the length field of the routing header,
causing it to be wrong.

This has 2 consequences:

1. defrag failure. As the now modified payload was used in defrag,
the decoding of the reassembled packet now contained a broken length
field for the routing header. This would lead to decoding failure.

The potential here is evasion, although it would trigger:
[1:2200014:1] SURICATA IPv6 truncated extension header

2. in IPS mode, especially the AF_PACKET mode, the modified and now
broken packet would be transmitted on the wire. It's likely that
end hosts and/or routers would reject this packet.

NFQ based IPS mode would be less affected, as it 'verdicts' based on
the packet handle. In case of replacing the packet (replace keyword
or stream normalization) it could broadcast the bad packet.

Additionally, the RH Type 0 address parsing was also broken. It too
would modify the original packet. As the result of this code was not
used anywhere else in the engine, this code is now disabled.

Reported-By: Rafael Schaefer <rschaefer@ernw.de>
11 years ago
Victor Julien 7cdc57060b af-packet: check pointers before use 11 years ago
Eric Leblond 1e36053eca af-packet: force suricata in IPS mode when needed
AF_PACKET is not setting the engine mode to IPS when some
interfaces are peered and use IPS mode. This is due to the
fact, it is possible to peer 2 interfaces and run an IPS on
them and have a third one that is running in normal IDS mode.

In fact this choice is the bad one as unwanted side effect is
that there is no drop log and that stream inline is not used.

To fix that, this patch puts suricata in IPS mode as soon as
there is two interfaces in IPS mode. And it displays a error
message to warn user that the accuracy of detection on IDS only
interfaces will be low.
11 years ago
Victor Julien 02529b13a8 rule parser: set flag for optionless keywords
If a keyword doesn't have an argument, it should set the SIGMATCH_NOOPT
flag so the parser knows.
11 years ago
Victor Julien 690a85698f rule parser: fix crashing on malformed options
Fix crashing on malformed rule options like 'rev;1;'.

Bug 1254.
11 years ago
Victor Julien 6720496324 detect: fix continue detection with amatch and tx
When using AMATCH, continue detection would fail if the tx part
had already run. This lead to start detection rerunning, causing
multiple alerts for the same issue.
11 years ago
Victor Julien c152ddf072 lua: fix http.request_line inspection
As there is no inspection engine for request_line, the sigmatch was
added to the AMATCH list. However, no AppLayerMatch function for
lua scripts was defined.

This patch defines a AppLayerMatch function.

Bug #1273.
11 years ago
Victor Julien 8b4615f8e7 tls: fix a tls.fingerprint issue in debug mode
Print proper variable so we don't NULL-deref.

Bug #1279.
11 years ago
Eric Leblond e0307b0993 source-nfq: fix display of next queue
Suricata was displaying an invalid queue number as the value is
shift at the moment of its assignement.
11 years ago
bmeeks8 61a9739f44 Bug fix: IPv6 addresses in negated range and IPv6 string into radix tree.
I found three somewhat serious IPv6 address bugs within the Suricata 2.0.x source code. Two are in the source module "detect-engine-address.c", and the third is in "util-radix-tree.c".

The first bug occurs within the function DetectAddressParse2(). When parsing an address string and a negated block is encountered (such as when parsing !$HOME_NET, for example), any corresponding IPv6 addresses were not getting added to the Group Heads in the DetectAddressList. Only IPv4 addresses were being added.

I discovered another bug related to IPv6 address ranges in the Signature Match Address Array comparison code for IPv6 addresses. The function DetectAddressMatchIPv6() walks a signature's source or destination match address list comparing each to the current packet's corresponding address value. The match address list consists of value pairs representing a lower and upper IP address range. If the packet's address is within that range (including equal to either the lower or upper bound), then a signature match flag is returned.

The original test of each signature match address to the packet was performed using a set of four compounded AND comparisons looking at each of the four 32-bit blocks that comprise an IPv6 address. The problem with the old comparison is that if ANY of the four 32-bit blocks failed the test, then a "no-match" was returned. This is incorrect. If one or more of the more significant 32-bit blocks met the condition, then it is a match no matter if some of the less significant 32-bit blocks did not meet the condition. Consider this example where Packet represents the packet address being checked, and Target represents the upper bound of a match address pair. We are testing if Packet is less than Target.

Packet -- 2001:0470 : 1f07:00e2 : 1988:01f1 : d468:27ab
Target -- 2001:0470 : 1f07:00e2 : a48c:2e52 : d121:101e

In this example the Packet's address is less than the target and it should give a match. However, the old code would compare each 32-bit block (shown spaced out above for clarity) and logically AND the result with the next least significant block comparison. If any of the four blocks failed the comparison, that kicked out the whole address. The flaw is illustrated above. The first two blocks are 2001:0470 and 1f07:00e2 and yield TRUE; the next less significant block is 1988:01f1 and a48c:2e52, and also yields TRUE (that is, Packet is less than Target); but the last block compare is FALSE (d468:27ab is not less than d121:101e). That last block is the least significant block, though, so its FALSE determination should not invalidate a TRUE from any of the more significant blocks. However, in the previous code using the compound logical AND block, that last least significant block would invalidate the tests done with the more significant blocks.

The other bug I found for IPv6 occurs when trying to parse and insert an IPv6 address into a Radix Tree using the function SCRadixAddKeyIPV6String(). The test for min and max values for an IPv6 CIDR mask incorrectly tests the upper limit as 32 when it should be 128 for an IPv6 address. I think this perhaps is an old copy-paste error if the IPv6 version of this function was initially copied from the corresponding IPv4 version directly above it in the code. Without this patch, the function will return null when you attempt to add an IPv6 network whose CIDR mask is larger than 32 (for example, the popular /64 mask will cause the function to return the NULL error condition).

(amended by Victor Julien)
11 years ago
Victor Julien 22272f6c5b lua: export packet keywords to detect scripts
Set packet pointer, so it's available to the lua keywords that
require it.
11 years ago
Victor Julien 5a86e57d41 detect-lua: register all 'output' keywords as well
Register all keywords available to output scripts to the detect
scripts as well.
11 years ago
Victor Julien 41523ede77 detect-lua: set tx ptr
Set tx ptr so it can be used later by other keywords.
11 years ago
Victor Julien 3b98a1ce66 detect: track current tx_id in det_ctx
When using the inspection engines, track the current tx_id in the
thread storage the detect thread uses. As 0 is a valid tx_id, add
a simple bool that indicates if the tx_id field is set.
11 years ago
Victor Julien a114787150 lua: move lua output code to generic lua file
So that other Lua scripts (detect) can also start using it.
11 years ago
Victor Julien fdc73eeba6 lua: remove LogLua prefix and replace it with Lua
Preparing making code available to more than just output.
11 years ago
Victor Julien e0d544fb86 lua: move output http funcs to generic util file
Move output Http functions to util-lua-http.c so that detect can use
it later.
11 years ago
Victor Julien f23399d672 Rename Lua code to just Lua
As we support regular Lua as well as LuaJIT, it makes more sense to call
it all Lua.
11 years ago
Victor Julien adfe17280b lua: use LuaPushStringBuffer in more places
Replace existing workarounds with LuaPushStringBuffer
11 years ago
Victor Julien 66019ba325 lua: LuaPushStringBuffer optimization
Only use a temp buffer when really necessary, which is when the
buffer size is not a multiple of 4.
11 years ago
Victor Julien 307ce40500 lua: move LuaPushStringBuffer to the generic util-lua.c 11 years ago
Victor Julien 90b5aff02e lua: rename LuaReturnStringBuffer to LuaPushStringBuffer
LuaPushStringBuffer is a wrapper for lua_pushlstring, so the new name
better reflects it's function.
11 years ago
Victor Julien 0e93a29274 output-lua: add SCFlowStats
SCFlowStats gets the packet and byte counts per flow:
    tscnt, tsbytes, tccnt, tcbytes = SCFlowStats()
11 years ago
Victor Julien 46ac85dea6 output lua: expose flow logging api
Allow use of the Flow Logging API through Lua scripts.

Minimal script:

function init (args)
    local needs = {}
    needs["type"] = "flow"
    return needs
end

function setup (args)
end

function log(args)
    startts = SCFlowTimeString()
    ipver, srcip, dstip, proto, sp, dp = SCFlowTuple()
    print ("Flow IPv" .. ipver .. " src " .. srcip .. " dst " .. dstip ..
            " proto " .. proto .. " sp " .. sp .. " dp " .. dp)
end

function deinit (args)
end
11 years ago
Victor Julien f7d890fe00 lua-output: add SCStreamingBuffer
Add SCStreamingBuffer lua function to retrieve the data passed
to the script per streaming API invocation.

Example:

    function log(args)
        data = SCStreamingBuffer()
        hex_dump(data)
    end
11 years ago
Victor Julien ca3be77008 output-lua: add support for streaming api
Add support to lua output for the streaming api. This allows for a
script to subscribe itself to streaming tcp data and http body data.
11 years ago
Victor Julien efb5c29698 output-lua: give access to packet payload
Add SCPacketPayload()

Example:
    function log(args)
        p = SCPacketPayload()
        print(p)
    end
11 years ago
Victor Julien 08b0d9a5b4 output-lua: expose http body data
Make normalized body data available to the script through
HttpGetRequestBody and HttpGetResponseBody.

There no guarantees that all of the body will be availble.

Example:
    function log(args)
        a, o, e = HttpGetResponseBody();
        --print("offset " .. o .. " end " .. e)

        for n, v in ipairs(a) do
            print(v)
        end
    end
11 years ago
Victor Julien 8360b707e8 output-lua: add HttpGetRequestHost callback
Get the host from libhtp's tx->request_hostname, which can either be
the host portion of the url or the host portion of the Host header.

Example:

    http_host = HttpGetRequestHost()
    if http_host == nil then
        http_host = "<hostname unknown>"
    end
11 years ago
Victor Julien a234a335ac output-lua: http alproto check 11 years ago
Victor Julien cb69cee4d8 output-lua: clean up flow lock handling 11 years ago
Victor Julien 19383fd428 output-lua: alproto string callback
SCFlowAppLayerProto: get alproto as string from the flow. If alproto
is not (yet) known, it returns "unknown".

    function log(args)
        alproto = SCFlowAppLayerProto()
        if alproto ~= nil then
            print (alproto)
        end
    end
11 years ago
Victor Julien 22dd14d560 output-lua: expose thread info
A new callback to give access to thread id, name and group name:
SCThreadInfo. It gives: tid (integer), tname (string), tgroup (string)

    function log(args)
        tid, tname, tgroup = SCThreadInfo()
11 years ago
Victor Julien 8802ba3f67 output-lua: expose flow start time string
SCFlowTimeString: returns string form of start time of a flow

Example:

    function log(args)
        startts = SCFlowTimeString()
        ts = SCPacketTimeString()
        if ts == startts then
            print("new flow")
        end
11 years ago
Victor Julien 07ff85a44e output-lua: add file callbacks
SCFileInfo: returns fileid (number), txid (number), name (string),
            size (number), magic (string), md5 in hex (string)

Example:

    function log(args)
        fileid, txid, name, size, magic, md5 = SCFileInfo()

SCFileState: returns state (string), stored (bool)

Example:
    function log(args)
        state, stored = SCFileState()
11 years ago
Victor Julien 3343060d85 output-lua: add SCPacketTimeString
Add SCPacketTimeString to get the packets time string in the format:
    11/24/2009-18:57:25.179869

Example use:

    function log(args)
        ts = SCPacketTimeString()
11 years ago
Victor Julien b3dfd3cd8e output-lua: rule info callback
SCRuleIds(): returns sid, rev, gid:

    function log(args)
        sid, rev, gid = SCRuleIds()

SCRuleMsg(): returns msg

    function log(args)
        msg = SCRuleMsg()

SCRuleClass(): returns class msg and prio:

    function log(args)
        class, prio = SCRuleClass()
        if class == nil then
            class = "unknown"
        end
11 years ago
Victor Julien d9efa7048a lua: add SCFlowTuple lua function
Like SCPacketTuple, only retrieves Tuple from the flow.

Minimal log function:

    function log(args)
        ipver, srcip, dstip, proto, sp, dp = SCFlowTuple()
        print ("Flow IPv" .. ipver .. " src " .. srcip .. " dst " .. dstip ..
               " proto " .. proto .. " sp " .. sp .. " dp " .. dp)
    end
11 years ago
Victor Julien f2da5dbbad detect-lua: convert extensions to use flow wrappers
Use the new flow wrapper functions in the lua flowvar and flowint
extensions.
11 years ago
Victor Julien affbd697ed lua: add flow store and retrieval wrappers
Add flow store and retrieval wrappers for accessing the flow through
Lua's lightuserdata method.

The flow functions store/retrieve a lock hint as well.
11 years ago
Victor Julien 599ec36b2c lua: introduce util-lua.[ch]
Shared functions for all lua parts of the engine.
11 years ago
Victor Julien 8bc01af581 output-lua: add all packets logging support
If the script needing a packet doesn't specify a filter, it will
be run against all packets. This patch adds the support for this
mode. It is a packet logger with a condition function that always
returns true.
11 years ago
Victor Julien fe3484fbc0 output-lua: improve error checking for init()
If init doesn't properly init the script, skip the script and error
out.
11 years ago
Victor Julien 0055a10b3a output-log: expose SCLog functions to lua scripts
The lua scripts can use SCLogDebug, SCLogInfo, SCLogNotice, SCLogWarning,
SCLogError. The latter 2 won't be able to add an error code though.
11 years ago
Victor Julien 51ab5e55c1 output-lua: make packet ptr available to all scripts
TxLogger and Packet logger need it to be able to use the Tuple
callback.
11 years ago
Victor Julien 1e836be3d8 output-lua: add SCLogPath callback
Add a lua callback for getting Suricata's log path, so that lua scripts
can easily get the logging directory Suricata uses.

Update the Setup logic to register callbacks before the scripts 'setup'
is called.

Example:

    name = "fast_lua.log"
    function setup (args)
        filename = SCLogPath() .. "/" .. name
        file = assert(io.open(filename, "a"))
    end
11 years ago
Victor Julien 31eea0f143 output-lua: TxLogger use proper stack function
Use proper wrapper to setup the stack.
11 years ago
Victor Julien 329f55598f output-lua: improve error handling and documentation
Better document the various functions and improve error handling.
11 years ago
Victor Julien c5ff94a319 output-lua: register common callbacks
Clean up callback registration in the setup-stage and register
common callbacks.
11 years ago
Victor Julien 0070aef3d1 output-lua: support File logging
Add file logger support. The script uses:

function init (args)
    local needs = {}
    needs['type'] = 'file'
    return needs
end

The type is set to file to make it a file logger.
11 years ago
Victor Julien 1517a2ca0e output-lua: rename LuaPacketLogger to ..Alerts
As the script is called for each alert, not for each packet, name
the script LuaPacketLoggerAlerts.
11 years ago
Victor Julien fe6cf00a8a output-lua: add stack utility functions
Add utility functions for placing things on the stack for use
by the scripts. Functions for numbers, strings and byte arrays.

Add callback for returing IP header info: ip version, src ip,
dst ip, proto, sp, dp (or type and code for icmp and icmpv6):
SCPacketTuple
11 years ago
Victor Julien 53d7f800bf output-lua: initial packet support
Add key for storing packet pointer in the lua stack and a utility
function to retrieve it from lua callbacks.
11 years ago
Victor Julien 15052e58a2 output-lua: move LuaPrintStack to common
It's a utility function that will be used in several other places
as well.
11 years ago
Victor Julien b60e28e1a4 output-lua: packet logger support
Through 'needs' the script init function can indicate it wants to
see packets and select a condition function. Currently only alerts
is an option:

    function init (args)
        local needs = {}
        needs["type"] = "packet"
        needs["filter"] = "alerts"
        return needs
    end
11 years ago
Victor Julien 0bd4b9beca output-lua: new file for common functions
Add output-lua-common.[ch] to store functions common to various parts
of the lua output framework.
11 years ago
Victor Julien db30ed8c3e output: Lua HTTP log initial implementation
Initial version of a HTTP LUA logger. Execute lua scripts from the
Tx-log API.
11 years ago
Victor Julien 95e0eae69a output-lua: support submodules
Use the OutputCtx::submodules list to register additional log modules.
Currently this is hardcoded to the 'lua' module.
11 years ago
Victor Julien 1fd0f96b49 output-lua: display warning if no lua support
Display a warning that the lua module is not available if we're
not compiled against lua(jit).
11 years ago
Victor Julien eb5a70fe09 output: add submodules list to OutputCtx
Add a list to the OutputCtx that can contain OutputModule structures.
This will be used by a 'parent' module to register submodules directly.
11 years ago
Victor Julien 6493554663 streaming: pass tx_id to logger
This way we can distinguish between various tx' in the logger.
11 years ago
Victor Julien ac2ef45a3d tcp-data-log: file and dir logging modes
Add a file logging mode, which logs all the data into a single log file.

Also, make the directory logging more configurable.
11 years ago
Victor Julien 3dec0e96f8 tcp-data: new streaming logger
tcp-data logs out reassembled stream data in a streaming fashion.

Records type to log into different directories.
11 years ago
Victor Julien bac6c3ab02 streaming logger: support Http Body logging
Add an argument to the registration to indicate which iterator
needs to be used: Stream or HttpBody

Add HttpBody Iterator, calling the logger(s) for each Http body chunk.
11 years ago
Victor Julien ab6fac884d output-streaming: StreamIterator
StreamIterator implementation for iterating over ACKed segments.

Flag each segment as logged when the log function has been called for it.

Set a 'OPEN' flag for the first segment in both directions.

Set a 'CLOSE' flag when the stream ends. If the last segment was already
logged, a empty CLOSE call is performed with NULL data.
11 years ago
Victor Julien 9d9ef983dd output-streaming: a Log API for streaming data
This patch adds a new Log API for streaming data such as TCP reassembled
data and HTTP body data. It could also replace Filedata API.

Each time a new chunk of data is available, the callback will be called.
11 years ago
Ken Steele fdcc7d18e7 Fix compiler warning about uninitialized variable in mpipe. 11 years ago
Duarte Silva 3a18db13dc Simple code fixes
- Removed unnecessary assignment of the data field
- Removed else condition (same function called for IPv4 and IPV6)
- Fixed constants to be a power of two (used in bitwise operations)
11 years ago
Victor Julien c20bd3bcb2 Optimize Packet Ext data freeing
Move the logic of PacketFreeExtData into a macro 'PACKET_FREE_EXTDATA'.
It was called for each packet.
11 years ago
Eric Leblond 80adc40f68 packet pool: fix ext_pkt cleaning
The field ext_pkt was cleaned before calling the release function.
The result was that IPS mode such as the one of AF_PACKET were not
working anymore because they were not able to send the data which
were initially pointed by ext_pkt.

This patch moves the ext_pkt cleaning to the cleaning macro. This
ensures that the cleaning is done for allocated and pool packets.
11 years ago
Victor Julien 3ee504a3dc packet recycle: remove mutex destroy/init
This was necessary earlier when there was a memset involved.
11 years ago
Victor Julien ed0b75e1e9 packet recycle: do most clean up on packet reuse
Call PACKET_RELEASE_REFS from PacketPoolGetPacket() so that
we only access the large packet structure just before actually
using it. Should give better cache behaviour.
11 years ago
Victor Julien 231b993f1f packet recycle: split macro
Split PACKET_RECYCLE into 2 parts. One part for cleanup to do before a
packet is returned to the pool, the other after it's retrieved from
the pool.
11 years ago
Victor Julien 04a0672f7a Fix decode tests calling PACKET_DO_RECYCLE instead of PACKET_RECYCLE 11 years ago
Ken Steele 44aeb9c637 Fix GRE Source Routing Header definition
The Source Routing Header had routing defined as a char* for a field
of variable size. Since that field was not being used in the code, I
removed the pointer and added a comment.
11 years ago
Ken Steele c91b7fd3bc More structures that need to be marked Packed.
These structures are cast from raw packet data, so they should be packed.
The case is:

typedef struct Foo_ {
} Foo;

Foo *f = (Foo *)pkt;
11 years ago
Ken Steele 045966676d Add Packed attribute on Header structures
Structures that are used to cast packet data into fields need to be packed
so that the compiler doesn't add any padding to these fields. This also helps
Tile-Gx to avoid unaligned loads because the compiler will insert code to
handle the possible unaligned load.
11 years ago
Victor Julien f453fb810f alert-json: clean up flags
Make payload/packet logging code also use the flags field in
AlertJsonOutputCtx, instead of in the LogFileCtx.
11 years ago
Giuseppe Longo b188d93630 json-alert: include HTTP info on the alerts
Extends the JSON alert output to include the HTTP data
at the time of the alert.
11 years ago
Giuseppe Longo 288f0b1fb7 json-http: refactoring output code
Splits the output code in two public functions and permits
to call them from the alert function
11 years ago
Duarte Silva db9588a2ce Use extra data structure in json alert output
to store local configuration
11 years ago
Victor Julien 6b0ff0193d stream: detect and filter out bad window updates
Reported in bug 1238 is an issue where stream reassembly can be
disrupted.

A packet that was in-window, but otherwise unexpected set the
window to a really low value, causing the next *expected* packet
to be considered out of window. This lead to missing data in the
stream reassembly.

The packet was unexpected in various ways:
- it would ack unseen traffic
- it's sequence number would not match the expected next_seq
- set a really low window, while not being a proper window update

Detection however, it greatly hampered by the fact that in case of
packet loss, quite similar packets come in. Alerting in this case
is unwanted. Ignoring/skipping packets in this case as well.

The logic used in this patch is as follows. If:

- the packet is not a window update AND
- packet seq > next_seq AND
- packet acq > next_seq (packet acks unseen data) AND
- packet shrinks window more than it's own data size
THEN set event and skip the packet in the stream engine.

So in case of a segment with no data, any window shrinking is rejected.

Bug #1238.
11 years ago
Victor Julien 7cc63918c3 ipv6: fix dst/hop header option parsing
The extension header option parsing used a uint8_t internally. However
much bigger option sizes are valid.
11 years ago
Victor Julien 2b84cd9483 defrag: use 'struct timeval' for timeout tracking
Until now the time out handling in defrag was done using a single
uint32_t that tracked seconds. This lead to corner cases, where
defrag trackers could be timed out a little too early.
11 years ago
Victor Julien 7c05685421 ipv6: set event on unsupported nh
If a next header / protocol is encountered that we can't handle (yet)
set an event. Disabled the rule by default.

    decode-event:ipv6.unknown_next_header;
11 years ago
Victor Julien bbcdb657da ipv6: more robust ipv6 exthdr handling
Skip past Shim6, HIP and Mobility header.

Detect data after 'none' header.
    decode-event:ipv6.data_after_none_header;
11 years ago
Victor Julien 938602c55e ipv6: detect frag header reserved field non-zero
Frag Header length field is reserved, and should be set to 0.

    decode-event:ipv6.fh_non_zero_reserved_field;
11 years ago
Victor Julien 8c19e5ff63 ipv6: make exthdr parsing more robust
Improve data length checks. Detect PadN option with 0 length.
11 years ago
Victor Julien abee95ca4f ipv6: set flag on type 0 routing header
Type 0 Routing headers are deprecated per RFC 5095.

This patch sets an decode event flag that can be matched on through:
    decode-event:ipv6.rh_type_0;
11 years ago
Victor Julien 83b031b4e0 ipv6 defrag: fix unfragmentable exthdr handling
Fix or rather implement handling of unfragmentable exthdrs in ipv6.
The exthdr(s) appearing before the frag header were copied into the
reassembled packet correctly, however the stripping of the frag header
did not work correctly.

Example:
The common case is a frag header directly after the ipv6 header:

[ipv6 header]->[frag header]->[icmpv6 (part1)]
[ipv6 header]->[frag header]->[icmpv6 (part2)]

This would result in:
[ipv6 header]->[icmpv6]

The ipv6 headers 'next header' setting would be updated to point to
whatever the frag header was pointing to.

This would also happen when is this case:

[ipv6 header]->[hop header]->[frag header]->[icmpv6 (part1)]
[ipv6 header]->[hop header]->[frag header]->[icmpv6 (part2)]

The result would be:
[ipv6 header]->[hop header]->[icmpv6]

However, here too the ipv6 header would have been updated to point
to what the frag header pointed at. So it would consider the hop header
as if it was an ICMPv6 header, or whatever the frag header pointed at.

The result is that packets would not be correctly parsed, and thus this
issue can lead to evasion.

This patch implements handling of the unfragmentable part. In the first
segment that is stored in the list for reassembly, this patch detects
unfragmentable headers and updates it to have the last unfragmentable
header point to the layer after the frag header.

Also, the ipv6 headers 'next hdr' is only updated if no unfragmentable
headers are used. If they are used, the original value is correct.

Reported-By: Rafael Schaefer <rschaefer@ernw.de>

Bug #1244.
11 years ago
Victor Julien e66c73abcd packet pool: init pthread key before using it
In the packet pool code, it's critical to initialize the pthread key
before using it. Applies only to the code used if __thread isn't
supported.
11 years ago
Victor Julien a441441636 packet pool: cosmetic cleanups 11 years ago
Victor Julien 6de34489b3 magic: disable tests depending on magic version
Some tests depend on specific results by specific magic versions.
Disable these.
11 years ago
Eric Leblond fe82a83e79 suricata: RunUnittests now return void
RunUnittests function is now a terminal function (calling exit
before leaving).
11 years ago
Eric Leblond 0780c07043 unittests: don't register app layer test
Some tests are already registered via the function
AppLayerParserRegisterProtocolUnittests. So we don't need to
egister them during runmode initialization.
11 years ago
Victor Julien a0b421c47e Fix up mistaken style change 11 years ago
Ken Steele 228abb89ac fixup 11 years ago
Ken Steele 8f1d75039a Enforce function coding standard
Functions should be defined as:

int foo(void)
{
}

Rather than:
int food(void) {
}

All functions where changed by a script to match this standard.
11 years ago
Victor Julien de4e2221d8 eve: add tx_id to output for alerts and events
Add tx_id field for correlating alerts and events per tx.
11 years ago
sxhlinux c85674b0a6 Update app-layer-htp.c
When keyword "boundary=" doesn't exist in the http_header, the value of r is 0 and this condition shouldn't return 0 instead 1;
11 years ago
Ken Steele 033ad9e974 Reduce reallocation in AC Tile MPM creation.
Exponentially increase the memory allocated for new states when adding new
states, then at the end resize down to the actually final size so that no space is wasted.
11 years ago
Alexander Gozman a6dbf627b2 Add input interface's name to JSON log 11 years ago
Victor Julien 0c1696f84b pcap-log: unify lock handling, fixes Coverity warn
*** CID 1229124:  Data race condition  (MISSING_LOCK)
/src/log-pcap.c: 363 in PcapLog()
357         {
358             return TM_ECODE_OK;
359         }
360
361         PcapLogLock(pl);
362
>>>     CID 1229124:  Data race condition  (MISSING_LOCK)
>>>     Accessing "pl->pkt_cnt" without holding lock "PcapLogData_.plog_lock". Elsewhere, "PcapLogData_.pkt_cnt" is accessed with "PcapLogData_.plog_lock" held 1 out of 2 times (1 of these accesses strongly imply that it is necessary).
363         pl->pkt_cnt++;
364         pl->h->ts.tv_sec = p->ts.tv_sec;
365         pl->h->ts.tv_usec = p->ts.tv_usec;
366         pl->h->caplen = GET_PKT_LEN(p);
367         pl->h->len = GET_PKT_LEN(p);
368         len = sizeof(*pl->h) + GET_PKT_LEN(p);
11 years ago
Ken Steele edb702a7b6 Cleanup Packet Pools when done. 11 years ago
Ken Steele b045fcb032 Fix Packet Stacks for non-TLS Operating Systems
On non-TLS systems, check each time the Thread Local Storage
is requested and if it has not been initialized for this thread, initialize it.
The prevents not initializing the worker threads in autofp run mode.
11 years ago
Victor Julien 0ac94ef777 flow-recycler: support multiple instances
Use new management API to run the flow recycler.

Make number of threads configurable:

flow:
  memcap: 64mb
  hash-size: 65536
  prealloc: 10000
  emergency-recovery: 30
  managers: 2
  recyclers: 2

This sets up 2 flow recyclers.
11 years ago
Victor Julien e0841218f0 flow-manager: support multiple instances
Use new management API to run the flow manager.

Support multiple flow managers, where each of them works with it's
own part of the flow hash.

Make number of threads configurable:

flow:
  memcap: 64mb
  hash-size: 65536
  prealloc: 10000
  emergency-recovery: 30
  managers: 2

This sets up 2 flow managers.

Handle misc tasks only in instance 1: Handle defrag hash timeout
handing, host hash timeout handling and flow spare queue updating
only from the first instance.
11 years ago
Victor Julien 46cee88ef8 threads: add management API
Currently management threads do their own thread setup and handling. This
patch introduces a new way of handling management threads.

Functionality that needs to run as a management thread can now register
itself as a regular 'thread module' (TmModule), where the 'Management'
callback is registered.
11 years ago
Victor Julien f1185d051c flow id: quick and dirty first stab at a flow id
Add a 'flow_id' that is the same for all records produced for packets
belonging to the same flow.

This patch simply takes the flow's memory address.
11 years ago
Victor Julien 9f55ca0057 flow: add flow_end_flags field, add logging
The flow end flags field is filled by the flow manager or the flow
hash (in case of forced timeout of a flow) to record the timeout
conditions in the flow:
- emergency mode
- state
- reason (timed out or forced)

Add logging to the flow logger.
11 years ago
Victor Julien fc6ad56944 flow: move FlowGetFlowState
Move FlowGetFlowState to flow-private.h so that all parts of the flow
engine can use it.
11 years ago
Victor Julien e6ed6731b1 flow log: log TCP state
Log the TCP state at timeout.
11 years ago
Victor Julien 8c231702d9 flow-recycler: speed up flow-recycler shutdown
Thread was killed by the generic TmThreadKillThreads instead of
the FlowKillFlowRecyclerThread. The latter wakes the thread up, so
that shutdown is quite a bit faster.
11 years ago
Victor Julien 6f9a2fcd58 flow: log individual tcp flags
Log the tcp flags.
11 years ago
Victor Julien f4dfaacff3 netflow: log individual tcp flags
Log the tcp flags.
11 years ago
Victor Julien eaf01449e3 json: add tcp flags to json utility function
Turns a flags bitfield into a set of json bools.
11 years ago
Victor Julien db15339f47 netflow-json: initial version
Initial version of netflow module, a flow logger that logs each
direction in a completely separate record (line).
11 years ago
Victor Julien 07b7f66f3c flow-log: log TCP flags per direction
In addition to flags for the entire session, also log out TCP flags
for both directions separately.
11 years ago
Victor Julien 3bb0ccba98 stream: track TCP flags per stream direction
For netflow logging track TCP flags per stream direction. As the struct
had no more space left without expanding it, the flags and wscale
fields are now compressed.
11 years ago
Victor Julien d19a15701c flow: init logger thread data for decoders
Initialize the output flow api thread data for the decoder threads.
11 years ago
Victor Julien 98c88d5170 decode: pass ThreadVars to DecodeThreadVarsFree
Flow output thread data deinit function which will be called from
DecodeThreadVarsFree will need it.
11 years ago
Victor Julien de034f1867 flow: prepare flow forced reuse logging
Most flows are marked for clean up by the flow manager, which then
passes them to the recycler. The recycler logs and cleans up. However,
under resource stress conditions, the packet threads can recycle
existing flow directly. So here the recycler has no role to play, as
the flow is immediately used.

For this reason, the packet threads need to be able to invoke the
flow logger directly.

The flow logging thread ctx will stored in the DecodeThreadVars
stucture. Therefore, this patch makes the DecodeThreadVars an argument
to FlowHandlePacket.
11 years ago
Victor Julien bd490736c2 flow: take flow pkt & byte count out of debug
Until now the flow packet and byte counters were only available in
DEBUG mode. For logging purposes they are now available always.
11 years ago
Victor Julien e6ee5feaba flow: don't BUG_ON if no loggers are enabled
API is always called, even if no loggers are enabled. Don't abort()
in this case.
11 years ago
Victor Julien 52b0ec027e flow: clean up recycle queue at shutdown
Mostly for tests that don't start the recycler thread, make sure
all flows are cleaned up.
11 years ago
Victor Julien 4aff4c650f flow unittest: update flow manager unit test
Test now tests a different queue.
11 years ago
Victor Julien 7acea2c66d flow: track lastts in struct timeval
Track full timestamp for lastts in flows to be able to log it.
11 years ago
Victor Julien c66a29b67d flow: track bytes per direction
Track bytes in both flow directions for logging purposes.
11 years ago
Victor Julien f828793f8f flow log: log start/end times
Log time of first packet (flow creation) and of the last packet.
11 years ago
Victor Julien 672f6523a7 flow-log: log TCP flags seen
Log TCP flags seen during the life time of a flow/session.
11 years ago
Victor Julien fddeca8aae tcp: track TCP packet flags per session
For logging out in flow logging.
11 years ago
Victor Julien ec7d446f16 flow-log: log pkts, bytes
Only in DEBUG currently.
11 years ago
Victor Julien 3c7af02067 flow-json-log: stub
Stub for JSON flow logger.
11 years ago
Victor Julien c7ebfd1b68 flow: flow log threading setup
Set up threading for the flow logger.
11 years ago
Victor Julien e30c083cff flow log: call logger from recycler
Call the flow logger API from the recycler thread, so that timed
out flows are logged.
11 years ago
Victor Julien 115ad1e81f flow: output api stub
Basic output API for flow logging.
11 years ago
Victor Julien a52a4ae9d4 flow recycler: unix socket support
Support starting and shutting down the flow recycler thread in the
unix socket runmode.
11 years ago
Victor Julien f476732139 flow recycler: shutdown
Only shut down when all flows in the recycle queue have been processed.
11 years ago
Victor Julien f26f82e9a6 flow: move flow cleanup to new 'recycler'
Move Flow clean up from the flow manager to the new flow recycler.
11 years ago
Victor Julien 94cb52897b flow: introduce FlowRecycler stub
FlowRecycler thread stub. Start/stop code.
11 years ago
Victor Julien e892d99827 flow: new flow queue: flow_recycle_q
This queue will be used by the FlowManager to pass timed out flows
to another thread that will do the actual cleanup.
11 years ago
Victor Julien fdd407751e Fix eve 'filetype' parsing
Now that we use 'filetype' instead of 'type', we should also
use 'regular' instead of 'file'.

Added fallback to make sure we stay compatible to old configs.
11 years ago
Alexander Gozman bfb6175bf6 Fixed memory leak 11 years ago
Alexander Gozman a0bb4477db Fix possible crash when logfile descriptor is invalid 11 years ago
Alexander Gozman 8048eebd39 Fix handling filetype for eve log 11 years ago
Alexander Gozman 54193e89d5 Fixed variables names in suricata.yaml.in Changed logging logic - now it's possible to enable different payload dumping modes separately Fixed bug in dumping packet without stream segments Fixed indents 11 years ago
Alexander Gozman 6d569013c6 Changed attribute name for printable payload 11 years ago
Alexander Gozman c770ade9c2 Changed variable name when dumping single packet 11 years ago
Alexander Gozman 2a4c7ee5dc Add ability to encode payload in Base64 11 years ago
Alexander Gozman ffac6b71e2 Fixed stream handling Fixed some coding style issues 11 years ago
Matt Carothers ab58ee2676 Add packet and payload logging to JSON alert output 11 years ago
Victor Julien c53b428079 Fix engine getting stuck because of optimizations
At -O1+ in both Gcc and Clang, PacketPoolWait would optimize the
wait loop in the wrong way. Adding a compiler barrier to prevent
this optimization issue.
11 years ago
Victor Julien c4a8e2cd14 Remove unused variables 11 years ago
Victor Julien 1d9278bef4 Fix packet pool pending stack adds
Add packets after the first as the list/stack head as well.
11 years ago
Victor Julien b5d3b7e92a Fix pcap packet acquisition methods
Fix pcap packet acquisition methods passing 0 to pcap_dispatch.
Previously they passed the packet pool size, but the packet_q_len
variable was now hardcoded at 0.

This patch sets packet_q_len to 64. If packet pool is empty, we fall
back to direct alloc. As the pcap_dispatch function is only called
when packet pool is not empty, we alloc at most 63 packets.
11 years ago
Ken Steele 0dd16461cf Update max-pending-packet comments to show it is now per-thread.
Updated suricata.yaml and comments in the code.
11 years ago
Ken Steele 28ccea51d3 Add error checking for pthread_setspecific() and pthread_key_create(). 11 years ago
Ken Steele b1a7e76ca7 Use posix_memalign instead of mm_malloc on non-Windows systems. 11 years ago
Ken Steele a38d5a0135 Implement thread specific data option when __thread is not available. 11 years ago
Ken Steele be448aef22 For PktPool add local pending freed packets list.
Better handle the autofp case where one thread allocates the majority
of the packets and other threads free those packets.

Add a list of locally pending packets. The first packet freed goes on the
pending list, then subsequent freed packets for the same Packet Pool are
added to this list until it hits a fixed number of packets, then the
entire list of packets is pushed onto the pool's return stack. If a freed
packet is not for the pending pool, it is freed immediately to its pool's
return stack, as before.

For the autofp case, since there is only one Packet Pool doing all the
allocation, every other thread will keep a list of pending packets for
that pool.

For the worker run mode, most packets are allocated and freed locally. For
the case where packets are being returned to a remote pool, a pending list
will be kept for one of those other threads, all others are returned as before.

Which remote pool for which to keep a pending list is changed each time the
pending list is returned. Since the return pending pool is cleared when it is
freed, then next packet to be freed chooses the new pending pool.
11 years ago
Ken Steele 3c6e01f653 Replace ringbuffer in Packet Pool with a stack for better cache locality
Using a stack for free Packet storage causes recently freed Packets to be
reused quickly, while there is more likelihood of the data still being in
cache.

The new structure has a per-thread private stack for allocating Packets
which does not need any locking. Since Packets can be freed by any thread,
there is a second stack (return stack) for freeing packets by other threads.
The return stack is protected by a mutex. Packets are moved from the return
stack to the private stack when the private stack is empty.

Returning packets back to their "home" stack keeps the stacks from getting out
of balance.

The PacketPoolInit() function is now called by each thread that will be
allocating packets. Each thread allocates max_pending_packets, which is a
change from before, where that was the total number of packets across all
threads.
11 years ago
Victor Julien 94571c5dd2 AC: shrink output table after initialization 11 years ago
Victor Julien 04c9db398e AC: reduce realloc for new states
Don't realloc per state add, but grow by larger blocks per realloc.
11 years ago
Ken Steele ba1e2ed69d Fix Boyer Moore Nocase bug where BoyerMooreCtxToNocase was missing.
Whenever DETECT_CONTENT_NOCASE is set for a BoyerMoore matcher, the
function BoyerMooreCtxToNocase() must be called. This call was missing
in AppLayerProtoDetectPMRegisterPattern().

Also created BoyerMooreNocaseCtxInit() that calls BoyerMooreCtxToNocase()
to make some code cleaner and safer.
11 years ago
Ken Steele 967f7aefde Store Boyer Moore no case strings in lower case.
Rather than converting the search string to lower case while searching,
convert it to lowercase during initialization.

Changes the Boyer Moore search API for take BmCtx

Change the API for BoyerMoore to take a BmCtx rather than the two parts that
are stored in the context. Which is how it is mostly used. This enforces
always calling BoyerMooreCtxToNocase() to convert to no-case.

Use CtxInit and CtxDeinit functions to create and destroy the context,
even in unit tests.
11 years ago
Ken Steele 54214d1251 Fix comment wording in Boyer Moore pattern matcher. 11 years ago
Eric Leblond de6dac0043 Remove pcapinfo output
EVE logging is a really good substitute for pcapinfo. Suriwire is
now supporting EVE output so it is not anymore necessary to have
pcapinfo in Suricata.
11 years ago
Victor Julien be1979b2f9 pcap-log: support dynamic file names in multi
When using multi mode, the filename can use a few variables:

%n -- thread number, where the 1st thread has 1, and it increments
%i -- thread id (system thread id, similar to pid)
%t -- timestamp, where seconds or seconds+usecs depends on
      the ts-format option.

Example:
filename: filename: pcaps/%n/pcap.%t
This will translate to: pcaps/3/pcap.1256792217 for the 3rd thread.

Note that while it's possible to use directories, they won't be
created. So make sure they exist.
11 years ago
Victor Julien 6cebe7ef7b pcap-log: performance optimizations
This patch adds a field 'is_private' to PcapLogData, so that the
using thread knows if it needs to lock access to it or not.

Reshuffle PcapLogData to roughly match order of access.
11 years ago
Victor Julien 923341fa05 pcap-log: implement multi mode
This patch implements a new mode in pcap-logging: 'multi'. It stores
a pcap file per logger thread, instead of just one file globally.

This removes lock contention, so it brings a lot more performance.

The trade off is that there are now mulitple files where there would
be one before.

Files have a thread id added to their name: base_name.tid.ts, so by
we have something like: "log.pcap.20057.1254500095".
11 years ago
Victor Julien 4922cd2d36 pcap-log: introduce PcapLogThreadData
PcapLog uses the global data structure PcapLogData as thread data
as well. This is possible because all operations on it are locked.

This patch introduces PcapLogThreadData. It contains a pointer to
the PcapLogData. Currently to the global instance, but in the future
it may hold a thread-local instance of PcapLogData.
11 years ago
Victor Julien bbc8c1ea05 log-pcap: multi mode yaml parsing
In preparation of the multi file mode, add 'multi' as a value to
the mode.
11 years ago
Victor Julien cf4db47931 log-pcap: lock profiling
Add lock profiling to pcap logging profiling.
11 years ago
Victor Julien adde58d2cb log-pcap: improve profiling
Add profiling to a logfile. Default is $log_dir/pcaplog_stats.log

The counters for open, close, rotate, write and handles are written
to it, as well as:
- total bytes written
- cost per MiB
- cost per GiB

Option is disabled by default.
11 years ago
Victor Julien f6c5b1715f Update log-pcap.h, add license
Clean up log-pcap.h and add the OISF license header.
11 years ago
Victor Julien 1af2f6528b log-pcap code cleanups
Code cleanups to make functions static.
11 years ago
Victor Julien fd7dd09f4c profiling: add pcap logger profiling
Tracks: file open, file close, file rotate (which includes open and
close), file write and open handles.

Open handles measures the cost of open the libpcap handles.
11 years ago
Victor Julien ed84c8795d Update version number to 2.1dev 11 years ago
Victor Julien 2646edc129 Profiling: fix compilation on CentOS5
Bug #1207
11 years ago
Victor Julien f232fdc0c9 htp: init memuse atomics
In case of the spinlocked fallback code the lock was uninitialized.
11 years ago
Victor Julien f06e5f3c73 ethtool: add missing include necessary for CentOS5 11 years ago
Alexander Gozman 405baa3cb2 Fix compile-time error on old kernels and ethtool.h 11 years ago
sxhlinux 546ae9737b Update log-file.c
test whether tx_ud is NULL
11 years ago
Ken Steele f2e777e3a5 Fix lowercase table initialization (bug 1221)
The for loop needed to check for < 256, not < 255.
11 years ago
Victor Julien 27eb0f450a defrag: fix timeout setting when config is missing
When the config is missing, DefragPolicyGetHostTimeout will default
to returning -1. This will effectively set no timeout at all, leading
to defrag trackers being freed too early.
11 years ago
Eric Leblond 97ca02f0c5 defrag: fix reconstruction
This patch is fixing an issue in defragmentation code. The
insertion of a fragment in the list of fragments is done with
respect to the offset of the fragment. But the code was using
the original offset of the fragment and not the one of the
new reconstructed fragment (which can be different in the
case of overlapping segment where the left part is trimmed).

This case could lead to some evasion techniques by causing
Suricata to analyse a different payload.
11 years ago
Eric Leblond 09fd7060ec unix socket: fix valgrind issue
This patch fixes the following issue reported by valgrind:
 31 errors in context 1 of 1:
 Conditional jump or move depends on uninitialised value(s)
    at 0x8AB2F8: UnixSocketPcapFilesCheck (runmode-unix-socket.c:279)
    by 0x97725D: UnixCommandBackgroundTasks (unix-manager.c:368)
    by 0x97BC52: UnixManagerThread (unix-manager.c:884)
    by 0x6155F6D: start_thread (pthread_create.c:311)
    by 0x6E3A9CC: clone (clone.S:113)

The running field in PcapCommand was not initialized.
11 years ago
Eric Leblond a33d1e28e9 unix-manager: fix crash when client disconnect
This patch fixes an issue in unix socket handling. It is possible
that a socket did disconnect when analysing a command and because
the data treatment is done in a loop on clients this was leading
to a update of the list of clients during the loop. So we need
in fact to use TAILQ_FOREACH_SAFE instead of TAILQ_FOREACH.

Reported-by: Luigi Sandon <luigi.sandon@gmail.com>
Fix-suggested-by: Luigi Sandon <luigi.sandon@gmail.com>
11 years ago
Ken Steele 6ebc20f6d8 Rework Tile CPU affinity setting to handle non-contiguous sets of CPUs.
It is possible to have a non-contiguous CPU set, which was not being
handled correctly on the TILE architecture.

Added a "rank" field in the ThreadVar to store the worker's rank separately
from the cpu for this case.
11 years ago
Mats Klepsland 1f3fbbc992 Fix bug #1206
PF_RING ZC uses clusters in the same way as PF_RING DNA. Therefore,
this bug can be fixed as it was fixed for DNA (bug #598).
11 years ago
Victor Julien 896b61452c htp: make htp state handling function more robust
Also, fix wrong cast that worked only by luck.
11 years ago
Victor Julien eff85aba5e http: remove BUG_ON(1) statement
Remove BUG_ON(1) statement that was a leftover from debugging.

Bug #1189
Bug #1212
11 years ago
Alessandro Guido 13448aca1c Fix issue #1214
When applying wildcard thresholds (with sid = 0 and/or gid = 0) it's wrong
to exit on the first signature already having an event filter. Indeed,
doing so results in the theshold not being applied to all subsequent
signatures. Change the code in order to skip signatures with event
filters instead of breaking out of the loop.
11 years ago
Victor Julien 9de536efdb Bug 1098: improve invalid pcre/R handling
When not using a file_data or similar 'sticky buffer', a pcre/R option
needs a content in the same buffer.
11 years ago
Giuseppe Longo 8db3f214f0 nflog: fix memory leaks
This fixes the following memory leaks:

[src/source-nflog.c:222]: (error) Memory leak: ntv
[src/source-nflog.c:236]: (error) Memory leak: ntv
[src/source-nflog.c:253]: (error) Memory leak: ntv
[src/source-nflog.c:258]: (error) Memory leak: ntv
11 years ago
Victor Julien cc54250cf9 Fix live reload segv when startup isn't complete
If a live reload signal was given before the engine was fully started
up (e.g. pcap file thread waiting for a disk to spin up), a segv could
occur.

This patch only enables live reloads after the threads have been
started up completely.
11 years ago
Victor Julien 2c20c9d409 Fix Coverity 1220098 and 1220099
*** CID 1220098:  Missing unlock  (LOCK)
/src/log-droplog.c: 195 in LogDropLogNetFilter()
189         SCMutexLock(&dlt->file_ctx->fp_mutex);
190
191         if (dlt->file_ctx->rotation_flag) {
192             dlt->file_ctx->rotation_flag  = 0;
193             if (SCConfLogReopen(dlt->file_ctx) != 0) {
194                 /* Rotation failed, error already logged. */
>>>     CID 1220098:  Missing unlock  (LOCK)
>>>     Returning without unlocking "dlt->file_ctx->fp_mutex".
195                 return TM_ECODE_FAILED;
196             }
197         }
198
199         if (dlt->file_ctx == NULL) {
200             return TM_ECODE_FAILED;

*** CID 1220099:  Dereference before null check  (REVERSE_INULL)
/src/log-droplog.c: 199 in LogDropLogNetFilter()
193             if (SCConfLogReopen(dlt->file_ctx) != 0) {
194                 /* Rotation failed, error already logged. */
195                 return TM_ECODE_FAILED;
196             }
197         }
198
>>>     CID 1220099:  Dereference before null check  (REVERSE_INULL)
>>>     Null-checking "dlt->file_ctx" suggests that it may be null, but it has already been dereferenced on all paths leading to the check.
199         if (dlt->file_ctx == NULL) {
200             return TM_ECODE_FAILED;
201         }
202
203         char srcip[46] = "";
204         char dstip[46] = "";
11 years ago
Victor Julien 8a77e6bc8e Fix Coverity 1220097
*** CID 1220097:  Missing unlock  (LOCK)
/src/log-file.c: 160 in LogFileWriteJsonRecord()
154             }
155         }
156
157         /* Bail early if no file pointer to write to (in the unlikely
158          * event file rotation failed. */
159         if (aft->file_ctx->fp == NULL) {
>>>     CID 1220097:  Missing unlock  (LOCK)
>>>     Returning without unlocking "aft->file_ctx->fp_mutex".
160             return;
161         }
162
163         FILE *fp = aft->file_ctx->fp;
164         char timebuf[64];
165         AppProto alproto = FlowGetAppProtocol(p->flow);
11 years ago
Jason Ish fc2014ab40 Unregister for file rotation notification when a context is
de-initialized.  Required for unix-socket mode where
contexts come and go.
11 years ago
Jason Ish e1b97fed70 Add signal based file rotation for:
- alert debug log
- fast log
- stats log
- dns log
- drop log
- file log
- http log
- tls log
- eve/json log
11 years ago