1 /* $Id$ */
2 
3 /*
4 ** Copyright (C) 2014-2021 Cisco and/or its affiliates. All rights reserved.
5 ** Copyright (C) 2002-2013 Sourcefire, Inc.
6 ** Copyright (C) 1998-2002 Martin Roesch <roesch@sourcefire.com>
7 **
8 ** This program is free software; you can redistribute it and/or modify
9 ** it under the terms of the GNU General Public License Version 2 as
10 ** published by the Free Software Foundation.  You may not use, modify or
11 ** distribute this program under any other version of the GNU General
12 ** Public License.
13 **
14 ** This program is distributed in the hope that it will be useful,
15 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ** GNU General Public License for more details.
18 **
19 ** You should have received a copy of the GNU General Public License
20 ** along with this program; if not, write to the Free Software
21 ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
22 */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27 
28 #ifdef HAVE_STRINGS_H
29 #include <strings.h>
30 #endif
31 
32 #include <string.h>
33 #include <stdlib.h>
34 
35 #ifdef HAVE_DUMBNET_H
36 #include <dumbnet.h>
37 #else
38 #include <dnet.h>
39 #endif
40 
41 #include "decode.h"
42 #include "snort.h"
43 #include "snort_debug.h"
44 #include "util.h"
45 #include "detect.h"
46 #include "checksum.h"
47 #include "log.h"
48 #include "generators.h"
49 #include "event_queue.h"
50 #include "active.h"
51 #include "sfxhash.h"
52 #include "snort_bounds.h"
53 #include "strlcpyu.h"
54 #include "sf_iph.h"
55 #include "fpdetect.h"
56 #include "profiler.h"
57 #include "sfActionQueue.h"
58 #include "mempool.h"
59 #include "spp_normalize.h"
60 #include "sfdaq.h"
61 #include "sfrf.h"
62 
63 #ifdef REG_TEST
64 #include "reg_test.h"
65 #include <stdio.h>
66 #endif
67 
68 extern tSfActionQueueId decoderActionQ;
69 extern MemPool decoderAlertMemPool;
70 
71 static IpAddrSet *SynToMulticastDstIp = NULL;
72 static IpAddrSet *MulticastReservedIp = NULL;
73 #ifdef PERF_PROFILING
74 PreprocStats decodePerfStats;
75 #endif
76 
77 // Array to check if the decoder rules are enabled in at least one policy
78 static uint8_t decodeRulesArray[DECODE_INDEX_MAX];
79 
80 //--------------------------------------------------------------------
81 // decode.c::event support
82 //--------------------------------------------------------------------
83 
84 #ifdef NORMALIZER
ScNormalDrop(NormFlags nf)85 static inline int ScNormalDrop (NormFlags nf)
86 {
87     return Normalize_GetMode(snort_conf, nf) == NORM_MODE_OFF;
88 }
89 #else
90 #define ScNormalDrop(nf) 1
91 #endif
92 
queueExecDrop(void (* callback)(void *),Packet * p)93 static inline void queueExecDrop(
94     void (*callback)(void *), Packet* p)
95 {
96     int ret = sfActionQueueAdd( decoderActionQ, callback, (void*)p);
97     if (ret == -1)
98     {
99         ErrorMessage("Could not add drop event to decoderActionQ\n");
100     }
101 }
102 
103 // no harm declaring the exec*Drop()s as inline, but since
104 // the only use is via pointer, these won't get inlined.
execDecoderDrop(void * data)105 static inline void execDecoderDrop (void *data)
106 {
107     if ( ScDecoderAlerts() && ScDecoderDrops() )
108     {
109         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
110            "Dropping bad packet\n"););
111         Active_DropSession((Packet*)data);
112         if (pkt_trace_enabled)
113             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
114                 "Snort: bad packet decode error, %s\n", getPktTraceActMsg()));
115         else addPktTraceData(VERDICT_REASON_SNORT, 0);
116     }
117 }
118 
execIpOptDrop(void * data)119 static inline void execIpOptDrop (void *data)
120 {
121     if ( ScDecoderIpOptDrops() )
122     {
123         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
124            "Dropping bad packet (IP opts)\n"););
125         Active_DropPacket((Packet*)data);
126         if (pkt_trace_enabled)
127             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
128                 "Snort: IP options decode error, %s\n", getPktTraceActMsg()));
129         else addPktTraceData(VERDICT_REASON_SNORT, 0);
130     }
131 }
132 
execMinTtlDrop(void * data)133 static inline void execMinTtlDrop (void *data)
134 {
135     if ( ScNormalDrop(NORM_IP4_TTL) &&
136             ScDecoderAlerts() && ScDecoderDrops() )
137     {
138         Packet* p = (Packet*)data;
139         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
140            "Dropping bad packet (IP4 min TTL)\n"););
141         p->error_flags |= PKT_ERR_BAD_TTL;
142         Active_DropPacket(p);
143         if (pkt_trace_enabled)
144             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
145                 "Snort: IP4 min TTL error, %s\n", getPktTraceActMsg()));
146         else addPktTraceData(VERDICT_REASON_SNORT, 0);
147     }
148 }
149 
execTtlDrop(void * data)150 static inline void execTtlDrop (void *data)
151 {
152     if ( ScNormalDrop(NORM_IP4_TTL) )
153     {
154         Packet* p = (Packet*)data;
155         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
156            "Dropping bad packet (IP4 zero TTL)\n"););
157         p->error_flags |= PKT_ERR_BAD_TTL;
158         Active_DropPacket(p);
159         if (pkt_trace_enabled)
160             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
161                 "Snort: IP4 zero TTL error, %s\n", getPktTraceActMsg()));
162         else addPktTraceData(VERDICT_REASON_SNORT, 0);
163     }
164 }
165 
execHopDrop(void * data)166 static inline void execHopDrop (void *data)
167 {
168     if ( ScNormalDrop(NORM_IP6_TTL) )
169     {
170         Packet* p = (Packet*)data;
171         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
172            "Dropping bad packet (IP6 zero hop)\n"););
173         p->error_flags |= PKT_ERR_BAD_TTL;
174         Active_DropPacket(p);
175         if (pkt_trace_enabled)
176             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
177                 "Snort: IP6 zero hop error, %s\n", getPktTraceActMsg()));
178         else addPktTraceData(VERDICT_REASON_SNORT, 0);
179     }
180 }
181 
execIpv6MinTtlDrop(void * data)182 static inline void execIpv6MinTtlDrop (void *data)
183 {
184     if ( ScNormalDrop(NORM_IP6_TTL) &&
185             ScDecoderAlerts() && ScDecoderDrops() )
186     {
187         Packet* p = (Packet*)data;
188         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
189            "Dropping bad packet (IP6 hop limit)\n"););
190         p->error_flags |= PKT_ERR_BAD_TTL;
191         Active_DropPacket(p);
192         if (pkt_trace_enabled)
193             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
194                 "Snort: IP6 hop limit error, %s\n", getPktTraceActMsg()));
195         else addPktTraceData(VERDICT_REASON_SNORT, 0);
196     }
197 }
198 
execTcpOptDrop(void * data)199 static inline void execTcpOptDrop (void *data)
200 {
201     if ( ScDecoderTcpOptDrops() )
202     {
203         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
204            "Dropping bad packet (TCP opts)\n"););
205         Active_DropPacket((Packet*)data);
206         if (pkt_trace_enabled)
207             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
208                 "Snort: TCP options decode error, %s\n", getPktTraceActMsg()));
209         else addPktTraceData(VERDICT_REASON_SNORT, 0);
210     }
211 }
212 
execTcpOptExpDrop(void * data)213 static inline void execTcpOptExpDrop (void *data)
214 {
215     if ( ScDecoderTcpOptExpDrops() )
216     {
217         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
218            "Dropping bad packet (TCP exp opts)\n"););
219         Active_DropPacket((Packet*)data);
220         if (pkt_trace_enabled)
221             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
222                 "Snort: TCP experimental options decode error, %s\n", getPktTraceActMsg()));
223         else addPktTraceData(VERDICT_REASON_SNORT, 0);
224     }
225 }
226 
execTcpOptObsDrop(void * data)227 static inline void execTcpOptObsDrop (void *data)
228 {
229     if (  ScDecoderTcpOptObsDrops() )
230     {
231         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
232            "Dropping bad packet (TCP obs opts)\n"););
233         Active_DropPacket((Packet*)data);
234         if (pkt_trace_enabled)
235             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
236                 "Snort: TCP obsolete options decode error, %s\n", getPktTraceActMsg()));
237         else addPktTraceData(VERDICT_REASON_SNORT, 0);
238     }
239 }
240 
execTcpOptTTcpDrop(void * data)241 static inline void execTcpOptTTcpDrop (void *data)
242 {
243     if ( ScDecoderTcpOptTTcpDrops() )
244     {
245         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
246             "Dropping bad packet (TTCP opts)\n"););
247         Active_DropPacket((Packet*)data);
248         if (pkt_trace_enabled)
249             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
250                 "Snort: Test TCP (TTCP) options decode error, %s\n", getPktTraceActMsg()));
251         else addPktTraceData(VERDICT_REASON_SNORT, 0);
252     }
253 }
254 
execIpChksmDrop(void * data)255 static inline void execIpChksmDrop (void *data)
256 {
257     // TBD only set policy csum drop if policy inline
258     // and delete this inline mode check
259     if( ScNapInlineMode() && ScIpChecksumDrops() )
260     {
261         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
262             "Dropping bad packet (IP checksum)\n"););
263         Active_NapDropPacket((Packet*)data);
264         if (pkt_trace_enabled)
265             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
266                 "Snort: IP checksum error, %s\n", getPktTraceActMsg()));
267         else addPktTraceData(VERDICT_REASON_SNORT, 0);
268     }
269 }
270 
execTcpChksmDrop(void * data)271 static inline void execTcpChksmDrop (void *data)
272 {
273     if( ScNapInlineMode() && ScTcpChecksumDrops() )
274     {
275         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
276             "Dropping bad packet (TCP checksum)\n"););
277         Active_NapDropPacket((Packet*)data);
278         if (pkt_trace_enabled)
279             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
280                 "Snort: TCP checksum error, %s\n", getPktTraceActMsg()));
281         else addPktTraceData(VERDICT_REASON_SNORT, 0);
282     }
283 }
284 
execUdpChksmDrop(void * data)285 static inline void execUdpChksmDrop (void *data)
286 {
287     if( ScNapInlineMode() && ScUdpChecksumDrops() )
288     {
289         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
290             "Dropping bad packet (UDP checksum)\n"););
291         Active_NapDropPacket((Packet*)data);
292         if (pkt_trace_enabled)
293             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
294                 "Snort: UDP checksum error, %s\n", getPktTraceActMsg()));
295         else addPktTraceData(VERDICT_REASON_SNORT, 0);
296     }
297 }
298 
execIcmpChksmDrop(void * data)299 static inline void execIcmpChksmDrop (void *data)
300 {
301     if( ScNapInlineMode() && ScIcmpChecksumDrops() )
302     {
303         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
304             "Dropping bad packet (ICMP checksum)\n"););
305         Active_NapDropPacket((Packet*)data);
306         if (pkt_trace_enabled)
307             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
308                 "Snort: ICMP checksum error, %s\n", getPktTraceActMsg()));
309         else addPktTraceData(VERDICT_REASON_SNORT, 0);
310     }
311 }
312 
execDecoderEvent(void * data)313 void execDecoderEvent(void *data)
314 {
315     MemBucket *alertBucket = (MemBucket *)data;
316     EventNode *en = (EventNode *)alertBucket->data;
317     int add;
318 
319     switch (en->sid)
320     {
321         case DECODE_IPV4OPT_BADLEN:
322         case DECODE_IPV4OPT_TRUNCATED:
323             add = ScDecoderIpOptAlerts();
324             break;
325 
326         case DECODE_TCPOPT_WSCALE_INVALID:
327         case DECODE_TCPOPT_BADLEN:
328         case DECODE_TCPOPT_TRUNCATED:
329             add = ScDecoderTcpOptAlerts();
330             break;
331 
332         case DECODE_TCPOPT_EXPERIMENT:
333             add = ScDecoderTcpOptExpAlerts();
334             break;
335 
336         case DECODE_TCPOPT_OBSOLETE:
337             add = ScDecoderTcpOptObsAlerts();
338             break;
339 
340         case DECODE_TCPOPT_TTCP:
341             add = ScDecoderTcpOptTTcpAlerts();
342             break;
343 
344         default:
345             add = ScDecoderAlerts();
346             break;
347     }
348 
349     if ( add )
350     {
351         SnortEventqAdd(en->gid, en->sid, en->rev, en->classification,
352             en->priority, en->msg, en->rule_info);
353     }
354     mempool_free(&decoderAlertMemPool, alertBucket);
355 }
356 
queueDecoderEvent(unsigned int gid,unsigned int sid,unsigned int rev,unsigned int classification,unsigned int pri,const char * msg,void * rule_info)357 void queueDecoderEvent(
358     unsigned int gid,
359     unsigned int sid,
360     unsigned int rev,
361     unsigned int classification,
362     unsigned int pri,
363     const char  *msg,
364     void        *rule_info)
365 {
366     MemBucket *alertBucket;
367     EventNode *en;
368     int ret;
369 
370     alertBucket = (MemBucket *)mempool_alloc(&decoderAlertMemPool);
371     if(!alertBucket)
372         return;
373 
374     en = (EventNode *)alertBucket->data;
375     en->gid = gid;
376     en->sid = sid;
377     en->rev = rev;
378     en->classification = classification;
379     en->priority = pri;
380     en->msg = msg;
381     en->rule_info = (OptTreeNode *) rule_info;
382 
383     ret = sfActionQueueAdd( decoderActionQ, execDecoderEvent, alertBucket);
384     if (ret == -1)
385     {
386         ErrorMessage("Could not add event to decoderActionQ\n");
387         mempool_free(&decoderAlertMemPool, alertBucket);
388     }
389 }
390 
DecoderEvent(Packet * p,int sid,const char * str,int event_flag,int drop_flag)391 static inline void DecoderEvent (
392     Packet *p, int sid, const char *str, int event_flag, int drop_flag)
393 {
394     if ( ScLogVerbose() )
395         ErrorMessage("%s\n", str);
396 
397     if (ScIdsMode() && event_flag)
398     {
399         queueDecoderEvent(GENERATOR_SNORT_DECODE, sid, 1,
400             DECODE_CLASS, 3, str, 0);
401 
402         if ( drop_flag )
403         {
404             queueExecDrop(execDecoderDrop, p);
405             if (pkt_trace_enabled)
406                 addPktTraceData(VERDICT_REASON_NO_BLOCK, snprintf(trace_line, MAX_TRACE_LINE,
407                     "Snort: gid %u, sid %u, bad packet queued for decoder drop\n", GENERATOR_SNORT_DECODE, sid));
408         }
409     }
410 }
411 
DecoderOptEvent(Packet * p,int sid,char * str,int event_flag,int drop_flag,void (* callback)(void *))412 static inline void DecoderOptEvent (
413     Packet *p, int sid, char *str, int event_flag, int drop_flag,
414     void (*callback)(void*) )
415 {
416     if ( ScLogVerbose() )
417         ErrorMessage("%s\n", str);
418 
419     if (ScIdsMode() && event_flag)
420     {
421         queueDecoderEvent(GENERATOR_SNORT_DECODE, sid, 1,
422             DECODE_CLASS, 3, str, 0);
423 
424         if ( drop_flag )
425         {
426             queueExecDrop(callback, p);
427         }
428     }
429 }
430 
DecoderEventDrop(Packet * p,int sid,char * str,int event_flag,int drop_flag)431 static inline void DecoderEventDrop (
432     Packet *p, int sid, char *str, int event_flag, int drop_flag)
433 {
434     if ( ScLogVerbose() )
435         ErrorMessage("%s\n", str);
436 
437     if (ScIdsMode() && event_flag)
438     {
439         queueDecoderEvent(GENERATOR_SNORT_DECODE, sid, 1,
440             DECODE_CLASS, 3, str, 0);
441 
442         if ( drop_flag )
443         {
444             Active_DropPacket(p);
445             if (pkt_trace_enabled)
446                 addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
447                     "Snort: decoder gid %u, sid %u, %s\n", GENERATOR_SNORT_DECODE, sid, getPktTraceActMsg()));
448             else addPktTraceData(VERDICT_REASON_SNORT, 0);
449         }
450     }
451 }
452 
DecoderAlertEncapsulated(Packet * p,int type,const char * str,const uint8_t * pkt,uint32_t len)453 void DecoderAlertEncapsulated(
454     Packet *p, int type, const char *str, const uint8_t *pkt, uint32_t len)
455 {
456     DecoderEvent(p, type, str, 1, 1);
457 
458     p->data = pkt;
459     p->dsize = (uint16_t)len;
460 
461     p->greh = NULL;
462 }
463 
464 #define EVARGS(ID) DECODE_ ## ID, DECODE_ ## ID ## _STR
465 
Event_Enabled(int sid)466 static inline int Event_Enabled(int sid)
467 {
468     return ( decodeRulesArray[sid] );
469 }
470 
471 //--------------------------------------------------------------------
472 // decode.c::miscellaneous public methods and helper functions
473 //--------------------------------------------------------------------
474 
475 #if defined(WORDS_MUSTALIGN) && !defined(__GNUC__)
EXTRACT_32BITS(u_char * p)476 uint32_t EXTRACT_32BITS (u_char *p)
477 {
478   uint32_t __tmp;
479 
480   memmove(&__tmp, p, sizeof(uint32_t));
481   return (uint32_t) ntohl(__tmp);
482 }
483 #endif /* WORDS_MUSTALIGN && !__GNUC__ */
484 
InitSynToMulticastDstIp(struct _SnortConfig * sc)485 void InitSynToMulticastDstIp( struct _SnortConfig *sc )
486 {
487     // Multicast addresses pursuant to RFC 5771
488     SynToMulticastDstIp = IpAddrSetParse(sc, "[224.0.0.0/4]");
489 
490     if( SynToMulticastDstIp == NULL )
491     {
492         FatalError("Could not initialize SynToMulticastDstIp\n");
493     }
494 }
495 
InitMulticastReservedIp(struct _SnortConfig * sc)496 void InitMulticastReservedIp( struct _SnortConfig *sc )
497 {
498     // Reserved addresses within multicast address space (See RFC 5771)
499     MulticastReservedIp = IpAddrSetParse(sc,
500             "[224.1.0.0/16,224.5.0.0/16,224.6.0.0/15,224.8.0.0/13,224.16.0.0/12,"
501              "224.32.0.0/11,224.64.0.0/10,224.128.0.0/9,225.0.0.0/8,226.0.0.0/7,"
502              "228.0.0.0/6,234.0.0.0/7,236.0.0.0/7,238.0.0.0/8]");
503 
504     if( MulticastReservedIp == NULL )
505     {
506         FatalError("Could not initialize MulticastReservedIp\n");
507     }
508 }
509 
SynToMulticastDstIpDestroy(void)510 void SynToMulticastDstIpDestroy( void )
511 {
512     if( SynToMulticastDstIp )
513     {
514         IpAddrSetDestroy(SynToMulticastDstIp);
515     }
516 }
517 
MulticastReservedIpDestroy(void)518 void MulticastReservedIpDestroy( void )
519 {
520     if( MulticastReservedIp )
521     {
522         IpAddrSetDestroy(MulticastReservedIp);
523     }
524 }
525 
CheckIPv4_MinTTL(Packet * p,uint8_t ttl)526 static inline void CheckIPv4_MinTTL(Packet *p, uint8_t ttl)
527 {
528 
529     // this sequence of tests is best for the "normal" case where
530     // the packet ttl is >= the configured min (the default is 1)
531     if( ttl < ScMinTTL() )
532     {
533         if ( Event_Enabled(DECODE_ZERO_TTL) && (ttl == 0) )
534         {
535             DecoderOptEvent(p, DECODE_ZERO_TTL, DECODE_ZERO_TTL_STR,
536                     1, 1, execTtlDrop);
537         }
538         else if ( Event_Enabled(DECODE_IP4_MIN_TTL) )
539         {
540             DecoderOptEvent(p, DECODE_IP4_MIN_TTL, DECODE_IP4_MIN_TTL_STR,
541                     1, 1, execMinTtlDrop);
542         }
543     }
544 }
545 
CheckIPv6_MinTTL(Packet * p,uint8_t hop_limit)546 static inline void CheckIPv6_MinTTL(Packet *p, uint8_t hop_limit)
547 {
548     // this sequence of tests is best for the "normal" case where
549     // the packet ttl is >= the configured min (the default is 1)
550     if( hop_limit < ScMinTTL() )
551     {
552         if ( Event_Enabled(DECODE_IP6_ZERO_HOP_LIMIT) && (hop_limit == 0) )
553         {
554             DecoderOptEvent(p, DECODE_IP6_ZERO_HOP_LIMIT,
555                    DECODE_IP6_ZERO_HOP_LIMIT_STR, 1, 1, execHopDrop);
556         }
557         else if ( Event_Enabled(DECODE_IPV6_MIN_TTL) )
558         {
559             DecoderOptEvent(p, DECODE_IPV6_MIN_TTL,
560                     DECODE_IPV6_MIN_TTL_STR, 1, 1, execIpv6MinTtlDrop);
561         }
562     }
563 }
564 
565 /* Decoding of ttl/hop_limit is based on the policy min_ttl */
DecodeIP_MinTTL(Packet * p)566 static inline void DecodeIP_MinTTL(Packet *p)
567 {
568     switch(p->outer_family)
569     {
570         case AF_INET:
571             CheckIPv4_MinTTL( p, p->outer_ip4h.ip_ttl);
572             return;
573 
574         case AF_INET6:
575             CheckIPv6_MinTTL( p, p->outer_ip6h.hop_lmt);
576             return;
577 
578         default:
579             break;
580     }
581 
582     switch(p->family)
583     {
584         case AF_INET:
585             CheckIPv4_MinTTL( p, p->ip4h->ip_ttl);
586             return;
587 
588         case AF_INET6:
589             CheckIPv6_MinTTL( p, p->ip6h->hop_lmt);
590             return;
591 
592         default:
593             break;
594     }
595 
596     return;
597 }
598 
599 /* Any policy specific decoding should be done in this function which is called by ProcessPacket*/
DecodePolicySpecific(Packet * p)600 void DecodePolicySpecific(Packet *p)
601 {
602     DecodeIP_MinTTL(p);
603 }
604 
605 /* This function enables or disables the decoder rule. value can only be 0 or 1*/
UpdateDecodeRulesArray(uint32_t sid,int value,int all_rules)606 void UpdateDecodeRulesArray(uint32_t sid, int value, int all_rules)
607 {
608     int i;
609 
610     if ( all_rules )
611     {
612         for( i = 0; i < DECODE_INDEX_MAX; i++ )
613             decodeRulesArray[i] = ( value != 0 );
614     }
615     else if ( sid < DECODE_INDEX_MAX )
616     {
617         decodeRulesArray[sid] = ( value != 0 );
618     }
619 }
620 
621 static ThrottleInfo log_throttleInfo = {0, 60, 0, 100};
622 
623 // this must be called iff the layer is successfully decoded because, when
624 // enabled, the normalizer assumes that the encoding is structurally sound
PushLayer(PROTO_ID type,Packet * p,const uint8_t * hdr,uint32_t len)625 static inline void PushLayer(PROTO_ID type, Packet* p, const uint8_t* hdr, uint32_t len)
626 {
627     if ( p->next_layer < LAYER_MAX )
628     {
629         Layer* lyr = p->layers + p->next_layer++;
630         lyr->proto = type;
631         lyr->start = (uint8_t*)hdr;
632         lyr->length = (uint16_t)len;
633     }
634     else
635     {
636         LogThrottledByTimeCount(&log_throttleInfo,
637                 "(snort_decoder) WARNING: Too many levels for decoding;"
638                 "next proto is %u.\n", type);
639         SnortEventqAdd(GENERATOR_SNORT_DECODE,
640                 DECODE_DECODING_DEPTH_EXCEEDED,
641                 1,
642                 0,
643                 1,
644                 DECODE_DECODING_DEPTH_EXCEEDED_STR,
645                 NULL);
646         pc.alert_pkts++;
647     }
648 }
649 
650 //--------------------------------------------------------------------
651 // decode.c::ARP
652 //--------------------------------------------------------------------
653 
654 /*
655  * Function: DecodeARP(uint8_t *, uint32_t, Packet *)
656  *
657  * Purpose: Decode ARP stuff
658  *
659  * Arguments: pkt => ptr to the packet data
660  *            len => length from here to the end of the packet
661  *            p   => pointer to decoded packet struct
662  *
663  * Returns: void function
664  */
DecodeARP(const uint8_t * pkt,uint32_t len,Packet * p)665 void DecodeARP(const uint8_t * pkt, uint32_t len, Packet * p)
666 {
667     pc.arp++;
668 
669 #ifdef GRE
670     if (p->greh != NULL)
671         pc.gre_arp++;
672 #endif
673 
674     p->ah = (EtherARP *) pkt;
675 
676     if(len < sizeof(EtherARP))
677     {
678         DecoderEvent(p, DECODE_ARP_TRUNCATED,
679                         DECODE_ARP_TRUNCATED_STR, 1, 1);
680 
681         pc.discards++;
682         return;
683     }
684 
685     p->proto_bits |= PROTO_BIT__ARP;
686     PushLayer(PROTO_ARP, p, pkt, sizeof(*p->ah));
687 }
688 
689 //--------------------------------------------------------------------
690 // decode.c::NULL and Loopback
691 //--------------------------------------------------------------------
692 
693 /*
694  * Function: DecodeNullPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
695  *
696  * Purpose: Decoding on loopback devices.
697  *
698  * Arguments: p => pointer to decoded packet struct
699  *            user => Utility pointer, unused
700  *            pkthdr => ptr to the packet header
701  *            pkt => pointer to the real live packet data
702  *
703  * Returns: void function
704  */
DecodeNullPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)705 void DecodeNullPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
706 {
707     uint32_t cap_len = pkthdr->caplen;
708     PROFILE_VARS;
709 
710     PREPROC_PROFILE_START(decodePerfStats);
711 
712     pc.total_processed++;
713 
714     memset(p, 0, PKT_ZERO_LEN);
715 
716     p->pkth = pkthdr;
717     p->pkt = pkt;
718 
719     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"); );
720 
721     /* do a little validation */
722     if(cap_len < NULL_HDRLEN)
723     {
724         if (ScLogVerbose())
725         {
726             ErrorMessage("NULL header length < captured len! (%d bytes)\n",
727                     cap_len);
728         }
729 
730         PREPROC_PROFILE_END(decodePerfStats);
731         return;
732     }
733 
734     DecodeIP(p->pkt + NULL_HDRLEN, cap_len - NULL_HDRLEN, p);
735     PREPROC_PROFILE_END(decodePerfStats);
736 }
737 
738 /*
739  * Function: DecodeEthLoopback(uint8_t *, uint32_t)
740  *
741  * Purpose: Just like IPX, it's just for counting.
742  *
743  * Arguments: pkt => ptr to the packet data
744  *            len => length from here to the end of the packet
745  *
746  * Returns: void function
747  */
DecodeEthLoopback(const uint8_t * pkt,uint32_t len,Packet * p)748 void DecodeEthLoopback(const uint8_t *pkt, uint32_t len, Packet *p)
749 {
750     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "EthLoopback is not supported.\n"););
751 
752     pc.ethloopback++;
753 
754 #ifdef GRE
755     if (p->greh != NULL)
756         pc.gre_loopback++;
757 #endif
758 
759     return;
760 }
761 
762 //--------------------------------------------------------------------
763 // decode.c::Ethernet
764 //--------------------------------------------------------------------
765 void DecodeEthTypes(Packet *p, const uint8_t *pkt, uint16_t ethtype, uint32_t cap_len, uint8_t linklen);
766 
DecodeCiscoMeta(const uint8_t * pkt,uint32_t rem_len,Packet * p)767 void DecodeCiscoMeta(const uint8_t *pkt, uint32_t rem_len, Packet *p)
768 {
769     uint16_t real_len;
770     uint16_t realeth;
771     int16_t cmdh_rem_len;
772     uint8_t i;
773 
774     if (rem_len < CISCO_META_PREHEADER_LEN)
775     {
776         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
777             "WARNING: Truncated Cisco Metadata header (%d bytes).\n", rem_len););
778 
779         if ( Event_Enabled(DECODE_CISCO_META_HDR_TRUNC) )
780             DecoderEvent(p, EVARGS(CISCO_META_HDR_TRUNC), 1, 1);
781 
782         pc.discards++;
783         return;
784     }
785 
786     p->cmdh = (CiscoMetaHdr*)pkt;
787     p->cmd_options = (CiscoMetaOpt*)(pkt + sizeof(CiscoMetaHdr));
788     cmdh_rem_len = p->cmdh->length << 3;
789 
790     /* validate CMD tag header */
791     if(rem_len < cmdh_rem_len || cmdh_rem_len == 0)
792     {
793         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
794             "WARNING: Truncated Cisco Metadata header (%d bytes).\n", rem_len););
795 
796         if ( Event_Enabled(DECODE_CISCO_META_HDR_TRUNC) )
797             DecoderEvent(p, EVARGS(CISCO_META_HDR_TRUNC), 1, 1);
798 
799         pc.discards++;
800         return;
801     }
802 
803     /* validate options, lengths, and SGTs*/
804     cmdh_rem_len -= sizeof(CiscoMetaHdr) + sizeof(uint16_t); //2 octects for ethertype
805     if(cmdh_rem_len == 0)
806         p->cmd_options = NULL;
807 
808     for(i = 0; cmdh_rem_len > 0; i++)
809     {
810         CiscoMetaOpt *opt;
811         uint8_t len;
812         uint16_t type;
813 
814         /* Top 3 bits (length) must be equal to 0 or 4 */
815         /* Bottom 13 bits (type) must be 1 to indicate SGT*/
816         opt = &p->cmd_options[i];
817         len = ntohs(opt->opt_len_type) >> CISCO_META_OPT_LEN_SHIFT;
818         type = ntohs(opt->opt_len_type) & CISCO_META_OPT_TYPE_MASK;
819 
820         /* 0 indicates 4 octets */
821         if(len != 0 && len != 4)
822         {
823             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
824                 "WARNING: Invalid Cisco Metadata option length (%u bytes).\n", (uint32_t)len););
825 
826             if ( Event_Enabled(DECODE_CISCO_META_HDR_OPT_LEN) )
827                 DecoderEvent(p, EVARGS(CISCO_META_HDR_OPT_LEN), 1, 1);
828 
829             pc.discards++;
830             return;
831         }
832 
833         if(type != CISCO_META_OPT_TYPE_SGT)
834         {
835             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
836                 "WARNING: Invalid Cisco Metadata option type (%u).\n", (uint32_t)len););
837 
838             if ( Event_Enabled(DECODE_CISCO_META_HDR_OPT_TYPE) )
839                 DecoderEvent(p, EVARGS(CISCO_META_HDR_OPT_TYPE), 1, 1);
840 
841             pc.discards++;
842             return;
843         }
844 
845         /* Tag value 0xFFFF is invalid */
846         if(opt->sgt == 0xFFFF)
847         {
848             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
849                 "WARNING: Invalid Cisco Metadata SGT (0xFFFF).\n"););
850 
851             if ( Event_Enabled(DECODE_CISCO_META_HDR_SGT) )
852                 DecoderEvent(p, EVARGS(CISCO_META_HDR_SGT), 1, 1);
853 
854             pc.discards++;
855             return;
856 
857         }
858         cmdh_rem_len -= sizeof(CiscoMetaOpt);
859     }
860 
861     /* Move to next header */
862     real_len = p->cmdh->length << 3;
863     realeth = ntohs(*((uint16_t*) (pkt + real_len - sizeof(uint16_t)))); //The last 2 octets of the header will be the real ethtype
864     PushLayer(PROTO_CISCO_META, p, pkt, real_len);
865 
866     //Decode the real ethtype
867     DecodeEthTypes(p, pkt, realeth, rem_len, real_len);
868 }
869 
870 /* Handles ethtypes. Used for ethtypes that chain to other ethtypes */
DecodeEthTypes(Packet * p,const uint8_t * pkt,uint16_t ethtype,uint32_t cap_len,uint8_t linklen)871 void DecodeEthTypes(Packet *p, const uint8_t *pkt, uint16_t ethtype, uint32_t cap_len, uint8_t linklen)
872 {
873     /* grab out the network type */
874     switch(ethtype)
875     {
876         case ETHERNET_TYPE_IP:
877             DEBUG_WRAP(
878                     DebugMessage(DEBUG_DECODE,
879                         "IP datagram size calculated to be %lu bytes\n",
880                         (unsigned long)(cap_len - linklen));
881                     );
882 
883             DecodeIP(pkt + linklen,
884                     cap_len - linklen, p);
885 
886             return;
887 
888         case ETHERNET_TYPE_ARP:
889         case ETHERNET_TYPE_REVARP:
890             DecodeARP(pkt + linklen,
891                     cap_len - linklen, p);
892             return;
893 
894         case ETHERNET_TYPE_IPV6:
895             DecodeIPV6(pkt + linklen,
896                     (cap_len - linklen), p);
897             return;
898 
899         case ETHERNET_TYPE_PPPoE_DISC:
900         case ETHERNET_TYPE_PPPoE_SESS:
901             DecodePPPoEPkt(pkt + linklen,
902                     (cap_len - linklen), p);
903             return;
904 
905 #ifndef NO_NON_ETHER_DECODER
906         case ETHERNET_TYPE_IPX:
907             DecodeIPX(pkt + linklen,
908                     (cap_len - linklen), p);
909             return;
910 #endif
911 
912         case ETHERNET_TYPE_LOOP:
913             DecodeEthLoopback(pkt + linklen,
914                     (cap_len - linklen), p);
915             return;
916 
917         case ETHERNET_TYPE_8021Q:
918         case ETHERNET_TYPE_8021AD:
919         case ETHERNET_TYPE_QINQ_NS1:
920         case ETHERNET_TYPE_QINQ_NS2:
921             DecodeVlan(pkt + linklen,
922                     cap_len - linklen, p);
923             return;
924 #ifdef MPLS
925         case ETHERNET_TYPE_MPLS_MULTICAST:
926             if(!ScMplsMulticast())
927             {
928                 //additional check for DecoderAlerts will be done now.
929             	DecoderEvent(p, DECODE_BAD_MPLS, DECODE_MULTICAST_MPLS_STR, 1, 1);
930             }
931         case ETHERNET_TYPE_MPLS_UNICAST:
932             DecodeMPLS(pkt + linklen,
933                 cap_len - linklen, p);
934             return;
935 #endif
936         case ETHERNET_TYPE_CISCO_META:
937             DecodeCiscoMeta(pkt + linklen,
938                 cap_len - linklen, p);
939             return;
940         default:
941             // TBD add decoder drop event for unknown eth type
942             pc.other++;
943             return;
944     }
945 }
946 
947 /*
948  * Function: DecodeEthPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
949  *
950  * Purpose: Decode those fun loving ethernet packets, one at a time!
951  *
952  * Arguments: p => pointer to the decoded packet struct
953  *            user => Utility pointer (unused)
954  *            pkthdr => ptr to the packet header
955  *            pkt => pointer to the real live packet data
956  *
957  * Returns: void function
958  */
DecodeEthPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)959 void DecodeEthPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
960 {
961     uint32_t cap_len = pkthdr->caplen;
962     uint32_t rem_len = cap_len;
963     uint8_t linklen = ETHERNET_HEADER_LEN;
964     PROFILE_VARS;
965 
966     PREPROC_PROFILE_START(decodePerfStats);
967     pc.eth++;
968     pc.total_processed++;
969 
970     memset(p, 0, PKT_ZERO_LEN);
971 
972     p->pkth = pkthdr;
973     p->pkt = pkt;
974 
975     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n");
976             DebugMessage(DEBUG_DECODE, "caplen: %lu    pktlen: %lu\n",
977                 (unsigned long)cap_len, (unsigned long)pkthdr->pktlen);
978             );
979 
980     while(true)
981     {
982     /* do a little validation */
983         if(rem_len < ETHERNET_HEADER_LEN)
984         {
985             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
986                 "WARNING: Truncated eth header (%d bytes).\n", rem_len););
987 
988             if ( Event_Enabled(DECODE_ETH_HDR_TRUNC) )
989                 DecoderEvent(p, EVARGS(ETH_HDR_TRUNC), 1, 1);
990 
991             pc.discards++;
992             pc.ethdisc++;
993             PREPROC_PROFILE_END(decodePerfStats);
994             return;
995         }
996 
997         /* lay the ethernet structure over the packet data */
998         p->eh = (EtherHdr *) pkt;
999 
1000         /* check if this is a FabricPath header */
1001         if(ntohs(p->eh->ether_type) == ETHERNET_TYPE_FPATH)
1002         {
1003             /* do a little validation */
1004             if(rem_len < FABRICPATH_HEADER_LEN)
1005             {
1006                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
1007                     "WARNING: Truncated FabricPath header (%d bytes).\n", rem_len););
1008 
1009                 if ( Event_Enabled(DECODE_FPATH_HDR_TRUNC) )
1010                     DecoderEvent(p, EVARGS(FPATH_HDR_TRUNC), 1, 1);
1011 
1012                 pc.discards++;
1013                 PREPROC_PROFILE_END(decodePerfStats);
1014                 return;
1015             }
1016             /* strip FabricPath header*/
1017             PushLayer(PROTO_FPATH, p, pkt, FABRICPATH_HEADER_LEN);
1018             pkt += FABRICPATH_HEADER_LEN;
1019             linklen += FABRICPATH_HEADER_LEN;
1020             rem_len -= FABRICPATH_HEADER_LEN;
1021         }
1022 
1023 
1024         else
1025             break;
1026     }
1027     PushLayer(PROTO_ETH, p, pkt, sizeof(*p->eh));
1028 
1029     DEBUG_WRAP(
1030             DebugMessage(DEBUG_DECODE, "%X:%X:%X:%X:%X:%X -> %X:%X:%X:%X:%X:%X\n",
1031                 p->eh->ether_src[0],
1032                 p->eh->ether_src[1], p->eh->ether_src[2], p->eh->ether_src[3],
1033                 p->eh->ether_src[4], p->eh->ether_src[5], p->eh->ether_dst[0],
1034                 p->eh->ether_dst[1], p->eh->ether_dst[2], p->eh->ether_dst[3],
1035                 p->eh->ether_dst[4], p->eh->ether_dst[5]);
1036             );
1037     DEBUG_WRAP(
1038             DebugMessage(DEBUG_DECODE, "type:0x%X len:0x%X\n",
1039                 ntohs(p->eh->ether_type), p->pkth->pktlen)
1040             );
1041     DecodeEthTypes(p, p->pkt, ntohs(p->eh->ether_type), cap_len, linklen);
1042     PREPROC_PROFILE_END(decodePerfStats);
1043 }
1044 
1045 #ifdef GRE
1046 /*
1047  * Function: DecodeTransBridging(uint8_t *, const uint32_t, Packet)
1048  *
1049  * Purpose: Decode Transparent Ethernet Bridging
1050  *
1051  * Arguments: pkt => pointer to the real live packet data
1052  *            len => length of remaining data in packet
1053  *            p => pointer to the decoded packet struct
1054  *
1055  *
1056  * Returns: void function
1057  *
1058  * Note: This is basically the code from DecodeEthPkt but the calling
1059  * convention needed to be changed and the stuff at the beginning
1060  * wasn't needed since we are already deep into the packet
1061  */
DecodeTransBridging(const uint8_t * pkt,const uint32_t len,Packet * p)1062 void DecodeTransBridging(const uint8_t *pkt, const uint32_t len, Packet *p)
1063 {
1064     pc.gre_eth++;
1065 
1066     if(len < ETHERNET_HEADER_LEN)
1067     {
1068         DecoderAlertEncapsulated(p, DECODE_GRE_TRANS_DGRAM_LT_TRANSHDR,
1069                         DECODE_GRE_TRANS_DGRAM_LT_TRANSHDR_STR,
1070                         pkt, len);
1071         return;
1072     }
1073 
1074     /* The Packet struct's ethernet header will now point to the inner ethernet
1075      * header of the packet
1076      */
1077     p->eh = (EtherHdr *)pkt;
1078     PushLayer(PROTO_ETH, p, pkt, sizeof(*p->eh));
1079 
1080     switch (ntohs(p->eh->ether_type))
1081     {
1082         case ETHERNET_TYPE_IP:
1083             DecodeIP(pkt + ETHERNET_HEADER_LEN, len - ETHERNET_HEADER_LEN, p);
1084             return;
1085 
1086         case ETHERNET_TYPE_ARP:
1087         case ETHERNET_TYPE_REVARP:
1088             DecodeARP(pkt + ETHERNET_HEADER_LEN, len - ETHERNET_HEADER_LEN, p);
1089             return;
1090 
1091         case ETHERNET_TYPE_IPV6:
1092             DecodeIPV6(pkt + ETHERNET_HEADER_LEN, len - ETHERNET_HEADER_LEN, p);
1093             return;
1094 
1095 #ifndef NO_NON_ETHER_DECODER
1096         case ETHERNET_TYPE_IPX:
1097             DecodeIPX(pkt + ETHERNET_HEADER_LEN, len - ETHERNET_HEADER_LEN, p);
1098             return;
1099 #endif
1100 
1101         case ETHERNET_TYPE_LOOP:
1102             DecodeEthLoopback(pkt + ETHERNET_HEADER_LEN, len - ETHERNET_HEADER_LEN, p);
1103             return;
1104 
1105         case ETHERNET_TYPE_8021Q:
1106             DecodeVlan(pkt + ETHERNET_HEADER_LEN, len - ETHERNET_HEADER_LEN, p);
1107             return;
1108 
1109         default:
1110             // TBD add decoder drop event for unknown xbrdg/eth type
1111             pc.other++;
1112             p->data = pkt + ETHERNET_HEADER_LEN;
1113             p->dsize = (uint16_t)(len - ETHERNET_HEADER_LEN);
1114             return;
1115     }
1116 }
1117 #endif  /* GRE */
1118 
1119 //--------------------------------------------------------------------
1120 // decode.c::MPLS
1121 //--------------------------------------------------------------------
1122 
1123 #ifdef MPLS
1124 /*
1125  * check if reserved labels are used properly
1126  */
checkMplsHdr(uint32_t label,uint8_t exp,uint8_t bos,uint8_t ttl,Packet * p)1127 static int checkMplsHdr(uint32_t label, uint8_t exp, uint8_t bos, uint8_t ttl, Packet *p)
1128 {
1129     int iRet = 0;
1130     switch(label)
1131     {
1132         case 0:
1133         case 2:
1134                /* check if this label is the bottom of the stack */
1135                if(bos)
1136                {
1137                    if ( label == 0 )
1138                        iRet = MPLS_PAYLOADTYPE_IPV4;
1139                    else if ( label == 2 )
1140                        iRet = MPLS_PAYLOADTYPE_IPV6;
1141 
1142 
1143                    /* when label == 2, IPv6 is expected;
1144                     * when label == 0, IPv4 is expected */
1145                    if((label&&(ScMplsPayloadType() != MPLS_PAYLOADTYPE_IPV6))
1146                        ||((!label)&&(ScMplsPayloadType() != MPLS_PAYLOADTYPE_IPV4)))
1147                    {
1148                         if( !label )
1149                             DecoderEvent(p, DECODE_BAD_MPLS_LABEL0,
1150                                             DECODE_BAD_MPLS_LABEL0_STR, 1, 1);
1151                         else
1152                             DecoderEvent(p, DECODE_BAD_MPLS_LABEL2,
1153                                             DECODE_BAD_MPLS_LABEL2_STR, 1, 1);
1154                    }
1155                    break;
1156                }
1157 
1158 #if 0
1159                /* This is valid per RFC 4182.  Just pop this label off, ignore it
1160                 * and move on to the next one.
1161                 */
1162                if( !label )
1163                    DecoderEvent(p, DECODE_BAD_MPLS_LABEL0,
1164                                    DECODE_BAD_MPLS_LABEL0_STR, 1, 1);
1165                else
1166                    DecoderEvent(p, DECODE_BAD_MPLS_LABEL2,
1167                                    DECODE_BAD_MPLS_LABEL2_STR, 1, 1);
1168 
1169                pc.discards++;
1170                p->iph = NULL;
1171                p->family = NO_IP;
1172                return(-1);
1173 #endif
1174                break;
1175         case 1:
1176                if(!bos) break;
1177 
1178        	       DecoderEvent(p, DECODE_BAD_MPLS_LABEL1,
1179                                DECODE_BAD_MPLS_LABEL1_STR, 1, 1);
1180 
1181                pc.discards++;
1182                p->iph = NULL;
1183                p->family = NO_IP;
1184                iRet = MPLS_PAYLOADTYPE_ERROR;
1185                break;
1186 
1187 	    case 3:
1188                DecoderEvent(p, DECODE_BAD_MPLS_LABEL3,
1189                                DECODE_BAD_MPLS_LABEL3_STR, 1, 1);
1190 
1191                pc.discards++;
1192                p->iph = NULL;
1193                p->family = NO_IP;
1194                iRet = MPLS_PAYLOADTYPE_ERROR;
1195                break;
1196         case 4:
1197         case 5:
1198         case 6:
1199         case 7:
1200         case 8:
1201         case 9:
1202         case 10:
1203         case 11:
1204         case 12:
1205         case 13:
1206         case 14:
1207         case 15:
1208                 DecoderEvent(p, DECODE_MPLS_RESERVED_LABEL,
1209                                 DECODE_MPLS_RESERVEDLABEL_STR, 1, 1);
1210                 break;
1211         default:
1212                 break;
1213     }
1214     if ( !iRet )
1215     {
1216         iRet = ScMplsPayloadType();
1217     }
1218     return iRet;
1219 }
1220 
DecodeMPLS(const uint8_t * pkt,const uint32_t len,Packet * p)1221 void DecodeMPLS(const uint8_t* pkt, const uint32_t len, Packet* p)
1222 {
1223     uint32_t* tmpMplsHdr;
1224     uint32_t mpls_h;
1225     uint32_t label;
1226     uint32_t mlen = 0;
1227 
1228     uint8_t exp;
1229     uint8_t bos = 0;
1230     uint8_t ttl;
1231     uint8_t chainLen = 0;
1232     uint32_t stack_len = len;
1233 
1234     int iRet = 0;
1235 
1236     pc.mpls++;
1237     UpdateMPLSStats(&sfBase, len, Active_PacketWasDropped());
1238     tmpMplsHdr = (uint32_t *) pkt;
1239     p->mpls = NULL;
1240 
1241     while (!bos)
1242     {
1243         if(stack_len < MPLS_HEADER_LEN)
1244         {
1245             DecoderEvent(p, DECODE_BAD_MPLS, DECODE_BAD_MPLS_STR, 1, 1);
1246 
1247             pc.discards++;
1248             p->iph = NULL;
1249             p->family = NO_IP;
1250             return;
1251         }
1252 
1253         mpls_h  = ntohl(*tmpMplsHdr);
1254         ttl = (uint8_t)(mpls_h & 0x000000FF);
1255         mpls_h = mpls_h>>8;
1256         bos = (uint8_t)(mpls_h & 0x00000001);
1257         exp = (uint8_t)(mpls_h & 0x0000000E);
1258         label = (mpls_h>>4) & 0x000FFFFF;
1259 
1260         if((label<NUM_RESERVED_LABELS)&&((iRet = checkMplsHdr(label, exp, bos, ttl, p)) < 0))
1261             return;
1262 
1263         if( bos )
1264         {
1265             p->mplsHdr.label = label;
1266             p->mplsHdr.exp = exp;
1267             p->mplsHdr.bos = bos;
1268             p->mplsHdr.ttl = ttl;
1269             /**
1270             p->mpls = &(p->mplsHdr);
1271 			**/
1272             p->mpls = tmpMplsHdr;
1273             if(!iRet)
1274             {
1275                 iRet = ScMplsPayloadType();
1276             }
1277         }
1278         tmpMplsHdr++;
1279         stack_len -= MPLS_HEADER_LEN;
1280 
1281         if ((ScMplsStackDepth() != -1) && (chainLen++ >= ScMplsStackDepth()))
1282         {
1283             DecoderEvent(p, DECODE_MPLS_LABEL_STACK,
1284                             DECODE_MPLS_LABEL_STACK_STR, 1, 1);
1285 
1286             pc.discards++;
1287             p->iph = NULL;
1288             p->family = NO_IP;
1289             return;
1290         }
1291     }   /* while bos not 1, peel off more labels */
1292 
1293     mlen = (uint8_t*)tmpMplsHdr - pkt;
1294     PushLayer(PROTO_MPLS, p, pkt, mlen);
1295     mlen = len - mlen;
1296 
1297     if ( ScTunnelBypassEnabled(TUNNEL_MPLS) )
1298         Active_SetTunnelBypass();
1299 
1300 #ifdef MPLS_RFC4023_SUPPORT
1301     /* Currently, this additional check for MPLS payload type presumes:
1302      * Only IPv4 or IPv6 payloads are supported (based on code inspection).
1303      *
1304      * If MPLS payload type is Ethernet or PWE extensions, the following
1305      * functions:
1306      *
1307      *    ScMplsPayloadCheck
1308      *    checkMplsHdr and
1309      *    ScMplsPayloadType
1310      *
1311      * must be revisited for performance and payload type checks as against,
1312      * static assignment from SnortConfig: sc->mpls_payload_type
1313      */
1314     iRet = ScMplsPayloadCheck(*(uint8_t *)tmpMplsHdr, iRet);
1315 #endif
1316 
1317     p->non_ip_pkt = 1;
1318 
1319     switch (iRet)
1320     {
1321         case MPLS_PAYLOADTYPE_IPV4:
1322             DecodeIP((uint8_t *)tmpMplsHdr, mlen, p);
1323             break;
1324 
1325         case MPLS_PAYLOADTYPE_IPV6:
1326             DecodeIPV6((uint8_t *)tmpMplsHdr, mlen, p);
1327             break;
1328 
1329         case MPLS_PAYLOADTYPE_ETHERNET:
1330             DecodeEthOverMPLS((uint8_t *)tmpMplsHdr, mlen, p);
1331             break;
1332 
1333         default:
1334             break;
1335     }
1336     return;
1337 }
1338 
DecodeEthOverMPLS(const uint8_t * pkt,const uint32_t len,Packet * p)1339 void DecodeEthOverMPLS(const uint8_t* pkt, const uint32_t len, Packet* p)
1340 {
1341     /* do a little validation */
1342     if(len < ETHERNET_HEADER_LEN)
1343     {
1344         if (ScLogVerbose())
1345         {
1346             ErrorMessage("Captured data length < Ethernet header length!"
1347                          " (%d bytes)\n", len);
1348         }
1349 
1350         p->iph = NULL;
1351         p->family = NO_IP;
1352         // TBD add decoder drop event for eth over MPLS cap len issue
1353         pc.discards++;
1354         pc.ethdisc++;
1355         return;
1356     }
1357 
1358     /* lay the ethernet structure over the packet data */
1359     p->eh = (EtherHdr *) pkt; // FIXTHIS squashes outer eth!
1360     PushLayer(PROTO_ETH, p, pkt, sizeof(*p->eh));
1361 
1362     DEBUG_WRAP(
1363             DebugMessage(DEBUG_DECODE, "%X   %X\n",
1364                 *p->eh->ether_src, *p->eh->ether_dst);
1365             );
1366 
1367     /* grab out the network type */
1368     switch(ntohs(p->eh->ether_type))
1369     {
1370         case ETHERNET_TYPE_IP:
1371             DEBUG_WRAP(
1372                     DebugMessage(DEBUG_DECODE,
1373                         "IP datagram size calculated to be %lu bytes\n",
1374                         (unsigned long)(len - ETHERNET_HEADER_LEN));
1375                     );
1376 
1377             DecodeIP(p->pkt + ETHERNET_HEADER_LEN,
1378                     len - ETHERNET_HEADER_LEN, p);
1379 
1380             return;
1381 
1382         case ETHERNET_TYPE_ARP:
1383         case ETHERNET_TYPE_REVARP:
1384             DecodeARP(p->pkt + ETHERNET_HEADER_LEN,
1385                     len - ETHERNET_HEADER_LEN, p);
1386             return;
1387 
1388         case ETHERNET_TYPE_IPV6:
1389             DecodeIPV6(p->pkt + ETHERNET_HEADER_LEN,
1390                     (len - ETHERNET_HEADER_LEN), p);
1391             return;
1392 
1393         case ETHERNET_TYPE_PPPoE_DISC:
1394         case ETHERNET_TYPE_PPPoE_SESS:
1395             DecodePPPoEPkt(p->pkt + ETHERNET_HEADER_LEN,
1396                     (len - ETHERNET_HEADER_LEN), p);
1397             return;
1398 
1399 #ifndef NO_NON_ETHER_DECODER
1400         case ETHERNET_TYPE_IPX:
1401             DecodeIPX(p->pkt + ETHERNET_HEADER_LEN,
1402                     (len - ETHERNET_HEADER_LEN), p);
1403             return;
1404 #endif
1405 
1406         case ETHERNET_TYPE_LOOP:
1407             DecodeEthLoopback(p->pkt + ETHERNET_HEADER_LEN,
1408                     (len - ETHERNET_HEADER_LEN), p);
1409             return;
1410 
1411         case ETHERNET_TYPE_8021Q:
1412             DecodeVlan(p->pkt + ETHERNET_HEADER_LEN,
1413                     len - ETHERNET_HEADER_LEN, p);
1414             return;
1415 
1416         default:
1417             // TBD add decoder drop event for unknown mpls/eth type
1418             pc.other++;
1419             return;
1420     }
1421 
1422     return;
1423 }
1424 
isPrivateIP(uint32_t addr)1425 int isPrivateIP(uint32_t addr)
1426 {
1427     switch (addr & 0xff)
1428     {
1429         case 0x0a:
1430             return 1;
1431             break;
1432         case 0xac:
1433             if ((addr & 0xf000) == 0x1000)
1434                 return 1;
1435             break;
1436         case 0xc0:
1437             if (((addr & 0xff00) ) == 0xa800)
1438                 return 1;
1439             break;
1440     }
1441     return 0;
1442 }
1443 #endif  // MPLS
1444 
1445 //--------------------------------------------------------------------
1446 // decode.c::VLAN
1447 //--------------------------------------------------------------------
1448 
1449 #define LEN_VLAN_LLC_OTHER (sizeof(VlanTagHdr) + sizeof(EthLlc) + sizeof(EthLlcOther))
1450 
DecodeVlan(const uint8_t * pkt,const uint32_t len,Packet * p)1451 void DecodeVlan(const uint8_t * pkt, const uint32_t len, Packet * p)
1452 {
1453     VlanTagHdr* vh;
1454 
1455     pc.vlan++;
1456 
1457 #ifdef GRE
1458     if (p->greh != NULL)
1459         pc.gre_vlan++;
1460 #endif
1461 
1462     if(len < sizeof(VlanTagHdr))
1463     {
1464         DecoderEvent(p, DECODE_BAD_VLAN, DECODE_BAD_VLAN_STR, 1, 1);
1465 
1466         // TBD add decoder drop event for VLAN hdr len issue
1467         pc.discards++;
1468         p->iph = NULL;
1469         p->family = NO_IP;
1470         return;
1471     }
1472 
1473     vh = (VlanTagHdr *) pkt;
1474 #ifdef HAVE_DAQ_REAL_ADDRESSES
1475     if (!(p->pkth->flags & DAQ_PKT_FLAG_IGNORE_VLAN))
1476 #endif
1477         p->vh = vh;
1478 
1479     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Vlan traffic:\n");
1480                DebugMessage(DEBUG_DECODE, "   Priority: %d(0x%X)\n",
1481                             VTH_PRIORITY(vh), VTH_PRIORITY(vh));
1482                DebugMessage(DEBUG_DECODE, "   CFI: %d\n", VTH_CFI(vh));
1483                DebugMessage(DEBUG_DECODE, "   Vlan ID: %d(0x%04X)\n",
1484                             VTH_VLAN(vh), VTH_VLAN(vh));
1485                DebugMessage(DEBUG_DECODE, "   Vlan Proto: 0x%04X\n",
1486                             ntohs(vh->vth_proto));
1487                );
1488 
1489     /* check to see if we've got an encapsulated LLC layer
1490      * http://www.geocities.com/billalexander/ethernet.html
1491      */
1492     if(ntohs(vh->vth_proto) <= ETHERNET_MAX_LEN_ENCAP)
1493     {
1494         if(len < sizeof(VlanTagHdr) + sizeof(EthLlc))
1495         {
1496             DecoderEvent(p, DECODE_BAD_VLAN_ETHLLC,
1497                             DECODE_BAD_VLAN_ETHLLC_STR, 1, 1);
1498 
1499             pc.discards++;
1500             p->iph = NULL;
1501             p->family = NO_IP;
1502             return;
1503         }
1504 
1505         p->ehllc = (EthLlc *) (pkt + sizeof(VlanTagHdr));
1506 
1507         DEBUG_WRAP(
1508                 DebugMessage(DEBUG_DECODE, "LLC Header:\n");
1509                 DebugMessage(DEBUG_DECODE, "   DSAP: 0x%X\n", p->ehllc->dsap);
1510                 DebugMessage(DEBUG_DECODE, "   SSAP: 0x%X\n", p->ehllc->ssap);
1511                 );
1512 
1513         if(p->ehllc->dsap == ETH_DSAP_IP && p->ehllc->ssap == ETH_SSAP_IP)
1514         {
1515             if ( len < LEN_VLAN_LLC_OTHER )
1516             {
1517                 DecoderEvent(p, DECODE_BAD_VLAN_OTHER,
1518                                 DECODE_BAD_VLAN_OTHER_STR, 1, 1);
1519 
1520                 pc.discards++;
1521                 p->iph = NULL;
1522                 p->family = NO_IP;
1523 
1524                 return;
1525             }
1526 
1527             p->ehllcother = (EthLlcOther *) (pkt + sizeof(VlanTagHdr) + sizeof(EthLlc));
1528 
1529             DEBUG_WRAP(
1530                     DebugMessage(DEBUG_DECODE, "LLC Other Header:\n");
1531                     DebugMessage(DEBUG_DECODE, "   CTRL: 0x%X\n",
1532                         p->ehllcother->ctrl);
1533                     DebugMessage(DEBUG_DECODE, "   ORG: 0x%02X%02X%02X\n",
1534                         p->ehllcother->org_code[0], p->ehllcother->org_code[1],
1535                         p->ehllcother->org_code[2]);
1536                     DebugMessage(DEBUG_DECODE, "   PROTO: 0x%04X\n",
1537                         ntohs(p->ehllcother->proto_id));
1538                     );
1539 
1540             PushLayer(PROTO_VLAN, p, pkt, sizeof(*vh));
1541 
1542             switch(ntohs(p->ehllcother->proto_id))
1543             {
1544                 case ETHERNET_TYPE_IP:
1545                     DecodeIP(p->pkt + LEN_VLAN_LLC_OTHER,
1546                              len - LEN_VLAN_LLC_OTHER, p);
1547                     return;
1548 
1549                 case ETHERNET_TYPE_ARP:
1550                 case ETHERNET_TYPE_REVARP:
1551                     DecodeARP(p->pkt + LEN_VLAN_LLC_OTHER,
1552                               len - LEN_VLAN_LLC_OTHER, p);
1553                     return;
1554 
1555                 case ETHERNET_TYPE_IPV6:
1556                     DecodeIPV6(p->pkt + LEN_VLAN_LLC_OTHER,
1557                                len - LEN_VLAN_LLC_OTHER, p);
1558                     return;
1559 
1560                 case ETHERNET_TYPE_8021Q:
1561                 case ETHERNET_TYPE_8021AD:
1562                 case ETHERNET_TYPE_QINQ_NS1:
1563                 case ETHERNET_TYPE_QINQ_NS2:
1564                     pc.nested_vlan++;
1565                     DecodeVlan(p->pkt + LEN_VLAN_LLC_OTHER,
1566                                len - LEN_VLAN_LLC_OTHER, p);
1567                     return;
1568 
1569                 case ETHERNET_TYPE_LOOP:
1570                     DecodeEthLoopback(p->pkt + LEN_VLAN_LLC_OTHER,
1571                                       len - LEN_VLAN_LLC_OTHER, p);
1572                     return;
1573 
1574 #ifndef NO_NON_ETHER_DECODER
1575                 case ETHERNET_TYPE_IPX:
1576                     DecodeIPX(p->pkt + LEN_VLAN_LLC_OTHER,
1577                               len - LEN_VLAN_LLC_OTHER, p);
1578                     return;
1579 #endif
1580 
1581                 case ETHERNET_TYPE_PPPoE_DISC:
1582                 case ETHERNET_TYPE_PPPoE_SESS:
1583                     DecodePPPoEPkt(p->pkt + LEN_VLAN_LLC_OTHER,
1584                               len - LEN_VLAN_LLC_OTHER, p);
1585                     return;
1586 #ifdef MPLS
1587                 case ETHERNET_TYPE_MPLS_MULTICAST:
1588                     if(!ScMplsMulticast())
1589                     {
1590                         DecoderEvent(p, DECODE_BAD_MPLS,
1591                                         DECODE_MULTICAST_MPLS_STR, 1, 1);
1592                     }
1593                 /* Fall through */
1594                 case ETHERNET_TYPE_MPLS_UNICAST:
1595                     DecodeMPLS(p->pkt + LEN_VLAN_LLC_OTHER,
1596                         len - LEN_VLAN_LLC_OTHER, p);
1597                     return;
1598 #endif
1599 
1600                 default:
1601                     // TBD add decoder drop event for unknown vlan/eth type
1602                     pc.other++;
1603                     return;
1604             }
1605         }
1606     }
1607     else
1608     {
1609         PushLayer(PROTO_VLAN, p, pkt, sizeof(*vh));
1610 
1611         switch(ntohs(vh->vth_proto))
1612         {
1613             case ETHERNET_TYPE_IP:
1614                 DecodeIP(pkt + sizeof(VlanTagHdr),
1615                          len - sizeof(VlanTagHdr), p);
1616                 return;
1617 
1618             case ETHERNET_TYPE_ARP:
1619             case ETHERNET_TYPE_REVARP:
1620                 DecodeARP(pkt + sizeof(VlanTagHdr),
1621                           len - sizeof(VlanTagHdr), p);
1622                 return;
1623 
1624             case ETHERNET_TYPE_IPV6:
1625                 DecodeIPV6(pkt +sizeof(VlanTagHdr),
1626                            len - sizeof(VlanTagHdr), p);
1627                 return;
1628 
1629             case ETHERNET_TYPE_8021Q:
1630             case ETHERNET_TYPE_8021AD:
1631             case ETHERNET_TYPE_QINQ_NS1:
1632             case ETHERNET_TYPE_QINQ_NS2:
1633                 pc.nested_vlan++;
1634                 DecodeVlan(pkt + sizeof(VlanTagHdr),
1635                            len - sizeof(VlanTagHdr), p);
1636                 return;
1637 
1638             case ETHERNET_TYPE_LOOP:
1639                 DecodeEthLoopback(pkt + sizeof(VlanTagHdr),
1640                                   len - sizeof(VlanTagHdr), p);
1641                 return;
1642 
1643 #ifndef NO_NON_ETHER_DECODER
1644             case ETHERNET_TYPE_IPX:
1645                 DecodeIPX(pkt + sizeof(VlanTagHdr),
1646                            len - sizeof(VlanTagHdr), p);
1647                 return;
1648 #endif
1649 
1650             case ETHERNET_TYPE_PPPoE_DISC:
1651             case ETHERNET_TYPE_PPPoE_SESS:
1652                 DecodePPPoEPkt(pkt + sizeof(VlanTagHdr),
1653                                len - sizeof(VlanTagHdr), p);
1654                 return;
1655 
1656 #ifdef MPLS
1657             case ETHERNET_TYPE_MPLS_MULTICAST:
1658                 if(!ScMplsMulticast())
1659                 {
1660                     SnortEventqAdd(GENERATOR_SNORT_DECODE, DECODE_BAD_MPLS, 1, DECODE_CLASS, 3, DECODE_MULTICAST_MPLS_STR, 0);
1661                 }
1662             case ETHERNET_TYPE_MPLS_UNICAST:
1663                 DecodeMPLS(pkt + sizeof(VlanTagHdr),
1664                     len - sizeof(VlanTagHdr), p);
1665                 return;
1666 #endif
1667             case ETHERNET_TYPE_CISCO_META:
1668                 DecodeCiscoMeta(pkt + sizeof(VlanTagHdr),
1669                    len - sizeof(VlanTagHdr), p);
1670                 return;
1671 
1672             default:
1673                 // TBD add decoder drop event for unknown vlan/eth type
1674                 pc.other++;
1675                 return;
1676         }
1677     }
1678 
1679     // TBD add decoder drop event for unknown vlan/llc type
1680     pc.other++;
1681     return;
1682 }
1683 
1684 //--------------------------------------------------------------------
1685 // decode.c::PPP related
1686 //--------------------------------------------------------------------
1687 
1688 /*
1689  * Function: DecodePPPoEPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
1690  *
1691  * Purpose: Decode those fun loving ethernet packets, one at a time!
1692  *
1693  * Arguments: p => pointer to the decoded packet struct
1694  *            user => Utility pointer (unused)
1695  *            pkthdr => ptr to the packet header
1696  *            pkt => pointer to the real live packet data
1697  *
1698  * Returns: void function
1699  *
1700  * see http://www.faqs.org/rfcs/rfc2516.html
1701  *
1702  */
DecodePPPoEPkt(const uint8_t * pkt,const uint32_t len,Packet * p)1703 void DecodePPPoEPkt(const uint8_t* pkt, const uint32_t len, Packet* p)
1704 {
1705     //PPPoE_Tag *ppppoe_tag=0;
1706     //PPPoE_Tag tag;  /* needed to avoid alignment problems */
1707 
1708     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "PPPoE with len: %lu\n",
1709         (unsigned long)len););
1710 
1711     /* do a little validation */
1712     if(len < PPPOE_HEADER_LEN)
1713     {
1714         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
1715             "Captured data length < PPPoE header length! "
1716             "(%d bytes)\n", len););
1717 
1718         DecoderEvent(p, DECODE_BAD_PPPOE, DECODE_BAD_PPPOE_STR, 1, 1);
1719 
1720         return;
1721     }
1722 
1723     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "%X   %X\n",
1724                 *p->eh->ether_src, *p->eh->ether_dst););
1725 
1726     /* lay the PPP over ethernet structure over the packet data */
1727     p->pppoeh = (PPPoEHdr *)pkt;
1728 
1729     /* grab out the network type */
1730     switch(ntohs(p->eh->ether_type))
1731     {
1732         case ETHERNET_TYPE_PPPoE_DISC:
1733             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "(PPPOE Discovery) "););
1734             break;
1735 
1736         case ETHERNET_TYPE_PPPoE_SESS:
1737             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "(PPPOE Session) "););
1738             break;
1739 
1740         default:
1741             return;
1742     }
1743 
1744 #ifdef DEBUG_MSGS
1745     switch(p->pppoeh->code)
1746     {
1747         case PPPoE_CODE_PADI:
1748             /* The Host sends the PADI packet with the DESTINATION_ADDR set
1749              * to the broadcast address.  The CODE field is set to 0x09 and
1750              * the SESSION_ID MUST be set to 0x0000.
1751              *
1752              * The PADI packet MUST contain exactly one TAG of TAG_TYPE
1753              * Service-Name, indicating the service the Host is requesting,
1754              * and any number of other TAG types.  An entire PADI packet
1755              * (including the PPPoE header) MUST NOT exceed 1484 octets so
1756              * as to leave sufficient room for a relay agent to add a
1757              * Relay-Session-Id TAG.
1758              */
1759             DebugMessage(DEBUG_DECODE, "Active Discovery Initiation (PADI)\n");
1760             break;
1761 
1762         case PPPoE_CODE_PADO:
1763             /* When the Access Concentrator receives a PADI that it can
1764              * serve, it replies by sending a PADO packet.  The
1765              * DESTINATION_ADDR is the unicast address of the Host that
1766              * sent the PADI.  The CODE field is set to 0x07 and the
1767              * SESSION_ID MUST be set to 0x0000.
1768              *
1769              * The PADO packet MUST contain one AC-Name TAG containing the
1770              * Access Concentrator's name, a Service-Name TAG identical to
1771              * the one in the PADI, and any number of other Service-Name
1772              * TAGs indicating other services that the Access Concentrator
1773              * offers.  If the Access Concentrator can not serve the PADI
1774              * it MUST NOT respond with a PADO.
1775              */
1776             DebugMessage(DEBUG_DECODE, "Active Discovery Offer (PADO)\n");
1777             break;
1778 
1779         case PPPoE_CODE_PADR:
1780             /* Since the PADI was broadcast, the Host may receive more than
1781              * one PADO.  The Host looks through the PADO packets it receives
1782              * and chooses one.  The choice can be based on the AC-Name or
1783              * the Services offered.  The Host then sends one PADR packet
1784              * to the Access Concentrator that it has chosen.  The
1785              * DESTINATION_ADDR field is set to the unicast Ethernet address
1786              * of the Access Concentrator that sent the PADO.  The CODE
1787              * field is set to 0x19 and the SESSION_ID MUST be set to 0x0000.
1788              *
1789              * The PADR packet MUST contain exactly one TAG of TAG_TYPE
1790              * Service-Name, indicating the service the Host is requesting,
1791              * and any number of other TAG types.
1792              */
1793             DebugMessage(DEBUG_DECODE, "Active Discovery Request (PADR)\n");
1794             break;
1795 
1796         case PPPoE_CODE_PADS:
1797             /* When the Access Concentrator receives a PADR packet, it
1798              * prepares to begin a PPP session.  It generates a unique
1799              * SESSION_ID for the PPPoE session and replies to the Host with
1800              * a PADS packet.  The DESTINATION_ADDR field is the unicast
1801              * Ethernet address of the Host that sent the PADR.  The CODE
1802              * field is set to 0x65 and the SESSION_ID MUST be set to the
1803              * unique value generated for this PPPoE session.
1804              *
1805              * The PADS packet contains exactly one TAG of TAG_TYPE
1806              * Service-Name, indicating the service under which Access
1807              * Concentrator has accepted the PPPoE session, and any number
1808              * of other TAG types.
1809              *
1810              * If the Access Concentrator does not like the Service-Name in
1811              * the PADR, then it MUST reply with a PADS containing a TAG of
1812              * TAG_TYPE Service-Name-Error (and any number of other TAG
1813              * types).  In this case the SESSION_ID MUST be set to 0x0000.
1814              */
1815             DebugMessage(DEBUG_DECODE, "Active Discovery "
1816                          "Session-confirmation (PADS)\n");
1817             break;
1818 
1819         case PPPoE_CODE_PADT:
1820             /* This packet may be sent anytime after a session is established
1821              * to indicate that a PPPoE session has been terminated.  It may
1822              * be sent by either the Host or the Access Concentrator.  The
1823              * DESTINATION_ADDR field is a unicast Ethernet address, the
1824              * CODE field is set to 0xa7 and the SESSION_ID MUST be set to
1825              * indicate which session is to be terminated.  No TAGs are
1826              * required.
1827              *
1828              * When a PADT is received, no further PPP traffic is allowed to
1829              * be sent using that session.  Even normal PPP termination
1830              * packets MUST NOT be sent after sending or receiving a PADT.
1831              * A PPP peer SHOULD use the PPP protocol itself to bring down a
1832              * PPPoE session, but the PADT MAY be used when PPP can not be
1833              * used.
1834              */
1835             DebugMessage(DEBUG_DECODE, "Active Discovery Terminate (PADT)\n");
1836             break;
1837 
1838         case PPPoE_CODE_SESS:
1839             DebugMessage(DEBUG_DECODE, "Session Packet (SESS)\n");
1840             break;
1841 
1842         default:
1843             DebugMessage(DEBUG_DECODE, "(Unknown)\n");
1844             break;
1845     }
1846 #endif
1847 
1848     if (ntohs(p->eh->ether_type) != ETHERNET_TYPE_PPPoE_DISC)
1849     {
1850         PushLayer(PROTO_PPPOE, p, pkt, PPPOE_HEADER_LEN);
1851         p->non_ip_pkt = 1;
1852         DecodePppPktEncapsulated(pkt + PPPOE_HEADER_LEN, len - PPPOE_HEADER_LEN, p);
1853         return;
1854     }
1855     else
1856     {
1857         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Returning early on PPPOE discovery packet\n"););
1858         return;
1859     }
1860 
1861 #if 0
1862     ppppoe_tag = (PPPoE_Tag *)(pkt + sizeof(PPPoEHdr));
1863 
1864     while (ppppoe_tag < (PPPoE_Tag *)(pkt + len))
1865     {
1866         if (((char*)(ppppoe_tag)+(sizeof(PPPoE_Tag)-1)) > (char*)(pkt + len))
1867         {
1868             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Not enough data in packet for PPPOE Tag\n"););
1869             break;
1870         }
1871 
1872         /* no guarantee in PPPoE spec that ppppoe_tag is aligned at all... */
1873         memcpy(&tag, ppppoe_tag, sizeof(tag));
1874 
1875         DEBUG_WRAP(
1876                 DebugMessage(DEBUG_DECODE, "\tPPPoE tag:\ntype: %04x length: %04x ",
1877                     ntohs(tag.type), ntohs(tag.length)););
1878 
1879 #ifdef DEBUG_MSGS
1880         switch(ntohs(tag.type))
1881         {
1882             case PPPoE_TAG_END_OF_LIST:
1883                 DebugMessage(DEBUG_DECODE, "(End of list)\n\t");
1884                 break;
1885             case PPPoE_TAG_SERVICE_NAME:
1886                 DebugMessage(DEBUG_DECODE, "(Service name)\n\t");
1887                 break;
1888             case PPPoE_TAG_AC_NAME:
1889                 DebugMessage(DEBUG_DECODE, "(AC Name)\n\t");
1890                 break;
1891             case PPPoE_TAG_HOST_UNIQ:
1892                 DebugMessage(DEBUG_DECODE, "(Host Uniq)\n\t");
1893                 break;
1894             case PPPoE_TAG_AC_COOKIE:
1895                 DebugMessage(DEBUG_DECODE, "(AC Cookie)\n\t");
1896                 break;
1897             case PPPoE_TAG_VENDOR_SPECIFIC:
1898                 DebugMessage(DEBUG_DECODE, "(Vendor Specific)\n\t");
1899                 break;
1900             case PPPoE_TAG_RELAY_SESSION_ID:
1901                 DebugMessage(DEBUG_DECODE, "(Relay Session ID)\n\t");
1902                 break;
1903             case PPPoE_TAG_SERVICE_NAME_ERROR:
1904                 DebugMessage(DEBUG_DECODE, "(Service Name Error)\n\t");
1905                 break;
1906             case PPPoE_TAG_AC_SYSTEM_ERROR:
1907                 DebugMessage(DEBUG_DECODE, "(AC System Error)\n\t");
1908                 break;
1909             case PPPoE_TAG_GENERIC_ERROR:
1910                 DebugMessage(DEBUG_DECODE, "(Generic Error)\n\t");
1911                 break;
1912             default:
1913                 DebugMessage(DEBUG_DECODE, "(Unknown)\n\t");
1914                 break;
1915         }
1916 #endif
1917 
1918 #ifdef DEBUG_MSGS
1919         if (ntohs(tag.length) > 0)
1920         {
1921             char *buf;
1922             int i;
1923 
1924             switch (ntohs(tag.type))
1925             {
1926                 case PPPoE_TAG_SERVICE_NAME:
1927                 case PPPoE_TAG_AC_NAME:
1928                 case PPPoE_TAG_SERVICE_NAME_ERROR:
1929                 case PPPoE_TAG_AC_SYSTEM_ERROR:
1930                 case PPPoE_TAG_GENERIC_ERROR: * ascii data *
1931                     buf = (char *)SnortAlloc(ntohs(tag.length) + 1);
1932                     strlcpy(buf, (char *)(ppppoe_tag+1), ntohs(tag.length));
1933                     DebugMessage(DEBUG_DECODE, "data (UTF-8): %s\n", buf);
1934                     free(buf);
1935                     break;
1936 
1937                 case PPPoE_TAG_HOST_UNIQ:
1938                 case PPPoE_TAG_AC_COOKIE:
1939                 case PPPoE_TAG_RELAY_SESSION_ID:
1940                     DebugMessage(DEBUG_DECODE, "data (bin): ");
1941                     for (i = 0; i < ntohs(tag.length); i++)
1942                         DebugMessage(DEBUG_DECODE,
1943                                 "%02x", *(((unsigned char *)ppppoe_tag) +
1944                                     sizeof(PPPoE_Tag) + i));
1945                     DebugMessage(DEBUG_DECODE, "\n");
1946                     break;
1947 
1948                 default:
1949                     DebugMessage(DEBUG_DECODE, "unrecognized data\n");
1950                     break;
1951             }
1952         }
1953 #endif
1954 
1955         ppppoe_tag = (PPPoE_Tag *)((char *)(ppppoe_tag+1)+ntohs(tag.length));
1956     }
1957 
1958 #endif   /* #if 0 */
1959 
1960     return;
1961 }
1962 
1963 /*
1964  * Function: DecodePppPktEncapsulated(Packet *, const uint32_t len, uint8_t*)
1965  *
1966  * Purpose: Decode PPP traffic (RFC1661 framing).
1967  *
1968  * Arguments: p => pointer to decoded packet struct
1969  *            len => length of data to process
1970  *            pkt => pointer to the real live packet data
1971  *
1972  * Returns: void function
1973  */
DecodePppPktEncapsulated(const uint8_t * pkt,const uint32_t len,Packet * p)1974 void DecodePppPktEncapsulated(const uint8_t* pkt, const uint32_t len, Packet* p)
1975 {
1976     static int had_vj = 0;
1977     uint16_t protocol;
1978     uint32_t hlen = 1; /* HEADER - try 1 then 2 */
1979 
1980     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "PPP Packet!\n"););
1981 
1982 #ifdef WORDS_MUSTALIGN
1983     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet with PPP header.  "
1984                             "PPP is only 1 or 2 bytes and will throw off "
1985                             "alignment on this architecture when decoding IP, "
1986                             "causing a bus error - stop decoding packet.\n"););
1987 
1988     p->data = pkt;
1989     p->dsize = (uint16_t)len;
1990     return;
1991 #endif  /* WORDS_MUSTALIGN */
1992 
1993 #ifdef GRE
1994     if (p->greh != NULL)
1995         pc.gre_ppp++;
1996 #endif  /* GRE */
1997 
1998     /* do a little validation:
1999      *
2000      */
2001     if(len < 2)
2002     {
2003         if (ScLogVerbose())
2004         {
2005             ErrorMessage("Length not big enough for even a single "
2006                          "header or a one byte payload\n");
2007         }
2008         return;
2009     }
2010 
2011 
2012     if(pkt[0] & 0x01)
2013     {
2014         /* Check for protocol compression rfc1661 section 5
2015          *
2016          */
2017         hlen = 1;
2018         protocol = pkt[0];
2019     }
2020     else
2021     {
2022         protocol = ntohs(*((uint16_t *)pkt));
2023         hlen = 2;
2024     }
2025 
2026     /*
2027      * We only handle uncompressed packets. Handling VJ compression would mean
2028      * to implement a PPP state machine.
2029      */
2030     switch (protocol)
2031     {
2032         case PPP_VJ_COMP:
2033             if (!had_vj)
2034                 ErrorMessage("PPP link seems to use VJ compression, "
2035                         "cannot handle compressed packets!\n");
2036             had_vj = 1;
2037             break;
2038         case PPP_VJ_UCOMP:
2039             /* VJ compression modifies the protocol field. It must be set
2040              * to tcp (only TCP packets can be VJ compressed) */
2041             if(len < (hlen + IP_HEADER_LEN))
2042             {
2043                 if (ScLogVerbose())
2044                     ErrorMessage("PPP VJ min packet length > captured len! "
2045                                  "(%d bytes)\n", len);
2046                 return;
2047             }
2048 
2049             ((IPHdr *)(pkt + hlen))->ip_proto = IPPROTO_TCP;
2050             /* fall through */
2051 
2052         case PPP_IP:
2053             PushLayer(PROTO_PPP_ENCAP, p, pkt, hlen);
2054             DecodeIP(pkt + hlen, len - hlen, p);
2055             break;
2056 
2057         case PPP_IPV6:
2058             PushLayer(PROTO_PPP_ENCAP, p, pkt, hlen);
2059             DecodeIPV6(pkt + hlen, len - hlen, p);
2060             break;
2061 
2062 #ifndef NO_NON_ETHER_DECODER
2063         case PPP_IPX:
2064             PushLayer(PROTO_PPP_ENCAP, p, pkt, hlen);
2065             DecodeIPX(pkt + hlen, len - hlen, p);
2066             break;
2067 #endif
2068     }
2069 }
2070 
2071 //--------------------------------------------------------------------
2072 // decode.c::Raw packets
2073 //--------------------------------------------------------------------
2074 
2075 /*
2076  * Function: DecodeRawPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
2077  *
2078  * Purpose: Decodes packets coming in raw on layer 2, like PPP.  Coded and
2079  *          in by Jed Pickle (thanks Jed!) and modified for a few little tweaks
2080  *          by me.
2081  *
2082  * Arguments: p => pointer to decoded packet struct
2083  *            pkthdr => ptr to the packet header
2084  *            pkt => pointer to the real live packet data
2085  *
2086  * Returns: void function
2087  */
DecodeRawPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)2088 void DecodeRawPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
2089 {
2090     PROFILE_VARS;
2091 
2092     PREPROC_PROFILE_START(decodePerfStats);
2093 
2094     pc.total_processed++;
2095 
2096     memset(p, 0, PKT_ZERO_LEN);
2097 
2098     p->pkth = pkthdr;
2099     p->pkt = pkt;
2100 
2101     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Raw IP4 Packet!\n"););
2102 
2103     DecodeIP(pkt, p->pkth->caplen, p);
2104 
2105     PREPROC_PROFILE_END(decodePerfStats);
2106     return;
2107 }
2108 
2109 // raw packets are predetermined to be ip4 (above) or ip6 (below) by the DLT
2110 
DecodeRawPkt6(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)2111 void DecodeRawPkt6(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
2112 {
2113     PROFILE_VARS;
2114     PREPROC_PROFILE_START(decodePerfStats);
2115 
2116     pc.total_processed++;
2117     memset(p, 0, PKT_ZERO_LEN);
2118 
2119     p->pkth = pkthdr;
2120     p->pkt = pkt;
2121 
2122     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Raw IP6 Packet!\n"););
2123 
2124     DecodeIPV6(pkt, p->pkth->caplen, p);
2125 
2126     PREPROC_PROFILE_END(decodePerfStats);
2127     return;
2128 }
2129 
2130 //--------------------------------------------------------------------
2131 // decode.c::IP4 misc
2132 //--------------------------------------------------------------------
2133 
2134 /*
2135  * Some IP Header tests
2136  * Land Attack(same src/dst ip)
2137  * Loopback (src or dst in 127/8 block)
2138  * Modified: 2/22/05-man for High Endian Architecture.
2139  */
2140 #define IP4_THIS_NET  0x00  // msb
2141 #define IP4_MULTICAST 0x0E  // ms nibble
2142 #define IP4_RESERVED  0x0F  // ms nibble
2143 #define IP4_LOOPBACK  0x7F  // msb
2144 #define IP4_BROADCAST 0xffffffff
2145 
IP4AddrTests(Packet * p)2146 void IP4AddrTests (Packet* p)
2147 {
2148     uint8_t msb_src, msb_dst;
2149 
2150 #if !defined(SFLINUX) && defined(DAQ_CAPA_VRF)
2151     uint16_t sAsId;
2152     uint16_t dAsId;
2153 
2154     sAsId = DAQ_GetSourceAddressSpaceID(p->pkth);
2155     dAsId = DAQ_GetDestinationAddressSpaceID(p->pkth);
2156 
2157     // check all 32 bits ...
2158     if((p->iph->ip_src.s_addr == p->iph->ip_dst.s_addr)
2159             && (sAsId == dAsId))
2160     {
2161         DecoderEvent(p, DECODE_BAD_TRAFFIC_SAME_SRCDST,
2162                      DECODE_BAD_TRAFFIC_SAME_SRCDST_STR, 1, 1);
2163         if( pkt_trace_enabled )
2164         {
2165             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
2166                         "Packet is blocked since same source and destination"));
2167         }
2168     }
2169 #else
2170     if(p->iph->ip_src.s_addr == p->iph->ip_dst.s_addr)
2171     {
2172         DecoderEvent(p, DECODE_BAD_TRAFFIC_SAME_SRCDST,
2173                      DECODE_BAD_TRAFFIC_SAME_SRCDST_STR, 1, 1);
2174     }
2175 #endif
2176 
2177     // check all 32 bits ...
2178     if ( Event_Enabled(DECODE_IP4_SRC_BROADCAST ) )
2179         if ( p->iph->ip_src.s_addr == IP4_BROADCAST  )
2180             DecoderEvent(p, EVARGS(IP4_SRC_BROADCAST), 1, 1);
2181 
2182     if ( Event_Enabled(DECODE_IP4_DST_BROADCAST ) )
2183         if ( p->iph->ip_dst.s_addr == IP4_BROADCAST  )
2184             DecoderEvent(p, EVARGS(IP4_DST_BROADCAST), 1, 1);
2185 
2186     /* Loopback traffic  - don't use htonl for speed reasons -
2187      * s_addr is always in network order */
2188 #ifdef WORDS_BIGENDIAN
2189     msb_src = (p->iph->ip_src.s_addr >> 24);
2190     msb_dst = (p->iph->ip_dst.s_addr >> 24);
2191 #else
2192     msb_src = (uint8_t)(p->iph->ip_src.s_addr & 0xff);
2193     msb_dst = (uint8_t)(p->iph->ip_dst.s_addr & 0xff);
2194 #endif
2195     // check the msb ...
2196     if ( msb_src == IP4_LOOPBACK || msb_dst == IP4_LOOPBACK )
2197     {
2198         DecoderEvent(p, DECODE_BAD_TRAFFIC_LOOPBACK,
2199                         DECODE_BAD_TRAFFIC_LOOPBACK_STR, 1, 1);
2200     }
2201     // check the msb ...
2202     if ( Event_Enabled(DECODE_IP4_SRC_THIS_NET ) )
2203         if ( msb_src == IP4_THIS_NET  )
2204             DecoderEvent(p, EVARGS(IP4_SRC_THIS_NET), 1, 1);
2205 
2206     if ( Event_Enabled(DECODE_IP4_DST_THIS_NET ) )
2207         if ( msb_dst == IP4_THIS_NET  )
2208             DecoderEvent(p, EVARGS(IP4_DST_THIS_NET), 1, 1);
2209 
2210     // check the 'msn' (most significant nibble) ...
2211     msb_src >>= 4;
2212     msb_dst >>= 4;
2213 
2214     if ( Event_Enabled(DECODE_IP4_SRC_MULTICAST) )
2215         if ( msb_src == IP4_MULTICAST )
2216             DecoderEvent(p, EVARGS(IP4_SRC_MULTICAST), 1, 1);
2217 
2218     if ( Event_Enabled(DECODE_IP4_SRC_RESERVED) )
2219     {
2220         if ( msb_src == IP4_RESERVED ||
2221              IpAddrSetContains(MulticastReservedIp, GET_SRC_ADDR(p)) )
2222         {
2223             DecoderEvent(p, EVARGS(IP4_SRC_RESERVED), 1, 1);
2224         }
2225     }
2226 
2227     if ( Event_Enabled(DECODE_IP4_DST_RESERVED) )
2228     {
2229         if ( msb_dst == IP4_RESERVED ||
2230              IpAddrSetContains(MulticastReservedIp, GET_DST_ADDR(p)) )
2231         {
2232             DecoderEvent(p, EVARGS(IP4_DST_RESERVED), 1, 1);
2233         }
2234     }
2235 }
2236 
ICMP4AddrTests(Packet * p)2237 static inline void ICMP4AddrTests (Packet* p)
2238 {
2239     uint8_t msb_dst;
2240 
2241     uint32_t dst = sfaddr_get_ip4_value(GET_DST_IP(p));
2242 
2243     // check all 32 bits; all set so byte order is irrelevant ...
2244     if ( Event_Enabled(DECODE_ICMP4_DST_BROADCAST ) )
2245         if ( dst == IP4_BROADCAST  )
2246             DecoderEvent(p, EVARGS(ICMP4_DST_BROADCAST), 1, 1);
2247 
2248     /* - don't use htonl for speed reasons -
2249      * s_addr is always in network order */
2250 #ifdef WORDS_BIGENDIAN
2251     msb_dst = (uint8_t)(dst >> 24);
2252 #else
2253     msb_dst = (uint8_t)(dst & 0xff);
2254 #endif
2255 
2256     // check the 'msn' (most significant nibble) ...
2257     msb_dst >>= 4;
2258 
2259     if ( Event_Enabled(DECODE_ICMP4_DST_MULTICAST) )
2260         if ( msb_dst == IP4_MULTICAST )
2261             DecoderEvent(p, EVARGS(ICMP4_DST_MULTICAST), 1, 1);
2262 }
2263 
ICMP4MiscTests(Packet * p)2264 static inline void ICMP4MiscTests (Packet *p)
2265 {
2266     if ( Event_Enabled(DECODE_ICMP_PING_NMAP) )
2267     {
2268         if ((p->dsize == 0) &&
2269             (p->icmph->type == ICMP_ECHO))
2270             DecoderEvent(p, EVARGS(ICMP_PING_NMAP), 1, 1);
2271     }
2272 
2273     if ( Event_Enabled(DECODE_ICMP_ICMPENUM) )
2274     {
2275         if ((p->dsize == 0) &&
2276             (p->icmph->s_icmp_seq == 666))
2277             DecoderEvent(p, EVARGS(ICMP_ICMPENUM), 1, 1);
2278     }
2279 
2280     if ( Event_Enabled(DECODE_ICMP_REDIRECT_HOST) )
2281     {
2282         if ((p->icmph->code == 1) &&
2283             (p->icmph->type == ICMP_REDIRECT))
2284             DecoderEvent(p, EVARGS(ICMP_REDIRECT_HOST), 1, 1);
2285     }
2286 
2287     if ( Event_Enabled(DECODE_ICMP_REDIRECT_NET) )
2288     {
2289         if ((p->icmph->type == ICMP_REDIRECT) &&
2290             (p->icmph->code == 0))
2291             DecoderEvent(p, EVARGS(ICMP_REDIRECT_NET), 1, 1);
2292     }
2293 
2294     if ( Event_Enabled(DECODE_ICMP_TRACEROUTE_IPOPTS) )
2295     {
2296         if (p->icmph->type == ICMP_ECHOREPLY)
2297         {
2298             int i;
2299             for (i = 0; i < p->ip_option_count; i++)
2300             {
2301                 if (p->ip_options[i].code == IPOPT_RR)
2302                     DecoderEvent(p, EVARGS(ICMP_TRACEROUTE_IPOPTS), 1, 1);
2303             }
2304         }
2305     }
2306 
2307     if ( Event_Enabled(DECODE_ICMP_SOURCE_QUENCH) )
2308     {
2309         if ((p->icmph->type == ICMP_SOURCE_QUENCH) &&
2310             (p->icmph->code == 0))
2311             DecoderEvent(p, DECODE_ICMP_SOURCE_QUENCH,
2312                          DECODE_ICMP_SOURCE_QUENCH_STR, 1, 1);
2313     }
2314 
2315     if ( Event_Enabled(DECODE_ICMP_BROADSCAN_SMURF_SCANNER) )
2316     {
2317         if ((p->dsize == 4) &&
2318             (p->icmph->type == ICMP_ECHO) &&
2319             (p->icmph->s_icmp_seq == 0) &&
2320             (p->icmph->code == 0))
2321             DecoderEvent(p, EVARGS(ICMP_BROADSCAN_SMURF_SCANNER), 1, 1);
2322     }
2323 
2324     if ( Event_Enabled(DECODE_ICMP_DST_UNREACH_ADMIN_PROHIBITED) )
2325     {
2326         if ((p->icmph->type == ICMP_DEST_UNREACH) &&
2327             (p->icmph->code == 13))
2328             DecoderEvent(p, EVARGS(ICMP_DST_UNREACH_ADMIN_PROHIBITED), 1, 1);
2329     }
2330 
2331     if ( Event_Enabled(DECODE_ICMP_DST_UNREACH_DST_HOST_PROHIBITED) )
2332     {
2333         if ((p->icmph->type == ICMP_DEST_UNREACH) &&
2334             (p->icmph->code == 10))
2335             DecoderEvent(p, EVARGS(ICMP_DST_UNREACH_DST_HOST_PROHIBITED), 1, 1);
2336     }
2337 
2338     if ( Event_Enabled(DECODE_ICMP_DST_UNREACH_DST_NET_PROHIBITED) )
2339     {
2340         if ((p->icmph->type == ICMP_DEST_UNREACH) &&
2341             (p->icmph->code == 9))
2342             DecoderEvent(p, EVARGS(ICMP_DST_UNREACH_DST_NET_PROHIBITED), 1, 1);
2343     }
2344 
2345 }
2346 
2347 /* IPv4-layer decoder rules */
IPMiscTests(Packet * p)2348 static inline void IPMiscTests(Packet *p)
2349 {
2350     if ( Event_Enabled(DECODE_ICMP_DOS_ATTEMPT) )
2351     {
2352         /* Yes, it's an ICMP-related vuln in IP options. */
2353         uint8_t i, length, pointer;
2354 
2355         /* Alert on IP packets with either 0x07 (Record Route) or 0x44 (Timestamp)
2356            options that are specially crafted. */
2357         for (i = 0; i < p->ip_option_count; i++)
2358         {
2359             if (p->ip_options[i].data == NULL)
2360                 continue;
2361 
2362             if (p->ip_options[i].code == IPOPT_RR)
2363             {
2364                 length = p->ip_options[i].len;
2365                 if (length < 1)
2366                     continue;
2367 
2368                 pointer = p->ip_options[i].data[0];
2369 
2370                 /* If the pointer goes past the end of the data, then the data
2371                    is full. That's okay. */
2372                 if (pointer >= length + 2)
2373                     continue;
2374                 /* If the remaining space in the option isn't a multiple of 4
2375                    bytes, alert. */
2376                 if (((length + 3) - pointer) % 4)
2377                     DecoderEvent(p, EVARGS(ICMP_DOS_ATTEMPT), 1, 1);
2378             }
2379             else if (p->ip_options[i].code == IPOPT_TS)
2380             {
2381                 length = p->ip_options[i].len;
2382                 if (length < 2)
2383                     continue;
2384 
2385                 pointer = p->ip_options[i].data[0];
2386 
2387                 /* If the pointer goes past the end of the data, then the data
2388                    is full. That's okay. */
2389                 if (pointer >= length + 2)
2390                     continue;
2391                 /* If the remaining space in the option isn't a multiple of 4
2392                    bytes, alert. */
2393                 if (((length + 3) - pointer) % 4)
2394                     DecoderEvent(p, EVARGS(ICMP_DOS_ATTEMPT), 1, 1);
2395                 /* If there is a timestamp + address, we need a multiple of 8
2396                    bytes instead. */
2397                 if ((p->ip_options[i].data[1] & 0x01) && /* address flag */
2398                    (((length + 3) - pointer) % 8))
2399                     DecoderEvent(p, EVARGS(ICMP_DOS_ATTEMPT), 1, 1);
2400             }
2401         }
2402     }
2403     if ( Event_Enabled(DECODE_IP_OPTION_SET) )
2404     {
2405         if (p->ip_option_count > 0)
2406             DecoderEvent(p, EVARGS(IP_OPTION_SET), 1, 1);
2407     }
2408 
2409     if ( Event_Enabled(DECODE_IP_RESERVED_FRAG_BIT) )
2410     {
2411         if (p->rf)
2412             DecoderEvent(p, EVARGS(IP_RESERVED_FRAG_BIT), 1, 1);
2413     }
2414 }
2415 
2416 //--------------------------------------------------------------------
2417 // decode.c::IP4 vulnerabilities
2418 //--------------------------------------------------------------------
2419 
2420 /* This PGM NAK function started off as an SO rule, sid 8351. */
pgm_nak_detect(const uint8_t * data,uint16_t length)2421 static inline int pgm_nak_detect (const uint8_t *data, uint16_t length) {
2422     uint16_t data_left;
2423     uint16_t  checksum;
2424     const PGM_HEADER *header;
2425 
2426     if (NULL == data) {
2427         return PGM_NAK_ERR;
2428     }
2429 
2430     /* request must be bigger than 44 bytes to cause vuln */
2431     if (length <= sizeof(PGM_HEADER) || (length % 4) != 0) {
2432         return PGM_NAK_ERR;
2433     }
2434 
2435     header = (PGM_HEADER *) data;
2436 
2437     if (8 != header->type) {
2438         return PGM_NAK_ERR;
2439     }
2440 
2441     if (2 != header->nak.opt.type) {
2442         return PGM_NAK_ERR;
2443     }
2444 
2445 
2446     /*
2447      * alert if the amount of data after the options is more than the length
2448      * specified.
2449      */
2450 
2451 
2452     data_left = length - 36;
2453     if (data_left > header->nak.opt.len) {
2454 
2455         /* checksum is expensive... do that only if the length is bad */
2456         if (header->checksum != 0) {
2457             checksum = in_chksum_ip((const unsigned short*)data, (int)length);
2458             if (checksum != 0)
2459                 return PGM_NAK_ERR;
2460         }
2461 
2462         return PGM_NAK_VULN;
2463     }
2464 
2465     return PGM_NAK_OK;
2466 }
2467 
CheckPGMVuln(Packet * p)2468 static inline void CheckPGMVuln(Packet *p)
2469 {
2470     if ( pgm_nak_detect(p->data, p->dsize) == PGM_NAK_VULN )
2471         DecoderEvent(p, EVARGS(PGM_NAK_OVERFLOW), 1, 1);
2472 }
2473 
2474 /* This function is a port of an old .so rule, sid 3:8092. */
CheckIGMPVuln(Packet * p)2475 static inline void CheckIGMPVuln(Packet *p)
2476 {
2477     int i, alert = 0;
2478 
2479     if (p->dsize >= 1 && p->data[0] == 0x11)
2480     {
2481         if (p->ip_options_data != NULL) {
2482             if (p->ip_options_len >= 2) {
2483                 if (*(p->ip_options_data) == 0 && *(p->ip_options_data+1) == 0)
2484                 {
2485                     DecoderEvent(p, EVARGS(IGMP_OPTIONS_DOS), 1, 1);
2486                     return;
2487                 }
2488             }
2489         }
2490 
2491         for(i=0; i< (int) p->ip_option_count; i++) {
2492             /* All IGMPv2 packets contain IP option code 148 (router alert).
2493                This vulnerability only applies to IGMPv3, so return early. */
2494             if (p->ip_options[i].code == 148) {
2495                 return; /* No alert. */
2496             }
2497 
2498             if (p->ip_options[i].len == 1) {
2499                 alert++;
2500             }
2501         }
2502 
2503         if (alert > 0)
2504             DecoderEvent(p, EVARGS(IGMP_OPTIONS_DOS), 1, 1);
2505     }
2506 }
2507 
2508 //--------------------------------------------------------------------
2509 // decode.c::IP4 decoder
2510 //--------------------------------------------------------------------
2511 
2512 /* Function: DecodeIPv4Proto
2513  *
2514  * Gernalized IPv4 next protocol decoder dispatching.
2515  *
2516  * Arguments: proto => IPPROTO value of the next protocol
2517  *            pkt => ptr to the packet data
2518  *            len => length from here to the end of the packet
2519  *            p   => pointer to the packet decode struct
2520  *
2521  */
DecodeIPv4Proto(const uint8_t proto,const uint8_t * pkt,const uint32_t len,Packet * p)2522 static inline void DecodeIPv4Proto(const uint8_t proto,
2523     const uint8_t *pkt, const uint32_t len, Packet *p)
2524 {
2525     switch(proto)
2526     {
2527         case IPPROTO_TCP:
2528             pc.tcp++;
2529             DecodeTCP(pkt, len, p);
2530             return;
2531 
2532         case IPPROTO_UDP:
2533             pc.udp++;
2534             DecodeUDP(pkt, len, p);
2535             return;
2536 
2537         case IPPROTO_ICMP:
2538             pc.icmp++;
2539             DecodeICMP(pkt, len, p);
2540             return;
2541 
2542 #ifdef MPLS_RFC4023_SUPPORT
2543         case IPPROTO_MPLS: /*MPLS IN IP (protocol number 137 */
2544             DecodeMPLS(pkt, len, p);
2545             return;
2546 #endif
2547 
2548 #ifdef GRE
2549         case IPPROTO_IPV6:
2550             if (len < 40)
2551             {
2552                 /* Insufficient size for IPv6 Header. */
2553                 /* This could be an attempt to exploit Linux kernel
2554                  * vulnerability, so log an alert */
2555                 DecoderEvent(p, DECODE_IPV6_TUNNELED_IPV4_TRUNCATED,
2556                             DECODE_IPV6_TUNNELED_IPV4_TRUNCATED_STR,
2557                             1, 1);
2558             }
2559             pc.ip4ip6++;
2560             if ( ScTunnelBypassEnabled(TUNNEL_6IN4) )
2561                 Active_SetTunnelBypass();
2562             DecodeIPV6(pkt, len, p);
2563             return;
2564 
2565         case IPPROTO_GRE:
2566             pc.gre++;
2567             DecodeGRE(pkt, len, p);
2568             return;
2569 
2570         case IPPROTO_IPIP:
2571             pc.ip4ip4++;
2572             if ( ScTunnelBypassEnabled(TUNNEL_4IN4) )
2573                 Active_SetTunnelBypass();
2574             p->IPnIPencapsulated = 1;
2575             DecodeIP(pkt, len, p);
2576             return;
2577 #endif
2578 
2579         case IPPROTO_ESP:
2580             if (ScESPDecoding())
2581                 DecodeESP(pkt, len, p);
2582             return;
2583 
2584         case IPPROTO_AH:
2585             DecodeAH(pkt, len, p);
2586             return;
2587 
2588         case IPPROTO_SWIPE:
2589         case IPPROTO_IP_MOBILITY:
2590         case IPPROTO_SUN_ND:
2591         case IPPROTO_PIM:
2592             if ( Event_Enabled(DECODE_IP_BAD_PROTO) )
2593                 DecoderEvent(p, EVARGS(IP_BAD_PROTO), 1, 1);
2594             pc.other++;
2595             p->data = pkt;
2596             p->dsize = (uint16_t)len;
2597             return;
2598 
2599         case IPPROTO_PGM:
2600             pc.other++;
2601             p->data = pkt;
2602             p->dsize = (uint16_t)len;
2603 
2604             if ( Event_Enabled(DECODE_PGM_NAK_OVERFLOW) )
2605                 CheckPGMVuln(p);
2606             return;
2607 
2608         case IPPROTO_IGMP:
2609             pc.other++;
2610             p->data = pkt;
2611             p->dsize = (uint16_t)len;
2612 
2613             if ( Event_Enabled(DECODE_IGMP_OPTIONS_DOS) )
2614                 CheckIGMPVuln(p);
2615             return;
2616 
2617         default:
2618             if ( Event_Enabled(DECODE_IP_UNASSIGNED_PROTO) )
2619             {
2620                 if (GET_IPH_PROTO(p) >= MIN_UNASSIGNED_IP_PROTO)
2621                     DecoderEvent(p, EVARGS(IP_UNASSIGNED_PROTO), 1, 1);
2622             }
2623             pc.other++;
2624             p->data = pkt;
2625             p->dsize = (uint16_t)len;
2626             return;
2627     }
2628 }
2629 
2630 /*
2631  * Function: DecodeIP(uint8_t *, const uint32_t, Packet *)
2632  *
2633  * Purpose: Decode the IP network layer
2634  *
2635  * Arguments: pkt => ptr to the packet data
2636  *            len => length from here to the end of the packet
2637  *            p   => pointer to the packet decode struct
2638  *
2639  * Returns: void function
2640  */
DecodeIP(const uint8_t * pkt,const uint32_t len,Packet * p)2641 void DecodeIP(const uint8_t * pkt, const uint32_t len, Packet * p)
2642 {
2643     uint32_t ip_len; /* length from the start of the ip hdr to the pkt end */
2644     uint32_t hlen;   /* ip header length */
2645 
2646     pc.ip++;
2647 
2648 #ifdef GRE
2649     if (p->greh != NULL)
2650         pc.gre_ip++;
2651 #endif
2652 
2653     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
2654 
2655     /* do a little validation */
2656     if(len < IP_HEADER_LEN)
2657     {
2658         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
2659             "WARNING: Truncated IP4 header (%d bytes).\n", len););
2660 
2661         if ( Event_Enabled(DECODE_IP4_HDR_TRUNC) && ((p->packet_flags & PKT_UNSURE_ENCAP) == 0))
2662             DecoderEvent(p, EVARGS(IP4_HDR_TRUNC), 1, 1);
2663 
2664         p->iph = NULL;
2665         p->family = NO_IP;
2666 
2667         pc.discards++;
2668         pc.ipdisc++;
2669         return;
2670     }
2671 
2672     if (p->family != NO_IP)
2673     {
2674         if (p->encapsulated)
2675         {
2676             DecoderAlertEncapsulated(p, DECODE_IP_MULTIPLE_ENCAPSULATION,
2677                 DECODE_IP_MULTIPLE_ENCAPSULATION_STR, pkt, len);
2678 
2679             return;
2680         }
2681         else
2682         {
2683             p->encapsulated = 1;
2684             p->outer_iph = p->iph;
2685             p->outer_ip_data = p->ip_data;
2686             p->outer_ip_dsize = p->ip_dsize;
2687         }
2688     }
2689 
2690     /* lay the IP struct over the raw data */
2691     p->inner_iph = p->iph = (IPHdr *)pkt;
2692 
2693     /*
2694      * with datalink DLT_RAW it's impossible to differ ARP datagrams from IP.
2695      * So we are just ignoring non IP datagrams
2696      */
2697     if(IP_VER((IPHdr*)pkt) != 4)
2698     {
2699         if ((p->packet_flags & PKT_UNSURE_ENCAP) == 0)
2700             DecoderEvent(p, DECODE_NOT_IPV4_DGRAM,
2701                             DECODE_NOT_IPV4_DGRAM_STR, 1, 1);
2702 
2703         p->iph = NULL;
2704         p->family = NO_IP;
2705 
2706         pc.discards++;
2707         pc.ipdisc++;
2708         return;
2709     }
2710 
2711     sfiph_build(p, p->iph, AF_INET);
2712 
2713     /* get the IP datagram length */
2714     ip_len = ntohs(p->iph->ip_len);
2715 
2716     /* get the IP header length */
2717     hlen = IP_HLEN(p->iph) << 2;
2718 
2719     /* header length sanity check */
2720     if(hlen < IP_HEADER_LEN)
2721     {
2722         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
2723             "Bogus IP header length of %i bytes\n", hlen););
2724 
2725         DecoderEvent(p, DECODE_IPV4_INVALID_HEADER_LEN,
2726                         DECODE_IPV4_INVALID_HEADER_LEN_STR, 1, 1);
2727 
2728         p->iph = NULL;
2729         p->family = NO_IP;
2730 
2731         pc.discards++;
2732         pc.ipdisc++;
2733         return;
2734     }
2735 
2736     if (ip_len > len)
2737     {
2738         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
2739             "IP Len field is %d bytes bigger than captured length.\n"
2740             "    (ip.len: %lu, cap.len: %lu)\n",
2741             ip_len - len, ip_len, len););
2742 
2743         DecoderEventDrop(p, DECODE_IPV4_DGRAM_GT_CAPLEN,
2744                             DECODE_IPV4_DGRAM_GT_CAPLEN_STR,
2745                             ScDecoderOversizedAlerts(),
2746                             ScDecoderOversizedDrops());
2747 
2748         p->iph = NULL;
2749         p->family = NO_IP;
2750 
2751         pc.discards++;
2752         pc.ipdisc++;
2753         return;
2754     }
2755 #if 0
2756     // There is no need to alert when (ip_len < len).
2757     // Libpcap will capture more bytes than are part of the IP payload.
2758     // These could be Ethernet trailers, ESP trailers, etc.
2759     // This code is left in, commented, to keep us from re-writing it later.
2760     else if (ip_len < len)
2761     {
2762         if (ScLogVerbose())
2763             ErrorMessage("IP Len field is %d bytes "
2764                     "smaller than captured length.\n"
2765                     "    (ip.len: %lu, cap.len: %lu)\n",
2766                     len - ip_len, ip_len, len);
2767     }
2768 #endif
2769 
2770     if(ip_len < hlen)
2771     {
2772         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
2773             "IP dgm len (%d bytes) < IP hdr "
2774             "len (%d bytes), packet discarded\n", ip_len, hlen););
2775 
2776         DecoderEvent(p, DECODE_IPV4_DGRAM_LT_IPHDR,
2777                         DECODE_IPV4_DGRAM_LT_IPHDR_STR, 1, 1);
2778 
2779         p->iph = NULL;
2780         p->family = NO_IP;
2781 
2782         pc.discards++;
2783         pc.ipdisc++;
2784         return;
2785     }
2786 
2787     /*
2788      * IP Header tests: Land attack, and Loop back test
2789      */
2790     if(ScIdsMode())
2791     {
2792         IP4AddrTests(p);
2793     }
2794 
2795 
2796 #ifdef HAVE_DAQ_DECRYPTED_SSL
2797     if (!(p->pkth->flags & DAQ_PKT_FLAG_DECRYPTED_SSL) && ScIpChecksums())
2798 #else
2799     if (ScIpChecksums())
2800 #endif
2801     {
2802 #if defined(DAQ_VERSION) && DAQ_VERSION > 12
2803         if ((((const uint8_t *)p->inner_iph - p->pkt) > p->pkth->checksum_offset) ||
2804                    p->pkth->checksum_error_flag)
2805 #endif
2806         {
2807             /* routers drop packets with bad IP checksums, we don't really
2808              * need to check them (should make this a command line/config
2809              * option
2810              */
2811            int16_t csum = in_chksum_ip((const unsigned short *)p->iph, hlen);
2812 
2813            if(csum)
2814            {
2815                 p->error_flags |= PKT_ERR_CKSUM_IP;
2816                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Bad IP checksum\n"););
2817 #ifdef REG_TEST
2818                 if (getRegTestFlags() & REG_TEST_FLAG_STREAM_DECODE)
2819                     printf("Bad IP checksum | ");
2820 #endif
2821 
2822                 if ( ScIdsMode() )
2823                     queueExecDrop(execIpChksmDrop, p);
2824            }
2825 #ifdef DEBUG_MSGS
2826            else
2827            {
2828                 DebugMessage(DEBUG_DECODE, "IP Checksum: OK\n");
2829            }
2830 #endif /* DEBUG */
2831         }
2832     }
2833 
2834     PushLayer(PROTO_IP4, p, pkt, hlen);
2835 
2836     /* test for IP options */
2837     p->ip_options_len = (uint16_t)(hlen - IP_HEADER_LEN);
2838 
2839     if(p->ip_options_len > 0)
2840     {
2841         p->ip_options_data = pkt + IP_HEADER_LEN;
2842         DecodeIPOptions((pkt + IP_HEADER_LEN), p->ip_options_len, p);
2843     }
2844     else
2845     {
2846 #ifdef GRE
2847         /* If delivery header for GRE encapsulated packet is IP and it
2848          * had options, the packet's ip options will be refering to this
2849          * outer IP's options
2850          * Zero these options so they aren't associated with this inner IP
2851          * since p->iph will be pointing to this inner IP
2852          */
2853         if (p->encapsulated)
2854         {
2855             p->ip_options_data = NULL;
2856             p->ip_options_len = 0;
2857         }
2858 #endif
2859         p->ip_option_count = 0;
2860     }
2861 
2862     /* set the real IP length for logging */
2863     p->actual_ip_len = (uint16_t) ip_len;
2864 
2865     /* set the remaining packet length */
2866     ip_len -= hlen;
2867 
2868     /* check for fragmented packets */
2869     p->frag_offset = ntohs(p->iph->ip_off);
2870 
2871     /*
2872      * get the values of the reserved, more
2873      * fragments and don't fragment flags
2874      */
2875     p->rf = (uint8_t)((p->frag_offset & 0x8000) >> 15);
2876     p->df = (uint8_t)((p->frag_offset & 0x4000) >> 14);
2877     p->mf = (uint8_t)((p->frag_offset & 0x2000) >> 13);
2878 
2879     /* mask off the high bits in the fragment offset field */
2880     p->frag_offset &= 0x1FFF;
2881 
2882     if ( Event_Enabled(DECODE_IP4_DF_OFFSET) )
2883         if ( p->df && p->frag_offset )
2884             DecoderEvent(p, EVARGS(IP4_DF_OFFSET), 1, 1);
2885 
2886     if ( Event_Enabled(DECODE_IP4_LEN_OFFSET) )
2887         if ( p->frag_offset + p->actual_ip_len > IP_MAXPACKET )
2888             DecoderEvent(p, EVARGS(IP4_LEN_OFFSET), 1, 1);
2889 
2890     if(p->frag_offset || p->mf)
2891     {
2892         if ( !ip_len && Event_Enabled(DECODE_ZERO_LENGTH_FRAG) )
2893         {
2894             DecoderEvent(p, DECODE_ZERO_LENGTH_FRAG,
2895                 DECODE_ZERO_LENGTH_FRAG_STR, 1, 1);
2896             p->frag_flag = 0;
2897         }
2898         else
2899         {
2900             /* set the packet fragment flag */
2901             p->frag_flag = 1;
2902             p->ip_frag_start = pkt + hlen;
2903             p->ip_frag_len = (uint16_t)ip_len;
2904             pc.frags++;
2905         }
2906     }
2907     else
2908     {
2909         p->frag_flag = 0;
2910     }
2911 
2912     if(Event_Enabled(DECODE_BAD_FRAGBITS))
2913     {
2914 
2915         if( p->mf && p->df )
2916         {
2917             DecoderEvent(p, DECODE_BAD_FRAGBITS,
2918                             DECODE_BAD_FRAGBITS_STR, 1, 1);
2919         }
2920     }
2921 
2922     /* Set some convienience pointers */
2923     p->ip_data = pkt + hlen;
2924     p->ip_dsize = (u_short) ip_len;
2925 
2926     if (ScIdsMode())
2927     {
2928         /* See if there are any ip_proto only rules that match */
2929         fpEvalIpProtoOnlyRules(snort_conf->ip_proto_only_lists, p);
2930         p->proto_bits |= PROTO_BIT__IP;
2931     }
2932 
2933     IPMiscTests(p);
2934 
2935     /* if this packet isn't a fragment
2936      * or if it is, its a UDP packet and offset is 0 */
2937     if(!(p->frag_flag) ||
2938             (p->frag_flag && (p->frag_offset == 0) &&
2939             (p->iph->ip_proto == IPPROTO_UDP)))
2940     {
2941         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "IP header length: %lu\n",
2942                     (unsigned long)hlen););
2943 
2944         DecodeIPv4Proto(p->iph->ip_proto, pkt+hlen, ip_len, p);
2945     }
2946     else
2947     {
2948         /* set the payload pointer and payload size */
2949         p->data = pkt + hlen;
2950         p->dsize = (u_short) ip_len;
2951     }
2952 }
2953 
2954 //--------------------------------------------------------------------
2955 // decode.c::ICMP
2956 //--------------------------------------------------------------------
2957 
2958 /*
2959  * Function: DecodeICMP(uint8_t *, const uint32_t, Packet *)
2960  *
2961  * Purpose: Decode the ICMP transport layer
2962  *
2963  * Arguments: pkt => ptr to the packet data
2964  *            len => length from here to the end of the packet
2965  *            p   => pointer to the decoded packet struct
2966  *
2967  * Returns: void function
2968  */
DecodeICMP(const uint8_t * pkt,const uint32_t len,Packet * p)2969 void DecodeICMP(const uint8_t * pkt, const uint32_t len, Packet * p)
2970 {
2971     if(len < ICMP_HEADER_LEN)
2972     {
2973         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
2974             "WARNING: Truncated ICMP4 header (%d bytes).\n", len););
2975 
2976         if ( Event_Enabled(DECODE_ICMP4_HDR_TRUNC) )
2977             DecoderEvent(p, EVARGS(ICMP4_HDR_TRUNC), 1, 1);
2978 
2979         p->icmph = NULL;
2980         pc.discards++;
2981         pc.icmpdisc++;
2982 
2983         return;
2984     }
2985 
2986     /* set the header ptr first */
2987     p->icmph = (ICMPHdr *) pkt;
2988 
2989     switch (p->icmph->type)
2990     {
2991             // fall through ...
2992         case ICMP_SOURCE_QUENCH:
2993         case ICMP_DEST_UNREACH:
2994         case ICMP_REDIRECT:
2995         case ICMP_TIME_EXCEEDED:
2996         case ICMP_PARAMETERPROB:
2997         case ICMP_ECHOREPLY:
2998         case ICMP_ECHO:
2999         case ICMP_ROUTER_ADVERTISE:
3000         case ICMP_ROUTER_SOLICIT:
3001         case ICMP_INFO_REQUEST:
3002         case ICMP_INFO_REPLY:
3003             if (len < 8)
3004             {
3005                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
3006                     "Truncated ICMP header(%d bytes)\n", len););
3007 
3008                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ICMPHDR,
3009                                 DECODE_ICMP_DGRAM_LT_ICMPHDR_STR, 1, 1);
3010 
3011                 p->icmph = NULL;
3012                 pc.discards++;
3013                 pc.icmpdisc++;
3014 
3015                 return;
3016             }
3017             break;
3018 
3019         case ICMP_TIMESTAMP:
3020         case ICMP_TIMESTAMPREPLY:
3021             if (len < 20)
3022             {
3023                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
3024                     "Truncated ICMP header(%d bytes)\n", len););
3025 
3026                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_TIMESTAMPHDR,
3027                                 DECODE_ICMP_DGRAM_LT_TIMESTAMPHDR_STR, 1, 1);
3028 
3029                 p->icmph = NULL;
3030                 pc.discards++;
3031                 pc.icmpdisc++;
3032 
3033                 return;
3034             }
3035             break;
3036 
3037         case ICMP_ADDRESS:
3038         case ICMP_ADDRESSREPLY:
3039             if (len < 12)
3040             {
3041                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
3042                     "Truncated ICMP header(%d bytes)\n", len););
3043 
3044 
3045                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ADDRHDR,
3046                                 DECODE_ICMP_DGRAM_LT_ADDRHDR_STR, 1, 1);
3047 
3048                 p->icmph = NULL;
3049                 pc.discards++;
3050                 pc.icmpdisc++;
3051 
3052                 return;
3053             }
3054             break;
3055 
3056         default:
3057             if ( Event_Enabled(DECODE_ICMP4_TYPE_OTHER) )
3058                 DecoderEvent(p, EVARGS(ICMP4_TYPE_OTHER), 1, 1);
3059             break;
3060     }
3061 
3062 
3063     if (ScIcmpChecksums())
3064     {
3065         uint16_t csum = in_chksum_icmp((uint16_t *)p->icmph, len);
3066 
3067         if(csum)
3068         {
3069             p->error_flags |= PKT_ERR_CKSUM_ICMP;
3070             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Bad ICMP Checksum\n"););
3071 
3072             if ( ScIdsMode() )
3073                 queueExecDrop(execIcmpChksmDrop, p);
3074         }
3075         else
3076         {
3077             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,"ICMP Checksum: OK\n"););
3078         }
3079     }
3080 
3081     p->dsize = (u_short)(len - ICMP_HEADER_LEN);
3082     p->data = pkt + ICMP_HEADER_LEN;
3083 
3084     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "ICMP type: %d   code: %d\n",
3085                 p->icmph->type, p->icmph->code););
3086 
3087     switch(p->icmph->type)
3088     {
3089         case ICMP_ECHO:
3090             ICMP4AddrTests(p);
3091         // fall through ...
3092 
3093         case ICMP_ECHOREPLY:
3094             /* setup the pkt id and seq numbers */
3095             p->dsize -= sizeof(struct idseq);   /* add the size of the
3096                                                  * echo ext to the data
3097                                                  * ptr and subtract it
3098                                                  * from the data size */
3099             p->data += sizeof(struct idseq);
3100             PushLayer(PROTO_ICMP4, p, pkt, ICMP_NORMAL_LEN);
3101             break;
3102 
3103         case ICMP_DEST_UNREACH:
3104             if ((p->icmph->code == ICMP_FRAG_NEEDED)
3105                     && (ntohs(p->icmph->s_icmp_nextmtu) < 576))
3106             {
3107                 if ( Event_Enabled(DECODE_ICMP_PATH_MTU_DOS) )
3108                     DecoderEvent(p, EVARGS(ICMP_PATH_MTU_DOS), 1, 1);
3109             }
3110 
3111             /* Fall through */
3112 
3113         case ICMP_SOURCE_QUENCH:
3114         case ICMP_REDIRECT:
3115         case ICMP_TIME_EXCEEDED:
3116         case ICMP_PARAMETERPROB:
3117             /* account for extra 4 bytes in header */
3118             p->dsize -= 4;
3119             p->data += 4;
3120 
3121             PushLayer(PROTO_ICMP4, p, pkt, ICMP_NORMAL_LEN);
3122             DecodeICMPEmbeddedIP(p->data, p->dsize, p);
3123             break;
3124 
3125         default:
3126             PushLayer(PROTO_ICMP4, p, pkt, ICMP_HEADER_LEN);
3127             break;
3128     }
3129 
3130     /* Run a bunch of ICMP decoder rules */
3131     ICMP4MiscTests(p);
3132 
3133     p->proto_bits |= PROTO_BIT__ICMP;
3134     p->proto_bits &= ~(PROTO_BIT__UDP | PROTO_BIT__TCP);
3135 }
3136 
3137 /*
3138  * Function: DecodeICMPEmbeddedIP(uint8_t *, const uint32_t, Packet *)
3139  *
3140  * Purpose: Decode the ICMP embedded IP header + 64 bits payload
3141  *
3142  * Arguments: pkt => ptr to the packet data
3143  *            len => length from here to the end of the packet
3144  *            p   => pointer to dummy packet decode struct
3145  *
3146  * Returns: void function
3147  */
DecodeICMPEmbeddedIP(const uint8_t * pkt,const uint32_t len,Packet * p)3148 void DecodeICMPEmbeddedIP(const uint8_t *pkt, const uint32_t len, Packet *p)
3149 {
3150     uint32_t ip_len;       /* length from the start of the ip hdr to the
3151                              * pkt end */
3152     uint32_t hlen;             /* ip header length */
3153     uint16_t orig_frag_offset;
3154 
3155     /* do a little validation */
3156     if(len < IP_HEADER_LEN)
3157     {
3158         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
3159             "ICMP: IP short header (%d bytes)\n", len););
3160 
3161         DecoderEvent(p, DECODE_ICMP_ORIG_IP_TRUNCATED,
3162                         DECODE_ICMP_ORIG_IP_TRUNCATED_STR, 1, 1);
3163 
3164         p->orig_family = NO_IP;
3165         p->orig_iph = NULL;
3166         return;
3167     }
3168 
3169     /* lay the IP struct over the raw data */
3170     sfiph_orig_build(p, pkt, AF_INET);
3171     p->orig_iph = (IPHdr *) pkt;
3172 
3173     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "DecodeICMPEmbeddedIP: ip header"
3174                     " starts at: %p, length is %lu\n", p->orig_iph,
3175                     (unsigned long) len););
3176     /*
3177      * with datalink DLT_RAW it's impossible to differ ARP datagrams from IP.
3178      * So we are just ignoring non IP datagrams
3179      */
3180     if((GET_ORIG_IPH_VER(p) != 4) && !IS_IP6(p))
3181     {
3182         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
3183             "ICMP: not IPv4 datagram ([ver: 0x%x][len: 0x%x])\n",
3184             GET_ORIG_IPH_VER(p), GET_ORIG_IPH_LEN(p)););
3185 
3186         DecoderEvent(p, DECODE_ICMP_ORIG_IP_VER_MISMATCH,
3187                         DECODE_ICMP_ORIG_IP_VER_MISMATCH_STR, 1, 1);
3188 
3189         p->orig_family = NO_IP;
3190         p->orig_iph = NULL;
3191         return;
3192     }
3193 
3194     /* set the IP datagram length */
3195     ip_len = ntohs(GET_ORIG_IPH_LEN(p));
3196 
3197     /* set the IP header length */
3198     hlen = (p->orig_ip4h->ip_verhl & 0x0f) << 2;
3199 
3200     if(len < hlen)
3201     {
3202         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
3203             "ICMP: IP len (%d bytes) < IP hdr len (%d bytes), packet discarded\n",
3204             ip_len, hlen););
3205 
3206         DecoderEvent(p, DECODE_ICMP_ORIG_DGRAM_LT_ORIG_IP,
3207                         DECODE_ICMP_ORIG_DGRAM_LT_ORIG_IP_STR, 1, 1);
3208 
3209         p->orig_family = NO_IP;
3210         p->orig_iph = NULL;
3211         return;
3212     }
3213 
3214     /* set the remaining packet length */
3215     ip_len = len - hlen;
3216 
3217     orig_frag_offset = ntohs(GET_ORIG_IPH_OFF(p));
3218     orig_frag_offset &= 0x1FFF;
3219 
3220     if (orig_frag_offset == 0)
3221     {
3222         /* Original IP payload should be 64 bits */
3223         if (ip_len < 8)
3224         {
3225             DecoderEvent(p, DECODE_ICMP_ORIG_PAYLOAD_LT_64,
3226                             DECODE_ICMP_ORIG_PAYLOAD_LT_64_STR, 1, 1);
3227 
3228             return;
3229         }
3230         /* ICMP error packets could contain as much of original payload
3231          * as possible, but not exceed 576 bytes
3232          */
3233         else if (ntohs(GET_IPH_LEN(p)) > 576)
3234         {
3235             DecoderEvent(p, DECODE_ICMP_ORIG_PAYLOAD_GT_576,
3236                             DECODE_ICMP_ORIG_PAYLOAD_GT_576_STR, 1, 1);
3237         }
3238     }
3239     else
3240     {
3241         /* RFC states that only first frag will get an ICMP response */
3242         DecoderEvent(p, DECODE_ICMP_ORIG_IP_WITH_FRAGOFFSET,
3243                         DECODE_ICMP_ORIG_IP_WITH_FRAGOFFSET_STR, 1, 1);
3244         return;
3245     }
3246 
3247     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "ICMP Unreachable IP header length: "
3248                             "%lu\n", (unsigned long)hlen););
3249 
3250     switch(GET_ORIG_IPH_PROTO(p))
3251     {
3252         case IPPROTO_TCP: /* decode the interesting part of the header */
3253             p->orig_tcph = (TCPHdr *)(pkt + hlen);
3254 
3255             /* stuff more data into the printout data struct */
3256             p->orig_sp = ntohs(p->orig_tcph->th_sport);
3257             p->orig_dp = ntohs(p->orig_tcph->th_dport);
3258 
3259             break;
3260 
3261         case IPPROTO_UDP:
3262             p->orig_udph = (UDPHdr *)(pkt + hlen);
3263 
3264             /* fill in the printout data structs */
3265             p->orig_sp = ntohs(p->orig_udph->uh_sport);
3266             p->orig_dp = ntohs(p->orig_udph->uh_dport);
3267 
3268             break;
3269 
3270         case IPPROTO_ICMP:
3271             p->orig_icmph = (ICMPHdr *)(pkt + hlen);
3272             break;
3273     }
3274 
3275     return;
3276 }
3277 
3278 /*
3279  * Function: DecodeIPV6(uint8_t *, uint32_t)
3280  *
3281  * Purpose: Decoding IPv6 headers
3282  *
3283  * Arguments: pkt => ptr to the packet data
3284  *            len => length from here to the end of the packet
3285  *
3286  * Returns: void function
3287  */
3288 
3289 //--------------------------------------------------------------------
3290 // decode.c::IP6 misc
3291 //--------------------------------------------------------------------
3292 
3293 #define IP6_MULTICAST  0xFF  // first/most significant octet
3294 #define IP6_MULTICAST_SCOPE_RESERVED    0x00
3295 #define IP6_MULTICAST_SCOPE_INTERFACE   0x01
3296 #define IP6_MULTICAST_SCOPE_LINK        0x02
3297 #define IP6_MULTICAST_SCOPE_ADMIN       0x04
3298 #define IP6_MULTICAST_SCOPE_SITE        0x05
3299 #define IP6_MULTICAST_SCOPE_ORG         0x08
3300 #define IP6_MULTICAST_SCOPE_GLOBAL      0x0E
3301 
3302 /* Check for multiple IPv6 Multicast-related alerts */
CheckIPV6Multicast(Packet * p)3303 static void CheckIPV6Multicast(Packet *p)
3304 {
3305     IP6RawHdr* hdr6 = (IP6RawHdr*)p->iph;
3306     uint8_t multicast_scope;
3307     struct in6_addr* ip_dst;
3308     uint32_t h_ip_dst;
3309 
3310     if ( hdr6->ip6_src.s6_addr[0] == IP6_MULTICAST )
3311     {
3312         DecoderEvent(p, DECODE_IPV6_SRC_MULTICAST,
3313                      DECODE_IPV6_SRC_MULTICAST_STR, 1, 1);
3314     }
3315     ip_dst = &hdr6->ip6_dst;
3316     if ( ip_dst->s6_addr[0] != IP6_MULTICAST )
3317     {
3318         return;
3319     }
3320 
3321     multicast_scope = ip_dst->s6_addr[1] & 0x0F;
3322     switch (multicast_scope)
3323     {
3324         case IP6_MULTICAST_SCOPE_RESERVED:
3325         case IP6_MULTICAST_SCOPE_INTERFACE:
3326         case IP6_MULTICAST_SCOPE_LINK:
3327         case IP6_MULTICAST_SCOPE_ADMIN:
3328         case IP6_MULTICAST_SCOPE_SITE:
3329         case IP6_MULTICAST_SCOPE_ORG:
3330         case IP6_MULTICAST_SCOPE_GLOBAL:
3331             break;
3332 
3333         default:
3334             DecoderEvent(p, DECODE_IPV6_BAD_MULTICAST_SCOPE,
3335                          DECODE_IPV6_BAD_MULTICAST_SCOPE_STR, 1, 1);
3336     }
3337 
3338     /* Check against assigned multicast addresses. These are listed at:
3339        http://www.iana.org/assignments/ipv6-multicast-addresses/    */
3340 
3341     /* Multicast addresses only specify the first 16 and last 40 bits.
3342        Others should be zero. */
3343     if ((ip_dst->s6_addr16[1] != 0) ||
3344         (ip_dst->s6_addr32[1] != 0) ||
3345         (ip_dst->s6_addr16[4] != 0) ||
3346         (ip_dst->s6_addr[10] != 0))
3347     {
3348         DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3349                      DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3350         return;
3351     }
3352 
3353     if (ip_dst->s6_addr[1] == IP6_MULTICAST_SCOPE_INTERFACE)
3354     {
3355         // Node-local scope
3356         if ((ip_dst->s6_addr16[1] != 0) ||
3357             (ip_dst->s6_addr32[1] != 0) ||
3358             (ip_dst->s6_addr32[2] != 0) ||
3359             (ip_dst->s6_addr16[6] != 0))
3360         {
3361 
3362             DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3363                          DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3364         }
3365         else
3366         {
3367             switch (ntohl(ip_dst->s6_addr32[3]))
3368             {
3369                 case 0x00000001: // All Nodes
3370                 case 0x00000002: // All Routers
3371                 case 0x000000FB: // mDNSv6
3372                     break;
3373                 default:
3374                     DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3375                                  DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3376             }
3377         }
3378     }
3379     else if (ip_dst->s6_addr[1] == IP6_MULTICAST_SCOPE_LINK)
3380     {
3381         // Link-local scope
3382         switch (ntohl(ip_dst->s6_addr32[3]))
3383         {
3384             case 0x00000001: // All Nodes
3385             case 0x00000002: // All Routers
3386             case 0x00000004: // DVMRP Routers
3387             case 0x00000005: // OSPFIGP
3388             case 0x00000006: // OSPFIGP Designated Routers
3389             case 0x00000007: // ST Routers
3390             case 0x00000008: // ST Hosts
3391             case 0x00000009: // RIP Routers
3392             case 0x0000000A: // EIGRP Routers
3393             case 0x0000000B: // Mobile-Agents
3394             case 0x0000000C: // SSDP
3395             case 0x0000000D: // All PIMP Routers
3396             case 0x0000000E: // RSVP-ENCAPSULATION
3397             case 0x0000000F: // UPnP
3398             case 0x00000012: // VRRP
3399             case 0x00000016: // All MLDv2-capable routers
3400             case 0x0000006A: // All-Snoopers
3401             case 0x0000006B: // PTP-pdelay
3402             case 0x0000006C: // Saratoga
3403             case 0x0000006D: // LL-MANET-Routers
3404             case 0x0000006E: // IGRS
3405             case 0x0000006F: // iADT Discovery
3406             case 0x000000FB: // mDNSv6
3407             case 0x00010001: // Link Name
3408             case 0x00010002: // All-dhcp-agents
3409             case 0x00010003: // Link-local Multicast Name Resolution
3410             case 0x00010004: // DTCP Announcement
3411                 break;
3412             default:
3413                 if ((ip_dst->s6_addr[11] == 1) &&
3414                     (ip_dst->s6_addr[12] == 0xFF))
3415                 {
3416                     break; // Solicited-Node Address
3417                 }
3418                 if ((ip_dst->s6_addr[11] == 2) &&
3419                     (ip_dst->s6_addr[12] == 0xFF))
3420                 {
3421                     break; // Node Information Queries
3422                 }
3423                 DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3424                              DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3425         }
3426     }
3427     else if (ip_dst->s6_addr[1] == IP6_MULTICAST_SCOPE_SITE)
3428     {
3429         // Site-local scope
3430         switch (ntohl(ip_dst->s6_addr32[3]))
3431         {
3432             case 0x00000002: // All Routers
3433             case 0x000000FB: // mDNSv6
3434             case 0x00010003: // All-dhcp-servers
3435             case 0x00010004: // Deprecated
3436             case 0x00010005: // SL-MANET-ROUTERS
3437                 break;
3438             default:
3439                 DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3440                              DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3441         }
3442     }
3443     else if ((ip_dst->s6_addr[1] & 0xF0) == 0)
3444     {
3445         h_ip_dst = ntohl(ip_dst->s6_addr32[3]);
3446 
3447         // Variable scope
3448         switch (h_ip_dst)
3449         {
3450             case 0x0000000C: // SSDP
3451             case 0x000000FB: // mDNSv6
3452             case 0x00000181: // PTP-primary
3453             case 0x00000182: // PTP-alternate1
3454             case 0x00000183: // PTP-alternate2
3455             case 0x00000184: // PTP-alternate3
3456             case 0x0000018C: // All ACs multicast address
3457             case 0x00000201: // "rwho" Group (BSD)
3458             case 0x00000202: // SUN RPC PMAPPROC_CALLIT
3459             case 0x00000204: // All C1222 Nodes
3460             case 0x00000300: // Mbus/IPv6
3461             case 0x00027FFE: // SAPv1 Announcements
3462             case 0x00027FFF: // SAPv0 Announcements
3463                 break;
3464             default:
3465                 if ((h_ip_dst >= 0x00000100) &&
3466                     (h_ip_dst <= 0x00000136))
3467                 {
3468                     break; // Several addresses assigned in a contiguous block
3469                 }
3470 
3471                 if ((h_ip_dst >= 0x00000140) &&
3472                     (h_ip_dst <= 0x0000014F))
3473                 {
3474                     break; // EPSON-disc-set
3475                 }
3476 
3477                 if ((h_ip_dst >= 0x00020000) &&
3478                     (h_ip_dst <= 0x00027FFD))
3479                 {
3480                     break; // Multimedia Conference Calls
3481                 }
3482 
3483                 if ((h_ip_dst >= 0x00011000) &&
3484                     (h_ip_dst <= 0x000113FF))
3485                 {
3486                     break; // Service Location, Version 2
3487                 }
3488 
3489                 if ((h_ip_dst >= 0x00028000) &&
3490                     (h_ip_dst <= 0x0002FFFF))
3491                 {
3492                     break; // SAP Dynamic Assignments
3493                 }
3494 
3495                 DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3496                              DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3497         }
3498     }
3499     else if ((ip_dst->s6_addr[1] & 0xF0) == 0x30)
3500     {
3501         h_ip_dst = ntohl(ip_dst->s6_addr32[3]);
3502 
3503         // Source-Specific Multicast block
3504         if ((h_ip_dst >= 0x40000001) &&
3505             (h_ip_dst <= 0x7FFFFFFF))
3506         {
3507             return; // IETF consensus
3508         }
3509         else if ((h_ip_dst >= 0x80000000) &&
3510             (h_ip_dst <= 0xFFFFFFFF))
3511         {
3512             return; // Dynamiclly allocated by hosts when needed
3513         }
3514         else
3515         {
3516             // Other addresses in this block are reserved.
3517             DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3518                          DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3519         }
3520     }
3521     else
3522     {
3523         /* Addresses not listed above are reserved. */
3524         DecoderEvent(p, DECODE_IPV6_DST_RESERVED_MULTICAST,
3525                      DECODE_IPV6_DST_RESERVED_MULTICAST_STR, 1, 1);
3526     }
3527 }
3528 
3529 /* Teredo packets need to have one of their IPs use either the Teredo prefix,
3530    or a link-local prefix (in the case of Router Solicitation messages) */
CheckTeredoPrefix(IP6RawHdr * hdr)3531 static inline int CheckTeredoPrefix(IP6RawHdr *hdr)
3532 {
3533     /* Check if src address matches 2001::/32 */
3534     if ((hdr->ip6_src.s6_addr[0] == 0x20) &&
3535         (hdr->ip6_src.s6_addr[1] == 0x01) &&
3536         (hdr->ip6_src.s6_addr[2] == 0x00) &&
3537         (hdr->ip6_src.s6_addr[3] == 0x00))
3538         return 1;
3539 
3540     /* Check if src address matches fe80::/64 */
3541     if ((hdr->ip6_src.s6_addr[0] == 0xfe) &&
3542         (hdr->ip6_src.s6_addr[1] == 0x80) &&
3543         (hdr->ip6_src.s6_addr[2] == 0x00) &&
3544         (hdr->ip6_src.s6_addr[3] == 0x00) &&
3545         (hdr->ip6_src.s6_addr[4] == 0x00) &&
3546         (hdr->ip6_src.s6_addr[5] == 0x00) &&
3547         (hdr->ip6_src.s6_addr[6] == 0x00) &&
3548         (hdr->ip6_src.s6_addr[7] == 0x00))
3549         return 1;
3550 
3551     /* Check if dst address matches 2001::/32 */
3552     if ((hdr->ip6_dst.s6_addr[0] == 0x20) &&
3553         (hdr->ip6_dst.s6_addr[1] == 0x01) &&
3554         (hdr->ip6_dst.s6_addr[2] == 0x00) &&
3555         (hdr->ip6_dst.s6_addr[3] == 0x00))
3556         return 1;
3557 
3558     /* Check if dst address matches fe80::/64 */
3559     if ((hdr->ip6_dst.s6_addr[0] == 0xfe) &&
3560         (hdr->ip6_dst.s6_addr[1] == 0x80) &&
3561         (hdr->ip6_dst.s6_addr[2] == 0x00) &&
3562         (hdr->ip6_dst.s6_addr[3] == 0x00) &&
3563         (hdr->ip6_dst.s6_addr[4] == 0x00) &&
3564         (hdr->ip6_dst.s6_addr[5] == 0x00) &&
3565         (hdr->ip6_dst.s6_addr[6] == 0x00) &&
3566         (hdr->ip6_dst.s6_addr[7] == 0x00))
3567         return 1;
3568 
3569     /* No Teredo prefix found. */
3570     return 0;
3571 }
3572 
3573 /* Function: IPV6MiscTests(Packet *p)
3574  *
3575  * Purpose: A bunch of IPv6 decoder alerts
3576  *
3577  * Arguments: p => the Packet to check
3578  *
3579  * Returns: void function
3580  */
IPV6MiscTests(Packet * p)3581 static inline void IPV6MiscTests(Packet *p)
3582 {
3583     IP6RawHdr* hdr6 = (IP6RawHdr*)p->iph;
3584     /*
3585      * Some IP Header tests
3586      * Land Attack(same src/dst ip)
3587      * Loopback (src or dst in 127/8 block)
3588      * Modified: 2/22/05-man for High Endian Architecture.
3589      *
3590      * some points in the code assume an IP of 0.0.0.0 matches anything, but
3591      * that is not so here.  The sfip_compare makes that assumption for
3592      * compatibility, but sfip_contains does not.  Hence, sfip_contains
3593      * is used here in the interrim. */
3594 #if !defined(SFLINUX) && defined(DAQ_CAPA_VRF)
3595     uint16_t sAsId;
3596     uint16_t dAsId;
3597 
3598     sAsId = DAQ_GetSourceAddressSpaceID(p->pkth);
3599     dAsId = DAQ_GetDestinationAddressSpaceID(p->pkth);
3600 
3601     if( sfip_fast_eq6((sfaddr_t*)&hdr6->ip6_src.s6_addr, (sfaddr_t*)&hdr6->ip6_dst.s6_addr)
3602             && (sAsId == dAsId))
3603     {
3604         DecoderEvent(p, DECODE_BAD_TRAFFIC_SAME_SRCDST,
3605                      DECODE_BAD_TRAFFIC_SAME_SRCDST_STR,
3606                      1, 1);
3607         if( pkt_trace_enabled )
3608         {
3609             addPktTraceData(VERDICT_REASON_SNORT, snprintf(trace_line, MAX_TRACE_LINE,
3610                         "Packet is blocked since same source and destination"));
3611         }
3612     }
3613 #else
3614     if( sfip_fast_eq6((sfaddr_t*)&hdr6->ip6_src.s6_addr, (sfaddr_t*)&hdr6->ip6_dst.s6_addr))
3615     {
3616         DecoderEvent(p, DECODE_BAD_TRAFFIC_SAME_SRCDST,
3617                      DECODE_BAD_TRAFFIC_SAME_SRCDST_STR,
3618                      1, 1);
3619     }
3620 #endif
3621     if(sfip_is_loopback((sfaddr_t*)&hdr6->ip6_src.s6_addr) || sfip_is_loopback((sfaddr_t*)&hdr6->ip6_dst.s6_addr))
3622     {
3623         DecoderEvent(p, DECODE_BAD_TRAFFIC_LOOPBACK,
3624                      DECODE_BAD_TRAFFIC_LOOPBACK_STR,
3625                      1,1);
3626     }
3627 
3628     /* Other decoder alerts for IPv6 addresses
3629        Added: 5/24/10 (Snort 2.9.0) */
3630     if (!sfraw_is_set(&hdr6->ip6_dst))
3631     {
3632         DecoderEvent(p, DECODE_IPV6_DST_ZERO, DECODE_IPV6_DST_ZERO_STR, 1, 1);
3633     }
3634 
3635     CheckIPV6Multicast(p);
3636 
3637     if ( Event_Enabled(DECODE_IPV6_ISATAP_SPOOF) )
3638     {
3639         /* Only check for IPv6 over IPv4 */
3640         if (p->outer_iph && p->outer_iph->ip_proto == IPPROTO_IPV6)
3641         {
3642             uint32_t isatap_interface_id = ntohl(hdr6->ip6_src.s6_addr32[2]) & 0xFCFFFFFF;
3643 
3644             /* ISATAP uses address with prefix fe80:0000:0000:0000:0200:5efe or
3645                fe80:0000:0000:0000:0000:5efe, followed by the IPv4 address. */
3646             if (isatap_interface_id == 0x00005EFE)
3647             {
3648                 if (p->outer_iph->ip_src.s_addr != hdr6->ip6_src.s6_addr32[3])
3649                     DecoderEvent(p, EVARGS(IPV6_ISATAP_SPOOF), 1, 1);
3650             }
3651         }
3652     }
3653 }
3654 
3655 //--------------------------------------------------------------------
3656 // decode.c::IP6 extensions
3657 //--------------------------------------------------------------------
3658 
IPV6ExtensionOrder(uint8_t type)3659 static inline int IPV6ExtensionOrder(uint8_t type)
3660 {
3661     switch (type)
3662     {
3663         case IPPROTO_HOPOPTS:   return 1;
3664         case IPPROTO_DSTOPTS:   return 2;
3665         case IPPROTO_ROUTING:   return 3;
3666         case IPPROTO_FRAGMENT:  return 4;
3667         case IPPROTO_AH:        return 5;
3668         case IPPROTO_ESP:       return 6;
3669         default:                return 7;
3670     }
3671 }
3672 
3673 /* Check for out-of-order IPv6 Extension Headers */
CheckIPv6ExtensionOrder(Packet * p)3674 static inline void CheckIPv6ExtensionOrder(Packet *p)
3675 {
3676     int routing_seen = 0;
3677     int current_type_order, next_type_order, i;
3678 
3679     if (Event_Enabled(DECODE_IPV6_UNORDERED_EXTENSIONS))
3680     {
3681         if (p->ip6_extension_count > 0)
3682             current_type_order = IPV6ExtensionOrder(p->ip6_extensions[0].type);
3683 
3684         for (i = 1; i < (p->ip6_extension_count); i++)
3685         {
3686             next_type_order = IPV6ExtensionOrder(p->ip6_extensions[i].type);
3687 
3688             if (p->ip6_extensions[i].type == IPPROTO_ROUTING)
3689                 routing_seen = 1;
3690 
3691             if (next_type_order <= current_type_order)
3692             {
3693                 /* A second "Destination Options" header is allowed iff:
3694                    1) A routing header was already seen, and
3695                    2) The second destination header is the last one before the upper layer.
3696                 */
3697                 if (!routing_seen ||
3698                     !(p->ip6_extensions[i].type == IPPROTO_DSTOPTS) ||
3699                     !(i+1 == p->ip6_extension_count))
3700                 {
3701                     DecoderEvent(p, EVARGS(IPV6_UNORDERED_EXTENSIONS), 1, 1);
3702                 }
3703             }
3704 
3705             current_type_order = next_type_order;
3706         }
3707     }
3708 }
3709 
3710 void DecodeIPV6Extensions(uint8_t next, const uint8_t *pkt, uint32_t len, Packet *p);
3711 
CheckIPV6HopOptions(const uint8_t * pkt,uint32_t len,Packet * p)3712 static inline int CheckIPV6HopOptions(const uint8_t *pkt, uint32_t len, Packet *p)
3713 {
3714     IP6Extension *exthdr = (IP6Extension *)pkt;
3715     uint32_t total_octets = (exthdr->ip6e_len * 8) + 8;
3716     const uint8_t *hdr_end = pkt + total_octets;
3717     uint8_t type, oplen;
3718 
3719     if (len < total_octets)
3720     {
3721         DecoderEvent(p, EVARGS(IPV6_TRUNCATED_EXT), 1, 1);
3722         return -1;
3723     }
3724 
3725     /* Skip to the options */
3726     pkt += 2;
3727 
3728     /* Iterate through the options, check for bad ones */
3729     while (pkt < hdr_end)
3730     {
3731         type = *pkt;
3732         switch (type)
3733         {
3734             case IP6_OPT_PAD1:
3735                 pkt++;
3736                 break;
3737             case IP6_OPT_PADN:
3738             case IP6_OPT_JUMBO:
3739             case IP6_OPT_RTALERT:
3740             case IP6_OPT_TUNNEL_ENCAP:
3741             case IP6_OPT_QUICK_START:
3742             case IP6_OPT_CALIPSO:
3743             case IP6_OPT_HOME_ADDRESS:
3744             case IP6_OPT_ENDPOINT_IDENT:
3745                 pkt++;
3746                 if (pkt < hdr_end)
3747                 {
3748                     oplen = *pkt;
3749                     if ((pkt + oplen + 1) > hdr_end)
3750                     {
3751                         DecoderEvent(p, EVARGS(IPV6_BAD_OPT_LEN), 1, 1);
3752                         return -1;
3753                     }
3754                     pkt += oplen + 1;
3755                 }
3756                 break;
3757             default:
3758                 DecoderEvent(p, EVARGS(IPV6_BAD_OPT_TYPE), 1, 1);
3759                 return -1;
3760         }
3761     }
3762 
3763     return 0;
3764 }
3765 
DecodeIPV6Options(int type,const uint8_t * pkt,uint32_t len,Packet * p)3766 void DecodeIPV6Options(int type, const uint8_t *pkt, uint32_t len, Packet *p)
3767 {
3768     IP6Extension *exthdr;
3769     uint32_t hdrlen = 0;
3770 
3771     /* This should only be called by DecodeIPV6 or DecodeIPV6Extensions
3772      * so no validation performed.  Otherwise, uncomment the following: */
3773     /* if(IPH_IS_VALID(p)) return */
3774 
3775     pc.ipv6opts++;
3776 
3777     /* Need at least two bytes, one for next header, one for len. */
3778     /* But size is an integer multiple of 8 octets, so 8 is min.  */
3779     if(len < sizeof(IP6Extension))
3780     {
3781         DecoderEvent(p, DECODE_IPV6_TRUNCATED_EXT,
3782                      DECODE_IPV6_TRUNCATED_EXT_STR,
3783                      1, 1);
3784         return;
3785     }
3786 
3787     if ( p->ip6_extension_count >= ScMaxIP6Extensions() )
3788     {
3789         DecoderEvent(p, DECODE_IP6_EXCESS_EXT_HDR,
3790                      DECODE_IP6_EXCESS_EXT_HDR_STR,
3791                      1, 1);
3792         return;
3793     }
3794 
3795     exthdr = (IP6Extension *)pkt;
3796 
3797     p->ip6_extensions[p->ip6_extension_count].type = type;
3798     p->ip6_extensions[p->ip6_extension_count].data = pkt;
3799 
3800     // TBD add layers for other ip6 ext headers
3801     switch (type)
3802     {
3803         case IPPROTO_HOPOPTS:
3804             hdrlen = sizeof(IP6Extension) + (exthdr->ip6e_len << 3);
3805 
3806             if ( CheckIPV6HopOptions(pkt, len, p) == 0 )
3807                 PushLayer(PROTO_IP6_HOP_OPTS, p, pkt, hdrlen);
3808             break;
3809 
3810         case IPPROTO_DSTOPTS:
3811             if (exthdr->ip6e_nxt == IPPROTO_ROUTING)
3812             {
3813                 DecoderEvent(p, DECODE_IPV6_DSTOPTS_WITH_ROUTING,
3814                              DECODE_IPV6_DSTOPTS_WITH_ROUTING_STR,
3815                              1, 1);
3816             }
3817             hdrlen = sizeof(IP6Extension) + (exthdr->ip6e_len << 3);
3818 
3819             if ( CheckIPV6HopOptions(pkt, len, p) == 0 )
3820                 PushLayer(PROTO_IP6_DST_OPTS, p, pkt, hdrlen);
3821             break;
3822 
3823         case IPPROTO_ROUTING:
3824 
3825             /* Routing type 0 extension headers are evil creatures. */
3826             {
3827                 IP6Route *rte = (IP6Route *)exthdr;
3828 
3829                 if (rte->ip6rte_type == 0)
3830                 {
3831                     DecoderEvent(p, DECODE_IPV6_ROUTE_ZERO,
3832                          DECODE_IPV6_ROUTE_ZERO_STR, 1, 1);
3833                 }
3834             }
3835 
3836             if (exthdr->ip6e_nxt == IPPROTO_HOPOPTS)
3837             {
3838                 DecoderEvent(p, DECODE_IPV6_ROUTE_AND_HOPBYHOP,
3839                              DECODE_IPV6_ROUTE_AND_HOPBYHOP_STR,
3840                              1, 1);
3841             }
3842             if (exthdr->ip6e_nxt == IPPROTO_ROUTING)
3843             {
3844                 DecoderEvent(p, DECODE_IPV6_TWO_ROUTE_HEADERS,
3845                              DECODE_IPV6_TWO_ROUTE_HEADERS_STR,
3846                              1, 1);
3847             }
3848             hdrlen = sizeof(IP6Extension) + (exthdr->ip6e_len << 3);
3849             break;
3850 
3851         case IPPROTO_FRAGMENT:
3852             if (len == sizeof(IP6Frag))
3853             {
3854                 DecoderEvent(p, DECODE_ZERO_LENGTH_FRAG,
3855                     DECODE_ZERO_LENGTH_FRAG_STR, 1, 1);
3856                 return;
3857             }
3858             else
3859             {
3860                 IP6Frag *ip6frag_hdr = (IP6Frag *)pkt;
3861                 /* If this is an IP Fragment, set some data... */
3862                 p->ip6_frag_index = p->ip6_extension_count;
3863                 p->ip_frag_start = pkt + sizeof(IP6Frag);
3864 
3865                 p->df = 0;
3866                 p->rf = IP6F_RES(ip6frag_hdr);
3867                 p->mf = IP6F_MF(ip6frag_hdr);
3868                 p->frag_offset = IP6F_OFFSET(ip6frag_hdr);
3869 
3870                 if ( p->frag_offset || p->mf )
3871                 {
3872                     p->frag_flag = 1;
3873                     pc.frag6++;
3874                 }
3875                 else
3876                 {
3877                     DecoderEvent(p, DECODE_IPV6_BAD_FRAG_PKT,
3878                         DECODE_IPV6_BAD_FRAG_PKT_STR , 1, 1);
3879                 }
3880                 if (
3881                     !(p->frag_offset) &&
3882                     Event_Enabled(DECODE_IPV6_UNORDERED_EXTENSIONS) )
3883                 {
3884                     // check header ordering of fragged (next) header
3885                     if ( IPV6ExtensionOrder(ip6frag_hdr->ip6f_nxt) <
3886                          IPV6ExtensionOrder(IPPROTO_FRAGMENT) )
3887                         DecoderEvent(p, EVARGS(IPV6_UNORDERED_EXTENSIONS), 1, 1);
3888                 }
3889             }
3890             hdrlen = sizeof(IP6Frag);
3891             p->ip_frag_len = (uint16_t)(len - hdrlen);
3892 
3893             if ( p->frag_flag && ((p->frag_offset > 0) ||
3894                  (exthdr->ip6e_nxt != IPPROTO_UDP)) )
3895             {
3896                 //check header order up thru frag header
3897                 p->ip6_extension_count++;
3898                 CheckIPv6ExtensionOrder(p);
3899 
3900                 /* For non-zero offset frags, we stop decoding after the
3901                    Frag header. According to RFC 2460, the "Next Header"
3902                    value may differ from that of the offset zero frag,
3903                    but only the Next Header of the original frag is used. */
3904                 // check DecodeIP(); we handle frags the same way here
3905                 return;
3906             }
3907             break;
3908 
3909         case IPPROTO_AH:
3910             /* Auth Headers work in both IPv4 & IPv6, and their lengths are
3911                given in 4-octet increments instead of 8-octet increments. */
3912             hdrlen = sizeof(IP6Extension) + (exthdr->ip6e_len << 2);
3913 
3914             if (hdrlen <= len)
3915                 PushLayer(PROTO_AH, p, pkt, hdrlen);
3916             break;
3917 
3918         default:
3919             hdrlen = sizeof(IP6Extension) + (exthdr->ip6e_len << 3);
3920             break;
3921     }
3922 
3923     p->ip6_extension_count++;
3924 
3925     if(hdrlen > len)
3926     {
3927         DecoderEvent(p, DECODE_IPV6_TRUNCATED_EXT,
3928                      DECODE_IPV6_TRUNCATED_EXT_STR,
3929                      1, 1);
3930         return;
3931     }
3932 
3933     if ( hdrlen > 0 )
3934     {
3935         DecodeIPV6Extensions(*pkt, pkt + hdrlen, len - hdrlen, p);
3936     }
3937 #ifdef DEBUG_MSGS
3938     else
3939     {
3940         DebugMessage(DEBUG_DECODE, "WARNING - no next ip6 header decoded\n");
3941     }
3942 #endif
3943 }
3944 
DecodeIPV6Extensions(uint8_t next,const uint8_t * pkt,uint32_t len,Packet * p)3945 void DecodeIPV6Extensions(uint8_t next, const uint8_t *pkt, uint32_t len, Packet *p)
3946 {
3947     pc.ip6ext++;
3948 
3949 #ifdef GRE
3950     if (p->greh != NULL)
3951         pc.gre_ipv6ext++;
3952 #endif
3953 
3954     /* XXX might this introduce an issue if the "next" field is invalid? */
3955     p->ip6h->next = next;
3956 
3957     if (ScIdsMode())
3958     {
3959         /* See if there are any ip_proto only rules that match */
3960         fpEvalIpProtoOnlyRules(snort_conf->ip_proto_only_lists, p);
3961         p->proto_bits |= PROTO_BIT__IP;
3962     }
3963 
3964     switch(next) {
3965         case IPPROTO_TCP:
3966             pc.tcp6++;
3967             CheckIPv6ExtensionOrder(p);
3968             DecodeTCP(pkt, len, p);
3969             return;
3970         case IPPROTO_UDP:
3971             pc.udp6++;
3972             CheckIPv6ExtensionOrder(p);
3973             DecodeUDP(pkt, len, p);
3974             return;
3975         case IPPROTO_ICMPV6:
3976             pc.icmp6++;
3977             CheckIPv6ExtensionOrder(p);
3978             DecodeICMP6(pkt , len, p);
3979             return;
3980         case IPPROTO_NONE:
3981             CheckIPv6ExtensionOrder(p);
3982             p->dsize = 0;
3983             return;
3984         case IPPROTO_HOPOPTS:
3985         case IPPROTO_DSTOPTS:
3986         case IPPROTO_ROUTING:
3987         case IPPROTO_FRAGMENT:
3988         case IPPROTO_AH:
3989             DecodeIPV6Options(next, pkt, len, p);
3990             // Anything special to do here?  just return?
3991             return;
3992 #ifdef MPLS_RFC4023_SUPPORT
3993         case IPPROTO_MPLS:
3994             DecodeMPLS(pkt, len, p);
3995             return;
3996 #endif
3997 #ifdef GRE
3998         case IPPROTO_GRE:
3999             pc.gre++;
4000             CheckIPv6ExtensionOrder(p);
4001             DecodeGRE(pkt, len, p);
4002             return;
4003         case IPPROTO_IPIP:
4004             pc.ip6ip4++;
4005             if ( ScTunnelBypassEnabled(TUNNEL_4IN6) )
4006                 Active_SetTunnelBypass();
4007             CheckIPv6ExtensionOrder(p);
4008             p->IPnIPencapsulated = 1;
4009             DecodeIP(pkt, len, p);
4010             return;
4011         case IPPROTO_IPV6:
4012             pc.ip6ip6++;
4013             if ( ScTunnelBypassEnabled(TUNNEL_6IN6) )
4014                 Active_SetTunnelBypass();
4015             CheckIPv6ExtensionOrder(p);
4016             DecodeIPV6(pkt, len, p);
4017             return;
4018         case IPPROTO_ESP:
4019             CheckIPv6ExtensionOrder(p);
4020             if (ScESPDecoding())
4021                 DecodeESP(pkt, len, p);
4022             return;
4023 #endif
4024         default:
4025             CheckIPv6ExtensionOrder(p);
4026             // There may be valid headers after this unsupported one,
4027             // need to decode this header, set "next" and continue
4028             // looping.
4029 
4030             DecoderEvent(p, DECODE_IPV6_BAD_NEXT_HEADER,
4031                          DECODE_IPV6_BAD_NEXT_HEADER_STR, 1, 1);
4032 
4033             pc.other++;
4034             p->data = pkt;
4035             p->dsize = (uint16_t)len;
4036             break;
4037     };
4038 }
4039 
4040 //--------------------------------------------------------------------
4041 // decode.c::IP6 decoder
4042 //--------------------------------------------------------------------
4043 
DecodeIPV6(const uint8_t * pkt,uint32_t len,Packet * p)4044 void DecodeIPV6(const uint8_t *pkt, uint32_t len, Packet *p)
4045 {
4046     IP6RawHdr *hdr;
4047     uint32_t payload_len;
4048 
4049     pc.ipv6++;
4050 
4051 #ifdef GRE
4052     if (p->greh != NULL)
4053         pc.gre_ipv6++;
4054 #endif
4055 
4056     hdr = (IP6RawHdr*)pkt;
4057 
4058     if(len < IP6_HDR_LEN)
4059     {
4060         if ((p->packet_flags & PKT_UNSURE_ENCAP) == 0)
4061             DecoderEvent(p, DECODE_IPV6_TRUNCATED, DECODE_IPV6_TRUNCATED_STR,
4062                          1, 1);
4063 
4064         goto decodeipv6_fail;
4065     }
4066 
4067     /* Verify version in IP6 Header agrees */
4068     if(IPRAW_HDR_VER(hdr) != 6)
4069     {
4070         if ((p->packet_flags & PKT_UNSURE_ENCAP) == 0)
4071             DecoderEvent(p, DECODE_IPV6_IS_NOT, DECODE_IPV6_IS_NOT_STR,
4072                          1, 1);
4073 
4074         goto decodeipv6_fail;
4075     }
4076 
4077     if (p->family != NO_IP)
4078     {
4079         /* Snort currently supports only 2 IP layers. Any more will fail to be
4080            decoded. */
4081         if (p->encapsulated)
4082         {
4083 
4084             DecoderAlertEncapsulated(p, DECODE_IP_MULTIPLE_ENCAPSULATION,
4085                             DECODE_IP_MULTIPLE_ENCAPSULATION_STR,
4086                             pkt, len);
4087             goto decodeipv6_fail;
4088         }
4089         else
4090         {
4091             p->encapsulated = 1;
4092         }
4093     }
4094     payload_len = ntohs(hdr->ip6plen) + IP6_HDR_LEN;
4095 
4096     if(payload_len != len)
4097     {
4098         if (payload_len > len)
4099         {
4100             if ((p->packet_flags & PKT_UNSURE_ENCAP) == 0)
4101                 DecoderEvent(p, DECODE_IPV6_DGRAM_GT_CAPLEN,
4102                              DECODE_IPV6_DGRAM_GT_CAPLEN_STR,
4103                              ScDecoderOversizedAlerts(), ScDecoderOversizedDrops());
4104 
4105             goto decodeipv6_fail;
4106         }
4107     }
4108 
4109     /* Teredo packets should always use the 2001:0000::/32 prefix, or in some
4110        cases the link-local prefix fe80::/64.
4111        Source: RFC 4380, section 2.6 & section 5.2.1
4112 
4113        Checking the addresses will save us from numerous false positives
4114        when UDP clients use 3544 as their ephemeral port, or "Deep Teredo
4115        Inspection" is turned on.
4116 
4117        If we ever start decoding more than 2 layers of IP in a packet, this
4118        check against p->proto_bits will need to be refactored. */
4119     if ((p->proto_bits & PROTO_BIT__TEREDO) && (CheckTeredoPrefix(hdr) == 0))
4120     {
4121         goto decodeipv6_fail;
4122     }
4123     if (p->encapsulated)
4124     {
4125        p->outer_iph = p->iph;
4126        p->outer_ip_data = p->ip_data;
4127        p->outer_ip_dsize = p->ip_dsize;
4128     }
4129     /* lay the IP struct over the raw data */
4130     // this is ugly but necessary to keep the rest of the code happy
4131     p->inner_iph = p->iph = (IPHdr *)pkt;
4132 
4133     /* Build Packet structure's version of the IP6 header */
4134     sfiph_build(p, hdr, AF_INET6);
4135 
4136 #ifdef GRE
4137     /* Remove outer IP options */
4138     if (p->encapsulated)
4139     {
4140         p->ip_options_data = NULL;
4141         p->ip_options_len = 0;
4142     }
4143 #endif
4144     p->ip_option_count = 0;
4145 
4146     /* set the real IP length for logging */
4147     p->actual_ip_len = ntohs(p->ip6h->len);
4148     p->ip_data = pkt + IP6_HDR_LEN;
4149     p->ip_dsize = ntohs(p->ip6h->len);
4150 
4151     PushLayer(PROTO_IP6, p, pkt, sizeof(*hdr));
4152 
4153     IPV6MiscTests(p);
4154 
4155     DecodeIPV6Extensions(GET_IPH_PROTO(p), pkt + IP6_HDR_LEN, ntohs(p->ip6h->len), p);
4156     return;
4157 
4158 decodeipv6_fail:
4159     /* If this was Teredo, back up and treat the packet as normal UDP. */
4160     if (p->proto_bits & PROTO_BIT__TEREDO)
4161     {
4162         pc.ipv6--;
4163         pc.teredo--;
4164         p->proto_bits &= ~PROTO_BIT__TEREDO;
4165 #ifdef GRE
4166         if (p->greh != NULL)
4167             pc.gre_ipv6--;
4168 #endif
4169         if ( ScTunnelBypassEnabled(TUNNEL_TEREDO) )
4170             Active_ClearTunnelBypass();
4171         return;
4172     }
4173 
4174     pc.discards++;
4175     pc.ipv6disc++;
4176 }
4177 
4178 //--------------------------------------------------------------------
4179 // decode.c::ICMP6
4180 //--------------------------------------------------------------------
4181 
DecodeICMP6(const uint8_t * pkt,const uint32_t len,Packet * p)4182 void DecodeICMP6(const uint8_t *pkt, const uint32_t len, Packet *p)
4183 {
4184     if(len < ICMP6_MIN_HEADER_LEN)
4185     {
4186         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4187             "WARNING: Truncated ICMP6 header (%d bytes).\n", len););
4188 
4189         if ( Event_Enabled(DECODE_ICMP6_HDR_TRUNC) )
4190             DecoderEvent(p, EVARGS(ICMP6_HDR_TRUNC), 1, 1);
4191 
4192         pc.discards++;
4193         return;
4194     }
4195 
4196     p->icmp6h = (ICMP6Hdr*)pkt;
4197     p->icmph = (ICMPHdr*)pkt; /* This is needed for icmp rules */
4198 
4199     /* Do checksums */
4200     if (ScIcmpChecksums())
4201     {
4202         uint16_t csum;
4203 
4204         if(IS_IP4(p))
4205         {
4206             csum = in_chksum_icmp((uint16_t *)(p->icmp6h), len);
4207         }
4208         /* IPv6 traffic */
4209         else
4210         {
4211             IP6RawHdr* hdr6 = (IP6RawHdr*)p->iph;
4212             pseudoheader6 ph6;
4213             COPY4(ph6.sip, hdr6->ip6_src.s6_addr32);
4214             COPY4(ph6.dip, hdr6->ip6_dst.s6_addr32);
4215             ph6.zero = 0;
4216             ph6.protocol = GET_IPH_PROTO(p);
4217             ph6.len = htons((u_short)len);
4218 
4219             csum = in_chksum_icmp6(&ph6, (uint16_t *)(p->icmp6h), len);
4220         }
4221         if(csum)
4222         {
4223             p->error_flags |= PKT_ERR_CKSUM_ICMP;
4224             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Bad ICMP Checksum\n"););
4225 
4226             if ( ScIdsMode() )
4227                 queueExecDrop(execIcmpChksmDrop, p);
4228         }
4229         else
4230         {
4231             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,"ICMP Checksum: OK\n"););
4232         }
4233     }
4234 
4235     p->dsize = (u_short)(len - ICMP6_MIN_HEADER_LEN);
4236     p->data = pkt + ICMP6_MIN_HEADER_LEN;
4237 
4238     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "ICMP type: %d   code: %d\n",
4239                 p->icmp6h->type, p->icmp6h->code););
4240 
4241     switch(p->icmp6h->type)
4242     {
4243         case ICMP6_ECHO:
4244         case ICMP6_REPLY:
4245             if (p->dsize >= sizeof(struct idseq))
4246             {
4247                 IP6RawHdr* hdr6 = (IP6RawHdr*)p->iph;
4248 
4249                 /* Set data pointer to that of the "echo message" */
4250                 /* add the size of the echo ext to the data
4251                  * ptr and subtract it from the data size */
4252                 p->dsize -= sizeof(struct idseq);
4253                 p->data += sizeof(struct idseq);
4254 
4255                 if ( Event_Enabled(DECODE_ICMP6_DST_MULTICAST) )
4256                     if ( hdr6->ip6_dst.s6_addr[0] == IP6_MULTICAST )
4257                         DecoderEvent(p, EVARGS(ICMP6_DST_MULTICAST), 1, 1);
4258 
4259                 PushLayer(PROTO_ICMP6, p, pkt, ICMP_NORMAL_LEN);
4260             }
4261             else
4262             {
4263                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4264                     "WARNING: Truncated ICMP Echo header (%d bytes).\n", len););
4265 
4266                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ICMPHDR,
4267                                 DECODE_ICMP_DGRAM_LT_ICMPHDR_STR, 1, 1);
4268 
4269                 p->icmph = NULL;
4270                 p->icmp6h = NULL;
4271                 pc.discards++;
4272                 pc.icmpdisc++;
4273                 return;
4274             }
4275             break;
4276 
4277         case ICMP6_BIG:
4278             if (p->dsize >= sizeof(ICMP6TooBig))
4279             {
4280                 ICMP6TooBig *too_big = (ICMP6TooBig *)pkt;
4281                 /* Set data pointer past MTU */
4282                 p->data += 4;
4283                 p->dsize -= 4;
4284 
4285                 if (ntohl(too_big->mtu) < 1280)
4286                 {
4287                     DecoderEvent(p, DECODE_ICMPV6_TOO_BIG_BAD_MTU,
4288                                  DECODE_ICMPV6_TOO_BIG_BAD_MTU_STR, 1, 1);
4289                 }
4290 
4291                 PushLayer(PROTO_ICMP6, p, pkt, ICMP_NORMAL_LEN);
4292                 DecodeICMPEmbeddedIP6(p->data, p->dsize, p);
4293             }
4294             else
4295             {
4296                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4297                     "WARNING: Truncated ICMP header (%d bytes).\n", len););
4298 
4299                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ICMPHDR,
4300                                 DECODE_ICMP_DGRAM_LT_ICMPHDR_STR, 1, 1);
4301 
4302                 p->icmph = NULL;
4303                 p->icmp6h = NULL;
4304                 pc.discards++;
4305                 pc.icmpdisc++;
4306                 return;
4307             }
4308             break;
4309 
4310         case ICMP6_TIME:
4311         case ICMP6_PARAMS:
4312         case ICMP6_UNREACH:
4313             if (p->dsize >= 4)
4314             {
4315                 /* Set data pointer past the 'unused/mtu/pointer block */
4316                 p->data += 4;
4317                 p->dsize -= 4;
4318 
4319                 if (p->icmp6h->type == ICMP6_UNREACH)
4320                 {
4321                     if (p->icmp6h->code == 2)
4322                     {
4323                         DecoderEvent(p, DECODE_ICMPV6_UNREACHABLE_NON_RFC_2463_CODE,
4324                                 DECODE_ICMPV6_UNREACHABLE_NON_RFC_2463_CODE_STR, 1, 1);
4325                     }
4326                     else if (p->icmp6h->code > 6)
4327                     {
4328                         DecoderEvent(p, DECODE_ICMPV6_UNREACHABLE_NON_RFC_4443_CODE,
4329                                 DECODE_ICMPV6_UNREACHABLE_NON_RFC_4443_CODE_STR, 1, 1);
4330                     }
4331                 }
4332 
4333                 PushLayer(PROTO_ICMP6, p, pkt, ICMP_NORMAL_LEN);
4334                 DecodeICMPEmbeddedIP6(p->data, p->dsize, p);
4335             }
4336             else
4337             {
4338                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4339                     "WARNING: Truncated ICMP header (%d bytes).\n", len););
4340 
4341                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ICMPHDR,
4342                                 DECODE_ICMP_DGRAM_LT_ICMPHDR_STR, 1, 1);
4343 
4344                 p->icmph = NULL;
4345                 p->icmp6h = NULL;
4346                 pc.discards++;
4347                 pc.icmpdisc++;
4348                 return;
4349             }
4350             break;
4351 
4352         case ICMP6_ADVERTISEMENT:
4353             if (p->dsize >= (sizeof(ICMP6RouterAdvertisement) - ICMP6_MIN_HEADER_LEN))
4354             {
4355                 ICMP6RouterAdvertisement *ra = (ICMP6RouterAdvertisement *)pkt;
4356                 if (p->icmp6h->code != 0)
4357                 {
4358                     DecoderEvent(p, DECODE_ICMPV6_ADVERT_BAD_CODE,
4359                                  DECODE_ICMPV6_ADVERT_BAD_CODE_STR, 1, 1);
4360                 }
4361                 if (ntohl(ra->reachable_time) > 3600000)
4362                 {
4363                     DecoderEvent(p, DECODE_ICMPV6_ADVERT_BAD_REACHABLE,
4364                                  DECODE_ICMPV6_ADVERT_BAD_REACHABLE_STR, 1, 1);
4365                 }
4366                 PushLayer(PROTO_ICMP6, p, pkt, ICMP_HEADER_LEN);
4367             }
4368             else
4369             {
4370                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4371                     "WARNING: Truncated ICMP header (%d bytes).\n", len););
4372 
4373                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ICMPHDR,
4374                                 DECODE_ICMP_DGRAM_LT_ICMPHDR_STR, 1, 1);
4375 
4376                 p->icmph = NULL;
4377                 p->icmp6h = NULL;
4378                 pc.discards++;
4379                 pc.icmpdisc++;
4380                 return;
4381             }
4382             break;
4383 
4384         case ICMP6_SOLICITATION:
4385             if (p->dsize >= (sizeof(ICMP6RouterSolicitation) - ICMP6_MIN_HEADER_LEN))
4386             {
4387                 ICMP6RouterSolicitation *rs = (ICMP6RouterSolicitation *)pkt;
4388                 if (rs->code != 0)
4389                 {
4390                     DecoderEvent(p, DECODE_ICMPV6_SOLICITATION_BAD_CODE,
4391                                  DECODE_ICMPV6_SOLICITATION_BAD_CODE_STR, 1, 1);
4392                 }
4393                 if (ntohl(rs->reserved) != 0)
4394                 {
4395                     DecoderEvent(p, DECODE_ICMPV6_SOLICITATION_BAD_RESERVED,
4396                                  DECODE_ICMPV6_SOLICITATION_BAD_RESERVED_STR, 1, 1);
4397                 }
4398                 PushLayer(PROTO_ICMP6, p, pkt, ICMP_HEADER_LEN);
4399             }
4400             else
4401             {
4402                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4403                     "WARNING: Truncated ICMP header (%d bytes).\n", len););
4404 
4405                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ICMPHDR,
4406                                 DECODE_ICMP_DGRAM_LT_ICMPHDR_STR, 1, 1);
4407 
4408                 p->icmph = NULL;
4409                 p->icmp6h = NULL;
4410                 pc.discards++;
4411                 pc.icmpdisc++;
4412                 return;
4413             }
4414             break;
4415 
4416         case ICMP6_NODE_INFO_QUERY:
4417         case ICMP6_NODE_INFO_RESPONSE:
4418             if (p->dsize >= (sizeof(ICMP6NodeInfo) - ICMP6_MIN_HEADER_LEN))
4419             {
4420                 ICMP6NodeInfo *ni = (ICMP6NodeInfo *)pkt;
4421                 if (ni->code > 2)
4422                 {
4423                     DecoderEvent(p, DECODE_ICMPV6_NODE_INFO_BAD_CODE,
4424                                  DECODE_ICMPV6_NODE_INFO_BAD_CODE_STR, 1, 1);
4425                 }
4426                 /* TODO: Add alert for INFO Response, code == 1 || code == 2)
4427                  * and there is data.
4428                  */
4429             }
4430             else
4431             {
4432                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4433                     "WARNING: Truncated ICMP header (%d bytes).\n", len););
4434 
4435                 DecoderEvent(p, DECODE_ICMP_DGRAM_LT_ICMPHDR,
4436                                 DECODE_ICMP_DGRAM_LT_ICMPHDR_STR, 1, 1);
4437 
4438                 p->icmph = NULL;
4439                 p->icmp6h = NULL;
4440                 pc.discards++;
4441                 pc.icmpdisc++;
4442                 return;
4443             }
4444             break;
4445 
4446         default:
4447             if ( Event_Enabled(DECODE_ICMP6_TYPE_OTHER) )
4448                 DecoderEvent(p, EVARGS(ICMP6_TYPE_OTHER), 1, 1);
4449 
4450             PushLayer(PROTO_ICMP6, p, pkt, ICMP_HEADER_LEN);
4451             break;
4452     }
4453 
4454     p->proto_bits |= PROTO_BIT__ICMP;
4455     p->proto_bits &= ~(PROTO_BIT__UDP | PROTO_BIT__TCP);
4456 }
4457 
4458 /*
4459  * Function: DecodeICMPEmbeddedIP6(uint8_t *, const uint32_t, Packet *)
4460  *
4461  * Purpose: Decode the ICMP embedded IP6 header + payload
4462  *
4463  * Arguments: pkt => ptr to the packet data
4464  *            len => length from here to the end of the packet
4465  *            p   => pointer to dummy packet decode struct
4466  *
4467  * Returns: void function
4468  */
DecodeICMPEmbeddedIP6(const uint8_t * pkt,const uint32_t len,Packet * p)4469 void DecodeICMPEmbeddedIP6(const uint8_t *pkt, const uint32_t len, Packet *p)
4470 {
4471 
4472     /* lay the IP struct over the raw data */
4473     IP6RawHdr* hdr = (IP6RawHdr*)pkt;
4474     pc.embdip++;
4475 
4476     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "DecodeICMPEmbeddedIP6: ip header"
4477                     " starts at: %p, length is %lu\n", hdr,
4478                     (unsigned long) len););
4479 
4480     /* do a little validation */
4481     if ( len < IP6_HDR_LEN )
4482     {
4483         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4484             "ICMP6: IP short header (%d bytes)\n", len););
4485 
4486         DecoderEvent(p, DECODE_ICMP_ORIG_IP_TRUNCATED,
4487                         DECODE_ICMP_ORIG_IP_TRUNCATED_STR, 1, 1);
4488 
4489         pc.discards++;
4490         return;
4491     }
4492 
4493     /*
4494      * with datalink DLT_RAW it's impossible to differ ARP datagrams from IP.
4495      * So we are just ignoring non IP datagrams
4496      */
4497     if(IPRAW_HDR_VER(hdr) != 6)
4498     {
4499         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
4500             "ICMP: not IPv6 datagram ([ver: 0x%x][len: 0x%x])\n",
4501             IPRAW_HDR_VER(hdr), len););
4502 
4503         DecoderEvent(p, DECODE_ICMP_ORIG_IP_VER_MISMATCH,
4504                         DECODE_ICMP_ORIG_IP_VER_MISMATCH_STR, 1, 1);
4505 
4506         pc.discards++;
4507         return;
4508     }
4509 
4510     sfiph_orig_build(p, pkt, AF_INET6);
4511 
4512 
4513     // XXX NOT YET IMPLEMENTED - fragments inside ICMP payload
4514 
4515     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "ICMP6 Unreachable IP6 header length: "
4516                             "%lu\n", (unsigned long)IP6_HDR_LEN););
4517 
4518     switch(GET_ORIG_IPH_PROTO(p))
4519     {
4520         case IPPROTO_TCP: /* decode the interesting part of the header */
4521             p->orig_tcph = (TCPHdr *)(pkt + IP6_HDR_LEN);
4522 
4523             /* stuff more data into the printout data struct */
4524             p->orig_sp = ntohs(p->orig_tcph->th_sport);
4525             p->orig_dp = ntohs(p->orig_tcph->th_dport);
4526 
4527             break;
4528 
4529         case IPPROTO_UDP:
4530             p->orig_udph = (UDPHdr *)(pkt + IP6_HDR_LEN);
4531 
4532             /* fill in the printout data structs */
4533             p->orig_sp = ntohs(p->orig_udph->uh_sport);
4534             p->orig_dp = ntohs(p->orig_udph->uh_dport);
4535 
4536             break;
4537 
4538         case IPPROTO_ICMP:
4539             p->orig_icmph = (ICMPHdr *)(pkt + IP6_HDR_LEN);
4540             break;
4541     }
4542 
4543     return;
4544 }
4545 
4546 //--------------------------------------------------------------------
4547 // decode.c::Teredo
4548 //--------------------------------------------------------------------
4549 
4550 /* Function: DecodeTeredo(uint8_t *, uint32_t, Packet *)
4551  *
4552  * Teredo is IPv6 layered over UDP, with optional "indicators" in between.
4553  * Decode these (if present) and go to DecodeIPv6.
4554  *
4555  */
4556 
DecodeTeredo(const uint8_t * pkt,uint32_t len,Packet * p)4557 void DecodeTeredo(const uint8_t *pkt, uint32_t len, Packet *p)
4558 {
4559     if (len < TEREDO_MIN_LEN)
4560         return;
4561 
4562     /* Decode indicators. If both are present, Auth always comes before Origin. */
4563     if (ntohs(*(uint16_t *)pkt) == TEREDO_INDICATOR_AUTH)
4564     {
4565         uint8_t client_id_length, auth_data_length;
4566 
4567         if (len < TEREDO_INDICATOR_AUTH_MIN_LEN)
4568             return;
4569 
4570         client_id_length = *(pkt + 2);
4571         auth_data_length = *(pkt + 3);
4572 
4573         if (len < (uint32_t)(TEREDO_INDICATOR_AUTH_MIN_LEN + client_id_length + auth_data_length))
4574             return;
4575 
4576         pkt += (TEREDO_INDICATOR_AUTH_MIN_LEN + client_id_length + auth_data_length);
4577         len -= (TEREDO_INDICATOR_AUTH_MIN_LEN + client_id_length + auth_data_length);
4578     }
4579 
4580     if (ntohs(*(uint16_t *)pkt) == TEREDO_INDICATOR_ORIGIN)
4581     {
4582         if (len < TEREDO_INDICATOR_ORIGIN_LEN)
4583             return;
4584 
4585         pkt += TEREDO_INDICATOR_ORIGIN_LEN;
4586         len -= TEREDO_INDICATOR_ORIGIN_LEN;
4587     }
4588 
4589     /* If this is an IPv6 datagram, the first 4 bits will be the number 6. */
4590     if (( (*pkt & 0xF0) >> 4) == 6)
4591     {
4592         p->proto_bits |= PROTO_BIT__TEREDO;
4593         pc.teredo++;
4594 
4595         if ( ScTunnelBypassEnabled(TUNNEL_TEREDO) )
4596             Active_SetTunnelBypass();
4597 
4598         if (ScDeepTeredoInspection() && (p->sp != TEREDO_PORT) && (p->dp != TEREDO_PORT))
4599             p->packet_flags |= PKT_UNSURE_ENCAP;
4600 
4601         DecodeIPV6(pkt, len, p);
4602 
4603         p->packet_flags &= ~PKT_UNSURE_ENCAP;
4604     }
4605 
4606     /* Otherwise, we treat this as normal UDP traffic. */
4607     return;
4608 }
4609 
4610 //--------------------------------------------------------------------
4611 // decode.c::ESP
4612 //--------------------------------------------------------------------
4613 
4614 /* Function: DecodeAH
4615  *
4616  * Purpose: Decode Authentication Header
4617  *
4618  * NOTE: This is for IPv4 Auth Headers, we leave IPv6 to do its own
4619  * work.
4620  *
4621  */
DecodeAH(const uint8_t * pkt,uint32_t len,Packet * p)4622 void DecodeAH(const uint8_t *pkt, uint32_t len, Packet *p)
4623 {
4624     IP6Extension *ah = (IP6Extension *)pkt;
4625     unsigned extlen;
4626 
4627     if ( len < sizeof(*ah) )
4628     {
4629         DecoderEvent(p, EVARGS(AUTH_HDR_TRUNC), 1, 1);
4630         pc.discards++;
4631         return;
4632     }
4633 
4634     extlen = sizeof(*ah) + (ah->ip6e_len << 2);
4635     if ( extlen > len )
4636     {
4637         DecoderEvent(p, EVARGS(AUTH_HDR_BAD_LEN), 1, 1);
4638         pc.discards++;
4639         return;
4640     }
4641 
4642     PushLayer(PROTO_AH, p, pkt, extlen);
4643     DecodeIPv4Proto(ah->ip6e_nxt, pkt+extlen, len-extlen, p);
4644 }
4645 
4646 /*
4647  * Function: DecodeESP(const uint8_t *, uint32_t, Packet *)
4648  *
4649  * Purpose: Attempt to decode Encapsulated Security Payload.
4650  *          The contents are probably encrypted, but ESP is sometimes used
4651  *          with "null" encryption, solely for Authentication.
4652  *          This is more of a heuristic -- there is no ESP field that specifies
4653  *          the encryption type (or lack thereof).
4654  *
4655  * Arguments: pkt => ptr to the packet data
4656  *            len => length from here to the end of the packet
4657  *            p   => ptr to the Packet struct being filled out
4658  *
4659  * Returns: void function
4660  */
DecodeESP(const uint8_t * pkt,uint32_t len,Packet * p)4661 void DecodeESP(const uint8_t *pkt, uint32_t len, Packet *p)
4662 {
4663     const uint8_t *esp_payload;
4664     uint8_t next_header;
4665     uint8_t pad_length;
4666     uint8_t save_layer = p->next_layer;
4667 
4668     /* The ESP header contains a crypto Initialization Vector (IV) and
4669        a sequence number. Skip these. */
4670     if (len < (ESP_HEADER_LEN + ESP_AUTH_DATA_LEN + ESP_TRAILER_LEN))
4671     {
4672         /* Truncated ESP traffic. Bail out here and inspect the rest as payload. */
4673         DecoderEvent(p, EVARGS(ESP_HEADER_TRUNC), 1, 1);
4674         p->data = pkt;
4675         p->dsize = (uint16_t) len;
4676         return;
4677     }
4678     esp_payload = pkt + ESP_HEADER_LEN;
4679 
4680     /* The Authentication Data at the end of the packet is variable-length.
4681        RFC 2406 says that Encryption and Authentication algorithms MUST NOT
4682        both be NULL, so we assume NULL Encryption and some other Authentication.
4683 
4684        The mandatory algorithms for Authentication are HMAC-MD5-96 and
4685        HMAC-SHA-1-96, so we assume a 12-byte authentication data at the end. */
4686     len -= (ESP_HEADER_LEN + ESP_AUTH_DATA_LEN + ESP_TRAILER_LEN);
4687 
4688     pad_length = *(esp_payload + len);
4689     next_header = *(esp_payload + len + 1);
4690 
4691     /* Adjust the packet length to account for the padding.
4692        If the padding length is too big, this is probably encrypted traffic. */
4693     if (pad_length < len)
4694     {
4695         len -= (pad_length);
4696     }
4697     else
4698     {
4699         p->packet_flags |= PKT_TRUST;
4700         p->data = esp_payload;
4701         p->dsize = (u_short) len;
4702         return;
4703     }
4704 
4705     /* Attempt to decode the inner payload.
4706        There is a small chance that an encrypted next_header would become a
4707        different valid next_header. The PKT_UNSURE_ENCAP flag tells the next
4708        decoder stage to silently ignore invalid headers. */
4709 
4710     p->packet_flags |= PKT_UNSURE_ENCAP;
4711     switch (next_header)
4712     {
4713        case IPPROTO_IPIP:
4714             p->IPnIPencapsulated = 1;
4715             DecodeIP(esp_payload, len, p);
4716             p->packet_flags &= ~PKT_UNSURE_ENCAP;
4717             break;
4718 
4719         case IPPROTO_IPV6:
4720             DecodeIPV6(esp_payload, len, p);
4721             p->packet_flags &= ~PKT_UNSURE_ENCAP;
4722             break;
4723 
4724        case IPPROTO_TCP:
4725             pc.tcp++;
4726             DecodeTCP(esp_payload, len, p);
4727             p->packet_flags &= ~PKT_UNSURE_ENCAP;
4728             break;
4729 
4730         case IPPROTO_UDP:
4731             pc.udp++;
4732             DecodeUDP(esp_payload, len, p);
4733             p->packet_flags &= ~PKT_UNSURE_ENCAP;
4734             break;
4735 
4736         case IPPROTO_ICMP:
4737             pc.icmp++;
4738             DecodeICMP(esp_payload, len, p);
4739             p->packet_flags &= ~PKT_UNSURE_ENCAP;
4740             break;
4741 
4742 #ifdef GRE
4743         case IPPROTO_GRE:
4744             pc.gre++;
4745             DecodeGRE(esp_payload, len, p);
4746             p->packet_flags &= ~PKT_UNSURE_ENCAP;
4747             break;
4748 #endif
4749 
4750         default:
4751             /* If we didn't get a valid next_header, this packet is probably
4752                encrypted. Start data here and treat it as an IP datagram. */
4753             p->data = esp_payload;
4754             p->dsize = (u_short) len;
4755             p->packet_flags &= ~PKT_UNSURE_ENCAP;
4756             p->packet_flags |= PKT_TRUST;
4757             return;
4758     }
4759 
4760     /* If no protocol was added to the stack, than we assume its'
4761      * encrypted. */
4762     if (save_layer == p->next_layer)
4763         p->packet_flags |= PKT_TRUST;
4764 }
4765 
4766 #ifdef GRE
4767 //--------------------------------------------------------------------
4768 // decode.c::ERSPAN
4769 //--------------------------------------------------------------------
4770 
4771 /*
4772  * Function: DecodeERSPANType2(uint8_t *, uint32_t, Packet *)
4773  *
4774  * Purpose: Decode Encapsulated Remote Switch Packet Analysis Type 2
4775  *          This will decode ERSPAN Type 2 Headers
4776  *
4777  * Arguments: pkt => ptr to the packet data
4778  *            len => length from here to the end of the packet
4779  *            p   => pointer to decoded packet struct
4780  *
4781  * Returns: void function
4782  *
4783  */
DecodeERSPANType2(const uint8_t * pkt,const uint32_t len,Packet * p)4784 void DecodeERSPANType2(const uint8_t *pkt, const uint32_t len, Packet *p)
4785 {
4786     uint32_t hlen = sizeof(ERSpanType2Hdr);
4787     uint32_t payload_len;
4788     ERSpanType2Hdr *erSpan2Hdr = (ERSpanType2Hdr *)pkt;
4789 
4790     if (len < sizeof(ERSpanType2Hdr))
4791     {
4792         DecoderAlertEncapsulated(p, DECODE_ERSPAN2_DGRAM_LT_HDR,
4793                         DECODE_ERSPAN2_DGRAM_LT_HDR_STR,
4794                         pkt, len);
4795         return;
4796     }
4797 
4798     if (p->encapsulated)
4799     {
4800         /* discard packet - multiple encapsulation */
4801         /* not sure if this is ever used but I am assuming it is not */
4802         DecoderAlertEncapsulated(p, DECODE_IP_MULTIPLE_ENCAPSULATION,
4803                         DECODE_IP_MULTIPLE_ENCAPSULATION_STR,
4804                         pkt, len);
4805         return;
4806     }
4807 
4808     /* Check that this is in fact ERSpan Type 2.
4809      */
4810     if (ERSPAN_VERSION(erSpan2Hdr) != 0x01) /* Type 2 == version 0x01 */
4811     {
4812         DecoderAlertEncapsulated(p, DECODE_ERSPAN_HDR_VERSION_MISMATCH,
4813                         DECODE_ERSPAN_HDR_VERSION_MISMATCH_STR,
4814                         pkt, len);
4815         return;
4816     }
4817 
4818     PushLayer(PROTO_ERSPAN, p, pkt, hlen);
4819     payload_len = len - hlen;
4820 
4821     DecodeTransBridging(pkt + hlen, payload_len, p);
4822 }
4823 
4824 /*
4825  * Function: DecodeERSPANType3(uint8_t *, uint32_t, Packet *)
4826  *
4827  * Purpose: Decode Encapsulated Remote Switch Packet Analysis Type 3
4828  *          This will decode ERSPAN Type 3 Headers
4829  *
4830  * Arguments: pkt => ptr to the packet data
4831  *            len => length from here to the end of the packet
4832  *            p   => pointer to decoded packet struct
4833  *
4834  * Returns: void function
4835  *
4836  */
DecodeERSPANType3(const uint8_t * pkt,const uint32_t len,Packet * p)4837 void DecodeERSPANType3(const uint8_t *pkt, const uint32_t len, Packet *p)
4838 {
4839     uint32_t hlen = sizeof(ERSpanType3Hdr);
4840     uint32_t payload_len;
4841     ERSpanType3Hdr *erSpan3Hdr = (ERSpanType3Hdr *)pkt;
4842 
4843     if (len < sizeof(ERSpanType3Hdr))
4844     {
4845         DecoderAlertEncapsulated(p, DECODE_ERSPAN3_DGRAM_LT_HDR,
4846                         DECODE_ERSPAN3_DGRAM_LT_HDR_STR,
4847                         pkt, len);
4848         return;
4849     }
4850 
4851     if (p->encapsulated)
4852     {
4853         /* discard packet - multiple encapsulation */
4854         /* not sure if this is ever used but I am assuming it is not */
4855         DecoderAlertEncapsulated(p, DECODE_IP_MULTIPLE_ENCAPSULATION,
4856                         DECODE_IP_MULTIPLE_ENCAPSULATION_STR,
4857                         pkt, len);
4858         return;
4859     }
4860 
4861     /* Check that this is in fact ERSpan Type 3.
4862      */
4863     if (ERSPAN_VERSION(erSpan3Hdr) != 0x02) /* Type 3 == version 0x02 */
4864     {
4865         DecoderAlertEncapsulated(p, DECODE_ERSPAN_HDR_VERSION_MISMATCH,
4866                         DECODE_ERSPAN_HDR_VERSION_MISMATCH_STR,
4867                         pkt, len);
4868         return;
4869     }
4870 
4871     PushLayer(PROTO_ERSPAN, p, pkt, hlen);
4872     payload_len = len - hlen;
4873 
4874     DecodeTransBridging(pkt + hlen, payload_len, p);
4875 }
4876 
4877 //--------------------------------------------------------------------
4878 // decode.c::GRE
4879 //--------------------------------------------------------------------
4880 
4881 /*
4882  * Function: DecodeGRE(uint8_t *, uint32_t, Packet *)
4883  *
4884  * Purpose: Decode Generic Routing Encapsulation Protocol
4885  *          This will decode normal GRE and PPTP GRE.
4886  *
4887  * Arguments: pkt => ptr to the packet data
4888  *            len => length from here to the end of the packet
4889  *            p   => pointer to decoded packet struct
4890  *
4891  * Returns: void function
4892  *
4893  * Notes: see RFCs 1701, 2784 and 2637
4894  */
DecodeGRE(const uint8_t * pkt,const uint32_t len,Packet * p)4895 void DecodeGRE(const uint8_t *pkt, const uint32_t len, Packet *p)
4896 {
4897     uint32_t hlen;    /* GRE header length */
4898     uint32_t payload_len;
4899 
4900     if (len < GRE_HEADER_LEN)
4901     {
4902         DecoderAlertEncapsulated(p, DECODE_GRE_DGRAM_LT_GREHDR,
4903                         DECODE_GRE_DGRAM_LT_GREHDR_STR,
4904                         pkt, len);
4905         return;
4906     }
4907 
4908     if (p->encapsulated)
4909     {
4910         /* discard packet - multiple GRE encapsulation */
4911         /* not sure if this is ever used but I am assuming it is not */
4912         DecoderAlertEncapsulated(p, DECODE_IP_MULTIPLE_ENCAPSULATION,
4913                         DECODE_IP_MULTIPLE_ENCAPSULATION_STR,
4914                         pkt, len);
4915         return;
4916     }
4917 
4918     p->GREencapsulated = 1;
4919 
4920     /* Note: Since GRE doesn't have a field to indicate header length and
4921      * can contain a few options, we need to walk through the header to
4922      * figure out the length
4923      */
4924 
4925     p->greh = (GREHdr *)pkt;
4926     hlen = GRE_HEADER_LEN;
4927 
4928     switch (GRE_VERSION(p->greh))
4929     {
4930         case 0x00:
4931             /* these must not be set */
4932             if (GRE_RECUR(p->greh) || GRE_FLAGS(p->greh))
4933             {
4934                 DecoderAlertEncapsulated(p, DECODE_GRE_INVALID_HEADER,
4935                                 DECODE_GRE_INVALID_HEADER_STR,
4936                                 pkt, len);
4937                 return;
4938             }
4939 
4940             if (GRE_CHKSUM(p->greh) || GRE_ROUTE(p->greh))
4941                 hlen += GRE_CHKSUM_LEN + GRE_OFFSET_LEN;
4942 
4943             if (GRE_KEY(p->greh))
4944                 hlen += GRE_KEY_LEN;
4945 
4946             if (GRE_SEQ(p->greh))
4947                 hlen += GRE_SEQ_LEN;
4948 
4949             /* if this flag is set, we need to walk through all of the
4950              * Source Route Entries */
4951             if (GRE_ROUTE(p->greh))
4952             {
4953                 uint16_t sre_addrfamily;
4954                 uint8_t sre_offset;
4955                 uint8_t sre_length;
4956                 const uint8_t *sre_ptr;
4957 
4958                 sre_ptr = pkt + hlen;
4959 
4960                 while (1)
4961                 {
4962                     hlen += GRE_SRE_HEADER_LEN;
4963                     if (hlen > len)
4964                         break;
4965 
4966                     sre_addrfamily = ntohs(*((uint16_t *)sre_ptr));
4967                     sre_ptr += sizeof(sre_addrfamily);
4968 
4969                     sre_offset = *((uint8_t *)sre_ptr);
4970                     sre_ptr += sizeof(sre_offset);
4971 
4972                     sre_length = *((uint8_t *)sre_ptr);
4973                     sre_ptr += sizeof(sre_length);
4974 
4975                     if ((sre_addrfamily == 0) && (sre_length == 0))
4976                         break;
4977 
4978                     hlen += sre_length;
4979                     sre_ptr += sre_length;
4980                 }
4981             }
4982 
4983             break;
4984 
4985         /* PPTP */
4986         case 0x01:
4987             /* these flags should never be present */
4988             if (GRE_CHKSUM(p->greh) || GRE_ROUTE(p->greh) || GRE_SSR(p->greh) ||
4989                 GRE_RECUR(p->greh) || GRE_V1_FLAGS(p->greh))
4990             {
4991                 DecoderAlertEncapsulated(p, DECODE_GRE_V1_INVALID_HEADER,
4992                                 DECODE_GRE_V1_INVALID_HEADER_STR,
4993                                 pkt, len);
4994                 return;
4995             }
4996 
4997             /* protocol must be 0x880B - PPP */
4998             if (GRE_PROTO(p->greh) != GRE_TYPE_PPP)
4999             {
5000                 DecoderAlertEncapsulated(p, DECODE_GRE_V1_INVALID_HEADER,
5001                                 DECODE_GRE_V1_INVALID_HEADER_STR,
5002                                 pkt, len);
5003                 return;
5004             }
5005 
5006             /* this flag should always be present */
5007             if (!(GRE_KEY(p->greh)))
5008             {
5009                 DecoderAlertEncapsulated(p, DECODE_GRE_V1_INVALID_HEADER,
5010                                 DECODE_GRE_V1_INVALID_HEADER_STR,
5011                                 pkt, len);
5012                 return;
5013             }
5014 
5015             hlen += GRE_KEY_LEN;
5016 
5017             if (GRE_SEQ(p->greh))
5018                 hlen += GRE_SEQ_LEN;
5019 
5020             if (GRE_V1_ACK(p->greh))
5021                 hlen += GRE_V1_ACK_LEN;
5022 
5023             break;
5024 
5025         default:
5026             DecoderAlertEncapsulated(p, DECODE_GRE_INVALID_VERSION,
5027                             DECODE_GRE_INVALID_VERSION_STR,
5028                             pkt, len);
5029             return;
5030     }
5031 
5032     if (hlen > len)
5033     {
5034         DecoderAlertEncapsulated(p, DECODE_GRE_DGRAM_LT_GREHDR,
5035                         DECODE_GRE_DGRAM_LT_GREHDR_STR,
5036                         pkt, len);
5037         return;
5038     }
5039 
5040     PushLayer(PROTO_GRE, p, pkt, hlen);
5041     payload_len = len - hlen;
5042 
5043     if ( ScTunnelBypassEnabled(TUNNEL_GRE) )
5044         Active_SetTunnelBypass();
5045 
5046     /* Send to next protocol decoder */
5047     /* As described in RFC 2784 the possible protocols are listed in
5048      * RFC 1700 under "ETHER TYPES"
5049      * See also "Current List of Protocol Types" in RFC 1701
5050      */
5051     switch (GRE_PROTO(p->greh))
5052     {
5053         case ETHERNET_TYPE_IP:
5054             DecodeIP(pkt + hlen, payload_len, p);
5055             return;
5056 
5057         case GRE_TYPE_TRANS_BRIDGING:
5058             DecodeTransBridging(pkt + hlen, payload_len, p);
5059             return;
5060 
5061         case ETHERNET_TYPE_ARP:
5062         case ETHERNET_TYPE_REVARP:
5063             /* clear outer IP headers */
5064             p->iph = NULL;
5065             p->family = NO_IP;
5066             DecodeARP(pkt + hlen, payload_len, p);
5067             return;
5068 
5069         case ETHERNET_TYPE_IPV6:
5070             DecodeIPV6(pkt + hlen, payload_len, p);
5071             return;
5072 
5073         case GRE_TYPE_PPP:
5074             DecodePppPktEncapsulated(pkt + hlen, payload_len, p);
5075             return;
5076 
5077         case ETHERNET_TYPE_ERSPAN_TYPE2:
5078             DecodeERSPANType2(pkt + hlen, payload_len, p);
5079             return;
5080 
5081         case ETHERNET_TYPE_ERSPAN_TYPE3:
5082             DecodeERSPANType3(pkt + hlen, payload_len, p);
5083             return;
5084 
5085 #ifndef NO_NON_ETHER_DECODER
5086         case ETHERNET_TYPE_IPX:
5087             DecodeIPX(pkt + hlen, payload_len, p);
5088             return;
5089 #endif
5090 
5091         case ETHERNET_TYPE_LOOP:
5092             DecodeEthLoopback(pkt + hlen, payload_len, p);
5093             return;
5094 
5095         /* not sure if this occurs, but 802.1q is an Ether type */
5096         case ETHERNET_TYPE_8021Q:
5097             DecodeVlan(pkt + hlen, payload_len, p);
5098             return;
5099 
5100 #ifdef MPLS_RFC4023_SUPPORT
5101         case ETHERNET_TYPE_MPLS_MULTICAST:
5102             if(!ScMplsMulticast())
5103             {
5104                 DecoderEvent(p, DECODE_BAD_MPLS,
5105                                 DECODE_MULTICAST_MPLS_STR, 1, 1);
5106             }
5107         /* Fall through */
5108         case ETHERNET_TYPE_MPLS_UNICAST:
5109             DecodeMPLS(p->pkt + LEN_VLAN_LLC_OTHER,
5110                 len - LEN_VLAN_LLC_OTHER, p);
5111             return;
5112 #endif
5113 
5114         default:
5115             // TBD add decoder drop event for unknown gre/eth type
5116             pc.other++;
5117             p->data = pkt + hlen;
5118             p->dsize = (uint16_t)payload_len;
5119             return;
5120     }
5121 }
5122 #endif // GRE
5123 
5124 //--------------------------------------------------------------------
5125 // decode.c::GTP
5126 //--------------------------------------------------------------------
5127 
5128 /* Function: DecodeGTP(uint8_t *, uint32_t, Packet *)
5129  *
5130  * GTP (GPRS Tunneling Protocol) is layered over UDP.
5131  * Decode these (if present) and go to DecodeIPv6/DecodeIP.
5132  *
5133  */
5134 
DecodeGTP(const uint8_t * pkt,uint32_t len,Packet * p)5135 void DecodeGTP(const uint8_t *pkt, uint32_t len, Packet *p)
5136 {
5137     uint32_t header_len;
5138     uint8_t  next_hdr_type;
5139     uint8_t  version;
5140     uint8_t  ip_ver;
5141     GTPHdr *hdr;
5142 
5143     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Start GTP decoding.\n"););
5144 
5145     hdr = (GTPHdr *) pkt;
5146 
5147     if (p->GTPencapsulated)
5148     {
5149         DecoderAlertEncapsulated(p, DECODE_GTP_MULTIPLE_ENCAPSULATION,
5150                 DECODE_GTP_MULTIPLE_ENCAPSULATION_STR,
5151                 pkt, len);
5152         return;
5153     }
5154     else
5155     {
5156         p->GTPencapsulated = 1;
5157     }
5158     /*Check the length*/
5159     if (len < GTP_MIN_LEN)
5160        return;
5161     /* We only care about PDU*/
5162     if ( hdr->type != 255)
5163        return;
5164     /*Check whether this is GTP or GTP', Exit if GTP'*/
5165     if (!(hdr->flag & 0x10))
5166        return;
5167 
5168     /*The first 3 bits are version number*/
5169     version = (hdr->flag & 0xE0) >> 5;
5170     switch (version)
5171     {
5172     case 0: /*GTP v0*/
5173         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "GTP v0 packets.\n"););
5174 
5175         header_len = GTP_V0_HEADER_LEN;
5176         /*Check header fields*/
5177         if (len < header_len)
5178         {
5179             DecoderEvent(p, EVARGS(GTP_BAD_LEN), 1, 1);
5180             return;
5181         }
5182 
5183         p->proto_bits |= PROTO_BIT__GTP;
5184 
5185         /*Check the length field. */
5186         if (len != ((unsigned int)ntohs(hdr->length) + header_len))
5187         {
5188             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Calculated length %d != %d in header.\n",
5189                     len - header_len, ntohs(hdr->length)););
5190             DecoderEvent(p, EVARGS(GTP_BAD_LEN), 1, 1);
5191             return;
5192         }
5193 
5194         break;
5195     case 1: /*GTP v1*/
5196         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "GTP v1 packets.\n"););
5197 
5198         /*Check the length based on optional fields and extension header*/
5199         if (hdr->flag & 0x07)
5200         {
5201 
5202             header_len = GTP_V1_HEADER_LEN;
5203 
5204             /*Check optional fields*/
5205             if (len < header_len)
5206             {
5207                 DecoderEvent(p, EVARGS(GTP_BAD_LEN), 1, 1);
5208                 return;
5209             }
5210             next_hdr_type = *(pkt + header_len - 1);
5211 
5212             /*Check extension headers*/
5213             while (next_hdr_type)
5214             {
5215                 uint16_t ext_hdr_len;
5216                 /*check length before reading data*/
5217                 if (len < header_len + 4)
5218                 {
5219                     DecoderEvent(p, EVARGS(GTP_BAD_LEN), 1, 1);
5220                     return;
5221                 }
5222 
5223                 ext_hdr_len = *(pkt + header_len);
5224 
5225                 if (!ext_hdr_len)
5226                 {
5227                     DecoderEvent(p, EVARGS(GTP_BAD_LEN), 1, 1);
5228                     return;
5229                 }
5230                 /*Extension header length is a unit of 4 octets*/
5231                 header_len += ext_hdr_len * 4;
5232 
5233                 /*check length before reading data*/
5234                 if (len < header_len)
5235                 {
5236                     DecoderEvent(p, EVARGS(GTP_BAD_LEN), 1, 1);
5237                     return;
5238                 }
5239                 next_hdr_type = *(pkt + header_len - 1);
5240             }
5241         }
5242         else
5243             header_len = GTP_MIN_LEN;
5244 
5245         p->proto_bits |= PROTO_BIT__GTP;
5246 
5247         /*Check the length field. */
5248         if (len != ((unsigned int)ntohs(hdr->length) + GTP_MIN_LEN))
5249         {
5250             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Calculated length %d != %d in header.\n",
5251                     len - GTP_MIN_LEN, ntohs(hdr->length)););
5252             DecoderEvent(p, EVARGS(GTP_BAD_LEN), 1, 1);
5253             return;
5254         }
5255 
5256         break;
5257     default:
5258         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Unknown protocol version.\n"););
5259         return;
5260 
5261     }
5262 
5263     PushLayer(PROTO_GTP, p, pkt, header_len);
5264 
5265     if ( ScTunnelBypassEnabled(TUNNEL_GTP) )
5266         Active_SetTunnelBypass();
5267 
5268     len -=  header_len;
5269     if (len > 0)
5270     {
5271         ip_ver = *(pkt+header_len) & 0xF0;
5272         if (ip_ver == 0x40)
5273             DecodeIP(pkt+header_len, len, p);
5274         else if (ip_ver == 0x60)
5275             DecodeIPV6(pkt+header_len, len, p);
5276         p->packet_flags &= ~PKT_UNSURE_ENCAP;
5277     }
5278 
5279 }
5280 
5281 //--------------------------------------------------------------------
5282 // decode.c::UDP
5283 //--------------------------------------------------------------------
5284 
5285 /* UDP-layer decoder alerts */
UDPMiscTests(Packet * p)5286 static inline void UDPMiscTests(Packet *p)
5287 {
5288     if ( Event_Enabled(DECODE_UDP_LARGE_PACKET) )
5289     {
5290         if (p->dsize > 4000)
5291             DecoderEvent(p, EVARGS(UDP_LARGE_PACKET), 1, 1);
5292     }
5293 
5294     if ( Event_Enabled(DECODE_UDP_PORT_ZERO) )
5295     {
5296         if (p->udph->uh_sport == 0 || p->udph->uh_dport == 0)
5297             DecoderEvent(p, EVARGS(UDP_PORT_ZERO), 1, 1);
5298     }
5299 }
5300 
5301 /*
5302  * Function: DecodeUDP(uint8_t *, const uint32_t, Packet *)
5303  *
5304  * Purpose: Decode the UDP transport layer
5305  *
5306  * Arguments: pkt => ptr to the packet data
5307  *            len => length from here to the end of the packet
5308  *            p   => pointer to decoded packet struct
5309  *
5310  * Returns: void function
5311  */
PopUdp(Packet * p)5312 static inline void PopUdp (Packet* p)
5313 {
5314     p->udph = p->outer_udph;
5315     p->outer_udph = NULL;
5316     pc.discards++;
5317     pc.udisc++;
5318 
5319     // required for detect.c to short-circuit preprocessing
5320     if ( !p->dsize )
5321         p->dsize = p->ip_dsize;
5322 }
5323 
DecodeUDP(const uint8_t * pkt,const uint32_t len,Packet * p)5324 void DecodeUDP(const uint8_t * pkt, const uint32_t len, Packet * p)
5325 {
5326     uint16_t uhlen;
5327     u_char fragmented_udp_flag = 0;
5328 
5329     if (p->proto_bits & (PROTO_BIT__TEREDO | PROTO_BIT__GTP))
5330         p->outer_udph = p->udph;
5331 
5332     if(len < sizeof(UDPHdr))
5333     {
5334         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
5335                 "Truncated UDP header (%d bytes)\n", len););
5336 
5337         DecoderEvent(p, DECODE_UDP_DGRAM_LT_UDPHDR,
5338                         DECODE_UDP_DGRAM_LT_UDPHDR_STR, 1, 1);
5339 
5340         PopUdp(p);
5341         return;
5342     }
5343 
5344     /* set the ptr to the start of the UDP header */
5345     p->inner_udph = p->udph = (UDPHdr *) pkt;
5346 
5347     if (!p->frag_flag)
5348     {
5349         uhlen = ntohs(p->udph->uh_len);
5350     }
5351     else
5352     {
5353         if(IS_IP6(p))
5354         {
5355             uint16_t ip_len = ntohs(GET_IPH_LEN(p));
5356             /* subtract the distance from udp header to 1st ip6 extension */
5357             /* This gives the length of the UDP "payload", when fragmented */
5358             uhlen = ip_len - ((u_char *)p->udph - (u_char *)p->ip6_extensions[0].data);
5359         }
5360         else
5361         {
5362             uint16_t ip_len = ntohs(GET_IPH_LEN(p));
5363             /* Don't forget, IP_HLEN is a word - multiply x 4 */
5364             uhlen = ip_len - (GET_IPH_HLEN(p) * 4 );
5365         }
5366         fragmented_udp_flag = 1;
5367     }
5368 
5369     /* verify that the header len is a valid value */
5370     if(uhlen < UDP_HEADER_LEN)
5371     {
5372         DecoderEvent(p, DECODE_UDP_DGRAM_INVALID_LENGTH,
5373                         DECODE_UDP_DGRAM_INVALID_LENGTH_STR, 1, 1);
5374 
5375         PopUdp(p);
5376         return;
5377     }
5378 
5379     /* make sure there are enough bytes as designated by length field */
5380     if(uhlen > len)
5381     {
5382         DecoderEventDrop(p, DECODE_UDP_DGRAM_SHORT_PACKET,
5383                          DECODE_UDP_DGRAM_SHORT_PACKET_STR,
5384                          ScDecoderOversizedAlerts(),
5385                          ScDecoderOversizedDrops());
5386 
5387         PopUdp(p);
5388         return;
5389     }
5390     else if(uhlen < len)
5391     {
5392         DecoderEvent(p, DECODE_UDP_DGRAM_LONG_PACKET,
5393                      DECODE_UDP_DGRAM_LONG_PACKET_STR, 1, 1);
5394 
5395         PopUdp(p);
5396         return;
5397     }
5398 
5399     if (ScUdpChecksums())
5400     {
5401         /* look at the UDP checksum to make sure we've got a good packet */
5402         uint16_t csum;
5403         if(IS_IP4(p))
5404         {
5405             pseudoheader ph;
5406             ph.sip = p->iph->ip_src.s_addr;
5407             ph.dip = p->iph->ip_dst.s_addr;
5408             ph.zero = 0;
5409             ph.protocol = GET_IPH_PROTO(p);
5410             ph.len = p->udph->uh_len;
5411             /* Don't do checksum calculation if
5412              * 1) Fragmented, OR
5413              * 2) UDP header chksum value is 0.
5414              */
5415             if(!fragmented_udp_flag && p->udph->uh_chk )
5416             {
5417 #if defined(DAQ_VERSION) && DAQ_VERSION > 12
5418                  if ((((const uint8_t *)p->inner_udph - p->pkt) > p->pkth->checksum_offset) ||
5419                                       (p->pkth->checksum_error_flag))
5420 #endif
5421                      csum = in_chksum_udp(&ph,(uint16_t *)(p->udph), uhlen);
5422             }
5423             else
5424             {
5425                      csum = 0;
5426             }
5427 
5428         }
5429         else
5430         {
5431             IP6RawHdr* hdr6 = (IP6RawHdr*)p->iph;
5432             pseudoheader6 ph6;
5433             COPY4(ph6.sip, hdr6->ip6_src.s6_addr32);
5434             COPY4(ph6.dip, hdr6->ip6_dst.s6_addr32);
5435             ph6.zero = 0;
5436             ph6.protocol = GET_IPH_PROTO(p);
5437             ph6.len = htons((u_short)len);
5438 
5439             /* Alert on checksum value 0 for ipv6 packets */
5440             if(!p->udph->uh_chk)
5441             {
5442                 csum = 1;
5443                 DecoderEvent(p, DECODE_UDP_IPV6_ZERO_CHECKSUM,
5444                                 DECODE_UDP_IPV6_ZERO_CHECKSUM_STR, 1, 1);
5445             }
5446             /* Don't do checksum calculation if
5447              * 1) Fragmented
5448              * (UDP checksum is not optional in IP6)
5449              */
5450             else if( !fragmented_udp_flag )
5451             {
5452 #if defined(DAQ_VERSION) && DAQ_VERSION > 12
5453                 if ((((const uint8_t *)p->inner_udph - p->pkt) > p->pkth->checksum_offset) ||
5454                                       (p->pkth->checksum_error_flag))
5455 #endif
5456                      csum = in_chksum_udp6(&ph6,(uint16_t *)(p->udph), uhlen);
5457             }
5458             else
5459             {
5460                 csum = 0;
5461             }
5462         }
5463         if(csum)
5464         {
5465             /* Don't drop the packet if this was ESP or Teredo.
5466                Just stop decoding. */
5467             if (p->packet_flags & PKT_UNSURE_ENCAP)
5468             {
5469                 PopUdp(p);
5470                 return;
5471             }
5472 
5473             p->error_flags |= PKT_ERR_CKSUM_UDP;
5474             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Bad UDP Checksum\n"););
5475 
5476             if ( ScIdsMode() )
5477                 queueExecDrop(execUdpChksmDrop, p);
5478         }
5479         else
5480         {
5481             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "UDP Checksum: OK\n"););
5482         }
5483     }
5484 
5485     /* fill in the printout data structs */
5486 #ifdef HAVE_DAQ_REAL_ADDRESSES
5487     if (p->outer_iph || !(p->pkth->flags & DAQ_PKT_FLAG_REAL_ADDRESSES))
5488     {
5489 #endif
5490         p->sp = ntohs(p->udph->uh_sport);
5491         p->dp = ntohs(p->udph->uh_dport);
5492 #ifdef HAVE_DAQ_REAL_ADDRESSES
5493     }
5494     else
5495     {
5496         p->sp = ntohs(p->pkth->n_real_sPort);
5497         p->dp = ntohs(p->pkth->n_real_dPort);
5498     }
5499 #endif
5500 
5501     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "UDP header starts at: %p\n", p->udph););
5502 
5503     PushLayer(PROTO_UDP, p, pkt, sizeof(*p->udph));
5504 
5505     p->data = (uint8_t *) (pkt + UDP_HEADER_LEN);
5506 
5507     /* length was validated up above */
5508     p->dsize = uhlen - UDP_HEADER_LEN;
5509 
5510     p->proto_bits |= PROTO_BIT__UDP;
5511 
5512     /*  Drop packet if we ignore this port  */
5513     if (ScIgnoreUdpPort(p->sp) || ScIgnoreUdpPort(p->dp))
5514     {
5515         /*  Ignore all preprocessors for this packet */
5516         p->packet_flags |= PKT_IGNORE;
5517         return;
5518     }
5519 
5520     UDPMiscTests(p);
5521 
5522     if (p->sp == TEREDO_PORT ||
5523         p->dp == TEREDO_PORT ||
5524         ScDeepTeredoInspection())
5525     {
5526         if ( !p->frag_flag )
5527             DecodeTeredo(pkt + sizeof(UDPHdr), len - sizeof(UDPHdr), p);
5528     }
5529     if (ScGTPDecoding() &&
5530          (ScIsGTPPort(p->sp)||ScIsGTPPort(p->dp)))
5531     {
5532         if ( !p->frag_flag )
5533             DecodeGTP(pkt + sizeof(UDPHdr), len - sizeof(UDPHdr), p);
5534     }
5535 
5536 }
5537 
5538 //--------------------------------------------------------------------
5539 // decode.c::TCP
5540 //--------------------------------------------------------------------
5541 
5542 /* TCP-layer decoder alerts */
TCPMiscTests(Packet * p)5543 static inline void TCPMiscTests(Packet *p)
5544 {
5545     if ( Event_Enabled(DECODE_TCP_SHAFT_SYNFLOOD) )
5546     {
5547         if ( ((p->tcph->th_flags & TH_NORESERVED) == TH_SYN ) &&
5548              (p->tcph->th_seq == htonl(674711609)) )
5549             DecoderEvent(p, EVARGS(TCP_SHAFT_SYNFLOOD), 1, 1);
5550     }
5551 
5552     if ( Event_Enabled(DECODE_TCP_PORT_ZERO) )
5553     {
5554         if (p->tcph->th_sport == 0 || p->tcph->th_dport == 0)
5555             DecoderEvent(p, EVARGS(TCP_PORT_ZERO), 1, 1);
5556     }
5557 }
5558 
5559 /*
5560  * Function: DecodeTCP(uint8_t *, const uint32_t, Packet *)
5561  *
5562  * Purpose: Decode the TCP transport layer
5563  *
5564  * Arguments: pkt => ptr to the packet data
5565  *            len => length from here to the end of the packet
5566  *            p   => Pointer to packet decode struct
5567  *
5568  * Returns: void function
5569  */
DecodeTCP(const uint8_t * pkt,const uint32_t len,Packet * p)5570 void DecodeTCP(const uint8_t * pkt, const uint32_t len, Packet * p)
5571 {
5572     uint32_t hlen;            /* TCP header length */
5573 
5574     if(len < TCP_HEADER_LEN)
5575     {
5576         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
5577             "TCP packet (len = %d) cannot contain " "20 byte header\n", len););
5578 
5579         DecoderEvent(p, DECODE_TCP_DGRAM_LT_TCPHDR,
5580                         DECODE_TCP_DGRAM_LT_TCPHDR_STR, 1, 1);
5581 
5582         p->tcph = NULL;
5583         pc.discards++;
5584         pc.tdisc++;
5585 
5586         return;
5587     }
5588 
5589     /* lay TCP on top of the data cause there is enough of it! */
5590     p->tcph = (TCPHdr *) pkt;
5591 
5592     /* multiply the payload offset value by 4 */
5593     hlen = TCP_OFFSET(p->tcph) << 2;
5594 
5595     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "TCP th_off is %d, passed len is %lu\n",
5596                 TCP_OFFSET(p->tcph), (unsigned long)len););
5597 
5598     if(hlen < TCP_HEADER_LEN)
5599     {
5600         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
5601             "TCP Data Offset (%d) < hlen (%d) \n",
5602             TCP_OFFSET(p->tcph), hlen););
5603 
5604         DecoderEvent(p, DECODE_TCP_INVALID_OFFSET,
5605                         DECODE_TCP_INVALID_OFFSET_STR, 1, 1);
5606 
5607         p->tcph = NULL;
5608         pc.discards++;
5609         pc.tdisc++;
5610 
5611         return;
5612     }
5613 
5614     if(hlen > len)
5615     {
5616         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
5617             "TCP Data Offset(%d) < longer than payload(%d)!\n",
5618             TCP_OFFSET(p->tcph) << 2, len););
5619 
5620         DecoderEventDrop(p, DECODE_TCP_LARGE_OFFSET,
5621                             DECODE_TCP_LARGE_OFFSET_STR,
5622                             ScDecoderOversizedAlerts(),
5623                             ScDecoderOversizedDrops());
5624 
5625         p->tcph = NULL;
5626         pc.discards++;
5627         pc.tdisc++;
5628 
5629         return;
5630     }
5631 
5632     /* Checksum code moved in front of the other decoder alerts.
5633        If it's a bad checksum (maybe due to encrypted ESP traffic), the other
5634        alerts could be false positives. */
5635 #ifdef HAVE_DAQ_DECRYPTED_SSL
5636     if (!(p->pkth->flags & DAQ_PKT_FLAG_DECRYPTED_SSL) && ScTcpChecksums())
5637 #else
5638     if (ScTcpChecksums())
5639 #endif
5640     {
5641 #if defined(DAQ_VERSION) && DAQ_VERSION > 12
5642         if ((((const uint8_t *)p->tcph - p->pkt) > p->pkth->checksum_offset) ||
5643                    p->pkth->checksum_error_flag)
5644 #endif
5645         {
5646             uint16_t csum;
5647             if(IS_IP4(p))
5648             {
5649                 pseudoheader ph;
5650                 ph.sip = p->iph->ip_src.s_addr;
5651                 ph.dip = p->iph->ip_dst.s_addr;
5652                   /* setup the pseudo header for checksum calculation */
5653                 ph.zero = 0;
5654                 ph.protocol = GET_IPH_PROTO(p);
5655                 ph.len = htons((u_short)len);
5656 
5657                    /* if we're being "stateless" we probably don't care about the TCP
5658                      * checksum, but it's not bad to keep around for shits and giggles */
5659                    /* calculate the checksum */
5660                 csum = in_chksum_tcp(&ph, (uint16_t *)(p->tcph), len);
5661             }
5662             /* IPv6 traffic */
5663             else
5664             {
5665                 IP6RawHdr* hdr6 = (IP6RawHdr*)p->iph;
5666                 pseudoheader6 ph6;
5667                 COPY4(ph6.sip, hdr6->ip6_src.s6_addr32);
5668                 COPY4(ph6.dip, hdr6->ip6_dst.s6_addr32);
5669                 ph6.zero = 0;
5670                 ph6.protocol = GET_IPH_PROTO(p);
5671                 ph6.len = htons((u_short)len);
5672 
5673                 csum = in_chksum_tcp6(&ph6, (uint16_t *)(p->tcph), len);
5674             }
5675 
5676             if(csum)
5677             {
5678             /* Don't drop the packet if this is encapuslated in Teredo or ESP.
5679                Just get rid of the TCP header and stop decoding. */
5680                 if (p->packet_flags & PKT_UNSURE_ENCAP)
5681                 {
5682                     p->tcph = NULL;
5683                     return;
5684                 }
5685 
5686                 p->error_flags |= PKT_ERR_CKSUM_TCP;
5687                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Bad TCP checksum\n",
5688                                     "0x%x versus 0x%x\n", csum,
5689                                     ntohs(p->tcph->th_sum)););
5690 #ifdef REG_TEST
5691                 if (getRegTestFlags() & REG_TEST_FLAG_STREAM_DECODE)
5692                     printf("Bad TCP checksum\n");
5693 #endif
5694 
5695                 if ( ScIdsMode() )
5696                     queueExecDrop(execTcpChksmDrop, p);
5697             }
5698             else
5699             {
5700                 DEBUG_WRAP(DebugMessage(DEBUG_DECODE,"TCP Checksum: OK\n"););
5701             }
5702         }
5703     }
5704 
5705     if(Event_Enabled(DECODE_TCP_XMAS) || Event_Enabled(DECODE_TCP_NMAP_XMAS))
5706     {
5707         if(TCP_ISFLAGSET(p->tcph, (TH_FIN|TH_PUSH|TH_URG)))
5708         {
5709             if(TCP_ISFLAGSET(p->tcph, (TH_SYN|TH_ACK|TH_RST)))
5710             {
5711                 DecoderEvent(p, DECODE_TCP_XMAS, DECODE_TCP_XMAS_STR, 1, 1);
5712             }
5713             else
5714             {
5715                 DecoderEvent(p, DECODE_TCP_NMAP_XMAS, DECODE_TCP_NMAP_XMAS_STR, 1, 1);
5716             }
5717             // Allowing this packet for further processing
5718             // (in case there is a valid data inside it).
5719             /*p->tcph = NULL;
5720             pc.discards++;
5721             pc.tdisc++;
5722             return;*/
5723         }
5724     }
5725 
5726     if(TCP_ISFLAGSET(p->tcph, (TH_SYN)))
5727     {
5728         /* check if only SYN is set */
5729         if( p->tcph->th_flags == TH_SYN )
5730         {
5731             if( Event_Enabled(DECODE_DOS_NAPTHA) )
5732             {
5733                 if( ntohl(p->tcph->th_seq) == 6060842 )
5734                 {
5735                     if( ntohs(GET_IPH_ID(p)) == 413 )
5736                     {
5737                         DecoderEvent(p, DECODE_DOS_NAPTHA,
5738                                         DECODE_DOS_NAPTHA_STR, 1, 1);
5739                     }
5740                 }
5741             }
5742 
5743             if(InternalEventIsEnabled(snort_conf->rate_filter_config,
5744                         INTERNAL_EVENT_SYN_RECEIVED))
5745             {
5746                 SFRF_InternalSynRecdEvent(p);
5747             }
5748 
5749         }
5750 
5751         if( Event_Enabled(DECODE_SYN_TO_MULTICAST) )
5752         {
5753             if( IpAddrSetContains(SynToMulticastDstIp, GET_DST_ADDR(p)) )
5754             {
5755                 DecoderEvent(p, DECODE_SYN_TO_MULTICAST,
5756                                 DECODE_SYN_TO_MULTICAST_STR, 1, 1);
5757             }
5758         }
5759         if ( Event_Enabled(DECODE_TCP_SYN_RST) )
5760             if ( (p->tcph->th_flags & TH_RST) )
5761                 DecoderEvent(p, EVARGS(TCP_SYN_RST), 1, 1);
5762 
5763         if ( Event_Enabled(DECODE_TCP_SYN_FIN) )
5764             if ( (p->tcph->th_flags & TH_FIN) )
5765                 DecoderEvent(p, EVARGS(TCP_SYN_FIN), 1, 1);
5766     }
5767     else
5768     {   // we already know there is no SYN
5769         if ( Event_Enabled(DECODE_TCP_NO_SYN_ACK_RST) )
5770             if ( !(p->tcph->th_flags & (TH_ACK|TH_RST)) )
5771                 DecoderEvent(p, EVARGS(TCP_NO_SYN_ACK_RST), 1, 1);
5772     }
5773 
5774     if ( Event_Enabled(DECODE_TCP_MUST_ACK) )
5775         if ( (p->tcph->th_flags & (TH_FIN|TH_PUSH|TH_URG)) &&
5776             !(p->tcph->th_flags & TH_ACK) )
5777             DecoderEvent(p, EVARGS(TCP_MUST_ACK), 1, 1);
5778 
5779     /* stuff more data into the printout data struct */
5780 #ifdef HAVE_DAQ_REAL_ADDRESSES
5781     if (p->outer_iph || !(p->pkth->flags & DAQ_PKT_FLAG_REAL_ADDRESSES))
5782     {
5783 #endif
5784         p->sp = ntohs(p->tcph->th_sport);
5785         p->dp = ntohs(p->tcph->th_dport);
5786 #ifdef HAVE_DAQ_REAL_ADDRESSES
5787     }
5788     else
5789     {
5790         p->sp = ntohs(p->pkth->n_real_sPort);
5791         p->dp = ntohs(p->pkth->n_real_dPort);
5792     }
5793 #endif
5794 
5795 
5796     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "tcp header starts at: %p\n", p->tcph););
5797 
5798     PushLayer(PROTO_TCP, p, pkt, hlen);
5799 
5800     /* if options are present, decode them */
5801     p->tcp_options_len = (uint16_t)(hlen - TCP_HEADER_LEN);
5802 
5803     if(p->tcp_options_len > 0)
5804     {
5805         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "%lu bytes of tcp options....\n",
5806                     (unsigned long)(p->tcp_options_len)););
5807 
5808         p->tcp_options_data = pkt + TCP_HEADER_LEN;
5809         DecodeTCPOptions((uint8_t *) (pkt + TCP_HEADER_LEN), p->tcp_options_len, p);
5810     }
5811     else
5812     {
5813         p->tcp_option_count = 0;
5814     }
5815 
5816     /* set the data pointer and size */
5817     p->data = (uint8_t *) (pkt + hlen);
5818 
5819     if(hlen < len)
5820     {
5821         p->dsize = (u_short)(len - hlen);
5822     }
5823     else
5824     {
5825         p->dsize = 0;
5826     }
5827 
5828     if ( Event_Enabled(DECODE_TCP_BAD_URP) )
5829         if ( (p->tcph->th_flags & TH_URG) &&
5830             (!p->dsize || ntohs(p->tcph->th_urp) > p->dsize) )
5831             DecoderEvent(p, EVARGS(TCP_BAD_URP), 1, 1);
5832 
5833     p->proto_bits |= PROTO_BIT__TCP;
5834 
5835     /*  Drop packet if we ignore this port  */
5836     if (ScIgnoreTcpPort(p->sp) || ScIgnoreTcpPort(p->dp))
5837     {
5838         /*  Ignore all preprocessors for this packet */
5839         p->packet_flags |= PKT_IGNORE;
5840         return;
5841     }
5842 
5843     TCPMiscTests(p);
5844 }
5845 
5846 //--------------------------------------------------------------------
5847 // decode.c::Option Handling
5848 //--------------------------------------------------------------------
5849 
5850 /**
5851  * Validate that the length is an expected length AND that it's in bounds
5852  *
5853  * EOL and NOP are handled separately
5854  *
5855  * @param option_ptr current location
5856  * @param end the byte past the end of the decode list
5857  * @param len_ptr the pointer to the length field
5858  * @param expected_len the number of bytes we expect to see per rfc KIND+LEN+DATA, -1 means dynamic.
5859  * @param tcpopt options structure to populate
5860  * @param byte_skip distance to move upon completion
5861  *
5862  * @return returns 0 on success, < 0 on error
5863  */
OptLenValidate(const uint8_t * option_ptr,const uint8_t * end,const uint8_t * len_ptr,int expected_len,Options * tcpopt,uint8_t * byte_skip)5864 static inline int OptLenValidate(const uint8_t *option_ptr,
5865                                  const uint8_t *end,
5866                                  const uint8_t *len_ptr,
5867                                  int expected_len,
5868                                  Options *tcpopt,
5869                                  uint8_t *byte_skip)
5870 {
5871     *byte_skip = 0;
5872 
5873     if(len_ptr == NULL)
5874     {
5875         return TCP_OPT_TRUNC;
5876     }
5877 
5878     if(*len_ptr == 0 || expected_len == 0 || expected_len == 1)
5879     {
5880         return TCP_OPT_BADLEN;
5881     }
5882     else if(expected_len > 1)
5883     {
5884         if((option_ptr + expected_len) > end)
5885         {
5886             /* not enough data to read in a perfect world */
5887             return TCP_OPT_TRUNC;
5888         }
5889 
5890         if(*len_ptr != expected_len)
5891         {
5892             /* length is not valid */
5893             return TCP_OPT_BADLEN;
5894         }
5895     }
5896     else /* expected_len < 0 (i.e. variable length) */
5897     {
5898         if(*len_ptr < 2)
5899         {
5900             /* RFC sez that we MUST have atleast this much data */
5901             return TCP_OPT_BADLEN;
5902         }
5903 
5904         if((option_ptr + *len_ptr) > end)
5905         {
5906             /* not enough data to read in a perfect world */
5907             return TCP_OPT_TRUNC;
5908         }
5909     }
5910 
5911     tcpopt->len = *len_ptr - 2;
5912 
5913     if(*len_ptr == 2)
5914     {
5915         tcpopt->data = NULL;
5916     }
5917     else
5918     {
5919         tcpopt->data = option_ptr + 2;
5920     }
5921 
5922     *byte_skip = *len_ptr;
5923 
5924     return 0;
5925 }
5926 
5927 /*
5928  * Function: DecodeTCPOptions(uint8_t *, uint32_t, Packet *)
5929  *
5930  * Purpose: Fairly self explainatory name, don't you think?
5931  *
5932  *          TCP Option Header length validation is left to the caller
5933  *
5934  *          For a good listing of TCP Options,
5935  *          http://www.iana.org/assignments/tcp-parameters
5936  *
5937  *   ------------------------------------------------------------
5938  *   From: "Kastenholz, Frank" <FKastenholz@unispherenetworks.com>
5939  *   Subject: Re: skeeter & bubba TCP options?
5940  *
5941  *   ah, the sins of ones youth that never seem to be lost...
5942  *
5943  *   it was something that ben levy and stev and i did at ftp many
5944  *   many moons ago. bridgham and stev were the instigators of it.
5945  *   the idea was simple, put a dh key exchange directly in tcp
5946  *   so that all tcp sessions could be encrypted without requiring
5947  *   any significant key management system. authentication was not
5948  *   a part of the idea, it was to be provided by passwords or
5949  *   whatever, which could now be transmitted over the internet
5950  *   with impunity since they were encrypted... we implemented
5951  *   a simple form of this (doing the math was non trivial on the
5952  *   machines of the day). it worked. the only failure that i
5953  *   remember was that it was vulnerable to man-in-the-middle
5954  *   attacks.
5955  *
5956  *   why "skeeter" and "bubba"? well, that's known only to stev...
5957  *   ------------------------------------------------------------
5958  *
5959  * 4.2.2.5 TCP Options: RFC-793 Section 3.1
5960  *
5961  *    A TCP MUST be able to receive a TCP option in any segment. A TCP
5962  *    MUST ignore without error any TCP option it does not implement,
5963  *    assuming that the option has a length field (all TCP options
5964  *    defined in the future will have length fields). TCP MUST be
5965  *    prepared to handle an illegal option length (e.g., zero) without
5966  *    crashing; a suggested procedure is to reset the connection and log
5967  *    the reason.
5968  *
5969  * Arguments: o_list => ptr to the option list
5970  *            o_len => length of the option list
5971  *            p     => pointer to decoded packet struct
5972  *
5973  * Returns: void function
5974  */
DecodeTCPOptions(const uint8_t * start,uint32_t o_len,Packet * p)5975 void DecodeTCPOptions(const uint8_t *start, uint32_t o_len, Packet *p)
5976 {
5977     const uint8_t *option_ptr = start;
5978     const uint8_t *end_ptr = start + o_len; /* points to byte after last option */
5979     const uint8_t *len_ptr;
5980     uint8_t opt_count = 0;
5981     u_char done = 0; /* have we reached TCPOPT_EOL yet?*/
5982     u_char experimental_option_found = 0;      /* are all options RFC compliant? */
5983     u_char obsolete_option_found = 0;
5984     u_char ttcp_found = 0;
5985 
5986     int code = 2;
5987     uint8_t byte_skip;
5988 
5989     /* Here's what we're doing so that when we find out what these
5990      * other buggers of TCP option codes are, we can do something
5991      * useful
5992      *
5993      * 1) get option code
5994      * 2) check for enough space for current option code
5995      * 3) set option data ptr
5996      * 4) increment option code ptr
5997      *
5998      * TCP_OPTLENMAX = 40 because of
5999      *        (((2^4) - 1) * 4  - TCP_HEADER_LEN)
6000      *
6001      */
6002 
6003     if(o_len > TCP_OPTLENMAX)
6004     {
6005         /* This shouldn't ever alert if we are doing our job properly
6006          * in the caller */
6007         p->tcph = NULL; /* let's just alert */
6008         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
6009                                 "o_len(%u) > TCP_OPTLENMAX(%u)\n",
6010                                 o_len, TCP_OPTLENMAX));
6011         return;
6012     }
6013 
6014     while((option_ptr < end_ptr) && (opt_count < TCP_OPTLENMAX) && (code >= 0) && !done)
6015     {
6016         p->tcp_options[opt_count].code = *option_ptr;
6017 
6018         if((option_ptr + 1) < end_ptr)
6019         {
6020             len_ptr = option_ptr + 1;
6021         }
6022         else
6023         {
6024             len_ptr = NULL;
6025         }
6026 
6027         switch(*option_ptr)
6028         {
6029         case TCPOPT_EOL:
6030             done = 1; /* fall through to the NOP case */
6031         case TCPOPT_NOP:
6032             p->tcp_options[opt_count].len = 0;
6033             p->tcp_options[opt_count].data = NULL;
6034             byte_skip = 1;
6035             code = 0;
6036             break;
6037         case TCPOPT_MAXSEG:
6038             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_MAXSEG,
6039                                   &p->tcp_options[opt_count], &byte_skip);
6040             break;
6041         case TCPOPT_SACKOK:
6042             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_SACKOK,
6043                                   &p->tcp_options[opt_count], &byte_skip);
6044             break;
6045         case TCPOPT_WSCALE:
6046             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_WSCALE,
6047                                   &p->tcp_options[opt_count], &byte_skip);
6048             if (code == 0)
6049             {
6050                 if (
6051                     ((uint16_t) p->tcp_options[opt_count].data[0] > 14))
6052                 {
6053                     /* LOG INVALID WINDOWSCALE alert */
6054                     if (ScDecoderTcpOptAlerts())
6055                     {
6056                         DecoderOptEvent(p, DECODE_TCPOPT_WSCALE_INVALID,
6057                                         DECODE_TCPOPT_WSCALE_INVALID_STR, 1, 1,
6058                                         execTcpOptDrop);
6059                     }
6060                 }
6061             }
6062             break;
6063         case TCPOPT_ECHO: /* both use the same lengths */
6064         case TCPOPT_ECHOREPLY:
6065             obsolete_option_found = 1;
6066             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_ECHO,
6067                                   &p->tcp_options[opt_count], &byte_skip);
6068             break;
6069         case TCPOPT_MD5SIG:
6070             /* RFC 5925 obsoletes this option (see below) */
6071             obsolete_option_found = 1;
6072             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_MD5SIG,
6073                                   &p->tcp_options[opt_count], &byte_skip);
6074             break;
6075         case TCPOPT_AUTH:
6076             /* Has to have at least 4 bytes - see RFC 5925, Section 2.2 */
6077             if ((len_ptr != NULL) && (*len_ptr < 4))
6078                 code = TCP_OPT_BADLEN;
6079             else
6080                 code = OptLenValidate(option_ptr, end_ptr, len_ptr, -1,
6081                         &p->tcp_options[opt_count], &byte_skip);
6082             break;
6083         case TCPOPT_SACK:
6084             code = OptLenValidate(option_ptr, end_ptr, len_ptr, -1,
6085                                   &p->tcp_options[opt_count], &byte_skip);
6086             if((code == 0) && (p->tcp_options[opt_count].data == NULL))
6087                 code = TCP_OPT_BADLEN;
6088 
6089             break;
6090         case TCPOPT_CC_ECHO:
6091             ttcp_found = 1;
6092             /* fall through */
6093         case TCPOPT_CC:  /* all 3 use the same lengths / T/TCP */
6094         case TCPOPT_CC_NEW:
6095             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_CC,
6096                                   &p->tcp_options[opt_count], &byte_skip);
6097             break;
6098         case TCPOPT_TRAILER_CSUM:
6099             experimental_option_found = 1;
6100             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_TRAILER_CSUM,
6101                                   &p->tcp_options[opt_count], &byte_skip);
6102             break;
6103 
6104         case TCPOPT_TFO:
6105             code = OptLenValidate(option_ptr, end_ptr, len_ptr, -1,
6106                                   &p->tcp_options[opt_count], &byte_skip);
6107             break;
6108 
6109         case TCPOPT_TIMESTAMP:
6110             code = OptLenValidate(option_ptr, end_ptr, len_ptr, TCPOLEN_TIMESTAMP,
6111                                   &p->tcp_options[opt_count], &byte_skip);
6112             break;
6113 
6114         case TCPOPT_SKEETER:
6115         case TCPOPT_BUBBA:
6116         case TCPOPT_UNASSIGNED:
6117             obsolete_option_found = 1;
6118             code = OptLenValidate(option_ptr, end_ptr, len_ptr, -1,
6119                                   &p->tcp_options[opt_count], &byte_skip);
6120             break;
6121         default:
6122         case TCPOPT_SCPS:
6123         case TCPOPT_SELNEGACK:
6124         case TCPOPT_RECORDBOUND:
6125         case TCPOPT_CORRUPTION:
6126         case TCPOPT_PARTIAL_PERM:
6127         case TCPOPT_PARTIAL_SVC:
6128         case TCPOPT_ALTCSUM:
6129         case TCPOPT_SNAP:
6130             experimental_option_found = 1;
6131             code = OptLenValidate(option_ptr, end_ptr, len_ptr, -1,
6132                                   &p->tcp_options[opt_count], &byte_skip);
6133             break;
6134         }
6135 
6136         if(code < 0)
6137         {
6138             if(code == TCP_OPT_BADLEN)
6139             {
6140                 DecoderOptEvent(p, DECODE_TCPOPT_BADLEN,
6141                                 DECODE_TCPOPT_BADLEN_STR, 1, 1,
6142                                 execTcpOptDrop);
6143             }
6144             else if(code == TCP_OPT_TRUNC)
6145             {
6146                 DecoderOptEvent(p, DECODE_TCPOPT_TRUNCATED,
6147                                 DECODE_TCPOPT_TRUNCATED_STR, 1, 1,
6148                                 execTcpOptDrop);
6149             }
6150 
6151             /* set the option count to the number of valid
6152              * options found before this bad one
6153              * some implementations (BSD and Linux) ignore
6154              * the bad ones, but accept the good ones */
6155             p->tcp_option_count = opt_count;
6156 
6157             return;
6158         }
6159 
6160         opt_count++;
6161 
6162         option_ptr += byte_skip;
6163     }
6164 
6165     p->tcp_option_count = opt_count;
6166 
6167     if (experimental_option_found)
6168     {
6169         DecoderOptEvent(p, DECODE_TCPOPT_EXPERIMENT,
6170                         DECODE_TCPOPT_EXPERIMENT_STR, 1, 1,
6171                         execTcpOptExpDrop);
6172     }
6173     else if (obsolete_option_found)
6174     {
6175         DecoderOptEvent(p, DECODE_TCPOPT_OBSOLETE,
6176                         DECODE_TCPOPT_OBSOLETE_STR, 1, 1,
6177                         execTcpOptObsDrop);
6178     }
6179     else if (ttcp_found)
6180     {
6181         DecoderOptEvent(p, DECODE_TCPOPT_TTCP,
6182                         DECODE_TCPOPT_TTCP_STR, 1, 1,
6183                         execTcpOptTTcpDrop);
6184     }
6185 
6186     return;
6187 }
6188 
6189 
6190 /*
6191  * Function: DecodeIPOptions(uint8_t *, uint32_t, Packet *)
6192  *
6193  * Purpose: Once again, a fairly self-explainatory name
6194  *
6195  * Arguments: o_list => ptr to the option list
6196  *            o_len => length of the option list
6197  *            p     => pointer to decoded packet struct
6198  *
6199  * Returns: void function
6200  */
DecodeIPOptions(const uint8_t * start,uint32_t o_len,Packet * p)6201 void DecodeIPOptions(const uint8_t *start, uint32_t o_len, Packet *p)
6202 {
6203     const uint8_t *option_ptr = start;
6204     u_char done = 0; /* have we reached IP_OPTEOL yet? */
6205     const uint8_t *end_ptr = start + o_len;
6206     uint8_t opt_count = 0; /* what option are we processing right now */
6207     uint8_t byte_skip;
6208     const uint8_t *len_ptr;
6209     int code = 0;  /* negative error codes are returned from bad options */
6210 
6211 
6212     DEBUG_WRAP(DebugMessage(DEBUG_DECODE,  "Decoding %d bytes of IP options\n", o_len););
6213 
6214 
6215     while((option_ptr < end_ptr) && (opt_count < IP_OPTMAX) && (code >= 0))
6216     {
6217         p->ip_options[opt_count].code = *option_ptr;
6218 
6219         if((option_ptr + 1) < end_ptr)
6220         {
6221             len_ptr = option_ptr + 1;
6222         }
6223         else
6224         {
6225             len_ptr = NULL;
6226         }
6227 
6228         switch(*option_ptr)
6229         {
6230         case IPOPT_NOP:
6231         case IPOPT_EOL:
6232             /* if we hit an EOL, we're done */
6233             if(*option_ptr == IPOPT_EOL)
6234                 done = 1;
6235 
6236             p->ip_options[opt_count].len = 0;
6237             p->ip_options[opt_count].data = NULL;
6238             byte_skip = 1;
6239             break;
6240         default:
6241             /* handle all the dynamic features */
6242             code = OptLenValidate(option_ptr, end_ptr, len_ptr, -1,
6243                                   &p->ip_options[opt_count], &byte_skip);
6244         }
6245 
6246         if(code < 0)
6247         {
6248             /* Yes, we use TCP_OPT_* for the IP option decoder.
6249             */
6250             if(code == TCP_OPT_BADLEN)
6251             {
6252                 DecoderOptEvent(p, DECODE_IPV4OPT_BADLEN,
6253                                 DECODE_IPV4OPT_BADLEN_STR, 1, 1,
6254                                 execIpOptDrop);
6255             }
6256             else if(code == TCP_OPT_TRUNC)
6257             {
6258                 DecoderOptEvent(p, DECODE_IPV4OPT_TRUNCATED,
6259                                 DECODE_IPV4OPT_TRUNCATED_STR, 1, 1,
6260                                 execIpOptDrop);
6261             }
6262             return;
6263         }
6264 
6265         if(!done)
6266             opt_count++;
6267 
6268         option_ptr += byte_skip;
6269     }
6270 
6271     p->ip_option_count = opt_count;
6272 
6273     return;
6274 }
6275 
6276 //--------------------------------------------------------------------
6277 // decode.c::NON-ETHER STUFF
6278 //--------------------------------------------------------------------
6279 
6280 #ifndef NO_NON_ETHER_DECODER
6281 #ifdef DLT_IEEE802_11
6282 /*
6283  * Function: DecodeIEEE80211Pkt(Packet *, char *, DAQ_PktHdr_t*,
6284  *                               uint8_t*)
6285  *
6286  * Purpose: Decode those fun loving wireless LAN packets, one at a time!
6287  *
6288  * Arguments: p => pointer to the decoded packet struct
6289  *            user => Utility pointer (unused)
6290  *            pkthdr => ptr to the packet header
6291  *            pkt => pointer to the real live packet data
6292  *
6293  * Returns: void function
6294  */
DecodeIEEE80211Pkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)6295 void DecodeIEEE80211Pkt(Packet * p, const DAQ_PktHdr_t * pkthdr,
6296                         const uint8_t * pkt)
6297 {
6298     uint32_t cap_len = pkthdr->caplen;
6299     PROFILE_VARS;
6300 
6301     PREPROC_PROFILE_START(decodePerfStats);
6302 
6303     pc.total_processed++;
6304 
6305     memset(p, 0, PKT_ZERO_LEN);
6306 
6307     p->pkth = pkthdr;
6308     p->pkt = pkt;
6309 
6310     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
6311     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "caplen: %lu    pktlen: %lu\n",
6312                 (unsigned long)cap_len, (unsigned long)pkthdr->pktlen););
6313 
6314     /* do a little validation */
6315     if(cap_len < MINIMAL_IEEE80211_HEADER_LEN)
6316     {
6317         if (ScLogVerbose())
6318         {
6319             ErrorMessage("Captured data length < IEEE 802.11 header length! "
6320                          "(%d bytes)\n", cap_len);
6321         }
6322 
6323         PREPROC_PROFILE_END(decodePerfStats);
6324         return;
6325     }
6326     /* lay the wireless structure over the packet data */
6327     p->wifih = (WifiHdr *) pkt;
6328 
6329     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "%X   %X\n", *p->wifih->addr1,
6330                 *p->wifih->addr2););
6331 
6332     /* determine frame type */
6333     switch(p->wifih->frame_control & 0x00ff)
6334     {
6335         /* management frames */
6336         case WLAN_TYPE_MGMT_ASREQ:
6337         case WLAN_TYPE_MGMT_ASRES:
6338         case WLAN_TYPE_MGMT_REREQ:
6339         case WLAN_TYPE_MGMT_RERES:
6340         case WLAN_TYPE_MGMT_PRREQ:
6341         case WLAN_TYPE_MGMT_PRRES:
6342         case WLAN_TYPE_MGMT_BEACON:
6343         case WLAN_TYPE_MGMT_ATIM:
6344         case WLAN_TYPE_MGMT_DIS:
6345         case WLAN_TYPE_MGMT_AUTH:
6346         case WLAN_TYPE_MGMT_DEAUTH:
6347             pc.wifi_mgmt++;
6348             break;
6349 
6350             /* Control frames */
6351         case WLAN_TYPE_CONT_PS:
6352         case WLAN_TYPE_CONT_RTS:
6353         case WLAN_TYPE_CONT_CTS:
6354         case WLAN_TYPE_CONT_ACK:
6355         case WLAN_TYPE_CONT_CFE:
6356         case WLAN_TYPE_CONT_CFACK:
6357             pc.wifi_control++;
6358             break;
6359             /* Data packets without data */
6360         case WLAN_TYPE_DATA_NULL:
6361         case WLAN_TYPE_DATA_CFACK:
6362         case WLAN_TYPE_DATA_CFPL:
6363         case WLAN_TYPE_DATA_ACKPL:
6364 
6365             pc.wifi_data++;
6366             break;
6367         case WLAN_TYPE_DATA_DTCFACK:
6368         case WLAN_TYPE_DATA_DTCFPL:
6369         case WLAN_TYPE_DATA_DTACKPL:
6370         case WLAN_TYPE_DATA_DATA:
6371             pc.wifi_data++;
6372 
6373             if(cap_len < IEEE802_11_DATA_HDR_LEN + sizeof(EthLlc))
6374             {
6375                 DecoderEvent(p, DECODE_BAD_80211_ETHLLC,
6376                                 DECODE_BAD_80211_ETHLLC_STR, 1, 1);
6377 
6378                 PREPROC_PROFILE_END(decodePerfStats);
6379                 return;
6380             }
6381 
6382             p->ehllc = (EthLlc *) (pkt + IEEE802_11_DATA_HDR_LEN);
6383 
6384 #ifdef DEBUG_MSGS
6385             PrintNetData(stdout,(uint8_t *)  p->ehllc, sizeof(EthLlc), NULL);
6386             //ClearDumpBuf();
6387 
6388             printf("LLC Header:\n");
6389             printf("   DSAP: 0x%X\n", p->ehllc->dsap);
6390             printf("   SSAP: 0x%X\n", p->ehllc->ssap);
6391 #endif
6392 
6393             if(p->ehllc->dsap == ETH_DSAP_IP && p->ehllc->ssap == ETH_SSAP_IP)
6394             {
6395                 if(cap_len < IEEE802_11_DATA_HDR_LEN +
6396                    sizeof(EthLlc) + sizeof(EthLlcOther))
6397                 {
6398                     DecoderEvent(p, DECODE_BAD_80211_OTHER,
6399                                     DECODE_BAD_80211_OTHER_STR, 1, 1);
6400 
6401                     PREPROC_PROFILE_END(decodePerfStats);
6402                     return;
6403                 }
6404 
6405                 p->ehllcother = (EthLlcOther *) (pkt + IEEE802_11_DATA_HDR_LEN + sizeof(EthLlc));
6406 #ifdef DEBUG_MSGS
6407                 PrintNetData(stdout,(uint8_t *) p->ehllcother, sizeof(EthLlcOther), NULL );
6408                 //ClearDumpBuf();
6409                 printf("LLC Other Header:\n");
6410                 printf("   CTRL: 0x%X\n", p->ehllcother->ctrl);
6411                 printf("   ORG: 0x%02X%02X%02X\n", p->ehllcother->org_code[0],
6412                         p->ehllcother->org_code[1], p->ehllcother->org_code[2]);
6413                 printf("   PROTO: 0x%04X\n", ntohs(p->ehllcother->proto_id));
6414 #endif
6415 
6416                 switch(ntohs(p->ehllcother->proto_id))
6417                 {
6418                     case ETHERNET_TYPE_IP:
6419                         DecodeIP(p->pkt + IEEE802_11_DATA_HDR_LEN + sizeof(EthLlc) +
6420                                 sizeof(EthLlcOther),
6421                                 cap_len - IEEE802_11_DATA_HDR_LEN - sizeof(EthLlc) -
6422                                 sizeof(EthLlcOther), p);
6423                         PREPROC_PROFILE_END(decodePerfStats);
6424                         return;
6425 
6426                     case ETHERNET_TYPE_ARP:
6427                     case ETHERNET_TYPE_REVARP:
6428                         DecodeARP(p->pkt + IEEE802_11_DATA_HDR_LEN + sizeof(EthLlc) +
6429                                 sizeof(EthLlcOther),
6430                                 cap_len - IEEE802_11_DATA_HDR_LEN - sizeof(EthLlc) -
6431                                 sizeof(EthLlcOther), p);
6432                         PREPROC_PROFILE_END(decodePerfStats);
6433                         return;
6434                     case ETHERNET_TYPE_EAPOL:
6435                         DecodeEapol(p->pkt + IEEE802_11_DATA_HDR_LEN + sizeof(EthLlc) +
6436                                 sizeof(EthLlcOther),
6437                                 cap_len - IEEE802_11_DATA_HDR_LEN - sizeof(EthLlc) -
6438                                 sizeof(EthLlcOther), p);
6439                         PREPROC_PROFILE_END(decodePerfStats);
6440                         return;
6441                     case ETHERNET_TYPE_8021Q:
6442                         DecodeVlan(p->pkt + IEEE802_11_DATA_HDR_LEN ,
6443                                    cap_len - IEEE802_11_DATA_HDR_LEN , p);
6444                         PREPROC_PROFILE_END(decodePerfStats);
6445                         return;
6446 
6447                     case ETHERNET_TYPE_IPV6:
6448                         DecodeIPV6(p->pkt + IEEE802_11_DATA_HDR_LEN,
6449                                 cap_len - IEEE802_11_DATA_HDR_LEN, p);
6450                         PREPROC_PROFILE_END(decodePerfStats);
6451                         return;
6452 
6453                     default:
6454                         // TBD add decoder drop event for unknown wifi/eth type
6455                         pc.other++;
6456                         PREPROC_PROFILE_END(decodePerfStats);
6457                         return;
6458                 }
6459             }
6460             break;
6461         default:
6462             // TBD add decoder drop event for unknown wlan frame type
6463             pc.other++;
6464             break;
6465     }
6466 
6467     PREPROC_PROFILE_END(decodePerfStats);
6468     return;
6469 }
6470 #endif  // DLT_IEEE802_11
6471 
6472 /*
6473  * Function: DecodeTRPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
6474  *
6475  * Purpose: Decode Token Ring packets!
6476  *
6477  * Arguments: p=> pointer to decoded packet struct
6478  *            user => Utility pointer, unused
6479  *            pkthdr => ptr to the packet header
6480  *            pkt => pointer to the real live packet data
6481  *
6482  * Returns: void function
6483  */
DecodeTRPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)6484 void DecodeTRPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
6485 {
6486     uint32_t cap_len = pkthdr->caplen;
6487     uint32_t dataoff;      /* data offset is variable here */
6488     PROFILE_VARS;
6489 
6490     PREPROC_PROFILE_START(decodePerfStats);
6491 
6492     pc.total_processed++;
6493 
6494     memset(p, 0, PKT_ZERO_LEN);
6495 
6496     p->pkth = pkthdr;
6497     p->pkt = pkt;
6498 
6499     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n");
6500             DebugMessage(DEBUG_DECODE, "caplen: %lu    pktlen: %lu\n",
6501                 (unsigned long)cap_len,(unsigned long) pkthdr->pktlen);
6502             );
6503 
6504     if(cap_len < sizeof(Trh_hdr))
6505     {
6506         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
6507             "Captured data length < Token Ring header length! "
6508             "(%d < %d bytes)\n", cap_len, TR_HLEN););
6509 
6510         DecoderEvent(p, DECODE_BAD_TRH, DECODE_BAD_TRH_STR, 1, 1);
6511 
6512         PREPROC_PROFILE_END(decodePerfStats);
6513         return;
6514     }
6515 
6516     /* lay the tokenring header structure over the packet data */
6517     p->trh = (Trh_hdr *) pkt;
6518 
6519     /*
6520      * according to rfc 1042:
6521      *
6522      *   The presence of a Routing Information Field is indicated by the Most
6523      *   Significant Bit (MSB) of the source address, called the Routing
6524      *   Information Indicator (RII).  If the RII equals zero, a RIF is
6525      *   not present.  If the RII equals 1, the RIF is present.
6526      *   ..
6527      *   However the MSB is already zeroed by this moment, so there's no
6528      *   real way to figure out whether RIF is presented in packet, so we are
6529      *   doing some tricks to find IPARP signature..
6530      */
6531 
6532     /*
6533      * first I assume that we have single-ring network with no RIF
6534      * information presented in frame
6535      */
6536     if(cap_len < (sizeof(Trh_hdr) + sizeof(Trh_llc)))
6537     {
6538         DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
6539             "Captured data length < Token Ring header length! "
6540             "(%d < %d bytes)\n", cap_len,
6541             (sizeof(Trh_hdr) + sizeof(Trh_llc))););
6542 
6543         DecoderEvent(p, DECODE_BAD_TR_ETHLLC, DECODE_BAD_TR_ETHLLC_STR, 1, 1);
6544 
6545         PREPROC_PROFILE_END(decodePerfStats);
6546         return;
6547     }
6548 
6549 
6550     p->trhllc = (Trh_llc *) (pkt + sizeof(Trh_hdr));
6551 
6552     if(p->trhllc->dsap != IPARP_SAP && p->trhllc->ssap != IPARP_SAP)
6553     {
6554         /*
6555          * DSAP != SSAP != 0xAA .. either we are having frame which doesn't
6556          * carry IP datagrams or has RIF information present. We assume
6557          * lattest ...
6558          */
6559 
6560         if(cap_len < (sizeof(Trh_hdr) + sizeof(Trh_llc) + sizeof(Trh_mr)))
6561         {
6562             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
6563                 "Captured data length < Token Ring header length! "
6564                 "(%d < %d bytes)\n", cap_len,
6565                 (sizeof(Trh_hdr) + sizeof(Trh_llc) + sizeof(Trh_mr))););
6566 
6567             DecoderEvent(p, DECODE_BAD_TRHMR, DECODE_BAD_TRHMR_STR, 1, 1);
6568 
6569             PREPROC_PROFILE_END(decodePerfStats);
6570             return;
6571         }
6572 
6573         p->trhmr = (Trh_mr *) (pkt + sizeof(Trh_hdr));
6574 
6575 
6576         if(cap_len < (sizeof(Trh_hdr) + sizeof(Trh_llc) +
6577                       sizeof(Trh_mr) + TRH_MR_LEN(p->trhmr)))
6578         {
6579             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
6580                 "Captured data length < Token Ring header length! "
6581                 "(%d < %d bytes)\n", cap_len,
6582                 (sizeof(Trh_hdr) + sizeof(Trh_llc) + sizeof(Trh_mr))););
6583 
6584             DecoderEvent(p, DECODE_BAD_TR_MR_LEN, DECODE_BAD_TR_MR_LEN_STR, 1, 1);
6585 
6586             PREPROC_PROFILE_END(decodePerfStats);
6587             return;
6588         }
6589 
6590         p->trhllc = (Trh_llc *) (pkt + sizeof(Trh_hdr) + TRH_MR_LEN(p->trhmr));
6591         dataoff   = sizeof(Trh_hdr) + TRH_MR_LEN(p->trhmr) + sizeof(Trh_llc);
6592 
6593     }
6594     else
6595     {
6596         p->trhllc = (Trh_llc *) (pkt + sizeof(Trh_hdr));
6597         dataoff = sizeof(Trh_hdr) + sizeof(Trh_llc);
6598     }
6599 
6600     /*
6601      * ideally we would need to check both SSAP, DSAP, and protoid fields: IP
6602      * datagrams and ARP requests and replies are transmitted in standard
6603      * 802.2 LLC Type 1 Unnumbered Information format, control code 3, with
6604      * the DSAP and the SSAP fields of the 802.2 header set to 170, the
6605      * assigned global SAP value for SNAP [6].  The 24-bit Organization Code
6606      * in the SNAP is zero, and the remaining 16 bits are the EtherType from
6607      * Assigned Numbers [7] (IP = 2048, ARP = 2054). .. but we would check
6608      * SSAP and DSAP and assume this would be enough to trust.
6609      */
6610     if(p->trhllc->dsap != IPARP_SAP && p->trhllc->ssap != IPARP_SAP)
6611     {
6612         DEBUG_WRAP(
6613                    DebugMessage(DEBUG_DECODE, "DSAP and SSAP arent set to SNAP\n");
6614                 );
6615         p->trhllc = NULL;
6616         PREPROC_PROFILE_END(decodePerfStats);
6617         return;
6618     }
6619 
6620     switch(htons(p->trhllc->ethertype))
6621     {
6622         case ETHERNET_TYPE_IP:
6623             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Decoding IP\n"););
6624             DecodeIP(p->pkt + dataoff, cap_len - dataoff, p);
6625             PREPROC_PROFILE_END(decodePerfStats);
6626             return;
6627 
6628         case ETHERNET_TYPE_ARP:
6629         case ETHERNET_TYPE_REVARP:
6630             DEBUG_WRAP(
6631                     DebugMessage(DEBUG_DECODE, "Decoding ARP\n");
6632                     );
6633             pc.arp++;
6634 
6635             PREPROC_PROFILE_END(decodePerfStats);
6636             return;
6637 
6638         case ETHERNET_TYPE_8021Q:
6639             DecodeVlan(p->pkt + dataoff, cap_len - dataoff, p);
6640             PREPROC_PROFILE_END(decodePerfStats);
6641             return;
6642 
6643         default:
6644             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Unknown network protocol: %d\n",
6645                         htons(p->trhllc->ethertype)));
6646             // TBD add decoder drop event for unknown tr/eth type
6647             pc.other++;
6648             PREPROC_PROFILE_END(decodePerfStats);
6649             return;
6650     }
6651 
6652     PREPROC_PROFILE_END(decodePerfStats);
6653     return;
6654 }
6655 
6656 
6657 /*
6658  * Function: DecodeFDDIPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
6659  *
6660  * Purpose: Mainly taken from CyberPsycotic's Token Ring Code -worm5er
6661  *
6662  * Arguments: p => pointer to decoded packet struct
6663  *            user => Utility pointer, unused
6664  *            pkthdr => ptr to the packet header
6665  *            pkt => pointer to the real live packet data
6666  *
6667  * Returns: void function
6668  */
DecodeFDDIPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)6669 void DecodeFDDIPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
6670 {
6671     uint32_t cap_len = pkthdr->caplen;
6672     uint32_t dataoff = sizeof(Fddi_hdr) + sizeof(Fddi_llc_saps);
6673     PROFILE_VARS;
6674 
6675     PREPROC_PROFILE_START(decodePerfStats);
6676 
6677     pc.total_processed++;
6678 
6679     memset(p, 0, PKT_ZERO_LEN);
6680 
6681     p->pkth = pkthdr;
6682     p->pkt = pkt;
6683 
6684     DEBUG_WRAP(DebugMessage(DEBUG_DECODE,"Packet!\n");
6685             DebugMessage(DEBUG_DECODE, "caplen: %lu    pktlen: %lu\n",
6686                 (unsigned long) cap_len,(unsigned long) pkthdr->pktlen);
6687             );
6688 
6689     /* Bounds checking (might not be right yet -worm5er) */
6690     if(cap_len < dataoff)
6691     {
6692         if (ScLogVerbose())
6693         {
6694             ErrorMessage("Captured data length < FDDI header length! "
6695                          "(%d %d bytes)\n", cap_len, dataoff);
6696             PREPROC_PROFILE_END(decodePerfStats);
6697             return;
6698         }
6699     }
6700     /* let's put this in as the fddi header structure */
6701     p->fddihdr = (Fddi_hdr *) pkt;
6702 
6703     p->fddisaps = (Fddi_llc_saps *) (pkt + sizeof(Fddi_hdr));
6704 
6705     /* First we'll check and see if it's an IP/ARP Packet... */
6706     /* Then we check to see if it's a SNA packet */
6707     /*
6708      * Lastly we'll declare it none of the above and just slap something
6709      * generic on it to discard it with (I know that sucks, but heck we're
6710      * only looking for IP/ARP type packets currently...  -worm5er
6711      */
6712     if((p->fddisaps->dsap == FDDI_DSAP_IP) && (p->fddisaps->ssap == FDDI_SSAP_IP))
6713     {
6714         dataoff += sizeof(Fddi_llc_iparp);
6715 
6716         if(cap_len < dataoff)
6717         {
6718             if (ScLogVerbose())
6719             {
6720                 ErrorMessage("Captured data length < FDDI header length! "
6721                              "(%d %d bytes)\n", cap_len, dataoff);
6722                 PREPROC_PROFILE_END(decodePerfStats);
6723                 return;
6724             }
6725         }
6726 
6727         p->fddiiparp = (Fddi_llc_iparp *) (pkt + sizeof(Fddi_hdr) + sizeof(Fddi_llc_saps));
6728     }
6729     else if((p->fddisaps->dsap == FDDI_DSAP_SNA) &&
6730             (p->fddisaps->ssap == FDDI_SSAP_SNA))
6731     {
6732         dataoff += sizeof(Fddi_llc_sna);
6733 
6734         if(cap_len < dataoff)
6735         {
6736             if (ScLogVerbose())
6737             {
6738                 ErrorMessage("Captured data length < FDDI header length! "
6739                              "(%d %d bytes)\n", cap_len, dataoff);
6740                 PREPROC_PROFILE_END(decodePerfStats);
6741                 return;
6742             }
6743         }
6744 
6745         p->fddisna = (Fddi_llc_sna *) (pkt + sizeof(Fddi_hdr) +
6746                                        sizeof(Fddi_llc_saps));
6747     }
6748     else
6749     {
6750         dataoff += sizeof(Fddi_llc_other);
6751         p->fddiother = (Fddi_llc_other *) (pkt + sizeof(Fddi_hdr) +
6752                 sizeof(Fddi_llc_other));
6753 
6754         if(cap_len < dataoff)
6755         {
6756             if (ScLogVerbose())
6757             {
6758                 ErrorMessage("Captured data length < FDDI header length! "
6759                              "(%d %d bytes)\n", cap_len, dataoff);
6760                 PREPROC_PROFILE_END(decodePerfStats);
6761                 return;
6762             }
6763         }
6764     }
6765 
6766     /*
6767      * Now let's see if we actually care about the packet... If we don't,
6768      * throw it out!!!
6769      */
6770     if((p->fddisaps->dsap != FDDI_DSAP_IP) || (p->fddisaps->ssap != FDDI_SSAP_IP))
6771     {
6772         DEBUG_WRAP(
6773                 DebugMessage(DEBUG_DECODE,
6774                     "This FDDI Packet isn't an IP/ARP packet...\n");
6775                 );
6776         PREPROC_PROFILE_END(decodePerfStats);
6777         return;
6778     }
6779 
6780     cap_len -= dataoff;
6781 
6782     switch(htons(p->fddiiparp->ethertype))
6783     {
6784         case ETHERNET_TYPE_IP:
6785             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Decoding IP\n"););
6786             DecodeIP(p->pkt + dataoff, cap_len, p);
6787             PREPROC_PROFILE_END(decodePerfStats);
6788             return;
6789 
6790         case ETHERNET_TYPE_ARP:
6791         case ETHERNET_TYPE_REVARP:
6792             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Decoding ARP\n"););
6793             pc.arp++;
6794 
6795             PREPROC_PROFILE_END(decodePerfStats);
6796             return;
6797 
6798         case ETHERNET_TYPE_8021Q:
6799             DecodeVlan(p->pkt + dataoff, cap_len, p);
6800             PREPROC_PROFILE_END(decodePerfStats);
6801             return;
6802 
6803 
6804         default:
6805             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Unknown network protocol: %d\n",
6806                         htons(p->fddiiparp->ethertype));
6807                     );
6808             // TBD add decoder drop event for unknown fddi/eth type
6809             pc.other++;
6810 
6811             PREPROC_PROFILE_END(decodePerfStats);
6812             return;
6813     }
6814 
6815     PREPROC_PROFILE_END(decodePerfStats);
6816     return;
6817 }
6818 
6819 #ifdef DLT_LINUX_SLL
6820 /*
6821  * Function: DecodeLinuxSLLPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
6822  *
6823  * Purpose: Decode those fun loving LinuxSLL (linux cooked sockets)
6824  *          packets, one at a time!
6825  *
6826  * Arguments: p => pointer to the decoded packet struct
6827  *            user => Utility pointer (unused)
6828  *            pkthdr => ptr to the packet header
6829  *            pkt => pointer to the real live packet data
6830  *
6831  * Returns: void function
6832  */
6833 
DecodeLinuxSLLPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)6834 void DecodeLinuxSLLPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
6835 {
6836     uint32_t cap_len = pkthdr->caplen;
6837     PROFILE_VARS;
6838 
6839     PREPROC_PROFILE_START(decodePerfStats);
6840 
6841     pc.total_processed++;
6842 
6843     memset(p, 0, PKT_ZERO_LEN);
6844 
6845     p->pkth = pkthdr;
6846     p->pkt = pkt;
6847 
6848     DEBUG_WRAP(DebugMessage(DEBUG_DECODE,"Packet!\n");
6849             DebugMessage(DEBUG_DECODE, "caplen: %lu    pktlen: %lu\n",
6850                 (unsigned long)cap_len, (unsigned long)pkthdr->pktlen););
6851 
6852     /* do a little validation */
6853     if(cap_len < SLL_HDR_LEN)
6854     {
6855         if (ScLogVerbose())
6856         {
6857             ErrorMessage("Captured data length < SLL header length (your "
6858                          "libpcap is broken?)! (%d bytes)\n", cap_len);
6859         }
6860         PREPROC_PROFILE_END(decodePerfStats);
6861         return;
6862     }
6863     /* lay the ethernet structure over the packet data */
6864     p->sllh = (SLLHdr *) pkt;
6865 
6866     /* grab out the network type */
6867     switch(ntohs(p->sllh->sll_protocol))
6868     {
6869         case ETHERNET_TYPE_IP:
6870             DEBUG_WRAP(DebugMessage(DEBUG_DECODE,
6871                         "IP datagram size calculated to be %lu bytes\n",
6872                         (unsigned long)(cap_len - SLL_HDR_LEN)););
6873 
6874             DecodeIP(p->pkt + SLL_HDR_LEN, cap_len - SLL_HDR_LEN, p);
6875             PREPROC_PROFILE_END(decodePerfStats);
6876             return;
6877 
6878         case ETHERNET_TYPE_ARP:
6879         case ETHERNET_TYPE_REVARP:
6880             DecodeARP(p->pkt + SLL_HDR_LEN, cap_len - SLL_HDR_LEN, p);
6881             PREPROC_PROFILE_END(decodePerfStats);
6882             return;
6883 
6884         case ETHERNET_TYPE_IPV6:
6885             DecodeIPV6(p->pkt + SLL_HDR_LEN, (cap_len - SLL_HDR_LEN), p);
6886             PREPROC_PROFILE_END(decodePerfStats);
6887             return;
6888 
6889         case ETHERNET_TYPE_IPX:
6890             DecodeIPX(p->pkt + SLL_HDR_LEN, (cap_len - SLL_HDR_LEN), p);
6891             PREPROC_PROFILE_END(decodePerfStats);
6892             return;
6893 
6894         case LINUX_SLL_P_802_3:
6895             DEBUG_WRAP(DebugMessage(DEBUG_DATALINK,
6896                         "Linux SLL P 802.3 is not supported.\n"););
6897             // TBD add decoder drop event for unsupported linux sll p 802.3
6898             pc.other++;
6899             PREPROC_PROFILE_END(decodePerfStats);
6900             return;
6901 
6902         case LINUX_SLL_P_802_2:
6903             DEBUG_WRAP(DebugMessage(DEBUG_DATALINK,
6904                         "Linux SLL P 802.2 is not supported.\n"););
6905             // TBD add decoder drop event for unsupported linux sll p 802.2
6906             pc.other++;
6907             PREPROC_PROFILE_END(decodePerfStats);
6908             return;
6909 
6910         case ETHERNET_TYPE_8021Q:
6911             DecodeVlan(p->pkt + SLL_HDR_LEN, cap_len - SLL_HDR_LEN, p);
6912             PREPROC_PROFILE_END(decodePerfStats);
6913             return;
6914 
6915         default:
6916             /* shouldn't go here unless pcap library changes again */
6917             /* should be a DECODE generated alert */
6918             DEBUG_WRAP(DebugMessage(DEBUG_DATALINK,"(Unknown) %X is not supported. "
6919                         "(need tcpdump snapshots to test. Please contact us)\n",
6920                         p->sllh->sll_protocol););
6921             // TBD add decoder drop event for unknown sll encapsulation
6922             pc.other++;
6923             PREPROC_PROFILE_END(decodePerfStats);
6924             return;
6925     }
6926 
6927     PREPROC_PROFILE_END(decodePerfStats);
6928     return;
6929 }
6930 #endif /* DLT_LINUX_SLL */
6931 
6932 /*
6933  * Function: DecodeOldPflog(Packet *, DAQ_PktHdr_t *, uint8_t *)
6934  *
6935  * Purpose: Pass old pflog format device packets off to IP or IP6 -fleck
6936  *
6937  * Arguments: p => pointer to the decoded packet struct
6938  *            pkthdr => ptr to the packet header
6939  *            pkt => pointer to the packet data
6940  *
6941  * Returns: void function
6942  *
6943  */
DecodeOldPflog(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)6944 void DecodeOldPflog(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
6945 {
6946     uint32_t cap_len = pkthdr->caplen;
6947     PROFILE_VARS;
6948 
6949     PREPROC_PROFILE_START(decodePerfStats);
6950 
6951     pc.total_processed++;
6952 
6953     memset(p, 0, PKT_ZERO_LEN);
6954 
6955     p->pkth = pkthdr;
6956     p->pkt = pkt;
6957 
6958     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n");
6959             DebugMessage(DEBUG_DECODE, "caplen: %lu    pktlen: %lu\n",
6960                 (unsigned long)cap_len, (unsigned long)pkthdr->pktlen););
6961 
6962     /* do a little validation */
6963     if(cap_len < PFLOG1_HDRLEN)
6964     {
6965         if (ScLogVerbose())
6966         {
6967             ErrorMessage("Captured data length < Pflog header length! "
6968                     "(%d bytes)\n", cap_len);
6969         }
6970         PREPROC_PROFILE_END(decodePerfStats);
6971         return;
6972     }
6973 
6974     /* lay the pf header structure over the packet data */
6975     p->pf1h = (Pflog1Hdr*)pkt;
6976 
6977     /*  get the network type - should only be AF_INET or AF_INET6 */
6978     switch(ntohl(p->pf1h->af))
6979     {
6980         case AF_INET:   /* IPv4 */
6981             DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "IP datagram size calculated to be %lu "
6982                         "bytes\n", (unsigned long)(cap_len - PFLOG1_HDRLEN)););
6983 
6984             DecodeIP(p->pkt + PFLOG1_HDRLEN, cap_len - PFLOG1_HDRLEN, p);
6985             PREPROC_PROFILE_END(decodePerfStats);
6986             return;
6987 
6988 #if defined(AF_INET6)
6989         case AF_INET6:  /* IPv6 */
6990             DecodeIPV6(p->pkt + PFLOG1_HDRLEN, cap_len - PFLOG1_HDRLEN, p);
6991             PREPROC_PROFILE_END(decodePerfStats);
6992             return;
6993 #endif
6994 
6995         default:
6996             /* To my knowledge, pflog devices can only
6997              * pass IP and IP6 packets. -fleck
6998              */
6999             // TBD add decoder drop event for unknown old pflog network type
7000             pc.other++;
7001             PREPROC_PROFILE_END(decodePerfStats);
7002             return;
7003     }
7004 
7005     PREPROC_PROFILE_END(decodePerfStats);
7006     return;
7007 }
7008 
7009 /*
7010  * Function: DecodePflog(Packet *, DAQ_PktHdr_t *, uint8_t *)
7011  *
7012  * Purpose: Pass pflog device packets off to IP or IP6 -fleck
7013  *
7014  * Arguments: p => pointer to the decoded packet struct
7015  *            pkthdr => ptr to the packet header
7016  *            pkt => pointer to the packet data
7017  *
7018  * Returns: void function
7019  *
7020  */
DecodePflog(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7021 void DecodePflog(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
7022 {
7023     uint32_t cap_len = pkthdr->caplen;
7024     uint8_t af, pflen;
7025     uint32_t hlen;
7026     uint32_t padlen = PFLOG_PADLEN;
7027     PROFILE_VARS;
7028 
7029     PREPROC_PROFILE_START(decodePerfStats);
7030 
7031     pc.total_processed++;
7032 
7033     memset(p, 0, PKT_ZERO_LEN);
7034 
7035     p->pkth = pkthdr;
7036     p->pkt = pkt;
7037 
7038     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n");
7039             DebugMessage(DEBUG_DECODE, "caplen: %lu    pktlen: %lu\n",
7040                 (unsigned long)cap_len, (unsigned long)pkthdr->pktlen););
7041 
7042     /* do a little validation */
7043     if(cap_len < PFLOG2_HDRMIN)
7044     {
7045         if (ScLogVerbose())
7046         {
7047             ErrorMessage("Captured data length < minimum Pflog length! "
7048                     "(%d < %lu)\n", cap_len, (unsigned long)PFLOG2_HDRMIN);
7049         }
7050         PREPROC_PROFILE_END(decodePerfStats);
7051         return;
7052     }
7053 
7054     /* lay the pf header structure over the packet data */
7055     switch(*((uint8_t*)pkt))
7056     {
7057         case PFLOG2_HDRMIN:
7058             p->pf2h = (Pflog2Hdr*)pkt;
7059             pflen = p->pf2h->length;
7060             hlen = PFLOG2_HDRLEN;
7061             af = p->pf2h->af;
7062             break;
7063         case PFLOG3_HDRMIN:
7064             p->pf3h = (Pflog3Hdr*)pkt;
7065             pflen = p->pf3h->length;
7066             hlen = PFLOG3_HDRLEN;
7067             af = p->pf3h->af;
7068             break;
7069         case PFLOG4_HDRMIN:
7070             p->pf4h = (Pflog4Hdr*)pkt;
7071             pflen = p->pf4h->length;
7072             hlen = PFLOG4_HDRLEN;
7073             af = p->pf4h->af;
7074             padlen = sizeof(p->pf4h->pad);
7075             break;
7076         default:
7077             if (ScLogVerbose())
7078             {
7079                 ErrorMessage("unrecognized pflog header length! (%d)\n",
7080                     *((uint8_t*)pkt));
7081             }
7082             pc.discards++;
7083             PREPROC_PROFILE_END(decodePerfStats);
7084             return;
7085     }
7086 
7087     /* now that we know a little more, do a little more validation */
7088     if(cap_len < hlen)
7089     {
7090         if (ScLogVerbose())
7091         {
7092             ErrorMessage("Captured data length < Pflog header length! "
7093                     "(%d < %d)\n", cap_len, hlen);
7094         }
7095         pc.discards++;
7096         PREPROC_PROFILE_END(decodePerfStats);
7097         return;
7098     }
7099     /* note that the pflen may exclude the padding which is always present */
7100     if(pflen < hlen - padlen || pflen > hlen)
7101     {
7102         if (ScLogVerbose())
7103         {
7104             ErrorMessage("Bad Pflog header length! (%d bytes)\n", pflen);
7105         }
7106         pc.discards++;
7107         PREPROC_PROFILE_END(decodePerfStats);
7108         return;
7109     }
7110     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "IP datagram size calculated to be "
7111                 "%lu bytes\n", (unsigned long)(cap_len - hlen)););
7112 
7113     /* check the network type - should only be AF_INET or AF_INET6 */
7114     switch(af)
7115     {
7116         case AF_INET:   /* IPv4 */
7117             DecodeIP(p->pkt + hlen, cap_len - hlen, p);
7118             PREPROC_PROFILE_END(decodePerfStats);
7119             return;
7120 
7121 #if defined(AF_INET6)
7122         case AF_INET6:  /* IPv6 */
7123             DecodeIPV6(p->pkt + hlen, cap_len - hlen, p);
7124             PREPROC_PROFILE_END(decodePerfStats);
7125             return;
7126 #endif
7127 
7128         default:
7129             /* To my knowledge, pflog devices can only
7130              * pass IP and IP6 packets. -fleck
7131              */
7132             // TBD add decoder drop event for unknown pflog network type
7133             pc.other++;
7134             PREPROC_PROFILE_END(decodePerfStats);
7135             return;
7136     }
7137 
7138     PREPROC_PROFILE_END(decodePerfStats);
7139     return;
7140 }
7141 
7142 /*
7143  * Function: DecodePppPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
7144  *
7145  * Purpose: Decode PPP traffic (either RFC1661 or RFC1662 framing).
7146  *          This really is intended to handle IPCP
7147  *
7148  * Arguments: p => pointer to decoded packet struct
7149  *            user => Utility pointer, unused
7150  *            pkthdr => ptr to the packet header
7151  *            pkt => pointer to the real live packet data
7152  *
7153  * Returns: void function
7154  */
7155 // DecodePppPkt() and DecodePppSerialPkt() may be incorrect ...
7156 // both skip past 2 byte protocol and then call DecodePppPktEncapsulated()
7157 // which does the same thing.  That one works inside DecodePPPoEPkt();
DecodePppPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7158 void DecodePppPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
7159 {
7160     uint32_t cap_len = pkthdr->caplen;
7161     int hlen = 0;
7162     PROFILE_VARS;
7163 
7164     PREPROC_PROFILE_START(decodePerfStats);
7165 
7166     pc.total_processed++;
7167 
7168     memset(p, 0, PKT_ZERO_LEN);
7169 
7170     p->pkth = pkthdr;
7171     p->pkt = pkt;
7172 
7173     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
7174 
7175     if(cap_len < 2)
7176     {
7177         if (ScLogVerbose())
7178         {
7179             ErrorMessage("Length not big enough for even a single "
7180                          "header or a one byte payload\n");
7181         }
7182         PREPROC_PROFILE_END(decodePerfStats);
7183         return;
7184     }
7185 
7186     if(pkt[0] == CHDLC_ADDR_BROADCAST && pkt[1] == CHDLC_CTRL_UNNUMBERED)
7187     {
7188         /*
7189          * Check for full HDLC header (rfc1662 section 3.2)
7190          */
7191         hlen = 2;
7192     }
7193 
7194     DecodePppPktEncapsulated(p->pkt + hlen, cap_len - hlen, p);
7195 
7196     PREPROC_PROFILE_END(decodePerfStats);
7197     return;
7198 }
7199 
7200 /*
7201  * Function: DecodePppSerialPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
7202  *
7203  * Purpose: Decode Mixed PPP/CHDLC traffic. The PPP frames will always have the
7204  *          full HDLC header.
7205  *
7206  * Arguments: p => pointer to decoded packet struct
7207  *            user => Utility pointer, unused
7208  *            pkthdr => ptr to the packet header
7209  *            pkt => pointer to the real live packet data
7210  *
7211  * Returns: void function
7212  */
DecodePppSerialPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7213 void DecodePppSerialPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
7214 {
7215     uint32_t cap_len = pkthdr->caplen;
7216     PROFILE_VARS;
7217 
7218     PREPROC_PROFILE_START(decodePerfStats);
7219 
7220     pc.total_processed++;
7221 
7222     memset(p, 0, PKT_ZERO_LEN);
7223 
7224     p->pkth = pkthdr;
7225     p->pkt = pkt;
7226 
7227     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
7228 
7229     if(cap_len < PPP_HDRLEN)
7230     {
7231         if (ScLogVerbose())
7232         {
7233             ErrorMessage("Captured data length < PPP header length"
7234                          " (%d bytes)\n", cap_len);
7235         }
7236         PREPROC_PROFILE_END(decodePerfStats);
7237         return;
7238     }
7239 
7240     if(pkt[0] == CHDLC_ADDR_BROADCAST && pkt[1] == CHDLC_CTRL_UNNUMBERED)
7241     {
7242         DecodePppPktEncapsulated(p->pkt + 2, cap_len - 2, p);
7243     } else {
7244         DecodeChdlcPkt(p, pkthdr, pkt);
7245     }
7246 
7247     PREPROC_PROFILE_END(decodePerfStats);
7248     return;
7249 }
7250 
7251 
7252 /*
7253  * Function: DecodeSlipPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
7254  *
7255  * Purpose: Decode SLIP traffic
7256  *
7257  * Arguments: p => pointer to decoded packet struct
7258  *            user => Utility pointer, unused
7259  *            pkthdr => ptr to the packet header
7260  *            pkt => pointer to the real live packet data
7261  *
7262  * Returns: void function
7263  */
DecodeSlipPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7264 void DecodeSlipPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
7265 {
7266     uint32_t cap_len = pkthdr->caplen;
7267     PROFILE_VARS;
7268 
7269     PREPROC_PROFILE_START(decodePerfStats);
7270 
7271     pc.total_processed++;
7272 
7273     memset(p, 0, PKT_ZERO_LEN);
7274 
7275     p->pkth = pkthdr;
7276     p->pkt = pkt;
7277 
7278     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
7279 
7280     /* do a little validation */
7281     if(cap_len < SLIP_HEADER_LEN)
7282     {
7283         ErrorMessage("SLIP header length < captured len! (%d bytes)\n",
7284                      cap_len);
7285         PREPROC_PROFILE_END(decodePerfStats);
7286         return;
7287     }
7288 
7289     DecodeIP(p->pkt + SLIP_HEADER_LEN, cap_len - SLIP_HEADER_LEN, p);
7290     PREPROC_PROFILE_END(decodePerfStats);
7291 }
7292 
7293 /*
7294  * Function: DecodeI4LRawIPPkt(Packet *, char *, DAQ_PktHdr_t*, uint8_t*)
7295  *
7296  * Purpose: Decodes packets coming in raw on layer 2, like PPP.  Coded and
7297  *          in by Jed Pickle (thanks Jed!) and modified for a few little tweaks
7298  *          by me.
7299  *
7300  * Arguments: p => pointer to decoded packet struct
7301  *            user => Utility pointer, unused
7302  *            pkthdr => ptr to the packet header
7303  *            pkt => pointer to the real live packet data
7304  *
7305  * Returns: void function
7306  */
DecodeI4LRawIPPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7307 void DecodeI4LRawIPPkt(Packet * p, const DAQ_PktHdr_t * pkthdr, const uint8_t * pkt)
7308 {
7309     PROFILE_VARS;
7310 
7311     PREPROC_PROFILE_START(decodePerfStats);
7312 
7313     pc.total_processed++;
7314 
7315     memset(p, 0, PKT_ZERO_LEN);
7316 
7317     p->pkth = pkthdr;
7318     p->pkt = pkt;
7319 
7320     if(p->pkth->pktlen < 2)
7321     {
7322         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "What the hell is this?\n"););
7323         // TBD add decoder drop event for bad i4l raw pkt
7324         pc.other++;
7325         PREPROC_PROFILE_END(decodePerfStats);
7326         return;
7327     }
7328 
7329     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
7330     DecodeIP(pkt + 2, p->pkth->pktlen - 2, p);
7331 
7332     PREPROC_PROFILE_END(decodePerfStats);
7333     return;
7334 }
7335 
7336 
7337 
7338 /*
7339  * Function: DecodeI4LCiscoIPPkt(Packet *, char *,
7340  *                               DAQ_PktHdr_t*, uint8_t*)
7341  *
7342  * Purpose: Decodes packets coming in raw on layer 2, like PPP.  Coded and
7343  *          in by Jed Pickle (thanks Jed!) and modified for a few little tweaks
7344  *          by me.
7345  *
7346  * Arguments: p => pointer to decoded packet struct
7347  *            user => Utility pointer, unused
7348  *            pkthdr => ptr to the packet header
7349  *            pkt => pointer to the real live packet data
7350  *
7351  * Returns: void function
7352  */
DecodeI4LCiscoIPPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7353 void DecodeI4LCiscoIPPkt(Packet *p, const DAQ_PktHdr_t *pkthdr, const uint8_t *pkt)
7354 {
7355     PROFILE_VARS;
7356 
7357     PREPROC_PROFILE_START(decodePerfStats);
7358 
7359     pc.total_processed++;
7360 
7361     memset(p, 0, PKT_ZERO_LEN);
7362 
7363     p->pkth = pkthdr;
7364     p->pkt = pkt;
7365 
7366     if(p->pkth->pktlen < 4)
7367     {
7368         DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "What the hell is this?\n"););
7369         // TBD add decoder drop event for bad i4l cisco pkt
7370         pc.other++;
7371         PREPROC_PROFILE_END(decodePerfStats);
7372         return;
7373     }
7374 
7375 
7376     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
7377 
7378     DecodeIP(pkt + 4, p->pkth->caplen - 4, p);
7379 
7380     PREPROC_PROFILE_END(decodePerfStats);
7381     return;
7382 }
7383 
7384 /*
7385  * Function: DecodeChdlcPkt(Packet *, char *,
7386  *                               DAQ_PktHdr_t*, uint8_t*)
7387  *
7388  * Purpose: Decodes Cisco HDLC encapsulated packets, f.ex. from SONET.
7389  *
7390  * Arguments: p => pointer to decoded packet struct
7391  *            user => Utility pointer, unused
7392  *            pkthdr => ptr to the packet header
7393  *            pkt => pointer to the real live packet data
7394  *
7395  * Returns: void function
7396  */
DecodeChdlcPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7397 void DecodeChdlcPkt(Packet *p, const DAQ_PktHdr_t *pkthdr, const uint8_t *pkt)
7398 {
7399     uint32_t cap_len = pkthdr->caplen;
7400     PROFILE_VARS;
7401 
7402     PREPROC_PROFILE_START(decodePerfStats);
7403 
7404     pc.total_processed++;
7405 
7406     memset(p, 0, PKT_ZERO_LEN);
7407 
7408     p->pkth = pkthdr;
7409     p->pkt = pkt;
7410 
7411     if(cap_len < CHDLC_HEADER_LEN)
7412     {
7413         if (ScLogVerbose())
7414         {
7415             ErrorMessage("Captured data length < CHDLC header length"
7416                          " (%d bytes)\n", cap_len);
7417         }
7418         PREPROC_PROFILE_END(decodePerfStats);
7419         return;
7420     }
7421 
7422     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "Packet!\n"););
7423 
7424     if ((pkt[0] == CHDLC_ADDR_UNICAST || pkt[0] == CHDLC_ADDR_MULTICAST) &&
7425     		ntohs(*(uint16_t *)&pkt[2]) == ETHERNET_TYPE_IP)
7426     {
7427         DecodeIP(p->pkt + CHDLC_HEADER_LEN,
7428                  cap_len - CHDLC_HEADER_LEN, p);
7429     } else {
7430         // TBD add decoder drop event for unsupported chdlc encapsulation
7431         pc.other++;
7432     }
7433 
7434     PREPROC_PROFILE_END(decodePerfStats);
7435     return;
7436 }
7437 
7438 /*
7439  * Function: DecodeEapol(uint8_t *, uint32_t, Packet *)
7440  *
7441  * Purpose: Decode 802.1x eapol stuff
7442  *
7443  * Arguments: pkt => ptr to the packet data
7444  *            len => length from here to the end of the packet
7445  *            p   => pointer to decoded packet struct
7446  *
7447  * Returns: void function
7448  */
DecodeEapol(const uint8_t * pkt,uint32_t len,Packet * p)7449 void DecodeEapol(const uint8_t * pkt, uint32_t len, Packet * p)
7450 {
7451     p->eplh = (EtherEapol *) pkt;
7452     pc.eapol++;
7453     if(len < sizeof(EtherEapol))
7454     {
7455         DecoderEvent(p, DECODE_EAPOL_TRUNCATED,
7456                         DECODE_EAPOL_TRUNCATED_STR, 1, 1);
7457 
7458         pc.discards++;
7459         return;
7460     }
7461     if (p->eplh->eaptype == EAPOL_TYPE_EAP) {
7462         DecodeEAP(pkt + sizeof(EtherEapol), len - sizeof(EtherEapol), p);
7463     }
7464     else if(p->eplh->eaptype == EAPOL_TYPE_KEY) {
7465         DecodeEapolKey(pkt + sizeof(EtherEapol), len - sizeof(EtherEapol), p);
7466     }
7467     return;
7468 }
7469 
7470 /*
7471  * Function: DecodeEapolKey(uint8_t *, uint32_t, Packet *)
7472  *
7473  * Purpose: Decode 1x key setup
7474  *
7475  * Arguments: pkt => ptr to the packet data
7476  *            len => length from here to the end of the packet
7477  *            p   => pointer to decoded packet struct
7478  *
7479  * Returns: void function
7480  */
DecodeEapolKey(const uint8_t * pkt,uint32_t len,Packet * p)7481 void DecodeEapolKey(const uint8_t * pkt, uint32_t len, Packet * p)
7482 {
7483     p->eapolk = (EapolKey *) pkt;
7484     if(len < sizeof(EapolKey))
7485     {
7486         DecoderEvent(p, DECODE_EAPKEY_TRUNCATED,
7487                         DECODE_EAPKEY_TRUNCATED_STR, 1, 1);
7488 
7489         pc.discards++;
7490         return;
7491     }
7492 
7493     return;
7494 }
7495 
7496 /*
7497  * Function: DecodeEAP(uint8_t *, uint32_t, Packet *)
7498  *
7499  * Purpose: Decode Extensible Authentication Protocol
7500  *
7501  * Arguments: pkt => ptr to the packet data
7502  *            len => length from here to the end of the packet
7503  *            p   => pointer to decoded packet struct
7504  *
7505  * Returns: void function
7506  */
DecodeEAP(const uint8_t * pkt,const uint32_t len,Packet * p)7507 void DecodeEAP(const uint8_t * pkt, const uint32_t len, Packet * p)
7508 {
7509     p->eaph = (EAPHdr *) pkt;
7510     if(len < sizeof(EAPHdr))
7511     {
7512         DecoderEvent(p, DECODE_EAP_TRUNCATED,
7513                         DECODE_EAP_TRUNCATED_STR, 1, 1);
7514 
7515         pc.discards++;
7516         return;
7517     }
7518     if (p->eaph->code == EAP_CODE_REQUEST ||
7519             p->eaph->code == EAP_CODE_RESPONSE) {
7520         p->eaptype = pkt + sizeof(EAPHdr);
7521     }
7522     return;
7523 }
7524 
7525 /*
7526  * Function: DecodeIPX(uint8_t *, uint32_t)
7527  *
7528  * Purpose: Well, it doesn't do much of anything right now...
7529  *
7530  * Arguments: pkt => ptr to the packet data
7531  *            len => length from here to the end of the packet
7532  *
7533  * Returns: void function
7534  *
7535  */
DecodeIPX(const uint8_t * pkt,uint32_t len,Packet * p)7536 void DecodeIPX(const uint8_t *pkt, uint32_t len, Packet *p)
7537 {
7538     DEBUG_WRAP(DebugMessage(DEBUG_DECODE, "IPX is not supported.\n"););
7539 
7540     pc.ipx++;
7541 
7542 #ifdef GRE
7543     if (p->greh != NULL)
7544         pc.gre_ipx++;
7545 #endif
7546 
7547     return;
7548 }
7549 
7550 #ifdef DLT_ENC
7551 /* see http://sourceforge.net/mailarchive/message.php?msg_id=1000380 */
7552 /*
7553  * Function: DecodeEncPkt(Packet *, DAQ_PktHdr_t *, uint8_t *)
7554  *
7555  * Purpose: Decapsulate packets of type DLT_ENC.
7556  *          XXX Are these always going to be IP in IP?
7557  *
7558  * Arguments: p => pointer to decoded packet struct
7559  *            pkthdr => pointer to the packet header
7560  *            pkt => pointer to the real live packet data
7561  */
DecodeEncPkt(Packet * p,const DAQ_PktHdr_t * pkthdr,const uint8_t * pkt)7562 void DecodeEncPkt(Packet *p, const DAQ_PktHdr_t *pkthdr, const uint8_t *pkt)
7563 {
7564     uint32_t cap_len = pkthdr->caplen;
7565     struct enc_header *enc_h;
7566     PROFILE_VARS;
7567 
7568     PREPROC_PROFILE_START(decodePerfStats);
7569 
7570     pc.total_processed++;
7571 
7572     memset(p, 0, PKT_ZERO_LEN);
7573     p->pkth = pkthdr;
7574     p->pkt = pkt;
7575 
7576     if (cap_len < ENC_HEADER_LEN)
7577     {
7578         if (ScLogVerbose())
7579         {
7580             ErrorMessage("Captured data length < Encap header length!  (%d bytes)\n",
7581                 cap_len);
7582         }
7583         PREPROC_PROFILE_END(decodePerfStats);
7584         return;
7585     }
7586 
7587     enc_h = (struct enc_header *)p->pkt;
7588     if (enc_h->af == AF_INET)
7589     {
7590         DecodeIP(p->pkt + ENC_HEADER_LEN + IP_HEADER_LEN,
7591                  cap_len - ENC_HEADER_LEN - IP_HEADER_LEN, p);
7592     }
7593     else
7594     {
7595         ErrorMessage("WARNING: Unknown address family (af: 0x%x).\n",
7596                 enc_h->af);
7597     }
7598     PREPROC_PROFILE_END(decodePerfStats);
7599     return;
7600 }
7601 #endif /* DLT_ENC */
7602 
7603 #endif  // NO_NON_ETHER_DECODER
7604 
7605