Commit Graph

10509 Commits (56541c7c37d0de3f4c7eaafc19118ad837bbbc3d)

Author SHA1 Message Date
Victor Julien 7ccec8f143 debug: add bool string print helper macro
(cherry picked from commit 0ec136621d)
4 years ago
Victor Julien 1ed8066d4e stream: support SYN/ACK with TFO only ack'ing ISN
Not ack'ing the data.

(cherry picked from commit 7ef57cc7cb)
4 years ago
Victor Julien 7f4a800156 stream: add liberal timetamps option
Linux is slightly more permissive wrt timestamps than many
other OS'. To avoid many events/issues with linux hosts, add an
option to allow for this slightly more permissive behavior.

Ideally the host-os config would be used, but in practice this
setting is rarely set up correctly, if at all.

This option is enabled by default.

(cherry picked from commit 01b7ccc224)
4 years ago
Victor Julien fee655bae6 stream: D-SACK detection and logging
RFC 2883 specifies a special use of SACKs to indicate a host has
received a segment it considers a spurious retransmission.

(cherry picked from commit d79a926085)
4 years ago
Victor Julien dcefc00b17 stream: fix next_seq updates after temporary gap
On every accepted packet in established state, update next_seq if
packet seq+len is larger than existing next_seq. This allows it to
catch up after large gaps that are filled again a bit later.

Bug: #5877.
(cherry picked from commit 76225bf9ac)
4 years ago
Victor Julien 006911fd5a stream: improve first FIN next_seq update
For accepted FIN packets, always update next_seq. This helps track the
FIN sequence.

Bug: #5877.
(cherry picked from commit 551fb80150)
4 years ago
Victor Julien a8cff36467 stream: improve FIN next_seq handling
Update next_seq to SEQ + payload_len + 1, so retransmission checks
work better.

Bug: #5877.
(cherry picked from commit 80a012a787)
4 years ago
Victor Julien f1904398a7 stream: set next_seq before last_ack
next_seq sometimes depends on last_ack in cases of packet loss
catch up, so first update it.

Bug: #5877.
(cherry picked from commit 20df715e64)
4 years ago
Eric Leblond 984698f8c5 stream/tcp: update ack handling logic
Only update the ack value of a session for regular packets when
the ACK bit is set.

(cherry picked from commit 0d81173d6e)
4 years ago
Victor Julien 237e06a991 stream/tcp: fix wrong ACK trigger FIN1 to FIN2
An ACK that ACK'd older data while still being in-window could
lead to FIN_WAIT1 to FIN_WAIT2 state transition. Detect this
case and generally harden the check.

Bug: #5877.
(cherry picked from commit 67af94f2e0)
4 years ago
Victor Julien 2b18412509 stream: fix overlap detection
If a in-tree segment was partly before base_seq the overlap detection
miscalculated the data offset. This lead to memcmp comparing the wrong
data.

Bug: #5881.

(cherry picked from commit cbcd70537a)
4 years ago
Victor Julien d0b1a04eb0 stream: set event on bad timestamp on syn_sent state
(cherry picked from commit fc376f8145)
4 years ago
Victor Julien 68bd193868 stream/tcp: allow tcp session reuse on null sessions
When a "stream starter" packet finds an existing TCP flow, the flow will be
evaluated for reuse.

The following scenario wasn't handled well:

1. Suricata starts after a tool has just stopped using lots of connections
   (e.g. ab stress testing a webserver)
2. even though the client is closed already, the server is still doing
   connection cleanup sending many FINs and later RSTs
3. Suricata creates flows for these packets, but no TCP sessions
4. client resumes testing, creating flows that have the same 5 tuple as the
   flows created for the FIN/RST packets
5. Suricata refuses to "reuse" the flows as the condition "tcp flow w/o session"
   is not considered valid for session reuse
6. new TCP connection is not properly tracked and evaluated in parsing and
   detection

There may be other vectors into this, like a flow w/o session because of
memcap issues.

Bug: #5843.
(cherry picked from commit 93c9594dd8)
4 years ago
Victor Julien d13bb7f5a7 flowworker: don't keep unnecessary flow reference
Flow stream/detect/log flush packets, don't hold on to the flow
beyond the flow worker module.

(cherry picked from commit a2dc9a40e7)
4 years ago
Victor Julien c08521cd52 threshold: suppress debug notice message 4 years ago
Victor Julien 777d88bd21 decode/events: add strict mode for udp.hlen_invalid; remove rule 4 years ago
Shivani Bhardwaj eb26d1a64d decode/udp: fix payload_len calculation
Fix payload_len calculation post removal of the condition that returned
error code if the length to the decode fn did not match the length of
header from the UDP packet.

Bug 5379

(cherry picked from commit f941ceae2b)
4 years ago
Shivani Bhardwaj bbd53bcdf6 decode/events: add event type UDP_LEN_INVALID
(cherry picked from commit eebdfe9a3e)
4 years ago
Lukas Sismis f6fa16ce25 decode-udp: Allow shorter UDP packets than the remaining payload length
If the packet is shorter than IP payload length we no longer flag it as an
invalid UDP packet. UDP packet can be therefore shorter than IP payload.
Keyword "udp.hlen_invalid" became outdated as we no longer flag short UDP
packets as invalid. The keyword's evaluation remains the same.

Inspired by commit: d18e52ed93

Redmine ticket: #5793
4 years ago
Philippe Antoine fd358a5616 fuzz: checks pcap timestamp consistency
Inspired by commit e22b59b8c1

Master7 is now diverging with use of SCTime_t
4 years ago
Philippe Antoine 4b2a59a4d9 detect: config keyword transaction logic fix
When the keyword config:logging disable,type tx is used,
OutputTxLog checks a flag to skip the transaction without logging
it, but AppLayerParserTransactionsCleanup waits for the
transaction to be marked as logged to clean it.

So, OutputTxLog now marks the tx as logged, so that it can
get cleaned away.

Ticket: #5456
(cherry picked from commit 0c0fcc9411)
4 years ago
Juliana Fajardini d47e8fffad stream/tcp: fix typos, update copyright year
Bug #5765
4 years ago
Juliana Fajardini 700b0a37a1 exceptions: ignore policy if stream.midstream=true
Set the engine to ignore the stream.midstream-policy if stream.midstream
is enabled.

If we had both stream.midstream AND stream.midstream_policy enabled,
this could lead to midstream flows being dropped (or bypassed, or...)
instead of being accepted by the engine, as it was probably meant when
the user enabled midstream flows.

Bug #5765

(cherry picked from commit 8e9905e0d8)
4 years ago
Philippe Antoine 7986919df0 fuzz: specify protocol with fuzz target name
cf https://redmine.openinfosecfoundation.org/issues/4125

This allows fuzz_applayerparser_parse to fuzz one specific
app-layer protocol based on the binary name, as is done
with the environment variable FUZZ_APPLAYER
That is if we rename/copy to fuzz_applayerparser_parse_smb,
it will fuzz only SMB protocol
This way, we can easily produce different fuzz targets for
each protocol in oss-fuzz

(cherry picked from commit e9b76a0e66)
4 years ago
Jeff Lucovsky 2f8f45ff6a netmap: Fixup issues with v14+ backport
This commit reduces the changes associated with adding the v14 api to
6.0.x

During the preparation of this commit, issues in the original backport
were corrected
- Failure to release a lock under error conditions
- Typo in an CPP ifdef
- Incorrect target for goto statement in an error handling case.

Issue: 5744
4 years ago
Philippe Antoine 2c49a268e2 test: do not output non ascii character
The unit test for content |aa bz| transforms in place the string
str to replace the 2 characters aa by one character 0xaa
Then, when z is not recognized as a valid hexadeicmal character,
the whole modified string is printed out, inclusing the non-ascii
0xaa

Ticket: #5558
(cherry picked from commit b281199e9a)
4 years ago
Victor Julien 26fc02227b streaming/sbb: fix debug message
(cherry picked from commit 989e5c7ba2)
4 years ago
Victor Julien eb03cdea85 stream: remove bug on from packet path
(cherry picked from commit a00db15bd4)
4 years ago
Victor Julien 9664d97129 src: fix deprecated-non-prototype compile warnings
Tested on Fedora 37 with clang 15.

util-strlcatu.c:45:8: error: a function definition without a prototype is deprecated in all versions of C and is not supported in C2x [-Werror,-Wdeprecated-non-prototype]
size_t strlcat(dst, src, siz)
           ^
1 error generated.

(cherry picked from commit 41ca206fdf)
4 years ago
Victor Julien 0a17103ab8 src: fix unused-but-set-variable compile warnings
Tested on Fedora 37 with clang 15.

datasets.c:852:9: error: variable 'n' set but not used [-Werror,-Wunused-but-set-variable]
    int n = 0;
        ^
1 error generated.

(cherry picked from commit 1bc6976a06)
4 years ago
Victor Julien 9f6862cb50 src: fix strict-prototype warnings
Tested on Fedora 37 with clang 15.

app-layer.c:1055:27: error: a function declaration without a prototype is deprecated in all versions of C [-Werror,-Wstrict-prototypes]
void AppLayerSetupCounters()
                          ^
                           void
app-layer.c:1176:29: error: a function declaration without a prototype is deprecated in all versions of C [-Werror,-Wstrict-prototypes]
void AppLayerDeSetupCounters()
                            ^
                             void
2 errors generated.

(cherry picked from commit ebd8728219)
4 years ago
Philippe Antoine 5c0bb7a616 ftp: completely resets port_line
In the case port_line is first allocated and port_line_len is set,
Then a second request reaches memcap and frees port_line,
port_line_len should also be reset, because both will get used
by the response parsing.

