Commit Graph

14767 Commits (3a6ecab0984745f0cefe3ca3c6dfee1eec7470d8)

Author SHA1 Message Date
Jason Ish 57ae57152c smtp: assign response frames to owning transaction
SMTPGetLine assigned response frames to the current transaction even when a
queued reply belonged to an older transaction.

Use the queued command owner so frame EVE output and frame-based detection
receive the correct transaction id.

Includes some re-org to avoid prototypes for static functions.

Ticket: #8741
3 months ago
Jason Ish 60e0df6530 smtp: recover from invalid BDAT command syntax
A BDAT command that failed to parse, such as "BDAT 5 X", returned -1,
disabling SMTP parsing for the rest of the flow. A server may reject the
command and continue the session, leaving following messages
uninspected.

Instead raise a decoder event and queue the command as an ordinary
command.

Ticket: #8741
3 months ago
Jason Ish ec0fec1a37 smtp: complete BDAT transactions at LAST
Track the BDAT LAST marker so the final chunk and its reply complete the
transaction in each direction, preventing a following MAIL FROM from
being merged into the previous transaction.

Ticket: #8741
3 months ago
Jason Ish 2676d1bc83 smtp: move transaction completion helpers
Simply makes the follow diff a little easier to read.
3 months ago
Stephen Donnelly a37b75a8ba dag: check rlen is a valid length
Ticket: 8797

Add check to rlen value read from ERF record to avoid potential infinite loop, must be >= dag_record_length (16).

Similar check exists in source_erf_file already.
3 months ago
Dmitry Uryvchikov d2497790f9 detect-engine-mpm: change transforms->cnt to uint8_t 3 months ago
Stephen Donnelly 03bc717877 dag: wrong stats registration causes compilation errors with --enable-dag
Bug: 8812
3 months ago
Uwez Khan 38b4ad79a3 decode/ipv6: bound hop-by-hop option to the option area
The TLV loop for the IPv6 hop-by-hop and destination option headers
gates each option on (offset + 1 + ip6_optlen) > optslen. An option is
two header bytes (type, length) plus ip6_optlen data bytes, so its data
ends at offset + 1 + ip6_optlen and the bound has to be
offset + 2 + ip6_optlen.

Before: an option that declares its data running one byte past the
option area is accepted, and the Router Alert / Jumbo / Home Address
memcpy then copies sizeof(value) bytes ending one byte past the area;
when the header sits at the tail of the IPv6 payload that read goes
past the payload.

After: the option is rejected with IPV6_EXTHDR_INVALID_OPTLEN, matching
how the IPv4 option loop already bounds a full option against the
remaining length. The check stays next to the read so each option type
does not need its own guard.

Ticket: #8817.
3 months ago
Victor Julien dde0d7295b tls: improve client/server hello parsing loops
Bug: #8795.
3 months ago
Philippe Antoine 425b9c6777 ftp/expectation: fix ippair leak
Ticket: 5204

ippair use_cnt increased by AppLayerExpectationCreate calling
IPPairGetIPPairFromHash was never decreased
3 months ago
Philippe Antoine dee0f03db4 detect/modbus: move modbus keyword to rust
Ticket: 3195
3 months ago
Philippe Antoine 3e70a79ed2 detect/nfs: move nfs.version to rust
Ticket: 3195
3 months ago
Philippe Antoine e976db7261 detect/template: remove template2
Ticket: 7278

Its usage was removed in 512bbe4de8
3 months ago
Jeff Lucovsky e7f1692a5c defrag: fix defrag.memuse counter reporting memcap
Populate defrag.memuse from DefragTrackerGetMemuse() rather than
DefragTrackerGetMemcap(), so it reports actual usage, not the cap.

Issue: 8752
3 months ago
Jason Ish 62fdb771b0 smtp: check transaction before to-client completion
Make sure the transaction still exists before completing it in the
to-client direction. A pipelined RSET reply may already have completed and
freed it while a later end-of-DATA marker still refers to it.

Found by OSS-Fuzz testcase 5498180758994944.

Bug #8739.
3 months ago
Victor Julien 8455efd9ac app-layer: add substate support to list hooks
Add substates to the --list-app-layer-hooks option.
4 months ago
Victor Julien 8a5e8c63b2 detect: strict validation of buffers
Make sure that every buffer in a signature is actually used in the
setup of the engines. Reject sigs that are locked to a certain substate
and use buffers that require another.
4 months ago
Victor Julien 89baff01c9 output/tx: allow registering logging at substate
Register HTTP/2 and DOH2 this way.
4 months ago
Victor Julien a824d97d71 detect: use sub state to select inspect engines
When building the per signature app_inspect list, only add engines
that match the sub state specified in the hook.
4 months ago
Victor Julien c5d4a250b5 detect/firewall: avoid passing state match for policy 4 months ago
Victor Julien 9a294bf73b app-layer: check if protocol is enabled for sub state callbacks 4 months ago
Victor Julien cf216b6309 http2: rename state *start to *started
This is to make the hook use names consistent with the default
hooks and other protocols.
4 months ago
Victor Julien f8f28c6f6f detect: sync prefilter and app inspect alproto logic
In firewall mode the alproto logic when building prefilter and rule
engines is strict, but was out of sync between prefilter and rule app
inspect engines.

