1 /* Copyright (C) 2007-2020 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Victor Julien <victor@inliniac.net>
22  */
23 
24 #ifndef __DECODE_H__
25 #define __DECODE_H__
26 
27 //#define DBG_THREADS
28 #define COUNTERS
29 
30 #include "suricata-common.h"
31 #include "suricata-plugin.h"
32 #include "threadvars.h"
33 #include "util-debug.h"
34 #include "decode-events.h"
35 #include "flow-worker.h"
36 
37 #ifdef HAVE_NAPATECH
38 #include "util-napatech.h"
39 #endif /* HAVE_NAPATECH */
40 
41 
42 typedef enum {
43     CHECKSUM_VALIDATION_DISABLE,
44     CHECKSUM_VALIDATION_ENABLE,
45     CHECKSUM_VALIDATION_AUTO,
46     CHECKSUM_VALIDATION_RXONLY,
47     CHECKSUM_VALIDATION_KERNEL,
48 } ChecksumValidationMode;
49 
50 enum PktSrcEnum {
51     PKT_SRC_WIRE = 1,
52     PKT_SRC_DECODER_GRE,
53     PKT_SRC_DECODER_IPV4,
54     PKT_SRC_DECODER_IPV6,
55     PKT_SRC_DECODER_TEREDO,
56     PKT_SRC_DEFRAG,
57     PKT_SRC_FFR,
58     PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH,
59     PKT_SRC_DECODER_VXLAN,
60     PKT_SRC_DETECT_RELOAD_FLUSH,
61     PKT_SRC_CAPTURE_TIMEOUT,
62     PKT_SRC_DECODER_GENEVE,
63 };
64 
65 #include "source-nflog.h"
66 #include "source-nfq.h"
67 #include "source-ipfw.h"
68 #include "source-pcap.h"
69 #include "source-af-packet.h"
70 #include "source-netmap.h"
71 #include "source-windivert.h"
72 #ifdef HAVE_PF_RING_FLOW_OFFLOAD
73 #include "source-pfring.h"
74 #endif
75 
76 #include "action-globals.h"
77 
78 #include "decode-erspan.h"
79 #include "decode-ethernet.h"
80 #include "decode-chdlc.h"
81 #include "decode-gre.h"
82 #include "decode-geneve.h"
83 #include "decode-ppp.h"
84 #include "decode-pppoe.h"
85 #include "decode-sll.h"
86 #include "decode-ipv4.h"
87 #include "decode-ipv6.h"
88 #include "decode-icmpv4.h"
89 #include "decode-icmpv6.h"
90 #include "decode-tcp.h"
91 #include "decode-udp.h"
92 #include "decode-sctp.h"
93 #include "decode-raw.h"
94 #include "decode-null.h"
95 #include "decode-vlan.h"
96 #include "decode-vntag.h"
97 #include "decode-vxlan.h"
98 #include "decode-mpls.h"
99 
100 #include "detect-reference.h"
101 
102 #include "app-layer-protos.h"
103 
104 /* forward declarations */
105 struct DetectionEngineThreadCtx_;
106 typedef struct AppLayerThreadCtx_ AppLayerThreadCtx;
107 
108 struct PktPool_;
109 
110 /* declare these here as they are called from the
111  * PACKET_RECYCLE and PACKET_CLEANUP macro's. */
112 typedef struct AppLayerDecoderEvents_ AppLayerDecoderEvents;
113 void AppLayerDecoderEventsResetEvents(AppLayerDecoderEvents *events);
114 void AppLayerDecoderEventsFreeEvents(AppLayerDecoderEvents **events);
115 
116 /* Address */
117 typedef struct Address_ {
118     char family;
119     union {
120         uint32_t        address_un_data32[4]; /* type-specific field */
121         uint16_t        address_un_data16[8]; /* type-specific field */
122         uint8_t         address_un_data8[16]; /* type-specific field */
123         struct in6_addr address_un_in6;
124     } address;
125 } Address;
126 
127 #define addr_data32 address.address_un_data32
128 #define addr_data16 address.address_un_data16
129 #define addr_data8  address.address_un_data8
130 #define addr_in6addr    address.address_un_in6
131 
132 #define COPY_ADDRESS(a, b) do {                    \
133         (b)->family = (a)->family;                 \
134         (b)->addr_data32[0] = (a)->addr_data32[0]; \
135         (b)->addr_data32[1] = (a)->addr_data32[1]; \
136         (b)->addr_data32[2] = (a)->addr_data32[2]; \
137         (b)->addr_data32[3] = (a)->addr_data32[3]; \
138     } while (0)
139 
140 /* Set the IPv4 addresses into the Addrs of the Packet.
141  * Make sure p->ip4h is initialized and validated.
142  *
143  * We set the rest of the struct to 0 so we can
144  * prevent using memset. */
145 #define SET_IPV4_SRC_ADDR(p, a) do {                              \
146         (a)->family = AF_INET;                                    \
147         (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_src.s_addr; \
148         (a)->addr_data32[1] = 0;                                  \
149         (a)->addr_data32[2] = 0;                                  \
150         (a)->addr_data32[3] = 0;                                  \
151     } while (0)
152 
153 #define SET_IPV4_DST_ADDR(p, a) do {                              \
154         (a)->family = AF_INET;                                    \
155         (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_dst.s_addr; \
156         (a)->addr_data32[1] = 0;                                  \
157         (a)->addr_data32[2] = 0;                                  \
158         (a)->addr_data32[3] = 0;                                  \
159     } while (0)
160 
161 /* clear the address structure by setting all fields to 0 */
162 #define CLEAR_ADDR(a) do {       \
163         (a)->family = 0;         \
164         (a)->addr_data32[0] = 0; \
165         (a)->addr_data32[1] = 0; \
166         (a)->addr_data32[2] = 0; \
167         (a)->addr_data32[3] = 0; \
168     } while (0)
169 
170 /* Set the IPv6 addresses into the Addrs of the Packet.
171  * Make sure p->ip6h is initialized and validated. */
172 #define SET_IPV6_SRC_ADDR(p, a) do {                    \
173         (a)->family = AF_INET6;                         \
174         (a)->addr_data32[0] = (p)->ip6h->s_ip6_src[0];  \
175         (a)->addr_data32[1] = (p)->ip6h->s_ip6_src[1];  \
176         (a)->addr_data32[2] = (p)->ip6h->s_ip6_src[2];  \
177         (a)->addr_data32[3] = (p)->ip6h->s_ip6_src[3];  \
178     } while (0)
179 
180 #define SET_IPV6_DST_ADDR(p, a) do {                    \
181         (a)->family = AF_INET6;                         \
182         (a)->addr_data32[0] = (p)->ip6h->s_ip6_dst[0];  \
183         (a)->addr_data32[1] = (p)->ip6h->s_ip6_dst[1];  \
184         (a)->addr_data32[2] = (p)->ip6h->s_ip6_dst[2];  \
185         (a)->addr_data32[3] = (p)->ip6h->s_ip6_dst[3];  \
186     } while (0)
187 
188 /* Set the TCP ports into the Ports of the Packet.
189  * Make sure p->tcph is initialized and validated. */
190 #define SET_TCP_SRC_PORT(pkt, prt) do {            \
191         SET_PORT(TCP_GET_SRC_PORT((pkt)), *(prt)); \
192     } while (0)
193 
194 #define SET_TCP_DST_PORT(pkt, prt) do {            \
195         SET_PORT(TCP_GET_DST_PORT((pkt)), *(prt)); \
196     } while (0)
197 
198 /* Set the UDP ports into the Ports of the Packet.
199  * Make sure p->udph is initialized and validated. */
200 #define SET_UDP_SRC_PORT(pkt, prt) do {            \
201         SET_PORT(UDP_GET_SRC_PORT((pkt)), *(prt)); \
202     } while (0)
203 #define SET_UDP_DST_PORT(pkt, prt) do {            \
204         SET_PORT(UDP_GET_DST_PORT((pkt)), *(prt)); \
205     } while (0)
206 
207 /* Set the SCTP ports into the Ports of the Packet.
208  * Make sure p->sctph is initialized and validated. */
209 #define SET_SCTP_SRC_PORT(pkt, prt) do {            \
210         SET_PORT(SCTP_GET_SRC_PORT((pkt)), *(prt)); \
211     } while (0)
212 
213 #define SET_SCTP_DST_PORT(pkt, prt) do {            \
214         SET_PORT(SCTP_GET_DST_PORT((pkt)), *(prt)); \
215     } while (0)
216 
217 
218 
219 #define GET_IPV4_SRC_ADDR_U32(p) ((p)->src.addr_data32[0])
220 #define GET_IPV4_DST_ADDR_U32(p) ((p)->dst.addr_data32[0])
221 #define GET_IPV4_SRC_ADDR_PTR(p) ((p)->src.addr_data32)
222 #define GET_IPV4_DST_ADDR_PTR(p) ((p)->dst.addr_data32)
223 
224 #define GET_IPV6_SRC_IN6ADDR(p) ((p)->src.addr_in6addr)
225 #define GET_IPV6_DST_IN6ADDR(p) ((p)->dst.addr_in6addr)
226 #define GET_IPV6_SRC_ADDR(p) ((p)->src.addr_data32)
227 #define GET_IPV6_DST_ADDR(p) ((p)->dst.addr_data32)
228 #define GET_TCP_SRC_PORT(p)  ((p)->sp)
229 #define GET_TCP_DST_PORT(p)  ((p)->dp)
230 
231 #define GET_PKT_LEN(p) ((p)->pktlen)
232 #define GET_PKT_DATA(p) ((((p)->ext_pkt) == NULL ) ? (uint8_t *)((p) + 1) : (p)->ext_pkt)
233 #define GET_PKT_DIRECT_DATA(p) (uint8_t *)((p) + 1)
234 #define GET_PKT_DIRECT_MAX_SIZE(p) (default_packet_size)
235 
236 #define SET_PKT_LEN(p, len) do { \
237     (p)->pktlen = (len); \
238     } while (0)
239 
240 
241 /* Port is just a uint16_t */
242 typedef uint16_t Port;
243 #define SET_PORT(v, p) ((p) = (v))
244 #define COPY_PORT(a,b) ((b) = (a))
245 
246 #define CMP_ADDR(a1, a2) \
247     (((a1)->addr_data32[3] == (a2)->addr_data32[3] && \
248       (a1)->addr_data32[2] == (a2)->addr_data32[2] && \
249       (a1)->addr_data32[1] == (a2)->addr_data32[1] && \
250       (a1)->addr_data32[0] == (a2)->addr_data32[0]))
251 #define CMP_PORT(p1, p2) \
252     ((p1) == (p2))
253 
254 /*Given a packet pkt offset to the start of the ip header in a packet
255  *We determine the ip version. */
256 #define IP_GET_RAW_VER(pkt) ((((pkt)[0] & 0xf0) >> 4))
257 
258 #define PKT_IS_IPV4(p)      (((p)->ip4h != NULL))
259 #define PKT_IS_IPV6(p)      (((p)->ip6h != NULL))
260 #define PKT_IS_TCP(p)       (((p)->tcph != NULL))
261 #define PKT_IS_UDP(p)       (((p)->udph != NULL))
262 #define PKT_IS_ICMPV4(p)    (((p)->icmpv4h != NULL))
263 #define PKT_IS_ICMPV6(p)    (((p)->icmpv6h != NULL))
264 #define PKT_IS_TOSERVER(p)  (((p)->flowflags & FLOW_PKT_TOSERVER))
265 #define PKT_IS_TOCLIENT(p)  (((p)->flowflags & FLOW_PKT_TOCLIENT))
266 
267 #define IPH_IS_VALID(p) (PKT_IS_IPV4((p)) || PKT_IS_IPV6((p)))
268 
269 /* Retrieve proto regardless of IP version */
270 #define IP_GET_IPPROTO(p) \
271     (p->proto ? p->proto : \
272     (PKT_IS_IPV4((p))? IPV4_GET_IPPROTO((p)) : (PKT_IS_IPV6((p))? IPV6_GET_L4PROTO((p)) : 0)))
273 
274 /* structure to store the sids/gids/etc the detection engine
275  * found in this packet */
276 typedef struct PacketAlert_ {
277     SigIntId num; /* Internal num, used for sorting */
278     uint8_t action; /* Internal num, used for sorting */
279     uint8_t flags;
280     const struct Signature_ *s;
281     uint64_t tx_id;
282 } PacketAlert;
283 
284 /* flag to indicate the rule action (drop/pass) needs to be applied to the flow */
285 #define PACKET_ALERT_FLAG_APPLY_ACTION_TO_FLOW 0x1
286 /** alert was generated based on state */
287 #define PACKET_ALERT_FLAG_STATE_MATCH   0x02
288 /** alert was generated based on stream */
289 #define PACKET_ALERT_FLAG_STREAM_MATCH  0x04
290 /** alert is in a tx, tx_id set */
291 #define PACKET_ALERT_FLAG_TX            0x08
292 /** action was changed by rate_filter */
293 #define PACKET_ALERT_RATE_FILTER_MODIFIED   0x10
294 
295 #define PACKET_ALERT_MAX 15
296 
297 typedef struct PacketAlerts_ {
298     uint16_t cnt;
299     PacketAlert alerts[PACKET_ALERT_MAX];
300     /* single pa used when we're dropping,
301      * so we can log it out in the drop log. */
302     PacketAlert drop;
303 } PacketAlerts;
304 
305 /** number of decoder events we support per packet. Power of 2 minus 1
306  *  for memory layout */
307 #define PACKET_ENGINE_EVENT_MAX 15
308 
309 /** data structure to store decoder, defrag and stream events */
310 typedef struct PacketEngineEvents_ {
311     uint8_t cnt;                                /**< number of events */
312     uint8_t events[PACKET_ENGINE_EVENT_MAX];   /**< array of events */
313 } PacketEngineEvents;
314 
315 typedef struct PktVar_ {
316     uint32_t id;
317     struct PktVar_ *next; /* right now just implement this as a list,
318                            * in the long run we have thing of something
319                            * faster. */
320     uint16_t key_len;
321     uint16_t value_len;
322     uint8_t *key;
323     uint8_t *value;
324 } PktVar;
325 
326 #ifdef PROFILING
327 
328 /** \brief Per TMM stats storage */
329 typedef struct PktProfilingTmmData_ {
330     uint64_t ticks_start;
331     uint64_t ticks_end;
332 #ifdef PROFILE_LOCKING
333     uint64_t mutex_lock_cnt;
334     uint64_t mutex_lock_wait_ticks;
335     uint64_t mutex_lock_contention;
336     uint64_t spin_lock_cnt;
337     uint64_t spin_lock_wait_ticks;
338     uint64_t spin_lock_contention;
339     uint64_t rww_lock_cnt;
340     uint64_t rww_lock_wait_ticks;
341     uint64_t rww_lock_contention;
342     uint64_t rwr_lock_cnt;
343     uint64_t rwr_lock_wait_ticks;
344     uint64_t rwr_lock_contention;
345 #endif
346 } PktProfilingTmmData;
347 
348 typedef struct PktProfilingData_ {
349     uint64_t ticks_start;
350     uint64_t ticks_end;
351 } PktProfilingData;
352 
353 typedef struct PktProfilingDetectData_ {
354     uint64_t ticks_start;
355     uint64_t ticks_end;
356     uint64_t ticks_spent;
357 } PktProfilingDetectData;
358 
359 typedef struct PktProfilingAppData_ {
360     uint64_t ticks_spent;
361 } PktProfilingAppData;
362 
363 typedef struct PktProfilingLoggerData_ {
364     uint64_t ticks_start;
365     uint64_t ticks_end;
366     uint64_t ticks_spent;
367 } PktProfilingLoggerData;
368 
369 typedef struct PktProfilingPrefilterEngine_ {
370     uint64_t ticks_spent;
371 } PktProfilingPrefilterEngine;
372 
373 typedef struct PktProfilingPrefilterData_ {
374     PktProfilingPrefilterEngine *engines;
375     uint32_t size;          /**< array size */
376 } PktProfilingPrefilterData;
377 
378 /** \brief Per pkt stats storage */
379 typedef struct PktProfiling_ {
380     uint64_t ticks_start;
381     uint64_t ticks_end;
382 
383     PktProfilingTmmData tmm[TMM_SIZE];
384     PktProfilingData flowworker[PROFILE_FLOWWORKER_SIZE];
385     PktProfilingAppData app[ALPROTO_MAX];
386     PktProfilingDetectData detect[PROF_DETECT_SIZE];
387     PktProfilingLoggerData logger[LOGGER_SIZE];
388     uint64_t proto_detect;
389 } PktProfiling;
390 
391 #endif /* PROFILING */
392 
393 /* forward declaration since Packet struct definition requires this */
394 struct PacketQueue_;
395 
396 /* sizes of the members:
397  * src: 17 bytes
398  * dst: 17 bytes
399  * sp/type: 1 byte
400  * dp/code: 1 byte
401  * proto: 1 byte
402  * recurs: 1 byte
403  *
404  * sum of above: 38 bytes
405  *
406  * flow ptr: 4/8 bytes
407  * flags: 1 byte
408  * flowflags: 1 byte
409  *
410  * sum of above 44/48 bytes
411  */
412 typedef struct Packet_
413 {
414     /* Addresses, Ports and protocol
415      * these are on top so we can use
416      * the Packet as a hash key */
417     Address src;
418     Address dst;
419     union {
420         Port sp;
421         // icmp type and code of this packet
422         struct {
423             uint8_t type;
424             uint8_t code;
425         } icmp_s;
426     };
427     union {
428         Port dp;
429         // icmp type and code of the expected counterpart (for flows)
430         struct {
431             uint8_t type;
432             uint8_t code;
433         } icmp_d;
434     };
435     uint8_t proto;
436     /* make sure we can't be attacked on when the tunneled packet
437      * has the exact same tuple as the lower levels */
438     uint8_t recursion_level;
439 
440     uint16_t vlan_id[2];
441     uint8_t vlan_idx;
442 
443     /* flow */
444     uint8_t flowflags;
445     /* coccinelle: Packet:flowflags:FLOW_PKT_ */
446 
447     /* Pkt Flags */
448     uint32_t flags;
449 
450     struct Flow_ *flow;
451 
452     /* raw hash value for looking up the flow, will need to modulated to the
453      * hash size still */
454     uint32_t flow_hash;
455 
456     struct timeval ts;
457 
458     union {
459         /* nfq stuff */
460 #ifdef HAVE_NFLOG
461         NFLOGPacketVars nflog_v;
462 #endif /* HAVE_NFLOG */
463 #ifdef NFQ
464         NFQPacketVars nfq_v;
465 #endif /* NFQ */
466 #ifdef IPFW
467         IPFWPacketVars ipfw_v;
468 #endif /* IPFW */
469 #ifdef AF_PACKET
470         AFPPacketVars afp_v;
471 #endif
472 #ifdef HAVE_NETMAP
473         NetmapPacketVars netmap_v;
474 #endif
475 #ifdef HAVE_PFRING
476 #ifdef HAVE_PF_RING_FLOW_OFFLOAD
477         PfringPacketVars pfring_v;
478 #endif
479 #endif
480 #ifdef WINDIVERT
481         WinDivertPacketVars windivert_v;
482 #endif /* WINDIVERT */
483 
484         /* A chunk of memory that a plugin can use for its packet vars. */
485         uint8_t plugin_v[PLUGIN_VAR_SIZE];
486 
487         /** libpcap vars: shared by Pcap Live mode and Pcap File mode */
488         PcapPacketVars pcap_v;
489     };
490 
491     /** The release function for packet structure and data */
492     void (*ReleasePacket)(struct Packet_ *);
493     /** The function triggering bypass the flow in the capture method.
494      * Return 1 for success and 0 on error */
495     int (*BypassPacketsFlow)(struct Packet_ *);
496 
497     /* pkt vars */
498     PktVar *pktvar;
499 
500     /* header pointers */
501     EthernetHdr *ethh;
502 
503     /* Checksum for IP packets. */
504     int32_t level3_comp_csum;
505     /* Check sum for TCP, UDP or ICMP packets */
506     int32_t level4_comp_csum;
507 
508     IPV4Hdr *ip4h;
509 
510     IPV6Hdr *ip6h;
511 
512     /* IPv4 and IPv6 are mutually exclusive */
513     union {
514         IPV4Vars ip4vars;
515         struct {
516             IPV6Vars ip6vars;
517             IPV6ExtHdrs ip6eh;
518         };
519     };
520     /* Can only be one of TCP, UDP, ICMP at any given time */
521     union {
522         TCPVars tcpvars;
523         ICMPV4Vars icmpv4vars;
524         ICMPV6Vars icmpv6vars;
525     } l4vars;
526 #define tcpvars     l4vars.tcpvars
527 #define icmpv4vars  l4vars.icmpv4vars
528 #define icmpv6vars  l4vars.icmpv6vars
529 
530     TCPHdr *tcph;
531 
532     UDPHdr *udph;
533 
534     SCTPHdr *sctph;
535 
536     ICMPV4Hdr *icmpv4h;
537 
538     ICMPV6Hdr *icmpv6h;
539 
540     PPPHdr *ppph;
541     PPPOESessionHdr *pppoesh;
542     PPPOEDiscoveryHdr *pppoedh;
543 
544     GREHdr *greh;
545 
546     /* ptr to the payload of the packet
547      * with it's length. */
548     uint8_t *payload;
549     uint16_t payload_len;
550 
551     /* IPS action to take */
552     uint8_t action;
553 
554     uint8_t pkt_src;
555 
556     /* storage: set to pointer to heap and extended via allocation if necessary */
557     uint32_t pktlen;
558     uint8_t *ext_pkt;
559 
560     /* Incoming interface */
561     struct LiveDevice_ *livedev;
562 
563     PacketAlerts alerts;
564 
565     struct Host_ *host_src;
566     struct Host_ *host_dst;
567 
568     /** packet number in the pcap file, matches wireshark */
569     uint64_t pcap_cnt;
570 
571 
572     /* engine events */
573     PacketEngineEvents events;
574 
575     AppLayerDecoderEvents *app_layer_events;
576 
577     /* double linked list ptrs */
578     struct Packet_ *next;
579     struct Packet_ *prev;
580 
581     /** data linktype in host order */
582     int datalink;
583 
584     /* tunnel/encapsulation handling */
585     struct Packet_ *root; /* in case of tunnel this is a ptr
586                            * to the 'real' packet, the one we
587                            * need to set the verdict on --
588                            * It should always point to the lowest
589                            * packet in a encapsulated packet */
590 
591     /** mutex to protect access to:
592      *  - tunnel_rtv_cnt
593      *  - tunnel_tpr_cnt
594      */
595     SCMutex tunnel_mutex;
596     /* ready to set verdict counter, only set in root */
597     uint16_t tunnel_rtv_cnt;
598     /* tunnel packet ref count */
599     uint16_t tunnel_tpr_cnt;
600 
601     /** tenant id for this packet, if any. If 0 then no tenant was assigned. */
602     uint32_t tenant_id;
603 
604     /* The Packet pool from which this packet was allocated. Used when returning
605      * the packet to its owner's stack. If NULL, then allocated with malloc.
606      */
607     struct PktPool_ *pool;
608 
609     /* count decoded layers of packet : too many layers
610      * cause issues with performance and stability (stack exhaustion)
611      */
612     uint8_t nb_decoded_layers;
613 
614 #ifdef PROFILING
615     PktProfiling *profile;
616 #endif
617 #ifdef HAVE_NAPATECH
618     NapatechPacketVars ntpv;
619 #endif
620 } Packet;
621 
622 /** highest mtu of the interfaces we monitor */
623 extern int g_default_mtu;
624 #define DEFAULT_MTU 1500
625 #define MINIMUM_MTU 68      /**< ipv4 minimum: rfc791 */
626 
627 #define DEFAULT_PACKET_SIZE (DEFAULT_MTU + ETHERNET_HEADER_LEN)
628 /* storage: maximum ip packet size + link header */
629 #define MAX_PAYLOAD_SIZE (IPV6_HEADER_LEN + 65536 + 28)
630 extern uint32_t default_packet_size;
631 #define SIZE_OF_PACKET (default_packet_size + sizeof(Packet))
632 
633 /** \brief Structure to hold thread specific data for all decode modules */
634 typedef struct DecodeThreadVars_
635 {
636     /** Specific context for udp protocol detection (here atm) */
637     AppLayerThreadCtx *app_tctx;
638 
639     /** stats/counters */
640     uint16_t counter_pkts;
641     uint16_t counter_bytes;
642     uint16_t counter_avg_pkt_size;
643     uint16_t counter_max_pkt_size;
644     uint16_t counter_max_mac_addrs_src;
645     uint16_t counter_max_mac_addrs_dst;
646 
647     uint16_t counter_invalid;
648 
649     uint16_t counter_eth;
650     uint16_t counter_chdlc;
651     uint16_t counter_ipv4;
652     uint16_t counter_ipv6;
653     uint16_t counter_tcp;
654     uint16_t counter_udp;
655     uint16_t counter_icmpv4;
656     uint16_t counter_icmpv6;
657 
658     uint16_t counter_sll;
659     uint16_t counter_raw;
660     uint16_t counter_null;
661     uint16_t counter_sctp;
662     uint16_t counter_ppp;
663     uint16_t counter_geneve;
664     uint16_t counter_gre;
665     uint16_t counter_vlan;
666     uint16_t counter_vlan_qinq;
667     uint16_t counter_vxlan;
668     uint16_t counter_vntag;
669     uint16_t counter_ieee8021ah;
670     uint16_t counter_pppoe;
671     uint16_t counter_teredo;
672     uint16_t counter_mpls;
673     uint16_t counter_ipv4inipv6;
674     uint16_t counter_ipv6inipv6;
675     uint16_t counter_erspan;
676 
677     /** frag stats - defrag runs in the context of the decoder. */
678     uint16_t counter_defrag_ipv4_fragments;
679     uint16_t counter_defrag_ipv4_reassembled;
680     uint16_t counter_defrag_ipv4_timeouts;
681     uint16_t counter_defrag_ipv6_fragments;
682     uint16_t counter_defrag_ipv6_reassembled;
683     uint16_t counter_defrag_ipv6_timeouts;
684     uint16_t counter_defrag_max_hit;
685 
686     uint16_t counter_flow_memcap;
687 
688     uint16_t counter_flow_tcp;
689     uint16_t counter_flow_udp;
690     uint16_t counter_flow_icmp4;
691     uint16_t counter_flow_icmp6;
692     uint16_t counter_flow_tcp_reuse;
693     uint16_t counter_flow_get_used;
694     uint16_t counter_flow_get_used_eval;
695     uint16_t counter_flow_get_used_eval_reject;
696     uint16_t counter_flow_get_used_eval_busy;
697     uint16_t counter_flow_get_used_failed;
698 
699     uint16_t counter_flow_spare_sync;
700     uint16_t counter_flow_spare_sync_empty;
701     uint16_t counter_flow_spare_sync_incomplete;
702     uint16_t counter_flow_spare_sync_avg;
703 
704     uint16_t counter_engine_events[DECODE_EVENT_MAX];
705 
706     /* thread data for flow logging api: only used at forced
707      * flow recycle during lookups */
708     void *output_flow_thread_data;
709 
710 } DecodeThreadVars;
711 
712 typedef struct CaptureStats_ {
713 
714     uint16_t counter_ips_accepted;
715     uint16_t counter_ips_blocked;
716     uint16_t counter_ips_rejected;
717     uint16_t counter_ips_replaced;
718 
719 } CaptureStats;
720 
721 void CaptureStatsUpdate(ThreadVars *tv, CaptureStats *s, const Packet *p);
722 void CaptureStatsSetup(ThreadVars *tv, CaptureStats *s);
723 
724 #define PACKET_CLEAR_L4VARS(p) do {                         \
725         memset(&(p)->l4vars, 0x00, sizeof((p)->l4vars));    \
726     } while (0)
727 
728 /**
729  *  \brief reset these to -1(indicates that the packet is fresh from the queue)
730  */
731 #define PACKET_RESET_CHECKSUMS(p) do { \
732         (p)->level3_comp_csum = -1;   \
733         (p)->level4_comp_csum = -1;   \
734     } while (0)
735 
736 /* if p uses extended data, free them */
737 #define PACKET_FREE_EXTDATA(p) do {                 \
738         if ((p)->ext_pkt) {                         \
739             if (!((p)->flags & PKT_ZERO_COPY)) {    \
740                 SCFree((p)->ext_pkt);               \
741             }                                       \
742             (p)->ext_pkt = NULL;                    \
743         }                                           \
744     } while(0)
745 
746 /**
747  *  \brief Initialize a packet structure for use.
748  */
749 #define PACKET_INITIALIZE(p) {         \
750     SCMutexInit(&(p)->tunnel_mutex, NULL); \
751     PACKET_RESET_CHECKSUMS((p)); \
752     (p)->livedev = NULL; \
753 }
754 
755 #define PACKET_RELEASE_REFS(p) do {              \
756         FlowDeReference(&((p)->flow));          \
757         HostDeReference(&((p)->host_src));      \
758         HostDeReference(&((p)->host_dst));      \
759     } while (0)
760 
761 /**
762  *  \brief Recycle a packet structure for reuse.
763  */
764 #define PACKET_REINIT(p) do {             \
765         CLEAR_ADDR(&(p)->src);                  \
766         CLEAR_ADDR(&(p)->dst);                  \
767         (p)->sp = 0;                            \
768         (p)->dp = 0;                            \
769         (p)->proto = 0;                         \
770         (p)->recursion_level = 0;               \
771         PACKET_FREE_EXTDATA((p));               \
772         (p)->flags = (p)->flags & PKT_ALLOC;    \
773         (p)->flowflags = 0;                     \
774         (p)->pkt_src = 0;                       \
775         (p)->vlan_id[0] = 0;                    \
776         (p)->vlan_id[1] = 0;                    \
777         (p)->vlan_idx = 0;                      \
778         (p)->ts.tv_sec = 0;                     \
779         (p)->ts.tv_usec = 0;                    \
780         (p)->datalink = 0;                      \
781         (p)->action = 0;                        \
782         if ((p)->pktvar != NULL) {              \
783             PktVarFree((p)->pktvar);            \
784             (p)->pktvar = NULL;                 \
785         }                                       \
786         (p)->ethh = NULL;                       \
787         if ((p)->ip4h != NULL) {                \
788             CLEAR_IPV4_PACKET((p));             \
789         }                                       \
790         if ((p)->ip6h != NULL) {                \
791             CLEAR_IPV6_PACKET((p));             \
792         }                                       \
793         if ((p)->tcph != NULL) {                \
794             CLEAR_TCP_PACKET((p));              \
795         }                                       \
796         if ((p)->udph != NULL) {                \
797             CLEAR_UDP_PACKET((p));              \
798         }                                       \
799         if ((p)->sctph != NULL) {               \
800             CLEAR_SCTP_PACKET((p));             \
801         }                                       \
802         if ((p)->icmpv4h != NULL) {             \
803             CLEAR_ICMPV4_PACKET((p));           \
804         }                                       \
805         if ((p)->icmpv6h != NULL) {             \
806             CLEAR_ICMPV6_PACKET((p));           \
807         }                                       \
808         (p)->ppph = NULL;                       \
809         (p)->pppoesh = NULL;                    \
810         (p)->pppoedh = NULL;                    \
811         (p)->greh = NULL;                       \
812         (p)->payload = NULL;                    \
813         (p)->payload_len = 0;                   \
814         (p)->BypassPacketsFlow = NULL;          \
815         (p)->pktlen = 0;                        \
816         (p)->alerts.cnt = 0;                    \
817         (p)->alerts.drop.action = 0;            \
818         (p)->pcap_cnt = 0;                      \
819         (p)->tunnel_rtv_cnt = 0;                \
820         (p)->tunnel_tpr_cnt = 0;                \
821         (p)->events.cnt = 0;                    \
822         AppLayerDecoderEventsResetEvents((p)->app_layer_events); \
823         (p)->next = NULL;                       \
824         (p)->prev = NULL;                       \
825         (p)->root = NULL;                       \
826         (p)->livedev = NULL;                    \
827         PACKET_RESET_CHECKSUMS((p));            \
828         PACKET_PROFILING_RESET((p));            \
829         p->tenant_id = 0;                       \
830         p->nb_decoded_layers = 0;                                                                  \
831     } while (0)
832 
833 #define PACKET_RECYCLE(p) do { \
834         PACKET_RELEASE_REFS((p)); \
835         PACKET_REINIT((p)); \
836     } while (0)
837 
838 /**
839  *  \brief Cleanup a packet so that we can free it. No memset needed..
840  */
841 #define PACKET_DESTRUCTOR(p) do {                  \
842         if ((p)->pktvar != NULL) {              \
843             PktVarFree((p)->pktvar);            \
844         }                                       \
845         PACKET_FREE_EXTDATA((p));               \
846         SCMutexDestroy(&(p)->tunnel_mutex);     \
847         AppLayerDecoderEventsFreeEvents(&(p)->app_layer_events); \
848         PACKET_PROFILING_RESET((p));            \
849     } while (0)
850 
851 
852 /* macro's for setting the action
853  * handle the case of a root packet
854  * for tunnels */
855 
856 #define PACKET_SET_ACTION(p, a) do { \
857     ((p)->root ? \
858      ((p)->root->action = a) : \
859      ((p)->action = a)); \
860 } while (0)
861 
862 #define PACKET_ALERT(p) PACKET_SET_ACTION(p, ACTION_ALERT)
863 
864 #define PACKET_ACCEPT(p) PACKET_SET_ACTION(p, ACTION_ACCEPT)
865 
866 #define PACKET_DROP(p) PACKET_SET_ACTION(p, ACTION_DROP)
867 
868 #define PACKET_REJECT(p) PACKET_SET_ACTION(p, (ACTION_REJECT|ACTION_DROP))
869 
870 #define PACKET_REJECT_DST(p) PACKET_SET_ACTION(p, (ACTION_REJECT_DST|ACTION_DROP))
871 
872 #define PACKET_REJECT_BOTH(p) PACKET_SET_ACTION(p, (ACTION_REJECT_BOTH|ACTION_DROP))
873 
874 #define PACKET_PASS(p) PACKET_SET_ACTION(p, ACTION_PASS)
875 
876 #define PACKET_TEST_ACTION(p, a) \
877     ((p)->root ? \
878      ((p)->root->action & a) : \
879      ((p)->action & a))
880 
881 #define PACKET_UPDATE_ACTION(p, a) do { \
882     ((p)->root ? \
883      ((p)->root->action |= a) : \
884      ((p)->action |= a)); \
885 } while (0)
886 
887 #define TUNNEL_INCR_PKT_RTV_NOLOCK(p) do {                                          \
888         ((p)->root ? (p)->root->tunnel_rtv_cnt++ : (p)->tunnel_rtv_cnt++);          \
889     } while (0)
890 
891 #define TUNNEL_INCR_PKT_TPR(p) do {                                                 \
892         SCMutexLock((p)->root ? &(p)->root->tunnel_mutex : &(p)->tunnel_mutex);     \
893         ((p)->root ? (p)->root->tunnel_tpr_cnt++ : (p)->tunnel_tpr_cnt++);          \
894         SCMutexUnlock((p)->root ? &(p)->root->tunnel_mutex : &(p)->tunnel_mutex);   \
895     } while (0)
896 
897 #define TUNNEL_PKT_RTV(p) ((p)->root ? (p)->root->tunnel_rtv_cnt : (p)->tunnel_rtv_cnt)
898 #define TUNNEL_PKT_TPR(p) ((p)->root ? (p)->root->tunnel_tpr_cnt : (p)->tunnel_tpr_cnt)
899 
900 #define IS_TUNNEL_PKT(p)            (((p)->flags & PKT_TUNNEL))
901 #define SET_TUNNEL_PKT(p)           ((p)->flags |= PKT_TUNNEL)
902 #define UNSET_TUNNEL_PKT(p)         ((p)->flags &= ~PKT_TUNNEL)
903 #define IS_TUNNEL_ROOT_PKT(p)       (IS_TUNNEL_PKT(p) && (p)->root == NULL)
904 
905 #define IS_TUNNEL_PKT_VERDICTED(p)  (((p)->flags & PKT_TUNNEL_VERDICTED))
906 #define SET_TUNNEL_PKT_VERDICTED(p) ((p)->flags |= PKT_TUNNEL_VERDICTED)
907 
908 enum DecodeTunnelProto {
909     DECODE_TUNNEL_ETHERNET,
910     DECODE_TUNNEL_ERSPANII,
911     DECODE_TUNNEL_ERSPANI,
912     DECODE_TUNNEL_VLAN,
913     DECODE_TUNNEL_IPV4,
914     DECODE_TUNNEL_IPV6,
915     DECODE_TUNNEL_IPV6_TEREDO, /**< separate protocol for stricter error handling */
916     DECODE_TUNNEL_PPP,
917     DECODE_TUNNEL_UNSET
918 };
919 
920 Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent,
921                              const uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto);
922 Packet *PacketDefragPktSetup(Packet *parent, const uint8_t *pkt, uint32_t len, uint8_t proto);
923 void PacketDefragPktSetupParent(Packet *parent);
924 void DecodeRegisterPerfCounters(DecodeThreadVars *, ThreadVars *);
925 Packet *PacketGetFromQueueOrAlloc(void);
926 Packet *PacketGetFromAlloc(void);
927 void PacketDecodeFinalize(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p);
928 void PacketUpdateEngineEventCounters(ThreadVars *tv,
929         DecodeThreadVars *dtv, Packet *p);
930 void PacketFree(Packet *p);
931 void PacketFreeOrRelease(Packet *p);
932 int PacketCallocExtPkt(Packet *p, int datalen);
933 int PacketCopyData(Packet *p, const uint8_t *pktdata, uint32_t pktlen);
934 int PacketSetData(Packet *p, const uint8_t *pktdata, uint32_t pktlen);
935 int PacketCopyDataOffset(Packet *p, uint32_t offset, const uint8_t *data, uint32_t datalen);
936 const char *PktSrcToString(enum PktSrcEnum pkt_src);
937 void PacketBypassCallback(Packet *p);
938 void PacketSwap(Packet *p);
939 
940 DecodeThreadVars *DecodeThreadVarsAlloc(ThreadVars *);
941 void DecodeThreadVarsFree(ThreadVars *, DecodeThreadVars *);
942 void DecodeUpdatePacketCounters(ThreadVars *tv,
943                                 const DecodeThreadVars *dtv, const Packet *p);
944 
945 /* decoder functions */
946 int DecodeEthernet(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
947 int DecodeSll(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
948 int DecodePPP(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
949 int DecodePPPOESession(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
950 int DecodePPPOEDiscovery(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
951 int DecodeNull(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
952 int DecodeRaw(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
953 int DecodeIPV4(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint16_t);
954 int DecodeIPV6(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint16_t);
955 int DecodeICMPV4(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
956 int DecodeICMPV6(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
957 int DecodeTCP(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint16_t);
958 int DecodeUDP(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint16_t);
959 int DecodeSCTP(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint16_t);
960 int DecodeGRE(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
961 int DecodeVLAN(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
962 int DecodeVNTag(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
963 int DecodeIEEE8021ah(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
964 int DecodeGeneve(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
965 int DecodeVXLAN(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
966 int DecodeVNTag(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
967 int DecodeMPLS(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
968 int DecodeERSPAN(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
969 int DecodeERSPANTypeI(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
970 int DecodeCHDLC(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
971 int DecodeTEMPLATE(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t);
972 
973 #ifdef UNITTESTS
974 void DecodeIPV6FragHeader(Packet *p, const uint8_t *pkt,
975                           uint16_t hdrextlen, uint16_t plen,
976                           uint16_t prev_hdrextlen);
977 #endif
978 
979 void AddressDebugPrint(Address *);
980 
981 typedef int (*DecoderFunc)(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p,
982          const uint8_t *pkt, uint32_t len);
983 void DecodeGlobalConfig(void);
984 void DecodeUnregisterCounters(void);
985 
986 /** \brief Set the No payload inspection Flag for the packet.
987  *
988  * \param p Packet to set the flag in
989  */
990 #define DecodeSetNoPayloadInspectionFlag(p) do { \
991         (p)->flags |= PKT_NOPAYLOAD_INSPECTION;  \
992     } while (0)
993 
994 #define DecodeUnsetNoPayloadInspectionFlag(p) do { \
995         (p)->flags &= ~PKT_NOPAYLOAD_INSPECTION;  \
996     } while (0)
997 
998 /** \brief Set the No packet inspection Flag for the packet.
999  *
1000  * \param p Packet to set the flag in
1001  */
1002 #define DecodeSetNoPacketInspectionFlag(p) do { \
1003         (p)->flags |= PKT_NOPACKET_INSPECTION;  \
1004     } while (0)
1005 #define DecodeUnsetNoPacketInspectionFlag(p) do { \
1006         (p)->flags &= ~PKT_NOPACKET_INSPECTION;  \
1007     } while (0)
1008 
1009 
1010 #define ENGINE_SET_EVENT(p, e) do { \
1011     SCLogDebug("p %p event %d", (p), e); \
1012     if ((p)->events.cnt < PACKET_ENGINE_EVENT_MAX) { \
1013         (p)->events.events[(p)->events.cnt] = e; \
1014         (p)->events.cnt++; \
1015     } \
1016 } while(0)
1017 
1018 #define ENGINE_SET_INVALID_EVENT(p, e) do { \
1019     p->flags |= PKT_IS_INVALID; \
1020     ENGINE_SET_EVENT(p, e); \
1021 } while(0)
1022 
1023 
1024 
1025 #define ENGINE_ISSET_EVENT(p, e) ({ \
1026     int r = 0; \
1027     uint8_t u; \
1028     for (u = 0; u < (p)->events.cnt; u++) { \
1029         if ((p)->events.events[u] == (e)) { \
1030             r = 1; \
1031             break; \
1032         } \
1033     } \
1034     r; \
1035 })
1036 
1037 #ifndef IPPROTO_IPIP
1038 #define IPPROTO_IPIP 4
1039 #endif
1040 
1041 /* older libcs don't contain a def for IPPROTO_DCCP
1042  * inside of <netinet/in.h>
1043  * if it isn't defined let's define it here.
1044  */
1045 #ifndef IPPROTO_DCCP
1046 #define IPPROTO_DCCP 33
1047 #endif
1048 
1049 /* older libcs don't contain a def for IPPROTO_SCTP
1050  * inside of <netinet/in.h>
1051  * if it isn't defined let's define it here.
1052  */
1053 #ifndef IPPROTO_SCTP
1054 #define IPPROTO_SCTP 132
1055 #endif
1056 
1057 #ifndef IPPROTO_MH
1058 #define IPPROTO_MH 135
1059 #endif
1060 
1061 /* Host Identity Protocol (rfc 5201) */
1062 #ifndef IPPROTO_HIP
1063 #define IPPROTO_HIP 139
1064 #endif
1065 
1066 #ifndef IPPROTO_SHIM6
1067 #define IPPROTO_SHIM6 140
1068 #endif
1069 
1070 /* pcap provides this, but we don't want to depend on libpcap */
1071 #ifndef DLT_EN10MB
1072 #define DLT_EN10MB 1
1073 #endif
1074 
1075 #ifndef DLT_C_HDLC
1076 #define DLT_C_HDLC 104
1077 #endif
1078 
1079 /* taken from pcap's bpf.h */
1080 #ifndef DLT_RAW
1081 #ifdef __OpenBSD__
1082 #define DLT_RAW     14  /* raw IP */
1083 #else
1084 #define DLT_RAW     12  /* raw IP */
1085 #endif
1086 #endif
1087 
1088 #ifndef DLT_NULL
1089 #define DLT_NULL 0
1090 #endif
1091 
1092 /** libpcap shows us the way to linktype codes
1093  * \todo we need more & maybe put them in a separate file? */
1094 #define LINKTYPE_NULL        DLT_NULL
1095 #define LINKTYPE_ETHERNET    DLT_EN10MB
1096 #define LINKTYPE_LINUX_SLL   113
1097 #define LINKTYPE_PPP         9
1098 #define LINKTYPE_RAW         DLT_RAW
1099 /* http://www.tcpdump.org/linktypes.html defines DLT_RAW as 101, yet others don't.
1100  * Libpcap on at least OpenBSD returns 101 as datalink type for RAW pcaps though. */
1101 #define LINKTYPE_RAW2        101
1102 #define LINKTYPE_IPV4        228
1103 #define LINKTYPE_GRE_OVER_IP 778
1104 #define LINKTYPE_CISCO_HDLC  DLT_C_HDLC
1105 #define PPP_OVER_GRE         11
1106 #define VLAN_OVER_GRE        13
1107 
1108 /*Packet Flags*/
1109 #define PKT_NOPACKET_INSPECTION         (1)         /**< Flag to indicate that packet header or contents should not be inspected*/
1110 #define PKT_NOPAYLOAD_INSPECTION        (1<<2)      /**< Flag to indicate that packet contents should not be inspected*/
1111 #define PKT_ALLOC                       (1<<3)      /**< Packet was alloc'd this run, needs to be freed */
1112 #define PKT_HAS_TAG                     (1<<4)      /**< Packet has matched a tag */
1113 #define PKT_STREAM_ADD                  (1<<5)      /**< Packet payload was added to reassembled stream */
1114 #define PKT_STREAM_EST                  (1<<6)      /**< Packet is part of established stream */
1115 #define PKT_STREAM_EOF                  (1<<7)      /**< Stream is in eof state */
1116 #define PKT_HAS_FLOW                    (1<<8)
1117 #define PKT_PSEUDO_STREAM_END           (1<<9)      /**< Pseudo packet to end the stream */
1118 #define PKT_STREAM_MODIFIED             (1<<10)     /**< Packet is modified by the stream engine, we need to recalc the csum and reinject/replace */
1119 #define PKT_MARK_MODIFIED               (1<<11)     /**< Packet mark is modified */
1120 #define PKT_STREAM_NOPCAPLOG            (1<<12)     /**< Exclude packet from pcap logging as it's part of a stream that has reassembly depth reached. */
1121 
1122 #define PKT_TUNNEL                      (1<<13)
1123 #define PKT_TUNNEL_VERDICTED            (1<<14)
1124 
1125 #define PKT_IGNORE_CHECKSUM             (1<<15)     /**< Packet checksum is not computed (TX packet for example) */
1126 #define PKT_ZERO_COPY                   (1<<16)     /**< Packet comes from zero copy (ext_pkt must not be freed) */
1127 
1128 #define PKT_HOST_SRC_LOOKED_UP          (1<<17)
1129 #define PKT_HOST_DST_LOOKED_UP          (1<<18)
1130 
1131 #define PKT_IS_FRAGMENT                 (1<<19)     /**< Packet is a fragment */
1132 #define PKT_IS_INVALID                  (1<<20)
1133 #define PKT_PROFILE                     (1<<21)
1134 
1135 /** indication by decoder that it feels the packet should be handled by
1136  *  flow engine: Packet::flow_hash will be set */
1137 #define PKT_WANTS_FLOW                  (1<<22)
1138 
1139 /** protocol detection done */
1140 #define PKT_PROTO_DETECT_TS_DONE        (1<<23)
1141 #define PKT_PROTO_DETECT_TC_DONE        (1<<24)
1142 
1143 #define PKT_REBUILT_FRAGMENT            (1<<25)     /**< Packet is rebuilt from
1144                                                      * fragments. */
1145 #define PKT_DETECT_HAS_STREAMDATA       (1<<26)     /**< Set by Detect() if raw stream data is available. */
1146 
1147 #define PKT_PSEUDO_DETECTLOG_FLUSH      (1<<27)     /**< Detect/log flush for protocol upgrade */
1148 
1149 /** Packet is part of stream in known bad condition (loss, wrong thread),
1150  *  so flag it for not setting stream events */
1151 #define PKT_STREAM_NO_EVENTS            (1<<28)
1152 
1153 /** \brief return 1 if the packet is a pseudo packet */
1154 #define PKT_IS_PSEUDOPKT(p) \
1155     ((p)->flags & (PKT_PSEUDO_STREAM_END|PKT_PSEUDO_DETECTLOG_FLUSH))
1156 
1157 #define PKT_SET_SRC(p, src_val) ((p)->pkt_src = src_val)
1158 
1159 #define PKT_DEFAULT_MAX_DECODED_LAYERS 16
1160 extern uint8_t decoder_max_layers;
1161 
PacketIncreaseCheckLayers(Packet * p)1162 static inline bool PacketIncreaseCheckLayers(Packet *p)
1163 {
1164     p->nb_decoded_layers++;
1165     if (p->nb_decoded_layers >= decoder_max_layers) {
1166         ENGINE_SET_INVALID_EVENT(p, GENERIC_TOO_MANY_LAYERS);
1167         return false;
1168     }
1169     return true;
1170 }
1171 
1172 /** \brief return true if *this* packet needs to trigger a verdict.
1173  *
1174  *  If we have the root packet, and we have none outstanding,
1175  *  we can verdict now.
1176  *
1177  *  If we have a upper layer packet, it's the only one and root
1178  *  is already processed, we can verdict now.
1179  *
1180  *  Otherwise, a future packet will issue the verdict.
1181  */
VerdictTunnelPacket(Packet * p)1182 static inline bool VerdictTunnelPacket(Packet *p)
1183 {
1184     bool verdict = true;
1185     SCMutex *m = p->root ? &p->root->tunnel_mutex : &p->tunnel_mutex;
1186     SCMutexLock(m);
1187     const uint16_t outstanding = TUNNEL_PKT_TPR(p) - TUNNEL_PKT_RTV(p);
1188     SCLogDebug("tunnel: outstanding %u", outstanding);
1189 
1190     /* if there are packets outstanding, we won't verdict this one */
1191     if (IS_TUNNEL_ROOT_PKT(p) && !IS_TUNNEL_PKT_VERDICTED(p) && !outstanding) {
1192         // verdict
1193         SCLogDebug("root %p: verdict", p);
1194     } else if (!IS_TUNNEL_ROOT_PKT(p) && outstanding == 1 && p->root && IS_TUNNEL_PKT_VERDICTED(p->root)) {
1195         // verdict
1196         SCLogDebug("tunnel %p: verdict", p);
1197     } else {
1198         verdict = false;
1199     }
1200     SCMutexUnlock(m);
1201     return verdict;
1202 }
1203 
DecodeLinkLayer(ThreadVars * tv,DecodeThreadVars * dtv,const int datalink,Packet * p,const uint8_t * data,const uint32_t len)1204 static inline void DecodeLinkLayer(ThreadVars *tv, DecodeThreadVars *dtv,
1205         const int datalink, Packet *p, const uint8_t *data, const uint32_t len)
1206 {
1207     /* call the decoder */
1208     switch (datalink) {
1209         case LINKTYPE_ETHERNET:
1210             DecodeEthernet(tv, dtv, p, data, len);
1211             break;
1212         case LINKTYPE_LINUX_SLL:
1213             DecodeSll(tv, dtv, p, data, len);
1214             break;
1215         case LINKTYPE_PPP:
1216             DecodePPP(tv, dtv, p, data, len);
1217             break;
1218         case LINKTYPE_RAW:
1219         case LINKTYPE_GRE_OVER_IP:
1220             DecodeRaw(tv, dtv, p, data, len);
1221             break;
1222         case LINKTYPE_NULL:
1223             DecodeNull(tv, dtv, p, data, len);
1224             break;
1225        case LINKTYPE_CISCO_HDLC:
1226             DecodeCHDLC(tv, dtv, p, data, len);
1227             break;
1228         default:
1229             SCLogError(SC_ERR_DATALINK_UNIMPLEMENTED, "datalink type "
1230                     "%"PRId32" not yet supported", datalink);
1231             break;
1232     }
1233 }
1234 
1235 /** \brief decode network layer
1236  *  \retval bool true if successful, false if unknown */
DecodeNetworkLayer(ThreadVars * tv,DecodeThreadVars * dtv,const uint16_t proto,Packet * p,const uint8_t * data,const uint32_t len)1237 static inline bool DecodeNetworkLayer(ThreadVars *tv, DecodeThreadVars *dtv,
1238         const uint16_t proto, Packet *p, const uint8_t *data, const uint32_t len)
1239 {
1240     switch (proto) {
1241         case ETHERNET_TYPE_IP: {
1242             uint16_t ip_len = (len < USHRT_MAX) ? (uint16_t)len : (uint16_t)USHRT_MAX;
1243             DecodeIPV4(tv, dtv, p, data, ip_len);
1244             break;
1245         }
1246         case ETHERNET_TYPE_IPV6: {
1247             uint16_t ip_len = (len < USHRT_MAX) ? (uint16_t)len : (uint16_t)USHRT_MAX;
1248             DecodeIPV6(tv, dtv, p, data, ip_len);
1249             break;
1250         }
1251         case ETHERNET_TYPE_PPPOE_SESS:
1252             DecodePPPOESession(tv, dtv, p, data, len);
1253             break;
1254         case ETHERNET_TYPE_PPPOE_DISC:
1255             DecodePPPOEDiscovery(tv, dtv, p, data, len);
1256             break;
1257         case ETHERNET_TYPE_VLAN:
1258         case ETHERNET_TYPE_8021AD:
1259         case ETHERNET_TYPE_8021QINQ:
1260             if (p->vlan_idx >= 2) {
1261                 ENGINE_SET_EVENT(p,VLAN_HEADER_TOO_MANY_LAYERS);
1262             } else {
1263                 DecodeVLAN(tv, dtv, p, data, len);
1264             }
1265             break;
1266         case ETHERNET_TYPE_8021AH:
1267             DecodeIEEE8021ah(tv, dtv, p, data, len);
1268             break;
1269         case ETHERNET_TYPE_ARP:
1270             break;
1271         case ETHERNET_TYPE_MPLS_UNICAST:
1272         case ETHERNET_TYPE_MPLS_MULTICAST:
1273             DecodeMPLS(tv, dtv, p, data, len);
1274             break;
1275         case ETHERNET_TYPE_DCE:
1276             if (unlikely(len < ETHERNET_DCE_HEADER_LEN)) {
1277                 ENGINE_SET_INVALID_EVENT(p, DCE_PKT_TOO_SMALL);
1278             } else {
1279                 DecodeEthernet(tv, dtv, p, data, len);
1280             }
1281             break;
1282         case ETHERNET_TYPE_VNTAG:
1283             DecodeVNTag(tv, dtv, p, data, len);
1284             break;
1285         default:
1286             SCLogDebug("unknown ether type: %" PRIx16 "", proto);
1287             return false;
1288     }
1289     return true;
1290 }
1291 
1292 #endif /* __DECODE_H__ */
1293