Ticket: #5701
(cherry picked from commit 1660172a8b)
4 years ago
Philippe Antoine 462366d447 tls: fix off by one in supported versions extension
Ticket: #5663
(cherry picked from commit b5147189ae)
4 years ago
Victor Julien b24ae521a2 ssl: add debug validation checks for recent changes
Make sure the assumptions are correct.

(cherry picked from commit 8f0d820218)
4 years ago
Philippe Antoine 97f97dd72a tls: fix buffer overread
Recently introduced by commit 4bab6e24e5

Ticket: #5564
(cherry picked from commit 3fbcba8ab7)
4 years ago
Philippe Antoine 9305538309 ssl: fix compiler warning
implicit conversion loses integer precision: 'int' to 'uint16_t'
because C shifts << translates automatically to signed integers

(cherry picked from commit ae6abd8ca3)
4 years ago
Victor Julien f0d9cc5a5e tls: handle incomplete header sooner
Make sure to exit the parser early on incomplete header data.

Additionally, make sure to not create duplicated tls frames in this
case.

Add a debug validation check for the header parser parsing too much
data, which should never happen.

(cherry picked from commit 1701a6b14c)
4 years ago
Victor Julien 541945f4a8 ssl: add debug validation check for incomplete api
(cherry picked from commit 9053c49178)
4 years ago
Victor Julien 29740e1c0c tls: improve record checks
Improve unknown record handling. Inspired by Wireshark 'unknown record'
handling, we take a best effort approach for records with unknown content
types in TLS versions 1.0, 1.1 and 1.2.

Improve record length check and set 'invalid_record_length' event instead
of 'invalid_tls_header'.

(cherry picked from commit 69be41b241)
4 years ago
Victor Julien dfc332fe49 tls: improve versions extension logic
Skip over unusable versions like GREASE.

(cherry picked from commit c028800ae1)
4 years ago
Victor Julien 43a3a7ee39 tls: make version and size checks stricter
This way bad records won't buffer lots of stream data.

(cherry picked from commit 599791fa33)
4 years ago
Victor Julien 5ef12461cf tls: store cert data in heap buffer
Cert chain is a list of pointers into this buffer, so can't use a
stream slice approach.

(cherry picked from commit c73d812026)
4 years ago
Victor Julien 5e834aca0f tls: prepare for client cert parsing
(cherry picked from commit 10f5e6cb66)
4 years ago
Victor Julien 4427809994 tls: make cert handling more generic
In preparation for client cert handling.

(cherry picked from commit 14b2e04b58)
4 years ago
Victor Julien 0f987a99dd tls: avoid tls.invalid_handshake_message FP
Don't set TLS_DECODER_EVENT_INVALID_HANDSHAKE_MESSAGE event on encrypted
handshake messages.

(cherry picked from commit cf4c201acb)
4 years ago
Victor Julien d787558b0f tls: don't set 2 events for a single exception
Keep the more specific ones.

(cherry picked from commit e9d63f3355)
4 years ago
Victor Julien 75a129f124 tls: remove incomplete tests
These tests are incompatible with the incomplete API usage and should
have been pcap based tests in the first place.

(cherry picked from commit 214e466b29)
4 years ago
Victor Julien 2870809f4e tls: set event if record size exceeds limit
(cherry picked from commit 82e03bd8fc)
4 years ago
Victor Julien 5551388d90 tls: support server hello done message
(cherry picked from commit e857c864ca)
4 years ago
Victor Julien 7be7f32a3d tls: support handshake fragmentation
Implement TLS record defrag for handshake messages.

Ticket: #5183.
(cherry picked from commit 4bab6e24e5)
4 years ago
Victor Julien 0489987afd tls: remove certificate buffering code
TCP Buffering is now done in the app-layer using the incomplete API, on
the SSL/TLS record level. TLS level fragmentation will be implemented
separately.

(cherry picked from commit bcaf0f6f7d)
4 years ago
Victor Julien 3785e03426 tls: parse handshake protocol records in single pass
(cherry picked from commit 0839317ea7)
4 years ago
Victor Julien b3bbac5eae sslv2: use version from client hello
Remove streaming code that is now unused.

Incomplete handling makes this record parsing work on full data.

(cherry picked from commit 9f0ea5e70c)
4 years ago
Victor Julien 253cdb9f8a ssl: implement 'incomplete' handling for SSLv2
(cherry picked from commit c8d79fb81f)
4 years ago
Victor Julien ba70d7b91a tls: streaming mode for application records
To avoid overhead of stream buffering for records we don't do
much with anyway, pass through application records instead of
buffering the entire record in the stream engine.

(cherry picked from commit 6076a51511)
4 years ago
Victor Julien 2651110e0a tls: use incomplete API to get full TLS records
The TLS record header is parsed in streaming mode still, but once the
record size is known we tell the app-layer API to give us the full
record.

Ticket: #5481

(cherry picked from commit 129fcb5c72)
4 years ago
Jeff Lucovsky ad8147a8c1 detect/tls: Improve tls.fingerprint rule handling
Issue: 4581

This commit improves the runtime performance of rules with
tls.fingerprint by using the inspection logic from tls.cert_fingerprint.

(cherry picked from commit 63745a7879)
4 years ago
Jeff Lucovsky 2ca1b7f39a detect/uri: Remove unnecessary include
This commit removes an unnecessary #include for detect-uricontent.h

(cherry picked from commit 6bccd5aa30)
4 years ago
Victor Julien 4d5041f82f detect/pcre: don't use JIT if disabled
If we determined not to use JIT at start up, really don't use
JIT.

Bug: #5762.
4 years ago
Sascha Steinbiss 5ccdded6ca ebpf: update deprecated API calls
This fixes build errors when libbpf 1.0 is used. It removes previously
deprecated API functions that were still in use in Suricata's eBPF
code.
4 years ago
Victor Julien 44a2e59cb2 radix: fix ipv6 address parsing warning
The check meant to see if the ip address part of the ip/cidr combo
was more specific than needed wasn't fully implemented, leading to
warnings being issued on completely valid and correct input.

This patch implements the same logic as in IPv4. If the ip address
as specified is different from the ip after the mask has been applied,
a warning is displayed.

Bug: #5747.
(cherry picked from commit 991f9fde32)
4 years ago
Philippe Antoine fb6f1b184c mime: do not skip empty lines for quoted-printable
As these lines are in the file...

Ticket: #5725
(cherry picked from commit 0e054af1ac)
4 years ago
Victor Julien 453366ccb9 mime/base64: unify space handling
(cherry picked from commit 7bfb63210e)
4 years ago
Philippe Antoine 1be913d49c eve: add common options to loggers missing it
So that we get community id for RFB for instance

Ticket: #5723
4 years ago
Victor Julien 002cd8e301 flow: cleanup and clarify ancient debug messages 4 years ago
Victor Julien 64adb30b5c decode: enforce layer limit through tunnel layers
Bug: #5686.
Bug: #5688.
4 years ago
Shivani Bhardwaj 433266b076 util/base64: fix heap buffer overflow
While updating the destination pointer, we were also adding the padded
bytes which are not a part of the decoded bytes. This led to running out
of space on the destination buffer.
Fix it by only incrementing destination buffer ptr by the number of
actual bytes that were decoded.

Ticket 5623
Ticket 5694
4 years ago
Shivani Bhardwaj 51c4b48f57 util/base64: use padding var for calculations
(cherry picked from commit 58e5033a44)
4 years ago
Shivani Bhardwaj 02377e9c25 base64: add and clean tests
(cherry picked from commit 7005443b8b)
4 years ago
Shivani Bhardwaj 6b2c49292a base64: add new mode as per RFC 4648
As per RFC 4648,
Implementations MUST reject the encoded data if it contains characters
outside the base alphabet when interpreting base-encoded data, unless
the specification referring to this document explicitly states
otherwise.

Add a new mode BASE64_MODE_RFC4648, and handle input strictly as per the
specification.

Bug 5223

(cherry picked from commit dad52f133d)
4 years ago
Victor Julien 2f35376482 smtp/files: don't modify prev file on open failure
(cherry picked from commit 9f4dd4fc56)
4 years ago
Victor Julien 5db0ef4415 files: always initialize inspect_window and min_inspect_depth
This is to make sure the files buffers are properly managed even
when there are no rules or when there are no file.data rules.

Bug: #5703.
(cherry picked from commit e601ebdfd8)
4 years ago
Victor Julien b68b170271 streaming/buffer: set hard limit on buffer size
Don't allow the buffer to grow beyond 1GiB. Add a once per thread
warning if it does reach it.

Bug: #5703.
(cherry picked from commit df7d8d96c9)
4 years ago
Victor Julien 82c24bf738 detect: fixes to action handling; fix PASS
Fix PASS handling by setting and checking in the correct packet.

There are 3 types of packets:
1. tunnel packets (inner layer of encapsulation)
2. "root" packets (outmost layer of encapsulated packet)
3. normal packets (no encapsulation)

Tunnel packet have a pointer to their "root". The "root" is the packet
that is ultimately used by the capture method to issue a verdict:
DROP or ACCEPT (forward).

For tunnels:
DROP actions are always issued on the root packet.
The PASS action is issued on the packet currently in the detection
engine.

Non-tunnels:
DROP and PASS are both set in the current packet.

Bug: #5697.
4 years ago
Philippe Antoine b9be616406 fuzz: fixes a leak in applayerparse target
If a protocol change was requested, the target did not handle
it as Suricata, as the target is meant to handle only one
app-layer protocol.

(cherry picked from commit ca054f7264)
4 years ago
Jason Ish e9a0ac187c afpacket/netmap: warn about mixed ips, ids/tap deprecation
Suricata already logs if AF_PACKET or Netmap are running in a mixed IPS
and IDS/TAP mode.  As the behavior is undefined when these modes are
mixed, it is best to deprecate and to not allow this behavior. For now
warn that it will be unsupported and fail in Suricata 8.