For SIGNATURE_HOOK_TYPE_APP rules the logic is strict, with an exception
for HTTP/2 and DOH2. DOH2 is not a full protocol implementation, but
rather HTTP/2 with a different alproto.

Fixes: d64954a873 ("detect: don't register unrelated inspect engines")
4 months ago
Victor Julien 56d9670af7 eve/alert: log sub state progress values 4 months ago
Victor Julien f02a427059 eve/alert: clean up state logging 4 months ago
Victor Julien 110e74642e detect/firewall: harden policy lookup logic 4 months ago
Victor Julien cfc98aeeaf detect: add debug validation checks to assert assumptions 4 months ago
Victor Julien 7517ba9f98 detect: give clear errors for http2 w/o substate
http2 states were not yet supported even if the built-in states could
already work. Clearly error out on a hook w/o substate.
4 months ago
Victor Julien e4176d2b9a detect/firewall: support substate in analyzer 4 months ago
Victor Julien 2511070a58 detect/firewall: support lte mode for substate 4 months ago
Victor Julien e1e24d6cb4 eve/alert: add sub state output 4 months ago
Victor Julien 7e60c3205e detect/alert: store sub-state in PacketAlert
In preparation of being able to log it.
4 months ago
Victor Julien 17a3e0d44f app-layer: use macro for progress ceiling 4 months ago
Victor Julien 2e1003a026 detect: add debug validation checks
Check that sub state handling is correct.
4 months ago
Victor Julien af1c72c37e detect/mpm: don't register engines for disabled protocols 4 months ago
Victor Julien 3b6b381f90 detect/firewall: add default alert signature to policy object
Now that there is a policy hash, make the alert signature object a
member of that to avoid another hash table lookup.
4 months ago
Victor Julien bffea309db detect/firewall: implement app policy as hash table
With substate support the fixed table approach for policies was no
longer a good fit, so convert to a hash table. The policies are stored
per alproto, sub_state, progress and direction.
4 months ago
Victor Julien eb87137471 detect/parse: allow bigger protocol/hook specifications 4 months ago
Victor Julien 6a3f9bc0b0 app-layer: for sub state API treat DOH2 as HTTP/2
Otherwise we'd have to re-register the relevant callbacks.
4 months ago
Victor Julien 956030452f detect/parse: don't setup sub states if protocol doesn't support it 4 months ago
Victor Julien 3ef0d2ce16 detect/parse: parse sub state hooks
Register a generic list for each sub state / progress combo.
4 months ago
Victor Julien 116a060092 detect/firewall: policy for substates
For the most part hard coded for HTTP/2 for now.
4 months ago
Victor Julien cedb836d01 output/dns: update for DOH2 change 4 months ago
Victor Julien 5735b87c3a detect: change how DOH2 inspection works
DNS/HTTP2 no longer automatically registers all keywords also for DOH2.

Instead, the DNS keywords and HTTP/2 stream keywords are registered for
DOH2 explicitly as well.

- flow alproto DOH2 + engine DOH2  -> inspect inner DNS
- flow alproto DOH2 + engine HTTP2 -> inspect outer HTTP/2
- flow alproto DOH2 + engine UNKNOWN -> inspect outer HTTP/2
4 months ago
Victor Julien 17953d2355 detect/http: register keywords for HTTP/2
Now that HTTP keywords are no longer automatically registered for
HTTP/2, register them manually.
4 months ago
Victor Julien b36ec146aa detect/dns: register keywords for DOH2 as well
Now that DNS keywords are no longer registered for DOH2, the keywords
need to manually registered for DOH2.
4 months ago
Victor Julien 1bb843d83f detect/http2: don't double register engines
Each keyword supporting DOH2 must register explicitly
4 months ago
Victor Julien 416b9c12ae detect/file: register http/2 with sub-state 4 months ago
Victor Julien c943de4fac detect/parse: initial http2 substate support
Hard coded for now.
4 months ago
Victor Julien 7ebc699df0 http2: split transaction state machines
Split into 2 sub-states:
- stream, which has the "HTTP" requests and responses, including DOH2
- global, which has the settings and other global or control handling

Introduce a simpler progress tracking for the global sub state:
- HTTP2ProgGlobalStart and HTTP2ProgGlobalComplete.

The stream sub state uses the same state machine as before.

Ticket: #8386.
4 months ago
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