Commit Graph

14767 Commits (3a6ecab0984745f0cefe3ca3c6dfee1eec7470d8)

Author SHA1 Message Date
Victor Julien 2f41e0ef2d output/tx: support substate completion flags 4 months ago
Victor Julien 67e2cb538a detect/app-layer-event: support sub-state progress handling 4 months ago
Victor Julien 59e2c5a40c detect/parse: initial substate support 4 months ago
Victor Julien 95365ce05b detect: support per tx sub states
Support for per transaction sub states: different state machines per
transaction type.

Skip engines not belonging to our substate.

Store tx_type in DetectTransaction.

Each protocol supporting sub states will register states from 1 and up.

To support:

Ticket: #8386.
4 months ago
Victor Julien b6bc025789 app-layer: start of substate API support
Allow registration of per substate progress name mappings.

Implement logic for getting sub-state names, id's.

Add transaction type and end of progress values to AppLayerTxData.

Introduce helpers to keep logic clean.
4 months ago
Shivani Bhardwaj 06db2e2698 detect/flowbits: add max usage per signature limit
Add a limit on the maximum number of times flowbits keyword that can be used in a
signature.

Task 8596
4 months ago
Shivani Bhardwaj 3462b126a3 detect: add max_flowbits option
Also move field around to pack holes and align the struct better.

Task 8596
4 months ago
Jason Ish 842b14ee1f smtp: don't create transaction for trailing quit
Also ensures that a quit or rset without a helo still creates a tx.

Ticket: #8728
4 months ago
Jason Ish e2a62dd1c0 smtp: handle pipelined replies on owning tx
Track the transaction id for each queued SMTP command so replies can update the
transaction that created the command instead of always using the current
transaction.

Ticket: #8393
4 months ago
Jason Ish 7b31f41878 smtp: complete transactions by progress state
Add directionality to completion states, and replace tx->done by checking for
both directions being complete.

This means that the transaction is now not complete until the server responds
to the clients of data marker, previously the tx was completed when the client
send end of data without waiting for the server response.

This keeps smtp:response_complete from being exposed before the server response
is parsed.

Ticket: #8393
4 months ago
Jason Ish c2728eee01 smtp: add firewall progress states
Add minimal SMTP progress states to support envelope validation before
moving to data.

Update SMTP, file and email keywords to hook into the appropriate
states.

Purposefully kept minimal for now as to not break the current idea of an
SMTP transaction, which is probably not ideal for firewall mode.

Ticket: #8393
4 months ago
Philippe Antoine 752dae89ea detect: add progress argument to SCDetectRegisterMpmGeneric
Will be needed by snmp
4 months ago
Philippe Antoine 7d024a840c rust: bindgen detect ThreadCtx keyword functions 4 months ago
Philippe Antoine 5fe920ec42 detect: make Http2ThreadBuf a generic DetectThreadBuf
to be used by snmp and other
4 months ago
Yash Datre 43bc2db41e detect: extend app-layer-protocol to accept a pipe-separated value list
Extend the app-layer-protocol keyword to accept a pipe-separated list of
protocol values, so a single rule can match any of several protocols:

    app-layer-protocol:[!]<proto1>|<proto2>[|...][,<qualifier>]...;

A non-negated list matches when the flow's protocol equals any listed value
(OR); a negated list matches when it equals none of them (NOR). The
single-value form and the trailing mode qualifier are unchanged.

Matching keeps the historical AppProtoEquals() equivalences by default
(dns/doh2, http/http1/http2, dcerpc/smb, ...). An `exact` qualifier selects
strict identity matching with no equivalences and no http umbrella; it
combines with a direction mode in any order. Because a flow is never the
generic ALPROTO_HTTP, `http,exact` is rejected at load.

Values are expanded once at rule load into an effective match-set bitmask, so
the per-packet match is a single bitmask test. Single-value rules remain
prefilterable; multi-value rules are excluded from prefiltering and an
explicit prefilter on them is rejected. Conflicting keyword combinations
(duplicate or overlapping negations, mixed positive/negated) are rejected at
load. Engine-analysis reports the effective match set.

Ticket: 7705
4 months ago
Philippe Antoine 7ec9d72d28 stream: disrupt never seen direction with async-oneside
Ticket: 8629

When we are in async-oneside mode, we see only one direction
of the traffic, and should not wait for the other direction
before cleaning up a transaction.
4 months ago
Philippe Antoine 392b6aee29 http1: limit the number of compression bombs per flow
Ticket: 8694

Otherwise, a flow full of small compression bombs is too slow
to process.

When the threshold is reached, decompression is skipped for the
rest of the flow.
4 months ago
Philippe Antoine bc41dcc854 flow: check ip family when comparing
Ticket: 8558

Do not accept an IPv6 as an IPv4 (even if the hash is likely
different in the first place)

Do the check also for ESP, and ebpf
4 months ago
Philippe Antoine 82c4190558 ftp: do not create more than max-tx transactions
Ticket: 8592