Ticket: 5587
(cherry picked from commit 0c00f28ebc)
4 years ago
Philippe Antoine 0ca12493e3 mime: handles multiple sections for a parameter
Ticket: 4386

as per RFC2231.
For instance filename can be split between filename*0,
filename*1, etc...

(cherry picked from commit 784558df2e)
4 years ago
Philippe Antoine 55781229d7 mime: move FindMimeHeaderTokenRestrict to rust
Also fixes the case where the token name is present
in a value

(cherry picked from commit 8feb9c35ae)
4 years ago
Jeff Lucovsky 1ba259450b netmap: V14 API changes
This commit modifies the Netmap packet handling to use API version 14.

@bmeeks8 contributed many changes instrumental to this effort.

(cherry picked from commit ca7d097225)
4 years ago
Jeff Lucovsky 5d0fe15f69 util: Add sys/ioctl.h to common include
This commit adds another system include file based on autoconf to the
common Suricata include file for convenience.

(cherry picked from commit 3496e543af)
4 years ago
Victor Julien 778faaed96 detect: apply drops to tunnel root
`PacketDrop` applied a DROP to the current packet unconditionally,
while in tunnel/encapsulated cases the DROP should have been applied
to the root packet.

Fixes: 6742ecbc9e ("decode: make PacketDrop use action as parameter")

Bug: #5600.
4 years ago
Philippe Antoine bcd8d7d6c4 threshold: fix regex to accept by_both and by_rule
As is done in detect-threshold.c or in DETECT_RATE_REGEX
and is expected by switch (rule_type) which makes the same
for THRESHOLD_TYPE_THRESHOLD and THRESHOLD_TYPE_RATE

Ticket: #5327
(cherry picked from commit a2f857ed90)
4 years ago
Lukas Sismis afbd68ad22 transversal: remove suricata-ids.org references
(cherry picked from commit e101384e7b)
4 years ago
Eric Leblond 50f0b6acac flow: fix FlowSwapFileFlags function
Ticket: #5625
(cherry picked from commit 4e1ff9a7ff)
4 years ago
Victor Julien a5bc56cecb detect/tag: improve time handling on windows
Bug: #5584.
(cherry picked from commit 0977f40d1c)
4 years ago
Victor Julien 985b93e80f eve: log mac addresses in packet direction
(cherry picked from commit 90f3823cad)
4 years ago
Victor Julien 3570ec6f6e stream: fix reachable assertion
Fix `Flow::thread_id` not always getting properly set up, leading to
a reachable assertion.

Bug #4582.

(cherry picked from commit b06c0579f5)
4 years ago
Juliana Fajardini aafbf368ac stream/tcp: typo fix 4 years ago
Philippe Antoine 047661a5cb source: pcap timestamp microsecond consistency
That is it should be less than 1 000 000.
Have the same for fuzz targets where the bug came from.

https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=44177
(cherry picked from commit 8ecf7e403e)
4 years ago
Philippe Antoine c31d3592a4 flow/icmpv4: fix vlan.use-for-tracking
For ICMPv4 error messages the vlan ids were always considered,
even if the 'vlan.use-for-tracking' option was disabled.

Ticket: #5330
(cherry picked from commit ce2775d331)
4 years ago
Jason Ish 0ca09ecbcd detect: fix user after free in debug log
Found by gcc 12.2.1.
4 years ago
Victor Julien 7183e766f9 detect/flowbits: more permissive parsing by default
To get strict parsing, `--strict-rule-keywords=flowbits` command line
option can be used.

Bug: #5547.
4 years ago
Jason Ish 8174ba9e6f content: don't error out on incomplete hex
Before 6.0.6 if hex content was incomplete, Suricata didn't error out.
With 6.0.6 incomplete hex was detected and errored on which is a
breaking change in a release branch.  Instead, only emit a warning
unless strict content checking has been requested.

To enable strict behaviour on incomplete content hex in a rule,
"--strict-rule-keywords=content" can be used on the command line.

Issue: #5546
4 years ago
Jason Ish 726de4e70c detect: allow rule errors to display error, but not be fatal
Add a new setup return code, -4 which will print the error, but not
error out in test mode. This is to support allowing incomplete hex, as
there is no context as to which rule had the issue.

For context:
- -3: error ok, no message
- -2: error not ok, no message
- -4: error ok, message
4 years ago
Victor Julien f40ad90adf detect: fix duplicate detect state issue
For protocols with multi buffer inspection there could be multiple times
the same sid would be queued into the candidates queue. This triggered
a debug validation check.

W/o debug validation this would lead to duplicate work and possibly multiple
alerts where a single one would be appropriate.

Bug: 5419.
(cherry picked from commit 1bff888947)
4 years ago
Philippe Antoine dbadca1567 detect: transforms check for 0-sized buffer
So as to avoid undefined behavior with a 0-sized variable length
array

Ticket: #5521
(cherry picked from commit 61b73416e2)
4 years ago
Juliana Fajardini fff9d529b7 exceptions: add reject support to exception policy
This enables the usage of 'reject' as an exception policy. As for both
IPS and IDS modes the intended result of sending a reject packet is to
reject the related flow, this will effectively mean setting the reject
action to the packet that triggered the exception condition, and then
dropping the associated flow.

Task #5503

(cherry picked from commit bbd968c738)
4 years ago
Victor Julien 336cd57234 stream/ids: make sure we don't slide past last_ack
Bug: #5401.
(cherry picked from commit f04b7a1827)
4 years ago
Victor Julien a383f29aa2 decode/tcp: allow 4 byte TFO with 2 byte cookie
(cherry picked from commit f5bd55dac8)
4 years ago
Gleb Smirnoff ae9b4144be ipfw: use PF_DIVERT on modern FreeBSD
(cherry picked from commit 5dbbc52b06)
4 years ago
Victor Julien d483ace444 unittests: optimize RunmodeIsUnittests()
(cherry picked from commit 86e600dab8)
4 years ago
Victor Julien 0a6e2b9d1a flow/recycler: bring back pthread_cond_t sleep
Bug #4379.

(cherry picked from commit f271fb4575)
4 years ago
Victor Julien 33446b0f64 flow/manager: sleep handled by pthread_cond_t again
Use only in live mode to allow FM to respond quickly to time
increases in offline mode.

Bug #4379.

(cherry picked from commit e6ac2e4e8a)
4 years ago
Victor Julien bb8f743870 time: add timeradd implementation
timeradd isn't available on MinGW.

(cherry picked from commit 39141a8836)
4 years ago
Philippe Antoine 739eba94a5 fuzz: restrict flags passed to AppLayerProtoDetectGetProto
Manual adaptation of 05f9b3f and f4449d3
4 years ago
Juliana Fajardini 05378946dc stream: add exception policy for midstream flows
This allows to set a midstream-policy that can:
- fail closed (stream.midstream-policy=drop-flow)
- fail open (stream.midstream-policy=pass-flow)
- bypass stream (stream.midstream-policy=bypass)
- do nothing (default behavior)

Usage and behavior:

If stream.midstream-policy is set then if Suricata identifies a midstream flow
it will apply the corresponding action associated with the policy.

No setting means Suricata will not apply such policies, either inspecting the
flow (if stream.midstream=true) or ignoring it stream.midstream=false.

Task #5468

(cherry picked from commit aa5bb2c329)
4 years ago
Juliana Fajardini 430bb1cf74 exceptions: add callbacks for drop-flow policy
Make sure that when the policy is to drop the flow, we set no inspection
for payload and packet and disable applayer inspection as well.

Task #5468

(cherry picked from commit 242b8f7d65)
4 years ago
Juliana Fajardini 0a124f2d27 exceptions: error out when invalid policy is used
Before, if an invalid value was passed as exception policy, Suricata
would log a warning and set the exception policy to "ignore". This is a
very different result, than, say, dropping or bypassing a midstream flow.

Task #5504

(cherry picked from commit 58ef3cde7a)
4 years ago
Juliana Fajardini d21d4c757e detect/parse: test sig parsing for more actions
Our unittests were only covering sig parsing for alert actions. As in
environments without LibNet the reject action will not work, we must
ensure that our parser properly fails in such cases, instead of silently
accepting an unsupported action.

Added tests for the reject and drop action.

Task #5496

(cherry picked from commit c81b78fd1c)
4 years ago
Juliana Fajardini 15ec08881e detect/engine: fix typos in assorted files
(cherry picked from commit 5f4bcfe313)
4 years ago
Juliana Fajardini 8f3ec86e17 commandline: add alert-queue expand failure option
For testing purposes. Meant to simulate a reallocation failure when
dynamically growing the alert queue in DetectEngineThreadCtx, so we can
check that Suri's behavior doesn't break under such circumstances.

Task #5319

(cherry picked from commit 58928b249d)
4 years ago
Philippe Antoine 7dc493cf55 fuzz: disable enip detection based on source port
So as to avoid fuzzing detecting protocol polyglots with enip

(cherry picked from commit d1ebf320f7)
4 years ago
Juliana Fajardini 1710c5f13d decode: remove unused macros
With the recent changes, these macros weren't being used anymore.

Related to
Bug #5458

(cherry picked from commit e7727c3744)
4 years ago
Juliana Fajardini dcf990c7d0 stream/tcp: remove repeated header declaration
StreamTcpRegisterTests was being declared twice.

(cherry picked from commit d07a6c6174)
4 years ago
Juliana Fajardini 2b59f65d02 detect/alert: add unittests to check packet action
Add unittests to check that packet flags are correctly updated after
detection finds drop or reject rules that match.

Related to
Bug #5458

(cherry picked from commit f897761ecb)
4 years ago
Juliana Fajardini b3ae9f840a decode: validate if dropped packet has drop reason
Related to
Bug #5458

(cherry picked from commit abd595d695)
4 years ago
Juliana Fajardini 32f90371d9 detect/alert: ensure reject action is applied
Bug 5458 states that the reject action is no longer working. While SV
tests that use the reject action still pass, it indeed seems that a
regression has happened with commit aa93984, because while the
function that applies rule actions to the flow (RuleActionToFlow) does
check for the reject action, the newly added function PacketApply
SignatureActions only checks for ACTION_DROP or ACTION_PASS when
deciding to call RuleActionToFlow.

Bug #5458

(cherry picked from commit 1f54e8611a)
4 years ago
Juliana Fajardini 6742ecbc9e decode: make PacketDrop use action as parameter
A Packet may be dropped due to several different reasons. This change
adds action as a parameter, so we can update the packet action when we
drop it, instead of setting it to drop.

Related to
Bug #5458

(cherry picked from commit 1774ff18a6)
4 years ago
Juliana Fajardini c56871c9e6 source/pcap: fix infinite loop if interface goes down
When in live-pcap mode, if the sniffed interface went down and up again,
Suri would enter an infinite and keep running, while not registering new
events. This fixes that behavior by allowing Suri to retry to open the
pcap in case of a retry on an already activated capture
('PCAP_ERROR_ACTIVATED').

This change is based on Zhiyuan Liao's work.

Bug #3846

(cherry picked from commit 2544be4672)
4 years ago
Jufajardini Reichow 41967bf119 detect/engine: init alert queue counters on reload
alert_queue_overflow and alerts_suppressed were not being
reinitialized when there was a reload of Suricata rules, leading to
non-valid stats counters if that happened.

Bug #5457

(cherry picked from commit 93c2c9743d)
4 years ago
Philippe Antoine 5df3973cc9 output: fix integer warnings
Ticket: 4516

(cherry picked from commit e3180e3248)
4 years ago
Philippe Antoine e55eeb3bde protocol: forbids concurrent protocol upgrades
Ticket: 5243

When switching from SMTP to TLS, and getting HTTP1 instead of
expected TLS, and HTTP1 requesting upgrade to HTTP2, we do not
overwrite the alproto_orig value so as not to have type confusion
in AppLayerParserStateProtoCleanup

(cherry picked from commit cedffdf14c)
4 years ago
Philippe Antoine 2c7c7cf315 output: skip files logging for ICMP packets
Ticket: #5408
(cherry picked from commit f8bf581775)
4 years ago
Philippe Antoine a71a474302 output: use flow's proto for file loggers
As there can be an ICMP packet which gets related to a TCP flow.

Ticket: #5408
(cherry picked from commit 5781631f85)
4 years ago
Eric Leblond 789b1ab4df output/alert: don't call basic logging twice
Issue: 4106
(cherry picked from commit 264eddb81f)
4 years ago
Philippe Antoine 84885c11c0 ftp: optimized tx iterator
To be more efficient with larger number of transactions.

Ticket: #5314
(cherry picked from commit 5a31b3508d)
4 years ago
Philippe Antoine ac6cdd973c event: only sets APPLAYER_UNEXPECTED_PROTOCOL once
If f->alproto == ALPROTO_UNKNOWN, we do not know the new protocol
yet, so we do not set the event yet.

(cherry picked from commit e692530021)
4 years ago
Philippe Antoine 48206f373d events: reset logged event
Otherwise, if we log a first app_layer_event, then reset
with AppLayerDecoderEventsResetEvents for a new packet,
then get another event, it does not get logged

Ticket: #5391
(cherry picked from commit b0298dd046)
4 years ago
Victor Julien c08a929de1 detect: impose limits on pcrexform
Impose match and recursion limits on pcrexform keywords.

Based on: 585e5e0d3c ("detect: impose limits on pcrexform")

Bug: #5414.
4 years ago
Victor Julien ac93f568eb fuzz/mime: fix call conditions and args
The SMTP parser should not supply lines w/o EOL chars to the mime
parser unless its in the BODY parsing stage. Mimic this in the fuzz
target by testing the state for inputs that have no EOL.

Additionally, make sure the delim cnt reflects the missing EOL.

(cherry picked from commit 816bbeb7dc)
4 years ago
Victor Julien 3384ca9be2 mime: fix and cleanup tests
Line count check was failing after recent delim handling updates.

(cherry picked from commit 074cfb5c68)
4 years ago
Victor Julien 7256445c21 mime: fix corner case
Fix a corner case where a base64 sequence including a space was followed
by a newline in the input data.

(cherry picked from commit d81582c4a2)
4 years ago
Victor Julien d15e0d5baf mime: add base64 related debug messages
(cherry picked from commit 5805ed47f5)
4 years ago
Victor Julien 9c25d10970 mime: improved empty line handling
Make sure a new body is not set up on empty lines unless it is
a body that is not encoded as base64/quoted printable.

(cherry picked from commit 41c2c1ed5a)
4 years ago
Victor Julien 7061dec732 smtp: fix passing a wrong delim len around
(cherry picked from commit 6e2c066ce1)
4 years ago
Victor Julien 58bce05764 mime: properly pass full lines to non-decoded body
Use actual delim count and make sure we also pass on empty lines
(so delim(s) only).

(cherry picked from commit b82b8825e7)
4 years ago
Victor Julien 420760a7ac mime/base64: fix final data not getting processed
If the last data of the body was not a multple of 4 and not padded
to be a multiple of 4, it would not be processed.

(cherry picked from commit 0d6ab727c5)
4 years ago
Victor Julien 909a3fdf42 stream: fix GAP check
Gap check would consider a GAP when the current data was in fact
exactly not a gap, but next segment(s) were already available.

(cherry picked from commit 100d821a9f)
4 years ago
Victor Julien 5740d10e34 mime: remove unused 'linerem' logic
(cherry picked from commit 0871029d17)
4 years ago
Victor Julien 0a6c61a564 smtp/mime: fix parsing edge case
Correctly track "remaining" bytes after partial base64 decoding.

Add comment clarifications and debug validation checks.

(cherry picked from commit 5953a7d2eb)
4 years ago
Victor Julien b4fd4c048b smtp: skip preprocessing for mime headers
Mime parser doesn't expect partial lines, which preprocessing can
provide. Add a check to let mime headers be handled by regular line
parsing.

(cherry picked from commit a38f2f2a52)
4 years ago
Victor Julien bf5d9d542b detect: set drop reason for rule based drops
Call `PacketDrop` with drop reason for drops, keep old logic
in place for the rest.

(cherry picked from commit a89840929b)
4 years ago
Victor Julien a32b02fb65 detect/tests: improve detection entry
Lots of tests still use SigMatchSignatures as their main detection
entry function, which bypassed some logic. Make it match main logic
more closely.

(cherry picked from commit e36b9b89a1)
4 years ago
Victor Julien 5fcbc8bb50 tests: fix drop test; cleanup
SigTestDropFlow04 was incorrectly expecting an alert in the packet
following a "drop" packet. The first drop is applied to the flow, so
it should lead to the 2nd packet being dropped before inspection is
run.

Clean up the test as well.

(cherry picked from commit 3874d08015)
4 years ago
Victor Julien 660484404f exceptions: initial exception-policy implementation
Adds a framework for setting exception policies. These would be called
when the engine reaches some kind of exception condition, like hitting
a memcap or some traffic processing error.

The policy gives control over what should happen next: drop the packet,
drop the packet and flow, bypass, etc.

Implements the policy for:

    stream: If stream session or reassembly memcaps are hit call the
    memcap policy on the packet and flow.

    flow: Apply policy when memcap is reached and no flow could be
    freed up.

    defrag: Apply policy when no tracker could be picked up.

    app-layer: Apply ppolicy if a parser reaches an error state.

All options default to 'ignore', which means the default behavior
is unchanged.

Adds commandline options: add simulation options for exceptions. These
are only exposed if compiled with `--enable-debug`.

Ticket: #5214.
Ticket: #5215.
Ticket: #5216.
Ticket: #5218.
Ticket: #5194.
(cherry picked from commit 8580499ded)
4 years ago
Victor Julien 3a55873eb8 eve/drop: log drop reason
Ticket: #5202.
(cherry picked from commit 0035673208)
4 years ago
Victor Julien aa66765253 flow: log action applied to all packets
Log if action applied to whole flow is drop or pass.

(cherry picked from commit 9a09fe454b)
4 years ago
Victor Julien 38744135ef detect: enforce flow drops earlier
Enforcing flow drops is now done earlier in the detection engine and
moved out of the IP-only engine where it didn't belong.

(cherry picked from commit 802c1ffee3)
4 years ago
Victor Julien d8b5d3d34a clang-format: disable for option table 4 years ago
Lukas Sismis 4c4b1de168 bypass: fix memory leak - reassign of FlowBypassInfo
In some situations bypass callback is called on already bypassed
flow. This allocates FlowBypassInfo structure for the flow but
does not check if the flow already has one.

Issue: #5368
(cherry picked from commit 05797c45bb)
4 years ago
Lukas Sismis 8fa5f3bdd4 bypass: af-packet: fix memory leak - reassign of EBPFBypassData
AF-Packet bypass function in some situations allocates EBPF bypass data
for an already bypassed flow and assigns it to the flow without any checks

Issue: #5368
(cherry picked from commit 8845c07a90)
4 years ago
Victor Julien e9b084e8ca detect/threshold: fix offline time handling issue
Due to the TIMEVAL_DIFF_SEC calculating the delta into an unsigned
integer, it would underflow to a high positive value leading to
and incorrect result if the packet timestamp was below the timestamp
for the threshold entry. In normal conditions this shouldn't happen,
but in offline mode each thread has its own concept of time which
might differ significantly based on the pcap. In this case the
overflow would be very common.

Changing it to a signed value calculation triggered fuzz undefined
behavior if the packet timeval was very high, so this patch takes a
new approach where it no longer calculates a diff but sets up the
"seconds" value we compare against as a timeval itself, and uses
that to compare.