Fixes: 5ddd808e9b ("ftp: don't halt the flow when raising
too_many_transactions")

In the case we receive a big chunk of TCP data, we end up
creating much more than max-tx transactions, and have
quadratic complexity on this packet, even if all
these transactions get cleaned up at the end of the processing
of this packet.
4 months ago
Philippe Antoine 4a728464e6 ippair: check ip family when comparing
Ticket: 8559

Do not accept an IPv6 as an IPv4 (even if the hash is likely
different in the first place)
4 months ago
Amir Boussejra f917926165 ebpf: raise RLIMIT_MEMLOCK only on kernel >= 5.11
EBPFLoadFile() unconditionally raised RLIMIT_MEMLOCK to infinity and
aborted the eBPF/XDP load if the call failed.

Since Linux 5.11 BPF map memory is memcg-accounted and is no longer
charged against RLIMIT_MEMLOCK (https://lwn.net/Articles/829307/), so
raising the limit is unnecessary on those kernels.

Ticket: 8719
4 months ago
Philippe Antoine d62acf5d75 detect: use only one non-prefilter frame for prefilter
Ticket: 8590
4 months ago
Adam Kiripolsky b8d7f894be flow/manager: no flow timeout when hash-size < 10
Fix Flow Manager error when flows were not being timed out
in case flow.hash-size < 10.
This happened because calculation of variable rows_per_sec in
flow-manager.c rounded the value to zero.

This commit ensures that variable rows_per_sec is at least 1.

Ticket: 8710
4 months ago
Victor Julien 9e31a21aba detect/firewall: apply accept if last tx was skipped
In firewall mode, a accept:hook or accept:tx needs to lead to a accept
packet when the action is applied to the last TX. For this the code
relied of the `DetectTransaction::is_last` field, where the assumption
was that there would always be an inspection on the last transaction.
This assumption was wrong however, as transactions can be skipped for a
few reasons: not updated, fully inspected, unidirectional for the other
direction. This would cause the accept not be applied to the packet,
leading to a default drop.

The reason this wasn't noticed before is that until now the work had
focused on protocols that used sequential transactions (http/tls),
and/or short lived sequential unidir transactions (dns)

This patch addresses the issue by making a simple assumption: if the
last available transaction in the main detection loop is skipped, it
means it has been accepted before. Therefore we can apply the "accept
packet" logic in this case.

Bug: #8698.
4 months ago
Victor Julien ee1b9b9212 detect: use next tx info from iterator
In non-sequential transaction handling, the is_last set could be
incorrect.
4 months ago
Victor Julien b065a4bf98 http1: fix transaction iterator
The has_next field was not correctly set.
4 months ago
Victor Julien 3b351e2574 detect: move packet alert logic into helper 4 months ago
Victor Julien 695c9d8d20 detect/alert: split append func per packet/tx 4 months ago
Adam Kiripolsky 74bc0feb1a af-packet: invert ebpf g_flowv4_ok log flag
Fix how error messages are printed in a case error occurs in the ebpf
flow table code. The log flag g_flowv4_ok was inverted,
so the error messages were never printed.

The fix follows g_flowv6_ok flag code structure.

Ticket: 8704
4 months ago
Philippe Antoine aa59bb040b detect: allocate array on the heap, with a dedicated struct
buffer_type_id is a u32

We have a list per buffer of a list of AppProto
But the list of AppProto can grow maximum for the case of file.data
to all the alprotos supporting files.

Ticket: 8001
4 months ago
Victor Julien c1392d99a3 http/xff: harden code against http in detection-only 4 months ago
Victor Julien c01aa71b56 app-layer: treat pstate as non-NULL
In almost every case, if there is a alstate there is also a pstate. So
remove the conditional pstate handling, and replace it by
unconditionally using the pointer. Add debug validation to make sure the
assumption is and stays correct.

Explicitly handle the one exception in AppLayerParserParse, which
follows an error before the pstate is allocated, or when pstate
allocation itself fails.
4 months ago
Victor Julien 7cc25599de app-layer: enforce pstate as non-NULL 4 months ago
Victor Julien f4f521272a app-layer: cleanup inspect id getter
Since pstate can't be NULL, remove the conditional logic.
4 months ago
Victor Julien 5a770adc27 app-layer/parser: remove misleading comment
Fixes: 833a738dd1 ("http: fail tx creation if we cannot allocate user data")
4 months ago
Victor Julien 280a1e5a59 app-layer: minor code cleanup for GetStateProgress
It used the alstate name where it meant tx.
4 months ago
Victor Julien 7fe8f63a89 detect/parse: tighten hook parsing
Don't allow trailing :
4 months ago
Victor Julien f8daaac096 detect/file: rename file registration type 4 months ago
Victor Julien 0123cfd9ca detect/file.data: reduce scope for MPM datatype 4 months ago
Victor Julien 5ae427b146 detect/file: minor cleanup
Rename progress vars.
4 months ago
Victor Julien 0e3c946836 detect/file: remove unused registration fields 4 months ago
Victor Julien d81be73ba3 htp: remove duplicate entries in the event table 4 months ago
Philippe Antoine 9bf9d53c42 detect/sctp: sctp.chunk_type does not support multi integer
Ticket: 7929

As it supports prefilter
4 months ago
Philippe Antoine 4649bb3838 detect/file: filesize does not support multi integer
Ticket: 7929
4 months ago
Philippe Antoine a6fcbb1ab7 flow: factorize duplicated code for hashing 4 months ago
Philippe Antoine fe728d97d8 flow: use livedev for ftp-hash
Completes commit 7e725c650d

autofp-scheduler with value ftp-hash ends up using
FlowGetIpPairProtoHash which ignores the ports for ftp-looking
flows so that the ftp and ftp-data flow get processed by the
same thread.

As for the other cases, we want to use every other parameter
to compute the flow hash, inclusing the live device
4 months ago
Philippe Antoine f4388d45c6 ebpf: remove unused macro 4 months ago
Philippe Antoine 2ee4ef0ec5 features: add EBPF as a feature
for SV to run tests based on the presence of this feature
4 months ago
Philippe Antoine ee9b48493b ebpf: factorize duplicated code for key setting 4 months ago
Philippe Antoine a81031591e detect/krb5: move krb5.ticket_encryption to rust
Ticket: 8648
4 months ago
Philippe Antoine 8f0dbc0b63 detect/krb5: move krb5.cname and krb5.sname to rust
Ticket: 8648
4 months ago
Philippe Antoine 3327cf42f0 detect/krb5: move krb5_err_code to rust
Ticket: 8648

Make it a generic integer on the way
4 months ago
Jason Ish e560db9d1f ftp: don't match unset ftp.dynamic_port
Treat dyn_port 0 as an absent value so numeric comparisons do not
match FTP transactions without a negotiated data port.

Ticket: #8392
4 months ago
Jason Ish dd600d0860 ftp: mark ftp.reply as firewall supported
Ticket: #8392
4 months ago
Jason Ish c6ec50ab6f ftp: mark ftp.command_data as firewall supported
Ticket: #8392
4 months ago
Jason Ish 1f30641a83 ftp: mark ftpbounce as firewall supported
Ticket: 8392
4 months ago
Jason Ish 974241aa50 ftp: mark ftp.reply_received as firewall supported
Ticket: #8392
4 months ago
Jason Ish f59960d42b ftp: support STOU data transfers
Support STOU on the FTP data channel.

With STOU a filename is optional. If no filname is provided, use
"<stou>". The server does respond with the filename to use, but there
can be a race condition in getting this filename and setting up file
storage before data starts flowing.

Ticket: #8664
4 months ago
Jason Ish e65bf4c905 ftp: support APPE data transfers
Support the APPE (append) command on the ftp data channel. Like STOR,
APPE uploads file content on the data channel.

Ticket: #8664
4 months ago
Jason Ish 5856ced29c ftp: support LIST and MLSD data channels
Support LIST and MLSD on the ftp data channel.

Ticket: #8664
4 months ago
Jason Ish be94ab952a ftp: register ftp.mode at response_complete
Also mark as supported by the firewall.

Ticket: #8392
4 months ago
Jason Ish fc1546e25e ftp: register ftp.completion_code at response_complete
Ticket: #8392
4 months ago
Jason Ish 1b289daea3 ftp: support nlst on the data channel
Ticket: #8664
4 months ago
Jason Ish 6bc2969b8d ftp: mark ftpdata_command as firewall supported 4 months ago
Jason Ish f93268e531 ftp: mark ftp.dynamic_port as firewall supported
Ticket: #8392
4 months ago
Jason Ish 41cad78506 ftp: register ftp.dynamic_port at response completion
Register ftp.dynamic_port at the FTP transaction completion progress
instead of progress 0. This allows ftp.dynamic_port to be used in
ftp:response_complete.

Ticket: #8392
4 months ago
Jason Ish 0d566f90ce ftp: mark ftp.command as firewall supported
Ticket: #8392
4 months ago
Jason Ish a6ce31d50d ftp: register ftp.command_data at request completion
Register ftp.command_data with the FTP request completion progress so it
can be used by firewall rules on the ftp:request_complete hook.

Ticket: #8392
4 months ago
Jason Ish bf63c574d3 ftp: register ftp.command buffer at request completion
Register ftp.command with the FTP request completion progress so it can
be used by firewall rules on the ftp:request_complete hook.

Ticket: #8392
4 months ago
Philippe Antoine f56501215f detect/file: reorder struct fields to reduce padding
and make scan-build happy
4 months ago
Philippe Antoine 89dbce1b46 detect: convert tx_progress to uint8_t 4 months ago
Jeff Lucovsky 30d4edf9eb detect: revert 2eede11195
Revert issue 8619 fix in favor of a more general change that
sets INSPECTED_T{S,C} correctly on passed flows. This makes clean no
longer need the FLOW_ACTION_PASS special case to free those
transactions.

Issue: 8621
4 months ago
Jeff Lucovsky 006e21c1cc app-layer: fix inverted tx inspected flag check
Issue: 8628

AppLayerParserSetTransactionInspectId() had an inverted guard when
tagging completed transactions as inspected: it set the INSPECTED flag
only on txs that already had it, so a finished tx was never newly
marked.

On a normal flow DetectRunTx() sets the same flag and masks the
mistake. On a passed flow -- a `pass` rule or a pass-the-flow exception
policy -- detection is skipped and this function is the only thing that
marks txs inspected. With the inverted guard the transactions are never
flagged, AppLayerParserTransactionsCleanup() never frees them, and the
per-flow transaction list grows without bound while each packet
re-scans it, giving O(n^2) cleanup cost.

This is an unintended regression from 834378ff88.
4 months ago
Philippe Antoine d9fae18432 swf: prevents overflow with bad config value
Ticket: 8642

Do not allocate too much by using the config value, when the flash
file does not require that much data anyways
4 months ago
Philippe Antoine 52490b8c26 ftp: do not error the flow on file before port
Ticket: 8659

If a client sends a SOTR/RETR command before doing a PASV/PORT
command, ther server may reply
425 Use PORT or PASV first.\r\n
and allow the client to continue sendinf other commands

So, Suricata should not put the whole flow into error, it just
sets an event, and continues to parse further
4 months ago
Philippe Antoine f092d07f6d decode/sctp: chunk_cnt can be a u16
Ticket: 8661
4 months ago
Philippe Antoine 3ca2ed25a3 detect/datajson: check json objects are string as expected
Ticket: 8624
4 months ago
Victor Julien 2b19f86ee6 Revert "af-packet: speed up thread sync during startup"
This reverts commit 923ad6af77.

Several issues have been reported:

1. non-deterministic thread to queue mapping (privately reported)

2. race condition causing IPS mode to loose packets, or get stuck
   completely, ticket 8667.

Ticket: #8667.
4 months ago
Philippe Antoine ac1b3cc1ef windows: always quote path for windows functions needing it
Ticket: 8600

CreateServiceA doc states for example :

> If the path contains a space, it must be quoted so that it is
  correctly interpreted.

Also fixes strlcat usage and check return value to error out on
truncated path
4 months ago
Philippe Antoine 114c80099c suricata: make FUZZING a feature
so as to skip SV tests that would fail when we are building in unsafe
fuzzing mode
4 months ago
Philippe Antoine 5a03fbfc61 detect/engine-analyzer: add note for pcre with \X
Ticket: 8634
4 months ago
Jason Ish 2fe4bb2872 ftpdata: ignore direction in ftpdata_command
The ftpdata_command would never match a RETR in the to_server direction,
or a STOR in the to_client direction, this effectively makes the
ftpdata_command applicable to passive mode only.

Instead, remove the directionality on the ftpdata_command. Its "meta"
information passed from the control channel and isn't really
directional. I think the idea was to abstract away active/passive from
the rule writer, but unfortunately doesn't allow the ftpdata_command
keyword to work in the more strict firewll mode.

Ticket: #8663
4 months ago
Jason Ish d346e469c5 ftp: skip ts inspection on tc only transactions
In FTP, the first transaction is a banner from the server. Skip TS
inspection on this transaction.

Allows firewall mode to get past this transaction and onto the next.

Ticket: #8662
4 months ago
Philippe Antoine 097975e289 fuzz: forbid usage of pcre with \X
Ticket: 8634
4 months ago
Abhijeet Singh 28b10fb042 util/log: rotate log file periodically
Fix log file not rotating during zero traffic periods by triggering rotation logic every second

Ticket: https://redmine.openinfosecfoundation.org/issues/8115
5 months ago
Victor Julien 7cb64cc20f nfq: suppress gcc analyzer warnings 5 months ago
Victor Julien 79ef58be12 mpm/hs: remove useless pointer check
Pointer can't be NULL, so don't check it.

Helps gcc analyzer as well.
5 months ago
Victor Julien f434732c73 util/var-name: help gcc analyzer
Help it understand TAILQ.
5 months ago
Victor Julien 32fc437568 spm/bm: match suff array to pattern size
Avoids gcc -fanalyzer warning about out of bounds write to the array.
5 months ago
Victor Julien 5179af5557 affinity: gcc analyzer warnings
The double strchr confused gcc -fanalyzer.
5 months ago
Victor Julien f9cf9c1de7 output: suppress gcc analyzer warnings
By teaching about TAILQ.
5 months ago
Victor Julien e2f9211727 log-pcap: address gcc analyzer warnings
Reopen file descriptor for lz4 with the init function. This helps
code analyzers understand the handle it's leaked.

Improve flow of profiling dumps to avoid analyzer confusion around the
file descriptor.

Suppress TAILQ related warnings.
5 months ago
Victor Julien 65f1a022f0 detect/ip_proto: clean up parsing function
Helps address a gcc -fanalyzer warning.
5 months ago
Victor Julien ff7fae54d2 detect/flowvar: help gcc -fanalyzer
Add debug validation statement to assert prev pointer is not NULL.
5 months ago
Victor Julien 05eac977f0 detect/sigorder: handle allocation failure
Addresses a gcc -fanalyzer warning.
5 months ago
Victor Julien caa9ddaa26 decode/tcp: only set data ptr for valid option lengths 5 months ago
Victor Julien 32414573a7 conf: assist gcc -fanalyzer
Work around TAILQ false positive.
5 months ago
Victor Julien 6e1f96f91a tm/queues: assist gcc -fanalyzer
Work around TAILQ false positive.
5 months ago
Victor Julien a5effad936 frames: avoid possible undefined behavior
Code analyzer flagged FrameCopy as a possible source of UB due to
both pointers passed to memcpy being the same.

app-layer-frames.c: In function ‘FrameCopy’:
app-layer-frames.c:236:5: warning: overlapping buffers passed as arguments to ‘memcpy’ [-Wanalyzer-overlapping-buffers]
  236 |     memcpy(dst, src, sizeof(*dst));
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  ‘FramePrune’: events 1-8
    │
    │  750 | static void FramePrune(Frames *frames, const TcpStream *stream, const bool eof)
    │      |             ^~~~~~~~~~
    │      |             |
    │      |             (1) entry to ‘FramePrune’
    │......
    │  766 |     for (uint16_t i = 0; i < frames->cnt; i++) {
    │      |                          ~~~~~~~~~~~~~~~
    │      |                            |
    │      |                            (2) following ‘true’ branch... ─>─┐
    │      |                                                              │
    │      |                                                              │
    │      |┌─────────────────────────────────────────────────────────────┘
    │  767 |│        if (i < FRAMES_STATIC_CNT) {
    │      |│           ~
    │      |│           |
    │      |└──────────>(3) ...to here
    │      |            (4) following ‘true’ branch (when ‘i <= 2’)... ─>─┐
    │      |                                                              │
    │      |                                                              │
    │      |┌─────────────────────────────────────────────────────────────┘
    │  768 |│            Frame *frame = &frames->sframes[i];
    │      |│                            ~~~~~~~~~~~~~~~~~~
    │      |│                                           |
    │      |└──────────────────────────────────────────>(5) ...to here
    │  769 |             FrameDebug("prune(s)", frames, frame);
    │  770 |             if (eof || FrameIsDone(frame, acked)) {
    │      |                ~
    │      |                |
    │      |                (6) following ‘false’ branch... ─>─┐
    │      |                                                   │
    │......
    │      |                                                   │
    │      |┌──────────────────────────────────────────────────┘
    │  779 |│                const uint64_t fle = FrameLeftEdge(stream, frame);
    │      |│                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    │      |│                                     |
    │      |└────────────────────────────────────>(7) ...to here
    │      |                                      (8) calling ‘FrameLeftEdge’ from ‘FramePrune’
    │
    └──> ‘FrameLeftEdge’: event 9
           │
           │  257 | static inline uint64_t FrameLeftEdge(const TcpStream *stream, const Frame *frame)
           │      |                        ^~~~~~~~~~~~~
           │      |                        |
           │      |                        (9) entry to ‘FrameLeftEdge’
           │
         ‘FrameLeftEdge’: event 10
           │
           │suricata-common.h:323:27:
           │  323 |         #define BUG_ON(x) assert(!(x))
           │      |                           ^~~~~~
           │      |                           |
           │      |                           (10) following ‘false’ branch (when ‘frame_offset <= app_progress’)... ─>─┐
           │      |                                                                                                     │
util-validate.h:95:36: note: in expansion of macro ‘BUG_ON’
           │   95 | #define DEBUG_VALIDATE_BUG_ON(exp) BUG_ON((exp))
           │      |                                    ^~~~~~
app-layer-frames.c:266:5: note: in expansion of macro ‘DEBUG_VALIDATE_BUG_ON’
           │  266 |     DEBUG_VALIDATE_BUG_ON(frame_offset > app_progress);
           │      |     ^~~~~~~~~~~~~~~~~~~~~
           │
         ‘FrameLeftEdge’: event 11
           │
           │      |                                                                                                     │
           │      |┌────────────────────────────────────────────────────────────────────────────────────────────────────┘
           │  269 |│    if (frame->len < 0) {
           │      |│        ~~~~~^~~~~
           │      |│             |
           │      |└────────────>(11) ...to here
           │
    <──────┘
    │
  ‘FramePrune’: events 12-13
    │
    │  779 |                 const uint64_t fle = FrameLeftEdge(stream, frame);
    │      |                                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
    │      |                                      |
    │      |                                      (12) returning to ‘FramePrune’ from ‘FrameLeftEdge’
    │......
    │  783 |                 FrameCopy(nframe, frame);
    │      |                 ~~~~~~~~~~~~~~~~~~~~~~~~
    │      |                 |
    │      |                 (13) calling ‘FrameCopy’ from ‘FramePrune’
    │
    └──> ‘FrameCopy’: events 14-15
           │
           │  234 | static void FrameCopy(Frame *dst, Frame *src)
           │      |             ^~~~~~~~~
           │      |             |
           │      |             (14) entry to ‘FrameCopy’
           │  235 | {
           │  236 |     memcpy(dst, src, sizeof(*dst));
           │      |     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
           │      |     |
           │      |     (15) ⚠️  overlapping buffers passed as arguments to ‘memcpy’
           │
In file included from suricata-common.h:129,
                 from app-layer-frames.c:25:
/usr/include/string.h:47:14: note: the behavior of ‘memcpy’ is undefined for overlapping buffers
   47 | extern void *memcpy (void *__restrict __dest, const void *__restrict __src,
      |              ^~~~~~
5 months ago
Victor Julien 188376b577 output/filestore: refactor file descriptor handling
To assist code analyzers. Gcc -fanalyzer got confused about it.

Also test data pointer and length before calling fwrite and check the
result better.

Use a single atomic for the max open files check.
5 months ago
Samaresh Kumar Singh 565e138754 pcap-file: skip setvbuf on non-seekable streams
Reading a pcap from /dev/stdin or a named pipe currently fails with "failed to get first packet timestamp. pcap_next_ex(): -1" because InitPcapFile calls setvbuf on the FILE* underlying the pcap handle after libpcap has already consumed the pcap header. On a non-seekable fd glibc cannot recover from that and the next read returns -1.

Detect non-regular files via fstat and skip setvbuf in that case so the read keeps working on pipes, fifos and stdin.

Accept pcap-file.buffer-size values of 0, which disables setvbuf buffering as an explicit opt-out, or PCAP_FILE_BUFFER_SIZE_MIN (4 KiB) to PCAP_FILE_BUFFER_SIZE_MAX (64 MiB). Treat any non-zero setvbuf return value as an error, not just negative values.

When pcap-file.buffer-size fails to parse, retain the default buffer size instead of falling through and setting it to 0. The branches are now mutually exclusive so only one of the parse-error, accepted, or out-of-range messages is logged.

Update the user guide: --pcap-file-buffer-size now documents valid values of 0 (disables setvbuf buffering) or 4 KiB to 64 MiB, and pcap-file.rst notes that 0 is the opt-out for non-seekable sources such as stdin and named pipes.
Bug: #8464.
5 months ago
Samaresh Kumar Singh df353242bd detect: fail thread init on keyword ctx error
DetectEngineThreadCtxInitKeywords returns TM_ECODE_FAILED when a per-thread keyword init fails (for example DetectFilemagicThreadInit), but ThreadCtxDoInit discarded that result and still returned OK. The detect thread then ran with a partially initialized keyword context array, producing indeterminate results. Propagate the failure so the callers abort thread init and clean up.

Add a unit test that registers a keyword whose thread init fails and verifies that DetectEngineThreadCtxInit reports the failure.

Ticket: #8237
5 months ago
Philippe Antoine 6bb271cee9 conf: uses SCConfGetNonNull
Ticke: 8651

Uses it in place when we dereferenced the value straight away
after checking SCConfGet result but not its value
5 months ago
Philippe Antoine a9e1dff4a6 conf: introduce SCConfGetNonNull
Ticket: 8651

Behaves like SCConfGet but returns 0 on null value
5 months ago
Victor Julien d154484cc6 detect/firewall: support hook LTE mode for built-in hooks
LTE support depended on registered hook names, but did not support the
built-in names. This commit adds the support.

Ticket: #8645.
5 months ago
Victor Julien b02fa53134 detect: add helper for getting hook name
To fetch hook name from app-layer, or use built-ins.
5 months ago
Victor Julien 2a2cb40336 detect: misc debug log additions 5 months ago
Victor Julien 569d27e153 detect: propagate inspect engine setup failures 5 months ago
Victor Julien d64954a873 detect: don't register unrelated inspect engines
For rules that specify an explicit app-layer hook,
e.g. http1:request_headers, don't register inspect engines for
other protocols like HTTP/2. These have their own progress tracking,
so should be excluded from these rules.
5 months ago
Urval 3b9dc5ad37 output-json: avoid freeing caller-owned JSON builder
EveEmailLogJsonData() freed the provided SCJsonBuilder when
SMTP state was unavailable, even though ownership remains with
the caller. The caller may continue using the builder for
cleanup after the function returns failure.

Return failure without freeing the builder and add defensive
NULL checks in EveSmtpDataLogger().

Signed-off-by: Urval Kheni <urvalkheni777@gmail.com>
5 months ago
Denis Balashov 17151571b8 detect: guard rate filter callback registration, return bool on failure
SCDetectEngineRegisterRateFilterCallback() dereferences the result of
DetectEngineGetCurrent() unconditionally. Add a NULL guard with
SCLogError and return false so callers can detect registration failure.

Flagged by Svace and confirmed by gcc -fanalyzer.

Ticket: 8560
5 months ago
Denis Balashov 4d4c6227e1 detect/parse: assert HashListTableLookup results in duplicate sig check
Add DEBUG_VALIDATE_BUG_ON() at four sites in DetectEngineSignatureIsDuplicate()
where HashListTableLookup() is assumed to return non-NULL. Documents the
invariant that every Signature in sig_list has a dup_sig_hash_table entry
and catches violations in debug builds.

Flagged by Svace static analyzer.

Ticket: 8635
5 months ago
Denis Balashov 3828de20ed decode: propagate PacketAlertCreate failure instead of crashing
PacketAlertCreate is called from PacketInit on the packet allocation
path. Make PacketInit return bool and propagate the NULL result from
PacketAlertCreate up through PacketGetFromAlloc, which already returns
NULL to signal allocation failure to its callers.

Update the UNITTESTS-only helpers in defrag.c accordingly: helpers
returning Packet * use an explicit NULL check; the one returning int
keeps the existing FAIL_IF style.
5 months ago
Denis Balashov 7124fdebf1 tests/fuzz: guard SCCalloc result in fuzz_decodebase64
If SCCalloc fails, decoded is NULL and the subsequent SCBase64Decode
call would dereference it. Return early on allocation failure.
5 months ago
Denis Balashov 2c16fb716b util/mpm-hs: fix null check parentheses; simplify SCHSConfigInit
Two fixes:
- Remove extra parentheses in existing NULL check: (*ext) -> *ext,
  which was causing the cocci script to miss the check as a false negative.
- Simplify SCHSConfigInit to return SCCalloc() directly; the caller
  in detect-engine.c already checks the return value for NULL.
5 months ago
Denis Balashov 04a1de1192 detect/reference: guard SCStrdup calls in DetectReferenceParse
Two SCStrdup calls that set ref->key had no NULL check. On allocation
failure the pointer would be used immediately, causing a NULL dereference.
5 months ago
Denis Balashov 01f64ea335 detect/flowbits: check SCRealloc result before overwriting pointer
The original pointer was overwritten with the SCRealloc result before
checking for NULL, causing a memory leak if reallocation fails.
Check the temporary pointer first before assigning.
5 months ago
Denis Balashov 21bcbe14c1 detect/alert: guard SCStrdup result before use
SCStrdup result was stored and immediately used without checking for
NULL, which would cause a NULL dereference if allocation fails.
5 months ago
Denis Balashov b2cd08bb91 util/log-redis: guard SCCalloc result for redis stream format
When Redis output is configured in stream/xadd mode with a positive
stream-maxlen, SCConfLogOpenRedis() allocates redis_setup.stream_format
and immediately passes it to snprintf().

If SCCalloc() fails, snprintf() receives a NULL destination pointer and
the process can crash during Redis output initialization. Handle this
unrecoverable setup failure with FatalError(), matching the surrounding
Redis initialization error handling.

Ticket: 8588
5 months ago
Giuseppe Longo dc44447ce6 detect/sctp: add sctp.chunk_data sticky buffer
Add a sctp.data sticky multi-buffer that allows content matching on the bytes
inside any of the SCTP DATA chunks extracted.

Ticket #4251
5 months ago
Giuseppe Longo 1413b082d3 decode/sctp: set p->payload to data chunk
Track the first DATA chunk's data offset and length during chunk iteration,
then reassign p->payload to point at the user data.

When no DATA chunk is present (INIT, SACK, HEARTBEAT, etc.),
payload_len is set to 0 since there is no application data.

Ticket #4251
5 months ago
Giuseppe Longo ede1bce923 output/json: add sctp metadata to alerts
Log SCTP-specific fields in the EVE JSON "sctp" object for alert events.

Ticket #4251
5 months ago
Giuseppe Longo 2116c3cafc detect/sctp: add sctp.vtag keyword
Add a U32 numeric keyword to match the SCTP verification tag
from the common header with prefilter support.

Ticket #4251
5 months ago
Giuseppe Longo 855f49b649 detect/sctp: add sctp.chunk_cnt keyword
Add a U8 numeric keyword to match the number of SCTP chunks
parsed in a packet with prefilter support.

Ticket #4251
5 months ago
Giuseppe Longo 88f17d7b20 detect/sctp: add sctp.chunk_type keyword
Add a U8 numeric keyword to match the first SCTP chunk type in a packet
with prefilter support.

Ticket #4251
5 months ago
Giuseppe Longo bbd0ecb616 detect/sctp: add sctp.hdr sticky buffer
Implement a sticky buffer to match the raw SCTP header
(common header + chunks)

Ticket #4251
5 months ago
Giuseppe Longo 21d35f6b37 decoder/sctp: extend decoder
Extend the SCTP decoder to parse chunk headers after the 12-byte common
header. Each chunk is validated for minimum header size and length
consistency per RFC 4960 sec 3.2.

Add SCTPChunkHdr and SCTPVars structs to track per-packet chunk metadata

Add five new decoder events for protocol violations:
- SCTP_CHUNK_TOO_SMALL: insufficient data for a chunk header
- SCTP_CHUNK_LEN_INVALID: chunk length < 4 or exceeds packet
- SCTP_INIT_CHUNK_NOT_ALONE: INIT/INIT_ACK bundled (RFC 4960 sec 6.10)
- SCTP_INIT_WITH_NON_ZERO_VTAG: INIT with vtag != 0 (RFC 4960 sec 8.5.1)
- SCTP_DATA_WITH_ZERO_VTAG: DATA chunk with vtag == 0

Ticket #4251
5 months ago
Martin Rehak 2ce2ebcdba suricata: guard RLIMIT_NPROC usage
Only use RLIMIT_NPROC when the platform exposes that resource limit constant.
5 months ago
Martin Rehak f34acfdeed util/cpu: enable SPARC misalignment emulation at startup
Call a SPARC-specific helper during pre-init so the kernel emulates unaligned accesses for this process instead of terminating on alignment faults. This matches the Solaris/SPARC portability fix that motivated the original patch.
5 months ago
Martin Rehak 1faa2921c1 util/syslog: guard LOG_FTP for Solaris
Only expose the ftp facility when the platform syslog headers define LOG_FTP.
5 months ago
Martin Rehak 823322cb1c util/time: avoid tm_gmtoff on Solaris
Skip tm_gmtoff and tm_zone initialization on Solaris where those struct tm members are not available.
5 months ago
Martin Rehak cf65f7692a build/solaris: use __sun and Solaris byteorder helpers
Replace uses of the non-standard sun macro with __sun and use Solaris byte swap helpers from <sys/byteorder.h>. This keeps the Solaris-specific code paths reachable when building with standard-conforming toolchains.
5 months ago
Martin Rehak 955827bc59 util/path: handle missing d_type definitions on Solaris
Guard DT_REG usage so directory walking code still builds on platforms where dirent does not expose d_type or DT_REG, such as Solaris.
5 months ago
Antoine Abou Faysal a3ab00e920 detect/dataset: add match subdomain option
Ticket: 8385

Add a new match subdomain option that enables blocking a domain and all its subdomains using datasets.
5 months ago
Shivani Bhardwaj 899eb38691 flowbits: deprecate toggle command
toggle command is not used by any major rulesets and increases the state
complexity of flowbits management. Also, all operations can be carried
out with the combination of other available commands. So, remove it.

Task 8595
5 months ago
Jason Ish 546209ff12 bindgen: fix include ordering
At some point, bindgen include ordering changed such that
AppLayerGetFileState was being bindgen'd as opaque, as the definition of
StreamBufferingConfig was not available when bindgen hit
AppLayerGetFileState, and bindgen processes in order.

Move the util includes before the app-layer includes to fix the ordering
problem, but still keep util includes grouped.

The sys diff is large as many things have been re-ordered.
5 months ago
Philippe Antoine 42fc785e12 fuzz/iprep: initialize to 0 buffer buffer before writing to it
And make MSAN happy
5 months ago
William Ling e7edc2a1e2 unittests: convert util-spm tests to FAIL/PASS API
Issue: 6334
5 months ago
Philippe Antoine af7fad5514 detect: allocate arrays on the heap
buffer_type_id is a u32

Ticket: 8001
5 months ago
Philippe Antoine 2eede11195 detect: clean app-layer txs when we pass the flow
Ticket: 8619

Do not wait to run inspection on the other side of transactions
as we do not run any tx detection on passing flows.
Avoids accumulating txs
5 months ago
Philippe Antoine daf68dc36f http2: split progress per direction
Ticket: 8518

Keywords that work for HTTP2 headers match now as soon as possible

A push promise is now considered like a headers frame with regards
to the progress (no dedicated "reserved" progress/state)

http.protocol and http.stat_msg keywords are now registered at
earliest progress, since these are synthetic like "HTTP/2" and
not really seen on the wire.

http.request_line and http.response_line match only on data,
and not on headers, since we must wait the end of headers
to be sure to have the full line

http2.size_update now matches at headers progress as it should

http2.frametype, http2.errorcode, http2.priority now match like
http2.window, when the tx is complete from both sides, as a
half-closed client may still send priority, rst_stream
or window_update frames
5 months ago
Philippe Antoine 567e824e44 fuzz: add target for iprep
Ticket: 3589
5 months ago
Philippe Antoine 29795be5a2 fuzz: make more unit test utilities available for fuzzing 5 months ago
Jason Ish 6687618b67 misc: remove log-cf-common
It was only used to http-log which is now removed.
5 months ago
Jason Ish 3806bf4260 util-time: relocate timestamp format unit test from log-cf-common
log-cf-common is not longer needed with the removal of http-log, but this test
is still valid, so move until util-time.
5 months ago
Jason Ish 865b7243a0 http-log: remove support for http-log
http-log was deprecated in Suricata 8, and marked for removal in
Suricata 9.0.

Ticket: #7232
5 months ago
Giuseppe Longo 0b20011a9f llmnr: implement sticky buffers
Add detection keywords for LLMNR protocol inspection:
- llmnr.queries.rrname
- llmnr.answers.rrname
- llmnr.authorities.rrname
- llmnr.additionals.rrname
- llmnr.response.rrname

LLMNR reuses the existing DNS functions since it follows the same
protocol structure. The implementation registers LLMNR-specific keywords
that leverage the DNS data extraction functions.

Both to_server and to_client directions are supported.

Ticket #8366
5 months ago
Giuseppe Longo 8f205bb34f llmnr: implement logger
This adds an LLMNR protocol logger that reuses existing DNS functions,
following the same approach as the mDNS logger:

- No grouped logging
- Rdata is logged in a field that is named after the rdata type
- Types are logged in lower case
- Flags are logged as an array

Ticket #8366
5 months ago
Giuseppe Longo 13df0f7a06 llmnr: implement parser
This adds a parser for LLMNR protocol over both UDP and TCP.

The parser reuses the existing DNS functions since LLMNR shares
the same wire format as DNS, but implements its own protocol-specific
validation:

- LLMNR-specific flag checks (C, TC, T bits)
- Opcode validation (only standard query opcode 0 is valid)
- An Event is set if Z-flag is set, since it's must be zero per RFC4795

LLMNR transactions inherit DNS behavior where each packet creates a new state
with one transaction.

Ticket #8366
5 months ago
Victor Julien 9e82ff82e2 fuzz: use heap threadvars allocations
Use new allocator to properly set up thread storage.
5 months ago
Victor Julien cefee1390e detect/threshold: don't double init per thread cache
Can get called multiple times in the multi-tenancy case.
5 months ago
Victor Julien f67dadc3d8 detect/threshold: fix unittests for storage based cache 5 months ago
Victor Julien c27868a8c5 threshold: use seed consistently in hashing
Use for IPv6 in the main hash.

Update IPv4 thread cache to also use a seed. For this the thread
initialization is done at thread init instead on the first packet. The
thread ctx is no longer stored in a thread_local, but instead uses the
thread storage API to store in the ThreadVars. This way it will stay
active during rule reloads as well.

Ticket: #8617.
5 months ago
Victor Julien b742d58544 hash: allow registing with a seed value
Seed value will have to be used by the caller's hash function.
5 months ago
Victor Julien 730ff5075d threads: use threadvars memory helpers 5 months ago
Victor Julien ad1459df72 threads: add threadvars allocator and free func
Mostly meant to help unittests and fuzz targets alloc the storage
correctly.
5 months ago
Victor Julien b11aa94d42 decode/vlan: implement max layers for IEEE8021ah
Ticket: #8615.
5 months ago
Victor Julien 377462ea63 defrag: decrement memuse on alloc failure
Ticket: #8613.
5 months ago
Jason Ish 9f40968bba rust/ffi: bindgen thread storage
Ticket: #8445
5 months ago
Victor Julien 736f50600f mpm/hs: fix compile warnings
CC       util-mpm-hs-cache.o
util-mpm-hs-cache.c:301:59: error: implicit conversion loses integer precision: '__size_t' (aka 'unsigned long') to 'uint32_t'
      (aka 'unsigned int') [-Werror,-Wshorten-64-to-32]
  301 |         SCSha256Update(hasher, (const uint8_t *)ref_info, strlen(ref_info));
      |         ~~~~~~~~~~~~~~                                    ^~~~~~~~~~~~~~~~
util-mpm-hs-cache.c:310:46: error: implicit conversion loses integer precision: 'size_t' (aka 'unsigned long') to 'uint32_t'
      (aka 'unsigned int') [-Werror,-Wshorten-64-to-32]
  310 |     if (!SCSha256FinalizeToHex(hasher, hash, hash_len)) {
      |          ~~~~~~~~~~~~~~~~~~~~~               ^~~~~~~~
2 errors generated.
5 months ago
Victor Julien e0b501a4b7 detect: cleanup last tx logic
Move into DetectTransaction.
5 months ago
Victor Julien 3d00e73d91 detect: make progress values uint8_t
Also reflect that it can be >= 48, like in prefilter.
5 months ago
Victor Julien a9b3ad49ea detect/firewall: minor code cleanup 5 months ago
Victor Julien 4db84cfa28 detect/firewall: clean up apply accept logic
Use end state from tx.

Handle flow control from inside the function consistently.
5 months ago
Victor Julien 68885e75e1 detect/firewall: refactor per tx rule result handling
Break out the 3 options: match, partial match, no match for firewall
into separate functions.

Additionally, handle the re-match case for matches on a hook where the
progress value didn't yet progress further. In this case the continue
inspection logic revisits the rule and the accept needs to be
re-applied.
5 months ago
Juliana Fajardini a783007408 detect/bypass: ban bypass keyword for firewall mode
Related to
Ticket #8551
5 months ago
Juliana Fajardini edaa912ed9 detect: ban `replace` keyword for firewall mode
Ticket #8551
5 months ago
Juliana Fajardini 6e71ff3013 detect/parse: allow banning keywords with fw mode
Related to
Ticket #8551
5 months ago
Juliana Fajardini 04a7674512 detect/parse: allow banning keywords from fw rules
Related to
Ticket #8551
5 months ago
Philippe Antoine e089ac9775 util/mpm-ac: preallocate on the heap rather than stack
Ticket: 8001

As the the size of the allocation can get large
5 months ago
Philippe Antoine dc5185e355 util/mpm-ac-ks: preallocate on the heap rather than stack
Ticket: 8001

As the the size of the allocation can get large
5 months ago
Philippe Antoine 94a3e03903 util/mpm: add MpmCtx argument to MpmInitThreadCtx
Ticket: 8001

Will allow algorithms such as ac to use the MpmCtx, especially
the number of patterns, to preallocate some structures.

For detect engine PatternMatchThreadPrepare, create a dummy
MpmCtx out of all the MpmCtx in the DetectEngineCtx,
and get the max value for the number of patterns
5 months ago
Philippe Antoine 25bf59f238 util/spm: explicit needle_len is u16
So, stack allocation is bounded

Ticket: 8001
5 months ago
Victor Julien 9c76480ac3 detect/firewall: further simplify flow control
For the last for progress case we can just break on a firewall drop.

For the accept:flow and accept:tx cases the next sig (if any) will check
the flow/tx flag and manage flow control from there.
5 months ago
Victor Julien bb6dc93789 detect/firewall: clean up per rule run check 5 months ago
Victor Julien 035e8bc851 detect/firewall: minor flow control cleanup 5 months ago
Victor Julien bb7aff36a8 detect/firewall: simplify pre-check flow
Simplify pre-check logic. Pre-check takes care of enforcing
FLOW_ACTION_ACCEPT, APP_LAYER_TX_ACCEPT and default policy enforcement
before the current rule's hook. This should be done in firewall mode for
each rule regardless whether it is a firewall or TD rule.

No need to track verdict state anymore.
5 months ago
Victor Julien 68f73302ce detect/firewall: clean up tx inspection loop 5 months ago
Victor Julien a86fe01cc3 detect/firewall: consolidate action handling
Step towards consolidating all action handling into a central location.
5 months ago
Victor Julien 1ad9c3ec29 detect/firewall: clean up pre-check policy logic 5 months ago
Victor Julien 52967c69ec detect/firewall: fix accept:tx,alert in default policy 5 months ago
Victor Julien 247c6a2333 detect/firewall: inject alert before default policy
If default policy is invoked because of missing rules for next hooks,
make sure to inject an alert before the next hook policies might do so.
5 months ago
Victor Julien 90a837cef3 detect/firewall: update discarded logic
Only count alert queue overflow here, not alerts in the queue after a drop.
5 months ago
Victor Julien 57b16c964e detect/firewall: drop in fw mode does not include alert
In TD mode the drop action also includes alert.

In firewall mode it should not to stay in line with accept.

Ticket: #8601.
5 months ago
Victor Julien f1090da254 detect/firewall: log alert for app default with alert
Fix missing alert on drop:flow,alert
5 months ago
Victor Julien 485f5243d5 detect/firewall: improve handle fw alert handling
More clearly define the relationship between PacketAlerts for firewall
and threat detection events.

Also no longer count firewall_discarded if drop rule came before a
another rule, causing the later rule to not be evaluated/alerted.

When packet:filter and app:filter alert appear in a single alert queue,
handle accept:hook by keeping track of the detect_table.
5 months ago
Victor Julien 7e9402a2e0 detect/alert: fix suppressed drop handling
If drop was issued for suppressed rule, still consider it for the
next alert.
5 months ago
Victor Julien 508bb71d78 detect: minor action handling cleanup
Don't run exact same check twice.
5 months ago
Victor Julien 9bcf0f332b detect/firewall: fix TD drop:flow after FW accept:flow
Threat detection can drop a flow that is but in accept:flow by the
firewall.
5 months ago
Victor Julien ecf2161f3b detect/firewall: fixup debug message 5 months ago
Victor Julien fb9747df8e detect/firewall: minor code cleanup 5 months ago
Victor Julien 8572088b0f eve/alert: firewall default policy logging improvements
Add firewall.hook to indicate the hook that the policy was set on.

Ticket: #8566.
5 months ago
Victor Julien dc4c22e906 detect/firewall: support alert in packet default policy
Support `alert` as a secondary action in packet firewall policies.

To implement this a Signature object is created per policy that uses
alert, and this is stored in a array table. When the policy is applied
the signature is looked up and used in the PacketAlert.

Ticket: #8566.
5 months ago
Victor Julien 2d4f1968b8 detect/firewall: support alert in default app policy
Support `alert` as a secondary action in app-layer firewall policies.

To implement this a Signature object is created per policy that uses
alert, and this is stored in a hash table. When the policy is applied
the signature is looked up and used in the PacketAlert.

Ticket: #8566.
5 months ago
Victor Julien 6e037d9783 detect/analyzer: log firewall lte rule for prior states as well 5 months ago
Victor Julien 71a6a9a746 detect/firewall: limit auto accept notation
Limit to accept:flow, accept:tx and accept:hook.
5 months ago
Victor Julien 651afba883 detect/firewall: implement initial state range support
Allow a single rule to accept a hook and the hooks prior to it.

Example:

        accept:flow tls:<client_hello_done ... \
                tls.sni; content:"suricata.io"; endswith;

This will evaluate the SNI at the client_hello_done hook, but will
act as if there is a `accept:hook tls:client_in_progress ...` as well.

Implementation is currently specific to this `<` operator. During
parsing the sig gets flagged for this case. During setup this has 3 main
effects:

1. prefilter is disabled as we need to eval this right at the first
   state (0)
2. for state 0 a non-PF "prefilter" engine is setup to make sure the
   rule is flagged for evaluation
3. In the Signature::app_inspect list a dummy inspect engine is
   registered per state before Signature::app_progress_hook

The matching logic is building on the stateful rule handling. The
stateful rule handling can now tell the inspection loop that a partial
match occured. For this rule type the partial match will act as a match
with action accept:hook.

Next app updates will then use the continue detection logic to continue
the stateful match. When that fully matches, the final actions are
applied, like accept:flow or accept:tx.

Ticket: #8472.
5 months ago
Victor Julien f6dc772677 detect/firewall: fix last for progress handling
In last_for_progress handling set accept only on packet if it was also
triggered on the last tx.

If there are more transactions, the accept can be set later (if policy
allows).
5 months ago
Juliana Fajardini 6933602050 detect/parse: convert Notice Log into Debug 5 months ago
Juliana Fajardini 8a8574b149 exceptions: add dedicated flow drop reason
To better control stats counters.
5 months ago
Juliana Fajardini 312967f291 detect: add flow drop by firewall as drop reason
To track flow drops triggered by the firewall.
Add flow drop by firewall as drop reason.

As part of
Ticket #7699
5 months ago
Juliana Fajardini 5b488feef5 detect/firewall: add dedicated stats counters
Add a `firewall` stats counter aggregator for all firewall-related
stats.
De-overload "detect.alert_queue_overflow", by adding
"firewall.discarded_alerts" to account for discarded drops in
Firewall mode.
Add Debug statements for tracking corner cases where it can be
difficult to know where a drop is coming from.

Added counters:
- stats.firewall.blocked
- stats.firewall.accepted
- stats.firewall.rejected
- stats.firewall.drop_reason.default_app_policy
- stats.firewall.drop_reason.default_packet_policy
- stats.firewall.drop_reason.flow_drop
- stats.firewall.drop_reason.pre_flow_hook
- stats.firewall.drop_reason.pre_stream_hook
- stats.firewall.drop_reason.rules
- stats.firewall.discarded_alerts

Ticket #7699
5 months ago
Jason Ish c689af0bbb rust/ffi: bindgen thread lifecycle callbacks
Ticket: #8605
5 months ago
Victor Julien 54322f38f8 common: fix cppcheck syntax error 5 months ago
Victor Julien bd198231a0 util/port-interval-tree: suppress cppcheck false positives 5 months ago
Victor Julien f138a64ad7 debug/validate: remove redundant checks
Pointed out by cppcheck.
5 months ago
Victor Julien 9869e9b9f5 detect/port: workaround cppcheck warning 5 months ago
Victor Julien 0af57040d9 detect/address: workaround cppcheck warning 5 months ago
Sergey Pinaev d55114e6d7 detect-engine-analyzer: remove unnecessary check
Always make sure, that smd is not NULL, as we dereference it a few
lines below and base64_data for instance is forbidden as a fast_pattern

Ticket: 8504
5 months ago
Promise Charles 5c9602bcf2 suricata: add error about missing runmode
If a runmode is missing but other params are passed on the commandline,
issue an error.

Ticket: #5711

Signed-off-by: Promise Charles <descencybobby@gmail.com>
5 months ago
Philippe Antoine 87db89ea4e fuzz: extend fuzz_siginit to do engine-rule-analysis 5 months ago
Philippe Antoine 0773fba5fd rust/ffi: move txdata flags to ffi
Ticket: 7666
5 months ago
Philippe Antoine 6dff07b631 detect/lua: remove unused macros 5 months ago
Victor Julien 95b7f2b998 scan-build: support taint filtering
Support scan-build's taint filtering logic. Adds a yaml config to mark
a dedicated debug validation function as filtering a taint.

Use to suppress warnings in reference, threshold and classification file
handling.

Ticket: #3153.
5 months ago
Victor Julien 524503b572 detect/prefilter: rewrite loop to assist scan-build
Also address a theoretical edge case where memory allocation failure
could lead to overrunning the sids array.
5 months ago
Victor Julien e5650ebcbd scan-build: suppress more warnings 5 months ago
Victor Julien 02f6a4fd87 detect: work around scan-build warning
detect-engine.c:2350:69: warning: Out of bound access to memory after the end of 'new_det_ctx' [security.ArrayBound]
 2350 |             FlowWorkerReplaceDetectCtx(SC_ATOMIC_GET(s->slot_data), new_det_ctx[i]);
      |                                                                     ^~~~~~~~~~~~~~
1 warning generated.
5 months ago
Victor Julien dc6696ac04 bpf: work around scan-build warning
suricata.c:574:5: warning: Potential out of bound access to the heap area with tainted index [security.ArrayBound]
  574 |     bpf_filter[nm] = '\0';
      |     ^~~~~~~~~~~~~~
1 warning generated.
5 months ago
Victor Julien 06dcb5aeb0 detect/flowbits: fix scan-build 0-size alloc warning
detect-flowbits.c:761:29: warning: Call to 'calloc' has an allocation size of 0 bytes [optin.portability.UnixAPI]
  761 |                             SCCalloc(sids_array_size, sizeof(uint32_t));
      |                             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
./util-mem.h:36:18: note: expanded from macro 'SCCalloc'
   36 | #define SCCalloc calloc
      |                  ^
1 warning generated.
5 months ago
Victor Julien 0c9e17b454 detect/file.data: suppress scan-build false positive 5 months ago
Victor Julien af937f61dc defrag: rearrange Frag struct to save 8 bytes
Avoid large gaps in the layout.
5 months ago
Victor Julien 9d693a72b6 stream: minor code cleanups 5 months ago
Victor Julien 24e7f3439e stream: don't double check pointer
Checked right above it as well.
5 months ago
Victor Julien d17c0bf096 stream: remove error messages in the packet path
Would only happen during allocation failure.
5 months ago
Victor Julien 2bcebe5285 stream: avoid double memset
Already done by StreamTcpThreadCacheGetSegment().
5 months ago
Victor Julien 474788fd49 pool: remove InitData argument
Only used in unittests.

Update Init callback and update callers.
5 months ago
Victor Julien dc05422769 defrag: remove pool Init callback
Built-in callback does the same thing (memset).
5 months ago
Victor Julien a27b9a6c49 defrag: remove unused InitData argument 5 months ago
Victor Julien af6ec14688 pool/thread: remove unused InitData argument
Only used in unittests, not by production code.
5 months ago
Victor Julien d0ad6ddf19 pool: remove unused Free callback
Not used so not tested.
5 months ago
Victor Julien d4575f5765 pool/thread: remove unused Free callback
Not used so not tested.
5 months ago
Victor Julien 4624028722 pool: fix scan-build warnings
util-pool.c:60:28: warning: Subtraction of a non-null pointer (from variable 'data') and a null pointer (via field 'data_buffer') results in undefined behavior [core.NullPointerArithm]
   60 |     ptrdiff_t delta = data - p->data_buffer;
      |                       ~~~~ ^    ~~~~~~~~~~~
util-pool.c:257:13: warning: Argument to 'free()' is offset by 24 bytes from the start of memory allocated by 'calloc()' [unix.Malloc]
  257 |             SCFree(pb);
      |             ^~~~~~~~~~
./util-mem.h:38:16: note: expanded from macro 'SCFree'
   38 | #define SCFree free
      |                ^
util-pool.c:262:9: warning: Attempt to release already released memory [unix.Malloc]
  262 |         SCFree(p->pb_buffer);
      |         ^~~~~~~~~~~~~~~~~~~~
./util-mem.h:38:16: note: expanded from macro 'SCFree'
   38 | #define SCFree free
      |                ^
3 warnings generated.

Also, after fixing these, this one came up.

  CC       util-pool.o
util-pool.c:244:9: warning: Attempt to release already released memory [unix.Malloc]
  244 |         SCFree(p->data_buffer);
      |         ^~~~~~~~~~~~~~~~~~~~~~
./util-mem.h:38:16: note: expanded from macro 'SCFree'
   38 | #define SCFree free
      |                ^
1 warning generated.

Address this as well.
5 months ago
Philippe Antoine 9aaa6f7854 http1: do not re-parse Content-Disposition header
Ticket: 8529

When Suricata handles a HTTP1 response body, it does so with a
file, and tries to get the filename from the Content-Disposition
header if any, then from the uri.

If it failed to find a file name, it tried again every time
there was new data from the response body, even if there was
no new data to find a file name in either the header nor the uri.

This causes a slowdown in the case the Content-Disposition header
is big.

Fix is to set the flag on the first call of the callback, to be
sure that we will parse the Content-Disposition header for a
filename header only once per http1 response.
5 months ago
Philippe Antoine 4c42998feb detect/engine: helper to know if a transform happens in-place 5 months ago
Jeff Lucovsky 1dc629d978 defrag: release tracker lock before decoding reassembled packet
Decoding the reassembled packet inside DefragInsertFrag while holding
the tracker mutex creates a deadlock situation if the reassembled packet
contains tunneled fragments: two threads could each hold one tracker
mutex and deadlock on the other. Move the decode in Defrag() after
DefragTrackerRelease() so no lock is held during decode (and possibly
re-entering the defrag system).

Make sure to fetch tracker->ip_hdr_offset after DefragInsertFrag since
it may be written during that call if the first fragment arrives last.

Issue: 8550
5 months ago
Philippe Antoine 7a9fc64882 detect/lua: move allow_restricted_functions out of struct
Ticket: 8556

Allows hardening against buffer overflos in the structure.
Reduces the scope of the variable.
5 months ago
Philippe Antoine 0b239c4848 lua: add bounds checks for flowints and flowvars
Ticket: 8556
5 months ago
Jason Ish 078c08d84b dnp3: bound response reassembly
Ticket: 8460
5 months ago
Philippe Antoine 38d41e6fa6 dnp3: fix off-by-one in array sizes
So that we can write a final zero without overflowing the array
and relying on padding to avoid further problems

Ticket: 8448
5 months ago
Philippe Antoine c25ccd299e dnp3: explicit application layer length is bounded in uint16_t
Ticket: 8460
5 months ago
Philippe Antoine 658684a252 dnp3: bounds reassembly
Ticket: 8460
5 months ago
Philippe Antoine c977b2f31b frames: make sure we use a lowercase buffer name
Ticket: 8526

As some C protocols accepted case-insensitive frame names,
a rule using the same frame twice with different cases,
ended up using 2 different buffers,
which ended up in triggering a buffer overflow
5 months ago
Jason Ish 2d6c3213ae lua: enforce allocation limit on first alloc
Instead of just on re-alloc.

Ticket: #8507
5 months ago
Philippe Antoine 24527d662a defrag: check tracker/packet family in compare
Ticket: 8510

Without this check, in case of a hash collision, and the other
fields are equal, we could end up consider adding an IPv6 packet
to a IPv4 tracker (or vice versa).

Doing so, we end up interpreting an IPv6 packet as an IPv4 one,
and we do not benefit from the bounds checks from ipv4/ipv6 decoder.
5 months ago
Jason Ish 74eb82a8a5 datasets: fix path setup when load and save used with different paths
If load and save were used in the same rule with different paths, proper path
setup was skipped.

Ticket: #8546
5 months ago
Victor Julien 367ca7f430 detect/tx: minor debug additions and fixes 5 months ago
Victor Julien b29226c7ea firewall/analyzer: include all hooks
For protocols using default 0-1 states, add support.

For others, print 'unknown' if no name is yet supported.

Ticket: #8514.
5 months ago
Victor Julien f7c44c4c23 detect/analyzer: log actual policy for app firewall 5 months ago
Victor Julien 7134592fea detect/firewall: configurable default policies
Allow configurable policies, including accept. For app-layer this
requires looping all available hooks to apply the policies.

Support configurable policies for packet-filter, pre-stream, pre-flow.

If there are no rules there is also no rule group (sgh). Make sure
the app hooks policies are correctly handled in this case by allowing
a NULL sgh to be handled as well.

For tx rule match actually apply drop directly. Previously this was
always handled by the default drop:flow policy.

Ticket: #7701.
5 months ago
Victor Julien eaacb41aaf firewall: accept:flow no longer implies pass:flow
Previously a `accept:flow` action would act as both a firewall "accept" and
a threat detection "pass" for the rest of the flow.

This patch changes that. The `accept:flow` action now only accepts the
rest of the packets for the firewall ruleset, but does still continue
threat detection rule evaluation.

Ticket: #8444.
5 months ago