Fixes: 9fafc1031c ("time: Add TIMEVAL_EARLIER and TIMEVAL_DIFF_SEC macros.")
Fixes: 82dc61f4c3 ("detect/threshold: Refactor threshold calculation to handle by_rule and by_both.")

Uses add `timeradd` specific version where available.

Bug: #5386.
(cherry picked from commit df2e408d96)
4 years ago
Victor Julien 643d502d9e stream/midstream: fix double flow reverse case
In the case of midstream SYN/ACK pickup, we reverse the flow based on
the SYN/ACK. If we then later get traffic that appears to be in the
reverse direction based on the app-layer, we would reverse it again.
This isn't correct. When we have the SYN/ACK we know the flow's real
direction.

(cherry picked from commit fea374626a)
4 years ago
Victor Julien 1f31eb9e58 app-layer: don't switch dir if proto already known
(cherry picked from commit 86e8611f5e)
4 years ago
Victor Julien 91ea80291f detect/dcerpc: simplify keyword validation
Now that the engine understands the relation between SMB and DCERPC better
we can get rid of some of the special case handling in keywords.

(cherry picked from commit 84e26d670e)
4 years ago
Victor Julien e65ab0fc90 detect/dcerpc: apply dcerpc to smb as well
So 'alert dcerpc' also matches if the DCERPC is over SMB.

Explicitly refuse smb keywords for the 'dcerpc' app proto setting:
`alert dceprc ... smb.share; ...` is rejected.

Remove a now useless special case in the stateless rule processing
matching for dcerpc/smb.

Bug: #5208.
(cherry picked from commit 7d38f5667d)
4 years ago
Victor Julien e9b88f67cc file: consistently track size of gaps
Until now only the size of gaps counted in the regular append, not
close and open.

Bug: #5392.
(cherry picked from commit 71ef62bfc5)
4 years ago
Michael Tremer aeee505ff2 stream: tcp: Handle retransmitted SYN with TSval
For connections that use TCP timestamps for which the first SYN packet
does not reach the server, any replies to retransmitted SYNs will be
tropped.

This is happening in StateSynSentValidateTimestamp, where the timestamp
value in a SYN-ACK packet must match the one from the SYN packet.
However, since the server never received the first SYN packet, it will
respond with an updated timestamp from any of the following SYN packets.

The timestamp value inside suricata is not being updated at any time
which should happen. This patch fixes that problem.

Bug: #4376.

Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
(cherry picked from commit f50af12068)
4 years ago
Victor Julien 9ab4c98430 detect/content: fix FNs due to bad depth calc
When trying to propegate the depth/offset, within/distance chains
a logic error would set too a restrictive depth on a pattern that
followed more than one "unchained" patterns.

Bug: #5162.
(cherry picked from commit 8d20b40cdd)
4 years ago
Victor Julien df0cca4537 detect/content: simplify int bounds checking
Use a macro to validate the ranges for overflows. This removes
the clutter of all the checks and warnings, and also no longer
puts the state machine in an undefined state when hitting such
a condition.

(cherry picked from commit 50d02ebc05)
4 years ago
Philippe Antoine 301af290ca detect: fix integer warnings for content
Ticket: #4516
(cherry picked from commit ac8fb553a1)
4 years ago
Philippe Antoine 249a3b5677 detect: parsing avoiding infinite loop
by comparing size_t to strlen result
Instead of uint16_t which would loop

Ticket: #5310
(cherry picked from commit ced96a8aad)
4 years ago
Jason Ish 6ba16e883e detect: introduce "like" ip-only signature type
Rules that look like they should be IP-only but contain a negated rule
address are now marked with an LIKE_IPONLY flag. This is so they are
treated like IPONLY rules with respect to flow action, but don't
interfere with other IPONLY processing like using the radix tree.

Ticket: #5361
(cherry picked from commit c8a5207083)
4 years ago
Victor Julien 5ed73e839f detect/iponly: remove unused code
(cherry picked from commit 51ef6f4e3a)
4 years ago
Victor Julien 0ffd310180 detect/iponly: include postmatch in determination
(cherry picked from commit beecc1890f)
4 years ago
Victor Julien ca3be76e23 smtp: remove defunct check for line with single LF
Don't fix it as DATA processing needs all the bytes.

(cherry picked from commit 96bb67f474)
4 years ago
Victor Julien 45083caf81 smtp: turn assertions in to debug asserts
(cherry picked from commit 77fae275ef)
4 years ago
Victor Julien 35145c1c6f smtp: simplify preprocess loop
(cherry picked from commit 3a631085bb)
4 years ago
Victor Julien 9e244a87ae mime/base64: decode cleanups and simplification
Addresses edge case: > 4 bytes at the end of the input with 2 or more
spaces.

Changes length type for remainder processing to allow for much longer
lines, which can happen in practice.

Adds a series of debug validation checks with real error handling
as well, to assist the fuzzer to find more edge cases.

(cherry picked from commit 30e47b2171)
4 years ago
Victor Julien e1a24c8ee7 base64: no special case for nul char
Let it be handled like other invalid input.

(cherry picked from commit 92cd95b416)
4 years ago
Shivani Bhardwaj 2eebad50cd base64: make decoder handle decoded data space constraints
So far, it was the job of caller to send the bae64 decoder a perfect
block of data and take care of the destination buffer (decoded data)
size. Now, make it the decoder's job to take care of any space
constraints that the destination buffer may have and return accordingly.

Also, handle space characters in base64 encoded data as per RFC 2045.

Update MIME parser accordingly to handle the base64 data.

Ticket: 5315
(cherry picked from commit 5b27619778)
4 years ago
Shivani Bhardwaj dec114d206 base64: add Base64Ecode enum
(cherry picked from commit cb01cc6929)
4 years ago
Shivani Bhardwaj 67220da86d base64: add Base64Mode enum
(cherry picked from commit 9131d1d857)
4 years ago
Shivani Bhardwaj 5390c61320 smtp: treat CR as a line terminator
The ideal line terminator for an SMTP line is <CRLF>. But, given that
bare LF is still allowed by many systems despite the prohibition by
standards, we have to consider that. In order to simplify things, we
consider bare CR as line terminators as well while updating the
delimiter parameter correctly if they were to be followed by a LF
immediately or as a part of next fragment.

This takes care of some edge cases that made base64 decoder error out
because unexpected data was sent to it at times.

Ticket: 5316
(cherry picked from commit 1e3282f363)
4 years ago
Victor Julien fef20c6426 runmodes: fix more warnings
(cherry picked from commit a535cc5a25)
4 years ago
Juliana Fajardini b3070b8ba9 detect/alert: directly increment alerts.discarded
In the unlikely case of AlertQueueExpand failure, we were incrementing
the discarded alerts stats in AlertQueueAppend via the Packet member in the
DetectEngineThreadCtx, which may not be initialized yet.

Bug #5353

(cherry picked from commit 28ac75b505)
4 years ago
Victor Julien afff6a3105 stream/unittests: fix failures after last_ack fix
Work around many tests not setting up stream completely or correctly.

(cherry picked from commit 3d6e733aa7)
4 years ago
Victor Julien 5be1c87a74 stream: improve last_ack validation check
If a packet after the initialization would come with ACK flag set
but a ACK value of 0, the last_ack tracking could get confused. Fix
this by not checking for 0 but instead checking if the ACK flag
has been seen.

Bug: #4549.
(cherry picked from commit 1f43e1477f)
4 years ago
Victor Julien cb51da6564 detect: optimize mpm-engine setup
Instead of a loop over the rules in a group *per engine* do a single
loop in which all the engines are prepared in parallel.

(cherry picked from commit 9e6370ae2e)
4 years ago
Philippe Antoine dfe3da7765 rust: RustParser same fields as AppLayerParser
So that there is no problem when crossing FFI

(cherry picked from commit c78722a671)
4 years ago
Sascha Steinbiss 87bec36093 util: add unit tests for CIDRFromMask()
(cherry picked from commit 5ec6f3ba51)
4 years ago
Sascha Steinbiss a2c5b8fc42 detect: make int CIDRFromMask() work on big endian platforms
(cherry picked from commit 394356f73c)
4 years ago
Victor Julien b4ee40eb38 detect: initialization optimization
A lot of time was spent in `SigMatchListSMBelongsTo` for the `mpm_sm`.

Optimize this by keeping the value at hand during Signature parsing and
detection engine setup.

(cherry picked from commit 3352c0bee4)
4 years ago
Victor Julien 246eb72ff4 memcmp: no-simd no case loop can scan forward
(cherry picked from commit f0479987ff)
4 years ago
Victor Julien 5f09a3245f memcmp: use SCMEMCMP_BYTES everywhere; general cleanups
(cherry picked from commit 0fc7ba45aa)
4 years ago
Victor Julien 37bd03f805 memcmp: remove unreachable code from memcmp simd
cppcheck:

src/util-memcmp.h:281:18: warning: Identical condition 'len-offset<16', second condition is always false [identicalConditionAfterEarlyExit]
        if (diff < 16) {
                 ^
src/util-memcmp.h:280:24: note: 'diff' is assigned value 'len-offset' here.
        int diff = len - offset;
                       ^
src/util-memcmp.h:269:33: note: If condition 'len-offset<16' is true, the function will return/exit
        if (likely(len - offset < 16)) {
                                ^
src/util-memcmp.h:281:18: note: Testing identical condition 'len-offset<16'
        if (diff < 16) {
                 ^
src/util-memcmp.h:344:18: warning: Identical condition 'len-offset<16', second condition is always false [identicalConditionAfterEarlyExit]
        if (diff < 16) {
                 ^
src/util-memcmp.h:343:24: note: 'diff' is assigned value 'len-offset' here.
        int diff = len - offset;
                       ^
src/util-memcmp.h:318:33: note: If condition 'len-offset<16' is true, the function will return/exit
        if (likely(len - offset < 16)) {
                                ^
src/util-memcmp.h:344:18: note: Testing identical condition 'len-offset<16'
        if (diff < 16) {
                 ^
src/util-memcmp.h:171:18: warning: Identical condition 'len-offset<16', second condition is always false [identicalConditionAfterEarlyExit]
        if (diff < 16) {
                 ^
src/util-memcmp.h:170:24: note: 'diff' is assigned value 'len-offset' here.
        int diff = len - offset;
                       ^
src/util-memcmp.h:159:33: note: If condition 'len-offset<16' is true, the function will return/exit
        if (likely(len - offset < 16)) {
                                ^
src/util-memcmp.h:171:18: note: Testing identical condition 'len-offset<16'
        if (diff < 16) {
                 ^
src/util-memcmp.h:233:18: warning: Identical condition 'len-offset<16', second condition is always false [identicalConditionAfterEarlyExit]
        if (diff < 16) {
                 ^
src/util-memcmp.h:232:24: note: 'diff' is assigned value 'len-offset' here.
        int diff = len - offset;
                       ^
src/util-memcmp.h:208:33: note: If condition 'len-offset<16' is true, the function will return/exit
        if (likely(len - offset < 16)) {
                                ^
src/util-memcmp.h:233:18: note: Testing identical condition 'len-offset<16'
        if (diff < 16) {
                 ^

(cherry picked from commit ca97ed4436)
4 years ago
Victor Julien 2dcb335993 memcmp: work around GCC 12+ 'blend' issues
Since GCC 12 the memcmp code using `_mm_blendv_epi8` failed to work.
Inspection of the disassembled objects suggests that it simply omits
the instruction on systems that are not AVX512 capable. On AVX512
it does replace it with VPCMPB logic that appears to work.

Luckily our use of blend is actually uncessary. A simple AND is sufficient.

Bug: #5312.
(cherry picked from commit 87c5d69437)
4 years ago
Arne Welzel 24caeb0f3f stacktrace-on-signal: Use kill(getpid(), sig_num)
kill(0, ...) re-raises the signal to every processes in the process
group which may impact unrelated processes.

Concretely, in our CI pipeline, a segfaulting Suricata process killed
the test driver.

(cherry picked from commit b6407c4253)
4 years ago
Eric Leblond 11159b3a21 util/ebpf: fix deprecation warning
The function bpf_program__title has been deprecated in favor of
bpf_program__section_name.

(cherry picked from commit d477d3a878)
4 years ago
Eric Leblond e8d96f71f1 util/ebpf: fix compilation
Bug: #5360
4 years ago
Victor Julien 1deba23376 log-pcap: remove redundant check
Check is always true but confuses cppcheck:

src/log-pcap.c:1224:32: warning: Either the condition 'filename' is redundant or there is possible null pointer dereference: filename. [nullPointerRedundantCheck]
    if ((pl->prefix = SCStrdup(filename)) == NULL) {
                               ^
src/log-pcap.c:1421:9: note: Assuming that condition 'filename' is not redundant
    if (filename) {
        ^
src/log-pcap.c:1224:32: note: Null pointer dereference
    if ((pl->prefix = SCStrdup(filename)) == NULL) {
                               ^

Bug: #5291.
(cherry picked from commit 3dfbf0bf11)
4 years ago
Eric Leblond bd66679b2e log/pcap: exit on invalid filename
If the filename has to % sign and if pcap logging is using multi
mode, then the pcap capture will fail. So let's exit if ever this
is the case.

(cherry picked from commit 921d44b262)
4 years ago
Victor Julien 9796c59b50 detect/pcre: assist code analyzer around pointer logic
cppcheck:

src/detect-pcre.c:381:27: warning: Either the condition 'pcap' is redundant or there is overflow in pointer subtraction. [nullPointerArithmeticRedundantCheck]
            cut_capture = MIN((pcap - regexstr), (fcap - regexstr));
                          ^
src/detect-pcre.c:378:18: note: Assuming that condition 'pcap' is not redundant
        else if (pcap && !fcap)
                 ^
src/detect-pcre.c:381:27: note: Null pointer subtraction
            cut_capture = MIN((pcap - regexstr), (fcap - regexstr));
                          ^

Bug: #5291.
(cherry picked from commit 69b8b48b94)
4 years ago
Victor Julien 10d697903f logopenfile: fix minor format string warning
cppcheck:

src/util-logopenfile.c:743:13: warning: %d in format string (no. 2) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
            snprintf(threaded_name, len, "%s.%d.%s", tname, unique_id, ext);
            ^
src/util-logopenfile.c:752:9: warning: %d in format string (no. 2) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
        snprintf(threaded_name, len, "%s.%d", original_name, unique_id);
        ^

Bug: #5291.
(cherry picked from commit 07d0ae04d3)
4 years ago
Victor Julien 0769cac7da ja3: fix minor format string warning
cppcheck:

src/util-ja3.c:197:28: warning: %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
        (*buffer)->used += snprintf((*buffer)->data, (*buffer)->size, "%d",
                           ^
src/util-ja3.c:201:28: warning: %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
        (*buffer)->used += snprintf((*buffer)->data + (*buffer)->used,
                           ^

Bug: #5291.
(cherry picked from commit 1e13f72785)
4 years ago
Victor Julien bd60eb1f44 af-packet/v2: use proper type for ring
cppcheck:

src/source-af-packet.c:1762:19: warning: Size of pointer 'v2' used instead of size of its data. This is likely to lead to a buffer overflow. You probably intend to write 'sizeof(*v2)'. [pointerSize]
        ptv->ring.v2 = SCMalloc(ptv->req.v2.tp_frame_nr * sizeof (union thdr *));
                  ^
src/source-af-packet.c:1767:26: warning: Size of pointer 'v2' used instead of size of its data. This is likely to lead to a buffer overflow. You probably intend to write 'sizeof(*v2)'. [pointerSize]
        memset(ptv->ring.v2, 0, ptv->req.v2.tp_frame_nr * sizeof (union thdr *));
                         ^

scan-build:

CC       source-af-packet.o
source-af-packet.c:1762:24: warning: Result of 'malloc' is converted to a pointer of type 'char', which is incompatible with sizeof operand type 'union thdr *' [unix.MallocSizeof]
        ptv->ring.v2 = SCMalloc(ptv->req.v2.tp_frame_nr * sizeof (union thdr *));
                       ^~~~~~~~                           ~~~~~~~~~~~~~~~~~~~~~
./util-mem.h:35:18: note: expanded from macro 'SCMalloc'
                 ^~~~~~
1 warning generated.

Bug: #5291.
(cherry picked from commit fedced209d)
4 years ago
Victor Julien f2e30e602c device: avoid uninit var warning
cppcheck:

src/util-device.c:455:17: error: Uninitialized variables: *ndev.dev, *ndev.tenant_id_set, *ndev.id, *ndev.next, *ndev.tenant_id, *ndev.offload_orig [uninitvar]
        *ldev = *ndev;
                ^
src/util-device.c:618:36: note: Calling function 'LiveDeviceForEach', 2nd argument '&ndev' value is <Uninit>
    while(LiveDeviceForEach(&ldev, &ndev)) {
                                   ^
src/util-device.c:455:17: note: Uninitialized variables: *ndev.dev, *ndev.tenant_id_set, *ndev.id, *ndev.next, *ndev.tenant_id, *ndev.offload_orig
        *ldev = *ndev;
                ^

Bug: #5291.
(cherry picked from commit 3bc50df9c3)
4 years ago
Victor Julien a6335a76b4 detect: fix bad BUG_ON pattern
cppcheck:

src/detect-engine-uint.c:73:13: warning: Conversion of string literal "unknown mode" to bool always evaluates to true. [incorrectStringBooleanError]
            BUG_ON("unknown mode");
            ^
src/detect-engine-uint.c:328:13: warning: Conversion of string literal "unknown mode" to bool always evaluates to true. [incorrectStringBooleanError]
            BUG_ON("unknown mode");
            ^
src/detect-pcre.c:291:25: warning: Conversion of string literal "Impossible captype" to bool always evaluates to true. [incorrectStringBooleanError]
                        BUG_ON("Impossible captype");
                        ^

Bug: #5291.
(cherry picked from commit 7e2ed11a11)
4 years ago
Victor Julien 33a65050fb time: fix warning in timestring creation
cppcheck:

src/util-time.c:255:18: warning: Either the condition 'str!=NULL' is redundant or there is possible null pointer dereference: str. [nullPointerRedundantCheck]
        snprintf(str, size, "ts-error");
                 ^
src/util-time.c:252:48: note: Assuming that condition 'str!=NULL' is not redundant
    if (likely(t != NULL && fmt != NULL && str != NULL)) {
                                               ^
src/util-time.c:255:18: note: Null pointer dereference
        snprintf(str, size, "ts-error");
                 ^

Only `t` could possibly be NULL if `localtime_r` fails elsewhere.

Bug: #5291.
(cherry picked from commit 2f48e432cd)
4 years ago
Victor Julien 60e50e0a0a detect/multi-tentancy: minor format string fixes
cppcheck:

src/detect-engine.c:3643:5: warning: %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
    snprintf(prefix, sizeof(prefix), "multi-detect.%d", tenant_id);
    ^
src/detect-engine.c:3707:5: warning: %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
    snprintf(prefix, sizeof(prefix), "multi-detect.%d.reload.%d", tenant_id, reload_cnt);
    ^
src/detect-engine.c:4086:17: warning: %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
                snprintf(prefix, sizeof(prefix), "multi-detect.%d", tenant_id);
                ^

Bug: #5291.
(cherry picked from commit 4fcb8740e7)
4 years ago
Victor Julien 447966db01 reference: remove useless var reset
cppcheck:

src/util-reference-config.c:179:9: warning: Assignment of function parameter has no effect outside the function. Did you forget dereferencing it? [uselessAssignmentPtrArg]
        fd = NULL;
        ^

Bug: #5291.
(cherry picked from commit 5a0bbb5289)
4 years ago
Victor Julien 1a4870b6f6 runmodes: minor format string fixes
cppcheck:

src/util-runmodes.c:210:9: warning: %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(tname, sizeof(tname), "%s#%02u", thread_name_workers, thread+1);
        ^
src/util-runmodes.c:211:9: warning: %u in format string (no. 1) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(qname, sizeof(qname), "pickup%u", thread+1);
        ^
src/util-runmodes.c:455:9: warning: %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(tname, sizeof(tname), "%s#%02u", thread_name_workers, thread+1);
        ^
src/util-runmodes.c:457:9: warning: %u in format string (no. 1) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(qname, sizeof(qname), "pickup%u", thread+1);
        ^

src/runmode-erf-file.c:188:9: warning: %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(tname, sizeof(tname), "%s#%02u", thread_name_workers, thread+1);
        ^
src/runmode-erf-file.c:189:9: warning: %u in format string (no. 1) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(qname, sizeof(qname), "pickup%u", thread+1);
        ^
src/runmode-pcap-file.c:201:9: warning: %u in format string (no. 2) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(tname, sizeof(tname), "%s#%02u", thread_name_workers, thread+1);
        ^
src/runmode-pcap-file.c:202:9: warning: %u in format string (no. 1) requires 'unsigned int' but the argument type is 'signed int'. [invalidPrintfArgType_uint]
        snprintf(qname, sizeof(qname), "pickup%u", thread+1);
        ^

Bug: #5291.
(cherry picked from commit 2965d809a4)
4 years ago
Victor Julien 346e69fc2b mpm/ac-ks: address int handling issues
cppcheck:

src/util-mpm-ac-ks.c:1452:5: warning: %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
    printf("Total states in the state table:    %d\n", ctx->state_count);
    ^
src/util-mpm-ac-ks.c:606:34: error: Signed integer overflow for expression '1<<31'. [integerOverflow]
        encoded_next_state |= (1 << 31);
                                 ^

Bug: #5291.
(cherry picked from commit a8d3cd6eb4)
4 years ago
Victor Julien c741f8cbad classification: remove useless clear
cppcheck:

src/util-classification-config.c:189:9: warning: Assignment of function parameter has no effect outside the function. Did you forget dereferencing it? [uselessAssignmentPtrArg]
        fd = NULL;
        ^

Bug: #5291.
(cherry picked from commit 9c672a805f)
4 years ago
Victor Julien a49450b70b detect/content-inspect: code cleanup
Rearrange code slightly to make it more clear that `found` cannot
be NULL further down the loop.

cppcheck:

src/detect-engine-content-inspection.c:316:50: warning: Either the condition 'found!=NULL' is redundant or there is overflow in pointer subtraction. [nullPointerArithmeticRedundantCheck]
                match_offset = (uint32_t)((found - buffer) + cd->content_len);
                                                 ^
src/detect-engine-content-inspection.c:308:30: note: Assuming that condition 'found!=NULL' is not redundant
            } else if (found != NULL && (cd->flags & DETECT_CONTENT_NEGATED)) {
                             ^
src/detect-engine-content-inspection.c:316:50: note: Null pointer subtraction
                match_offset = (uint32_t)((found - buffer) + cd->content_len);
                                                 ^

Bug: #5291.
(cherry picked from commit 27e9a871d0)
4 years ago
Victor Julien 8d05086608 detect/analyzer: minor format string fixes
cppcheck flagged this as:

src/detect-engine-analyzer.c:1359:13: warning: %d in format string (no. 1) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
            fprintf(rule_engine_analysis_FD, "    Rule contains %d content options, %d http content options, %d pcre options, and %d pcre options with http modifiers.\n", rule_content, rule_content_http, rule_pcre, rule_pcre_http);
            ^
src/detect-engine-analyzer.c:1359:13: warning: %d in format string (no. 2) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
            fprintf(rule_engine_analysis_FD, "    Rule contains %d content options, %d http content options, %d pcre options, and %d pcre options with http modifiers.\n", rule_content, rule_content_http, rule_pcre, rule_pcre_http);
            ^
src/detect-engine-analyzer.c:1359:13: warning: %d in format string (no. 3) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
            fprintf(rule_engine_analysis_FD, "    Rule contains %d content options, %d http content options, %d pcre options, and %d pcre options with http modifiers.\n", rule_content, rule_content_http, rule_pcre, rule_pcre_http);
            ^
src/detect-engine-analyzer.c:1359:13: warning: %d in format string (no. 4) requires 'int' but the argument type is 'unsigned int'. [invalidPrintfArgType_sint]
            fprintf(rule_engine_analysis_FD, "    Rule contains %d content options, %d http content options, %d pcre options, and %d pcre options with http modifiers.\n", rule_content, rule_content_http, rule_pcre, rule_pcre_http);
            ^

Bug: #5291.
(cherry picked from commit a0847e6c69)
4 years ago
Victor Julien 51bcec25a5 detect/address: remove useless checks
Cppcheck flagged this:

src/detect-engine-address.c:1035:48: warning: Either the condition 'ghn!=NULL' is redundant or there is possible null pointer dereference: gh. [nullPointerRedundantCheck]
    int r = DetectAddressIsCompleteIPSpaceIPv4(gh->ipv4_head);
                                               ^
src/detect-engine-address.c:1297:17: note: Assuming that condition 'ghn!=NULL' is not redundant
        if (ghn != NULL) {
                ^
src/detect-engine-address.c:1283:44: note: Calling function 'DetectAddressIsCompleteIPSpace', 1st argument 'ghn' value is 0
        if (DetectAddressIsCompleteIPSpace(ghn)) {
                                           ^
src/detect-engine-address.c:1035:48: note: Null pointer dereference
    int r = DetectAddressIsCompleteIPSpaceIPv4(gh->ipv4_head);
                                               ^

Cleanup code could only be reached with non-NULL pointers, so simplify checks.

Bug: #5291.
(cherry picked from commit f8a0f3d9b9)
4 years ago
Victor Julien 6a3517ce5d detect/ipv6: remove useless code
Remove useless allocation and free.

Found by cppcheck as a potential issue:

src/detect-engine-address-ipv6.c:385:12: warning: Either the condition 'tmp!=NULL' is redundant or there is possible null pointer dereference: tmp. [nullPointerRedundantCheck]
    memset(tmp,0,sizeof(DetectAddress));
           ^
src/detect-engine-address-ipv6.c:525:13: note: Assuming that condition 'tmp!=NULL' is not redundant
    if (tmp != NULL)
            ^
src/detect-engine-address-ipv6.c:385:12: note: Null pointer dereference
    memset(tmp,0,sizeof(DetectAddress));
           ^

But code turned out not to do anything, so removed.

Bug: #5291.
(cherry picked from commit bad9005161)
4 years ago
Victor Julien 0cc9d2445d datasets: fix cppcheck warning
src/datasets.c:107:17: error: Uninitialized variable: hash [uninitvar]
    memcpy(out, hash, outs);
                ^
src/datasets.c:93:26: note: Assuming condition is false
    for (x = 0, i = 0; i < ins; i+=2, x++) {
                         ^
src/datasets.c:107:17: note: Uninitialized variable: hash
    memcpy(out, hash, outs);
                ^

Bug: #5291.
(cherry picked from commit ea2d0ecf08)
4 years ago
Victor Julien 35f335ea86 ftp-data: fix direction for active mode commands
Set correct direction for PORT mode, where the server connects
to the client.

The direction is not also strictly enforced. No data in the wrong
direction will be accepted to setup the file or to be added to the
file after setup.

This also fixes files getting closed twice.

Adds some general cleanups.

Bug: #3542.
(cherry picked from commit 07bf921451)
4 years ago
Juliana Fajardini 3a249507b7 ippair/storage: use dedicated 'id' type
- Wrap the id in a new IPPairStorageId struct, to avoid id
confusion with other storage API calls.
- Formatting fixes by clang.

(cherry picked from commit cf516de587)
4 years ago
Victor Julien bf98494ae8 flow/storage: use dedicated 'id' type
Wrap the id in a new FlowStorageId struct to avoid id confusion with other
storage API calls.

(cherry picked from commit bc667a4a93)
4 years ago
Victor Julien 781712a338 app-layer/expectation: clean up storage id logic
(cherry picked from commit 4b3be24506)
4 years ago
Shivani Bhardwaj d11948d631 detect/flowbits: remove dead code 4 years ago
Shivani Bhardwaj c3f26ac44c detect/flowbits: add test for bug 5154 4 years ago
Shivani Bhardwaj 044709e933 detect/flowbits: use strtok_r for parsing
Fixes underlying parsing issues by keeping stricter argument checks.

Redmine Bug: 5154
4 years ago
Jason Ish 8c459af51b ftp: truncate first segment if over max length
The first segment was not limited to the configured maximum line length
allowing it to be up to 65k. This could result in the next input length
being negative, which while handled properly by the code, did trigger a
debug validation assertion.

The fix is to be consistent and apply the limit to the first segment as
well, which does ensure the input_len could never be less than 0.

Ticket #5281

(cherry picked from commit 9645285dff)
4 years ago
Juliana Fajardini 667dc6135c detect: update copyright years
(cherry picked from commit 192360aa05)
4 years ago
Juliana Fajardini dfb503b597 assorted: fix low hanging typos
(cherry picked from commit 29b5f68bf0)
4 years ago
Juliana Fajardini 0ca01f5003 detect/stats: log out total of suppressed alerts
Related to
Task #4943
Task #5179

(cherry picked from commit 877b32c1e4)
4 years ago
Juliana Fajardini 04eefa5ab8 detect/stats: log out total of discarded alerts
Add a counter to our stats log with the total of alerts that have been
discarded due to packet alert queue overflow.

Task #5179

(cherry picked from commit 8616c90fe7)
4 years ago
Juliana Fajardini d5fc80e79a detect/alert: move apply-action-flow code to func
Trying to clean PacketAlertFinalize a bit more.

(cherry picked from commit 9b275d3878)
4 years ago
Juliana Fajardini 5932b9f822 detect/alert: remove unused functions
Since we now only copy the PacketAlerts to the Packet's queue after
processing them, we no longer do packet alert appending from
detect-engine-alert, nor do we remove PacketAlerts from the queue (if
they're discarded by overflow or thresholding, they're not copied to the
final alert queue).

Task #4943

(cherry picked from commit e4e688a9b0)
4 years ago
Juliana Fajardini faea583d9b detect/alert: preprocess then append alert queue
Do all alert queue processing before actually appending
the PacketAlerts to the Packet's alert queue.

Adjusted changes to use macro instead of functions, in cases where the
latter didn't exist in this branch.

Task #4943

(cherry picked from commit 185b43edff)
4 years ago
Juliana Fajardini 13fd8ced10 detect/engine: use alert queue from det_ctx
Task #4943

(cherry picked from commit aa547a8de3)
4 years ago
Juliana Fajardini b27c6bac38 detect/alert: add infra for new alert queue
Initial work to bring part of the alert queue processing to
DetectEngineThreadCtx.

Task #4943

(cherry picked from commit 88805f03ee)
4 years ago
Juliana Fajardini b699be4da9 decode: make packet_alert_max configurable
The maximum of possible alerts triggered by a unique packet was
hardcoded to 15. With usage of 'noalert' rules, that limit could be
reached somewhat easily. Make that configurable via suricata.yaml.

Conf Bug#4941

Task #4207

(cherry picked from commit 3ace577d54)
4 years ago
Juliana Fajardini ccd4534581 unittests: alloc Packet with PacketGetFromAlloc
Some unittests used SCMalloc for allocating new Packet the unittests.
While this is valid, it leads to segmentation faults when we move to
dynamic allocation of the maximum alerts allowed to be triggered by a
single packet.

This massive patch uses PacketGetFromAlloc, which initializes a Packet
in such a way that any dynamic allocated structures within will also be
initialized.

Backport: edit a few more files/unittests that were not present in 7.0.x

Related to
Task #4207

(cherry picked from commit a6bda3596b)
4 years ago
Jeff Lucovsky 6d40181ede signal/stack: Default stack-on-signal setting: off
Ticket: 5228

This commit changes the default value of the stack-on-signal feature to
be disabled.
4 years ago
Jeff Lucovsky 5c997a7e16 signal/stack: Remove redundant initialization
Ticket: 5228

This commit removes the redundant initialization of the stack-on-signal
functionality.
4 years ago
Victor Julien 8a353c5775 detect: fix rule inspection order
Fix rules from the 'match' list getting added to the tx candidates list
unsorted. In some cases this could lead to the same sid getting inspected
twice leading to a DEBUG_VALIDATION_BUG_ON trigger.

Bug: #5144.
(cherry picked from commit 4bb00964ac)
4 years ago
Victor Julien f4a556c936 detect: use bool for uint16_t used as bool
(cherry picked from commit bb3d49d5bf)
4 years ago
Victor Julien 386b646887 stream: improve flow end payload logging
Use all available data, including un-ACK'd, when in flow timeout
mode.

Bug: #5276.
(cherry picked from commit c40df43609)
4 years ago
Victor Julien ab97fbbc38 stream/unittests: fix failures after last_ack fix
Work around many tests not setting up stream completely or correctly.

(cherry picked from commit 3d6e733aa7)
4 years ago
Victor Julien 51c1a54dfb stream: improve last_ack validation check
If a packet after the initialization would come with ACK flag set
but a ACK value of 0, the last_ack tracking could get confused. Fix
this by not checking for 0 but instead checking if the ACK flag
has been seen.

Bug: #4549.
(cherry picked from commit 1f43e1477f)
4 years ago
Victor Julien bb0a947b79 smtp: support per-tx file accounting
(cherry picked from commit 0867b0dbcd)
4 years ago
Modupe Falodun e137627e72 detect-file-data: remove SMTP unittests
These tests are reimplemented as Suricata-verify tests

Task: 4938
(cherry picked from commit 3dbf74ff10)
4 years ago
Victor Julien cb3e66d6e9 smtp: don't pass partial boundary on to mime parser
If the start of a line looks like it might be a mime boundary we
yield to the get line logic if we don't have enough data to be
conclusive.

(cherry picked from commit e7417a8e96)
4 years ago
Victor Julien 17ed7836a3 mime: allow partial lines as input
If we get a zero length delim we assume its a partial line and we
won't append CRLF just yet.

(cherry picked from commit 6e800a8548)
4 years ago
Shivani Bhardwaj a63133a4b6 smtp: pre process DATA and BDAT commands
The input data received in DATA and BDAT command modes can be huge and
could have important data, like a legit huge email. Therefore, exempt
these from the line buffering limits which were introduced to regulate
the size of lines that we buffer at any point in time.

As a part of this patch, anything that comes under DATA or BDAT is
processed early without buffering as and when it arrives. The ways of
processing remain the same as before.

(cherry picked from commit cf749fd450)
4 years ago
Shivani Bhardwaj 7f5115395f smtp: fix indefinite buffering if no LF in line
Issue
-----
So far, with the SMTP parser, we would buffer data up until an LF char
was found indicating the end of one line. This would happen in case of
fragmented data where a line might come broken into multiple chunks.
This was problematic if there was a really long line without any LF
character. It would mean that we'd keep buffering data up until we
encounter one such LF char which may be many many bytes of data later.

Fix
---
Fix this issue by setting an upper limit of 4KB on the buffering of
lines. If the limit is reached then we save the data into current line
and process it as if it were a regular request/response up until 4KB
only. Any data after 4KB is discarded up until there is a new LF char in
the received input.

Cases
-----
1. Fragmentation
The limit is enforced for any cases where a line of >= 4KB comes as diff
fragments that are each/some < 4KB.
2. Single too long line
The limit is also enforced for any cases where a single line exceeds the
limit of buffer.

Reported by Victor Julien.
Ticket 5023

(cherry picked from commit 078c251dea)
4 years ago
Shivani Bhardwaj 7d30fb152a smtp: add truncated line event
(cherry picked from commit 57a7cf7a0b)
4 years ago
Shivani Bhardwaj fba25c1923 smtp: use AppLayerResult instead of buffering
Also, remove tests that check for the removed buffers and any middle
states while parsing and buffering.

Ticket 4907

(cherry picked from commit 8918f53f6b)
4 years ago
Jason Ish 008dd8bde5 ftp: truncate command data that is too long
FTP control commands will be buffered forever until a new line is seen,
this can lead to memory exhaustion in Suricata.

To fix, set an upper bound, 4096 bytes on the size of the command that
is saved in the transaction. The input continues to be parsed to find
the end of the command so the parser can continue to move onto the next
command.

The result is that the command data in the transaction is truncated,
which also shows up in the ftp transaction logs.

This value is configurable with the max-line-length field in the ftp
app-layer.protocols section.

As FTP doesn't have events at this time, add a new fields to eve-log
that specificy if the request, or the response has been truncated.

Ticket #5024

(cherry-picked from commit cf8ed576e0)
4 years ago
Philippe Antoine da824d8252 detect: config checks alstate before getting tx
Ticket: 4972

As is done in detect-lua-extensions.
We can have a flow with alproto unknown, no state, and therefore
cannot run AppLayerParserGetTx which could try to run a NULL
function

(cherry picked from commit dccf2e4c30)
4 years ago
Philippe Antoine 483194893e detect: not an iponly signature if it needs app-layer
Ticket: 4972

This may happen with `config` keyword which is postmatch,
but may require a transaction

(cherry picked from commit 0cba561fec)
4 years ago
Philippe Antoine d4d8b4c5b3 detect: makes config keyword really require a flow
Ticket: 4972

Completes commit c3a220647

DETECT_CONFIG is added as DETECT_SM_LIST_POSTMATCH and not
as DETECT_SM_LIST_MATCH as other keywords handled in SignatureCreateMask

(cherry picked from commit 00da0d3420)
4 years ago
Philippe Antoine 272f082b85 detect: only apply ConfigApplyTx with app-layers
Ticket: 4972

Otherwise, it makes no sense to look for a tx...

(cherry picked from commit c3a220647b)
4 years ago
Jason Ish 947cb09e5b smb: protocol detection on pattern without midstream
To recognize a protocol, Suricata first looks for
patterns, which can be confirmed by a probing parser.
If this does not work, Suricata can try to run
some probing parsers on some ports.

This is the case for SMB.

This commit makes handling the confirming and the probing
paser differently even if they share much code.

The confirmation parser knows that a pattern has been found.
So, it must not do the midstream case of looking for this
pattern in the whole buffer, but only check it at the beginning.
But it must reverse direction if needed.

Ticket #4849

Backported manually by jason.ish@oisf.net.

(cherry picked from commit 464ff80c6a)
4 years ago
Philippe Antoine c6a0709dc8 ftp: do not set alproto if one was already found
Ticket: 4857

If a pattern such as GET is seen ine the beginning of the
file transferred over ftp-data, this flow will get recognized
as HTTP, and a HTTP state will be created during parsing.

Thus, we cannot override directly alproto's values

This solves the segfault, but not the logical bug that the flow
should be classified as FTP-DATA instead of HTTP

(cherry picked from commit dd32238667)
4 years ago