create_dissector_handle -> new_create_dissector_handle
[metze/wireshark/wip.git] / epan / dissectors / packet-ipsec.c
1 /* packet-ipsec.c
2  * Routines for IPsec/IPComp packet disassembly
3  *
4  * Wireshark - Network traffic analyzer
5  * By Gerald Combs <gerald@wireshark.org>
6  * Copyright 1998 Gerald Combs
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23
24 /*
25
26 Addon: ESP Decryption and Authentication Checking
27
28 Frederic ROUDAUT (frederic.roudaut@free.fr)
29 Copyright 2006 Frederic ROUDAUT
30
31 - Decrypt ESP Payload for the following Algorithms defined in RFC 4305:
32
33 Encryption Algorithm
34 --------------------
35 NULL
36 TripleDES-CBC [RFC2451] : keylen 192 bits.
37 AES-CBC with 128-bit keys [RFC3602] : keylen 128 and 192/256 bits.
38 AES-CTR [RFC3686] : keylen 160/224/288 bits. The remaining 32 bits will be used as nonce.
39 DES-CBC [RFC2405] : keylen 64 bits
40
41 - Add ESP Payload Decryption support for the following Encryption Algorithms :
42 BLOWFISH-CBC : keylen 128 bits.
43 TWOFISH-CBC : keylen 128/256 bits.
44 CAST5-CBC :  keylen 128
45
46 - Check ESP Authentication for the following Algorithms defined in RFC 4305:
47
48 Authentication Algorithm
49 ------------------------
50 NULL
51 HMAC-SHA1-96 [RFC2404] : any keylen
52 HMAC-MD5-96 [RFC2403] : any keylen
53 AES-XCBC-MAC-96 [RFC3566] : Not available because no implementation found.
54
55 - Add ESP Authentication checking for the following Authentication Algorithm :
56 HMAC-SHA256 : any keylen
57 HMAC-RIPEMD160-96 [RFC2857] : any keylen
58
59 - Added/Modified Authentication checking (David Dahlberg <dahlberg@fgan.de>):
60 CHG: HMAC-SHA256 is now HMAC-SHA-256-96 [draft-ietf-ipsec-ciph-sha-256-00]
61      -> It is implemented this way in USAGI/KAME (Linux/BSD).
62 ADD: HMAC-SHA-256-128 [RFC4868]
63      ICV length of HMAC-SHA-256 was changed in draft-ietf-ipsec-ciph-sha-256-01
64      to 128 bit. This is "SHOULD" be the standard now!
65 ADD: Additional generic (non-checked) ICV length of 128, 192 and 256.
66      This follows RFC 4868 for the SHA-256+ family.
67
68 */
69
70 #include "config.h"
71
72
73 #include <epan/packet.h>
74 #include <epan/addr_resolv.h>
75 #include <epan/ipproto.h>
76 #include <epan/prefs.h>
77 #include <epan/expert.h>
78 #include <epan/tap.h>
79 #include <epan/exported_pdu.h>
80
81 /* If you want to be able to decrypt or Check Authentication of ESP packets you MUST define this : */
82 #ifdef HAVE_LIBGCRYPT
83 #include <stdio.h>
84 #include <epan/uat.h>
85 #include <wsutil/wsgcrypt.h>
86 #endif /* HAVE_LIBGCRYPT */
87
88 #include "packet-ipsec.h"
89
90 void proto_register_ipsec(void);
91 void proto_reg_handoff_ipsec(void);
92
93 static int proto_ah = -1;
94 static int hf_ah_next_header = -1;
95 static int hf_ah_length = -1;
96 static int hf_ah_spi = -1;
97 static int hf_ah_iv = -1;
98 static int hf_ah_sequence = -1;
99 static int proto_esp = -1;
100 static int hf_esp_spi = -1;
101 static int hf_esp_iv = -1;
102 static int hf_esp_icv_good = -1;
103 static int hf_esp_icv_bad = -1;
104 static int hf_esp_sequence = -1;
105 static int hf_esp_pad = -1;
106 static int hf_esp_pad_len = -1;
107 static int hf_esp_protocol = -1;
108 static int hf_esp_authentication_data = -1;
109 static int hf_esp_sequence_analysis_expected_sn = -1;
110 static int hf_esp_sequence_analysis_previous_frame = -1;
111
112 static int proto_ipcomp = -1;
113 static int hf_ipcomp_next_header = -1;
114 static int hf_ipcomp_flags = -1;
115 static int hf_ipcomp_cpi = -1;
116
117 static gint ett_ah = -1;
118 static gint ett_esp = -1;
119 static gint ett_esp_icv = -1;
120 static gint ett_ipcomp = -1;
121
122 static expert_field ei_esp_sequence_analysis_wrong_sequence_number = EI_INIT;
123
124
125 static gint exported_pdu_tap = -1;
126
127 static dissector_handle_t data_handle;
128
129 static dissector_table_t ip_dissector_table;
130
131 #ifdef  HAVE_LIBGCRYPT
132 /* Encryption algorithms defined in RFC 4305 */
133 #define IPSEC_ENCRYPT_NULL 0
134 #define IPSEC_ENCRYPT_3DES_CBC 1
135 #define IPSEC_ENCRYPT_AES_CBC 2
136 #define IPSEC_ENCRYPT_AES_CTR 3
137 #define IPSEC_ENCRYPT_DES_CBC 4
138 #define IPSEC_ENCRYPT_BLOWFISH_CBC 5
139 #define IPSEC_ENCRYPT_TWOFISH_CBC 6
140
141 /* Encryption algorithm defined in RFC 2144 */
142 #define IPSEC_ENCRYPT_CAST5_CBC 7
143
144 /* Encryption algorithm defined in RFC 4106 */
145 #define IPSEC_ENCRYPT_AES_GCM 8
146
147 /* Authentication algorithms defined in RFC 4305 */
148 #define IPSEC_AUTH_NULL 0
149 #define IPSEC_AUTH_HMAC_SHA1_96 1
150 #define IPSEC_AUTH_HMAC_SHA256_96 2
151 #define IPSEC_AUTH_HMAC_SHA256_128 3
152 #define IPSEC_AUTH_HMAC_SHA384_192 4
153 #define IPSEC_AUTH_HMAC_SHA512_256 5
154 #define IPSEC_AUTH_HMAC_MD5_96 6
155 #define IPSEC_AUTH_HMAC_RIPEMD160_96 7
156 /* define IPSEC_AUTH_AES_XCBC_MAC_96 6 */
157 #define IPSEC_AUTH_ANY_64BIT 8
158 #define IPSEC_AUTH_ANY_96BIT 9
159 #define IPSEC_AUTH_ANY_128BIT 10
160 #define IPSEC_AUTH_ANY_192BIT 11
161 #define IPSEC_AUTH_ANY_256BIT 12
162
163 #define IPSEC_IPV6_ADDR_LEN 128
164 #define IPSEC_IPV4_ADDR_LEN 32
165 #define IPSEC_STRLEN_IPV6 32
166 #define IPSEC_STRLEN_IPV4 8
167 #define IPSEC_SA_IPV4 1
168 #define IPSEC_SA_IPV6 2
169 #define IPSEC_SA_UNKNOWN -1
170 #define IPSEC_SA_WILDCARDS_ANY '*'
171 /* the maximum number of bytes (10)(including the terminating nul character(11)) */
172 #define IPSEC_SPI_LEN_MAX 11
173
174 #endif
175
176 /* well-known algorithm number (in CPI), from RFC2409 */
177 #define IPCOMP_OUI      1       /* vendor specific */
178 #define IPCOMP_DEFLATE  2       /* RFC2394 */
179 #define IPCOMP_LZS      3       /* RFC2395 */
180 #define IPCOMP_MAX      4
181
182
183 static const value_string cpi2val[] = {
184   { IPCOMP_OUI, "OUI" },
185   { IPCOMP_DEFLATE, "DEFLATE" },
186   { IPCOMP_LZS, "LZS" },
187   { 0, NULL },
188 };
189
190 struct newah {
191   guint8        ah_nxt;         /* Next Header */
192   guint8        ah_len;         /* Length of data + 1, in 32bit */
193   guint16       ah_reserve;     /* Reserved for future use */
194   guint32       ah_spi;         /* Security parameter index */
195   guint32       ah_seq;         /* Sequence number field */
196   /* variable size, 32bit bound*/       /* Authentication data */
197 };
198
199 struct newesp {
200   guint32       esp_spi;        /* ESP */
201   guint32       esp_seq;        /* Sequence number */
202   /*variable size*/             /* (IV and) Payload data */
203   /*variable size*/             /* padding */
204   /*8bit*/                      /* pad size */
205   /*8bit*/                      /* next header */
206   /*8bit*/                      /* next header */
207   /*variable size, 32bit bound*/        /* Authentication data */
208 };
209
210 struct ipcomp {
211   guint8 comp_nxt;      /* Next Header */
212   guint8 comp_flags;    /* Must be zero */
213   guint16 comp_cpi;     /* Compression parameter index */
214 };
215
216 struct ah_header_data {
217   proto_tree *next_tree;
218   guint8 nxt;               /* Next Header */
219 };
220
221 #ifdef HAVE_LIBGCRYPT
222 /*-------------------------------------
223  * UAT for ESP
224  *-------------------------------------
225  */
226 /* UAT entry structure. */
227 typedef struct {
228   guint8 protocol;
229   gchar *srcIP;
230   gchar *dstIP;
231   gchar *spi;
232
233   guint8 encryption_algo;
234   gchar *encryption_key_string;
235   gchar *encryption_key;
236   gint encryption_key_length;
237   gboolean         cipher_hd_created;
238   gcry_cipher_hd_t cipher_hd;     /* Key is stored here and closed with the SA */
239
240   guint8 authentication_algo;
241   gchar *authentication_key_string;
242   gchar *authentication_key;
243   gint authentication_key_length;
244 } uat_esp_sa_record_t;
245
246 static uat_esp_sa_record_t *uat_esp_sa_records = NULL;
247
248 /* Extra SA records that may be set programmatically */
249 /* 'records' array is now allocated on the heap */
250 #define MAX_EXTRA_SA_RECORDS 16
251 typedef struct extra_esp_sa_records_t {
252   guint num_records;
253   uat_esp_sa_record_t *records;
254 } extra_esp_sa_records_t;
255 static extra_esp_sa_records_t extra_esp_sa_records;
256
257 static uat_t * esp_uat = NULL;
258 static guint num_sa_uat = 0;
259
260 /*
261    Name : static gint compute_ascii_key(gchar **ascii_key, gchar *key)
262    Description : Allocate memory for the key and transform the key if it is hexadecimal
263    Return : Return the key length
264    Params:
265       - gchar **ascii_key : the resulting ascii key allocated here
266       - gchar *key : the key to compute
267 */
268 static gint
269 compute_ascii_key(gchar **ascii_key, const gchar *key)
270 {
271   guint key_len = 0;
272   gint hex_digit;
273   guchar key_byte;
274   guint i, j;
275
276   if(key != NULL)
277   {
278     if((strlen(key) > 2) && (key[0] == '0') && ((key[1] == 'x') || (key[1] == 'X')))
279     {
280       /*
281        * Key begins with "0x" or "0X"; skip that and treat the rest
282        * as a sequence of hex digits.
283        */
284       i = 2;    /* first character after "0[Xx]" */
285       j = 0;
286       if(strlen(key) %2  == 1)
287       {
288         /*
289          * Key has an odd number of characters; we act as if the
290          * first character had a 0 in front of it, making the
291          * number of characters even.
292          */
293         key_len = ((guint) strlen(key) - 2) / 2 + 1;
294         *ascii_key = (gchar *) g_malloc ((key_len + 1)* sizeof(gchar));
295         hex_digit = g_ascii_xdigit_value(key[i]);
296         i++;
297         if (hex_digit == -1)
298         {
299           g_free(*ascii_key);
300           *ascii_key = NULL;
301           return -1;    /* not a valid hex digit */
302         }
303         (*ascii_key)[j] = (guchar)hex_digit;
304         j++;
305       }
306       else
307       {
308         /*
309          * Key has an even number of characters, so we treat each
310          * pair of hex digits as a single byte value.
311          */
312         key_len = ((guint) strlen(key) - 2) / 2;
313         *ascii_key = (gchar *) g_malloc ((key_len + 1)* sizeof(gchar));
314       }
315
316       while(i < (strlen(key) -1))
317       {
318         hex_digit = g_ascii_xdigit_value(key[i]);
319         i++;
320         if (hex_digit == -1)
321         {
322           g_free(*ascii_key);
323           *ascii_key = NULL;
324           return -1;    /* not a valid hex digit */
325         }
326         key_byte = ((guchar)hex_digit) << 4;
327         hex_digit = g_ascii_xdigit_value(key[i]);
328         i++;
329         if (hex_digit == -1)
330         {
331           g_free(*ascii_key);
332           *ascii_key = NULL;
333           return -1;    /* not a valid hex digit */
334         }
335         key_byte |= (guchar)hex_digit;
336         (*ascii_key)[j] = key_byte;
337         j++;
338       }
339       (*ascii_key)[j] = '\0';
340     }
341
342     else if((strlen(key) == 2) && (key[0] == '0') && ((key[1] == 'x') || (key[1] == 'X')))
343     {
344       return 0;
345     }
346     else
347     {
348       key_len = (guint) strlen(key);
349       *ascii_key = g_strdup(key);
350     }
351   }
352
353   return key_len;
354 }
355
356
357 static gboolean uat_esp_sa_record_update_cb(void* r, char** err _U_) {
358   uat_esp_sa_record_t* rec = (uat_esp_sa_record_t *)r;
359
360   /* Compute keys & lengths once and for all */
361   if (rec->encryption_key_string) {
362     rec->encryption_key_length = compute_ascii_key(&rec->encryption_key, rec->encryption_key_string);
363     rec->cipher_hd_created = FALSE;
364   }
365   else {
366     rec->encryption_key_length = 0;
367     rec->encryption_key = NULL;
368   }
369
370   if (rec->authentication_key_string) {
371     rec->authentication_key_length = compute_ascii_key(&rec->authentication_key, rec->authentication_key_string);
372   }
373   else {
374     rec->authentication_key_length = 0;
375     rec->authentication_key = NULL;
376   }
377   return TRUE;
378 }
379
380 static void* uat_esp_sa_record_copy_cb(void* n, const void* o, size_t siz _U_) {
381   uat_esp_sa_record_t* new_rec = (uat_esp_sa_record_t *)n;
382   const uat_esp_sa_record_t* old_rec = (const uat_esp_sa_record_t *)o;
383
384   /* Copy UAT fields */
385   new_rec->srcIP = (old_rec->srcIP) ? g_strdup(old_rec->srcIP) : NULL;
386   new_rec->dstIP = (old_rec->dstIP) ? g_strdup(old_rec->dstIP) : NULL;
387   new_rec->spi = (old_rec->spi) ? g_strdup(old_rec->spi) : NULL;
388   new_rec->encryption_key_string = (old_rec->encryption_key_string) ? g_strdup(old_rec->encryption_key_string) : NULL;
389   new_rec->authentication_key_string = (old_rec->authentication_key_string) ? g_strdup(old_rec->authentication_key_string) : NULL;
390
391   /* Parse keys as in an update */
392   uat_esp_sa_record_update_cb(new_rec, NULL);
393
394   return new_rec;
395 }
396
397 static void uat_esp_sa_record_free_cb(void*r) {
398   uat_esp_sa_record_t* rec = (uat_esp_sa_record_t*)r;
399
400   g_free(rec->srcIP);
401   g_free(rec->dstIP);
402   g_free(rec->spi);
403   g_free(rec->encryption_key_string);
404   g_free(rec->encryption_key);
405   g_free(rec->authentication_key_string);
406   g_free(rec->authentication_key);
407
408   if (rec->cipher_hd_created) {
409     gcry_cipher_close(rec->cipher_hd);
410     rec->cipher_hd_created = FALSE;
411   }
412 }
413
414 UAT_VS_DEF(uat_esp_sa_records, protocol, uat_esp_sa_record_t, guint8, IPSEC_SA_IPV4, "IPv4")
415 UAT_CSTRING_CB_DEF(uat_esp_sa_records, srcIP, uat_esp_sa_record_t)
416 UAT_CSTRING_CB_DEF(uat_esp_sa_records, dstIP, uat_esp_sa_record_t)
417 UAT_CSTRING_CB_DEF(uat_esp_sa_records, spi, uat_esp_sa_record_t)
418 UAT_VS_DEF(uat_esp_sa_records, encryption_algo, uat_esp_sa_record_t, guint8, 0, "FIXX")
419 UAT_CSTRING_CB_DEF(uat_esp_sa_records, encryption_key_string, uat_esp_sa_record_t)
420 UAT_VS_DEF(uat_esp_sa_records, authentication_algo, uat_esp_sa_record_t, guint8, 0, "FIXX")
421 UAT_CSTRING_CB_DEF(uat_esp_sa_records, authentication_key_string, uat_esp_sa_record_t)
422
423
424 /* Configure a new SA (programmatically, most likely from a private dissector).
425    The arugments here are deliberately in the same string formats as the UAT fields
426    in order to keep code paths common.
427    Note that an attempt to match with these entries will be made *before* entries
428    added through the UAT entry interface/file. */
429 void esp_sa_record_add_from_dissector(guint8 protocol, const gchar *srcIP, const char *dstIP,
430                                       gchar *spi,
431                                       guint8 encryption_algo, const gchar *encryption_key,
432                                       guint8 authentication_algo, const gchar *authentication_key)
433 {
434    uat_esp_sa_record_t* record = NULL;
435    if (extra_esp_sa_records.num_records == 0) {
436       extra_esp_sa_records.records = (uat_esp_sa_record_t *)g_malloc(sizeof(uat_esp_sa_record_t)*MAX_EXTRA_SA_RECORDS);
437    }
438    if (extra_esp_sa_records.num_records < MAX_EXTRA_SA_RECORDS) {
439       record = &extra_esp_sa_records.records[extra_esp_sa_records.num_records++];
440    }
441    else {
442       /* No room left!! */
443       fprintf(stderr, "<IPsec/ESP Dissector> Failed to add UE as already have max (%d) configured\n",
444               MAX_EXTRA_SA_RECORDS);
445       return;
446    }
447
448    /* Copy key fields */
449    record->protocol = protocol;
450    record->srcIP = g_strdup(srcIP);
451    record->dstIP = g_strdup(dstIP);
452    record->spi = g_strdup(spi);
453
454    /* Encryption */
455    record->encryption_algo = encryption_algo;
456    record->encryption_key_string = g_strdup(encryption_key);
457
458    /* Authentication */
459    record->authentication_algo = authentication_algo;
460    if (authentication_key) {
461       record->authentication_key_string = g_strdup(authentication_key);
462    }
463    else {
464       record->authentication_key_string = NULL;
465    }
466
467    /* Parse keys */
468    uat_esp_sa_record_update_cb(record, NULL);
469 }
470
471 /*************************************/
472 /* Preference settings               */
473
474 /* Default ESP payload decode to off */
475 static gboolean g_esp_enable_encryption_decode = FALSE;
476
477 /* Default ESP payload Authentication Checking to off */
478 static gboolean g_esp_enable_authentication_check = FALSE;
479 #endif
480
481 /**************************************************/
482 /* Sequence number analysis                       */
483
484 /* SPI state, key is just 32-bit SPI */
485 typedef struct
486 {
487     guint32  previousSequenceNumber;
488     guint32  previousFrameNum;
489 } spi_status;
490
491 /* The sequence analysis SPI hash table.
492    Maps SPI -> spi_status */
493 static GHashTable *esp_sequence_analysis_hash = NULL;
494
495 /* Equal keys */
496 static gint word_equal(gconstpointer v, gconstpointer v2)
497 {
498     /* Key fits in 4 bytes, so just compare pointers! */
499     return (v == v2);
500 }
501
502 /* Compute a hash value for a given key. */
503 static guint word_hash_func(gconstpointer v)
504 {
505     /* Just use pointer, as the fields are all in this value */
506     return GPOINTER_TO_UINT(v);
507 }
508
509 /* Results are stored here: framenum -> spi_status */
510 /* N.B. only store entries for out-of-order frames, if there is no entry for
511    a given frame, it was found to be in-order */
512 static GHashTable *esp_sequence_analysis_report_hash = NULL;
513
514 /* During the first pass, update the SPI state.  If the sequence numbers
515    are out of order, add an entry to the report table */
516 static void check_esp_sequence_info(guint32 spi, guint32 sequence_number, packet_info *pinfo)
517 {
518   /* Do the table lookup */
519   spi_status *status = (spi_status*)g_hash_table_lookup(esp_sequence_analysis_hash,
520                                                         GUINT_TO_POINTER((guint)spi));
521   if (status == NULL) {
522     /* Create an entry for this SPI */
523     status = wmem_new0(wmem_file_scope(), spi_status);
524     status->previousSequenceNumber = sequence_number;
525     status->previousFrameNum = pinfo->fd->num;
526
527     /* And add it to the table */
528     g_hash_table_insert(esp_sequence_analysis_hash, GUINT_TO_POINTER((guint)spi), status);
529   }
530   else {
531     spi_status *frame_status;
532
533     /* Entry already existed, so check that we got the sequence number we expected. */
534     if (sequence_number != status->previousSequenceNumber+1) {
535       /* Create report entry */
536       frame_status = wmem_new0(wmem_file_scope(), spi_status);
537       /* Copy what was expected */
538       *frame_status = *status;
539       /* And add it into the report table */
540       g_hash_table_insert(esp_sequence_analysis_report_hash, GUINT_TO_POINTER(pinfo->fd->num), frame_status);
541     }
542     /* Adopt this setting as 'current' regardless of whether expected */
543     status->previousSequenceNumber = sequence_number;
544     status->previousFrameNum = pinfo->fd->num;
545   }
546 }
547
548 /* Check to see if there is a report stored for this frame.  If there is,
549    add it to the tree and report using expert info */
550 static void show_esp_sequence_info(guint32 spi, guint32 sequence_number,
551                                    tvbuff_t *tvb, proto_tree *tree, packet_info *pinfo)
552 {
553   /* Look up this frame in the report table. */
554   spi_status *status = (spi_status*)g_hash_table_lookup(esp_sequence_analysis_report_hash,
555                                                         GUINT_TO_POINTER(pinfo->fd->num));
556   if (status != NULL) {
557     proto_item *sn_ti, *frame_ti;
558
559     /* Expected sequence number */
560     sn_ti = proto_tree_add_uint(tree, hf_esp_sequence_analysis_expected_sn,
561                                 tvb, 0, 0, status->previousSequenceNumber+1);
562     if (sequence_number > (status->previousSequenceNumber+1)) {
563       proto_item_append_text(sn_ti, " (%u SNs missing)",
564                              sequence_number - (status->previousSequenceNumber+1));
565     }
566     PROTO_ITEM_SET_GENERATED(sn_ti);
567
568     /* Link back to previous frame for SPI */
569     frame_ti = proto_tree_add_uint(tree, hf_esp_sequence_analysis_previous_frame,
570                                    tvb, 0, 0, status->previousFrameNum);
571     PROTO_ITEM_SET_GENERATED(frame_ti);
572
573     /* Expert info */
574     if (sequence_number == status->previousSequenceNumber) {
575       expert_add_info_format(pinfo, sn_ti, &ei_esp_sequence_analysis_wrong_sequence_number,
576                              "Wrong Sequence Number for SPI %08x - %u repeated",
577                              spi, sequence_number);
578     }
579     else if (sequence_number > status->previousSequenceNumber+1) {
580       expert_add_info_format(pinfo, sn_ti, &ei_esp_sequence_analysis_wrong_sequence_number,
581                              "Wrong Sequence Number for SPI %08x - %u missing",
582                              spi,
583                              sequence_number - (status->previousSequenceNumber+1));
584     }
585     else {
586       expert_add_info_format(pinfo, sn_ti, &ei_esp_sequence_analysis_wrong_sequence_number,
587                              "Wrong Sequence Number for SPI %08x - %u less than expected",
588                              spi,
589                              (status->previousSequenceNumber+1) - sequence_number);
590     }
591   }
592 }
593
594 /*
595    Default ESP payload heuristic decode to off
596    (only works if payload is NULL encrypted and ESP payload decode is off or payload is NULL encrypted
597    and the packet does not match a Security Association).
598 */
599 static gboolean g_esp_enable_null_encryption_decode_heuristic = FALSE;
600
601 /* Default to doing ESP sequence analysis */
602 static gboolean g_esp_do_sequence_analysis = TRUE;
603
604 /* Place AH payload in sub tree */
605 static gboolean g_ah_payload_in_subtree = FALSE;
606
607 #ifndef offsetof
608 #define offsetof(type, member)  ((size_t)(&((type *)0)->member))
609 #endif
610
611
612
613
614 #ifdef HAVE_LIBGCRYPT
615 #if 0
616
617 /*
618    Name : static int get_ipv6_suffix(char* ipv6_suffix, char *ipv6_address)
619    Description : Get the extended IPv6 Suffix of an IPv6 Address
620    Return : Return the number of char of the IPv6 address suffix parsed
621    Params:
622       - char *ipv6_address : the valid ipv6 address to parse in char *
623       - char *ipv6_suffix : the ipv6 suffix associated in char *
624
625       ex: if IPv6 address is "3ffe::1" the IPv6 suffix will be "0001" and the function will return 3
626 */
627 static int get_ipv6_suffix(char* ipv6_suffix, char *ipv6_address)
628 {
629   char suffix[IPSEC_STRLEN_IPV6 + 1];
630   int cpt = 0;
631   int cpt_suffix = 0;
632   int cpt_seg = 0;
633   int j =0;
634   int ipv6_len = 0;
635   gboolean found = FALSE;
636
637   ipv6_len = (int) strlen(ipv6_address);
638   if(ipv6_len  == 0)
639     {
640       /* Found a suffix */
641       found = TRUE;
642     }
643   else
644     {
645       while ( (cpt_suffix < IPSEC_STRLEN_IPV6) && (ipv6_len - cpt -1 >= 0) && (found == FALSE))
646         {
647           if(ipv6_address[ipv6_len - cpt - 1] == ':')
648             {
649               /* Add some 0 to the prefix; */
650               for(j = cpt_seg; j < 4; j++)
651                 {
652                   suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = '0';
653                   cpt_suffix ++;
654                 }
655               cpt_seg = 0;
656
657               if(ipv6_len - cpt - 1 == 0)
658                 {
659                   /* Found a suffix */
660                   found = TRUE;
661                 }
662               else
663                 if(ipv6_address[ipv6_len - cpt - 2] == ':')
664                   {
665                     /* found a suffix */
666                     cpt +=2;
667                     found = TRUE;
668                   }
669
670                 else
671                   {
672                     cpt++;
673                   }
674             }
675           else
676             {
677               suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = g_ascii_toupper(ipv6_address[ipv6_len - cpt - 1]);
678               cpt_seg ++;
679               cpt_suffix ++;
680               cpt++;
681             }
682         }
683
684       if(cpt_suffix % 4 != 0)
685         {
686           for(j = cpt_seg; j < 4; j++)
687             {
688               suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = '0';
689               cpt_suffix ++;
690             }
691           cpt_seg = 0;
692         }
693
694     }
695
696   for(j = 0 ; j < cpt_suffix ; j ++)
697     {
698       suffix[j] = suffix[j + IPSEC_STRLEN_IPV6 - cpt_suffix] ;
699     }
700
701   suffix[j] = '\0';
702   memcpy(ipv6_suffix,suffix,j + 1);
703   return cpt;
704 }
705
706 /*
707    Name : static int get_full_ipv6_addr(char* ipv6_addr_expanded, char *ipv6_addr)
708    Description : Get the extended IPv6 Address of an IPv6 Address
709    Return : Return the remaining number of char of the IPv6 address parsed
710    Params:
711       - char *ipv6_addr : the valid ipv6 address to parse in char *
712       - char *ipv6_addr_expansed : the expanded ipv6 address associated in char *
713
714       ex: if IPv6 address is "3ffe::1" the IPv6 expanded address
715             will be "3FFE0000000000000000000000000001" and the function will return 0
716           if IPV6 address is "3ffe::*" the IPv6 expanded address
717             will be "3FFE000000000000000000000000****" and the function will return 0
718 */
719 static int
720 get_full_ipv6_addr(char* ipv6_addr_expanded, char *ipv6_addr)
721 {
722   char suffix[IPSEC_STRLEN_IPV6 + 1];
723   char prefix[IPSEC_STRLEN_IPV6 + 1];
724   char *prefix_addr;
725
726   int suffix_cpt = 0;
727   int suffix_len = 0;
728   int prefix_remaining = 0;
729   int prefix_len = 0;
730   int j = 0;
731
732
733   if((ipv6_addr == NULL) || (strcmp(ipv6_addr, "") == 0))  return -1;
734   if((strlen(ipv6_addr) == 1) && (ipv6_addr[0] == IPSEC_SA_WILDCARDS_ANY))
735     {
736       for(j = 0; j <= IPSEC_STRLEN_IPV6; j++)
737         {
738           ipv6_addr_expanded[j] = IPSEC_SA_WILDCARDS_ANY;
739         }
740       ipv6_addr_expanded[IPSEC_STRLEN_IPV6] = '\0';
741       return 0;
742     }
743
744   suffix_cpt = get_ipv6_suffix(suffix,ipv6_addr);
745   suffix_len = (int) strlen(suffix);
746
747   if(suffix_len <  IPSEC_STRLEN_IPV6)
748     {
749       prefix_addr = wmem_strndup(wmem_packet_scope(), ipv6_addr,strlen(ipv6_addr) - suffix_cpt);
750       prefix_remaining = get_ipv6_suffix(prefix,prefix_addr);
751       prefix_len = (int) strlen(prefix);
752       memcpy(ipv6_addr_expanded,prefix,prefix_len);
753     }
754
755
756   for(j = 0; j <= IPSEC_STRLEN_IPV6 - prefix_len - suffix_len; j++)
757     {
758       ipv6_addr_expanded[j + prefix_len] = '0';
759     }
760
761   memcpy(ipv6_addr_expanded + IPSEC_STRLEN_IPV6 - suffix_len, suffix,suffix_len + 1);
762
763   if(suffix_len < IPSEC_STRLEN_IPV6)
764     return (prefix_len - prefix_remaining);
765   else
766     return (int) strlen(ipv6_addr) - suffix_cpt;
767 }
768
769
770 /*
771    Name : static gboolean get_full_ipv4_addr(char* ipv4_addr_expanded, char *ipv4_addr)
772    Description : Get the extended IPv4 Address of an IPv4 Address
773    Return : Return true if it can derive an IPv4 address. It does not mean that
774             the previous one was valid.
775    Params:
776       - char *ipv4_addr : the valid ipv4 address to parse in char *
777       - char *ipv4_addr_expansed : the expanded ipv4 address associated in char *
778
779       ex: if IPv4 address is "190.*.*.1" the IPv4 expanded address will be "BE****01" and
780             the function will return 0
781           if IPv4 address is "*" the IPv4 expanded address will be "********" and
782             the function will return 0
783 */
784 static gboolean
785 get_full_ipv4_addr(char* ipv4_address_expanded, char *ipv4_address)
786 {
787   char addr_byte_string_tmp[4];
788   char addr_byte_string[4];
789
790   guint addr_byte = 0;
791   guint i = 0;
792   guint j = 0;
793   guint k = 0;
794   guint cpt = 0;
795   gboolean done_flag = FALSE;
796
797   if((ipv4_address == NULL) || (strcmp(ipv4_address, "") == 0))  return done_flag;
798
799   if((strlen(ipv4_address) == 1) && (ipv4_address[0] == IPSEC_SA_WILDCARDS_ANY))
800   {
801     for(i = 0; i <= IPSEC_STRLEN_IPV4; i++)
802     {
803       ipv4_address_expanded[i] = IPSEC_SA_WILDCARDS_ANY;
804     }
805     ipv4_address_expanded[IPSEC_STRLEN_IPV4] = '\0';
806     done_flag = TRUE;
807   }
808
809   else {
810     j = 0;
811     cpt = 0;
812     k = 0;
813     while((done_flag == FALSE) && (j <= strlen(ipv4_address)) && (cpt < IPSEC_STRLEN_IPV4))
814     {
815       if(j == strlen(ipv4_address))
816       {
817         addr_byte_string_tmp[k] = '\0';
818         if((strlen(addr_byte_string_tmp) == 1) && (addr_byte_string_tmp[0] == IPSEC_SA_WILDCARDS_ANY))
819         {
820           for(i = 0; i < 2; i++)
821           {
822             ipv4_address_expanded[cpt] = IPSEC_SA_WILDCARDS_ANY;
823             cpt ++;
824           }
825         }
826         else
827         {
828           sscanf(addr_byte_string_tmp,"%u",&addr_byte);
829           if(addr_byte < 16) g_snprintf(addr_byte_string,4,"0%X",addr_byte);
830           else g_snprintf(addr_byte_string,4,"%X",addr_byte);
831           for(i = 0; i < strlen(addr_byte_string); i++)
832           {
833             ipv4_address_expanded[cpt] = addr_byte_string[i];
834             cpt ++;
835           }
836         }
837         done_flag = TRUE;
838       }
839
840       else if(ipv4_address[j] == '.')
841       {
842         addr_byte_string_tmp[k] = '\0';
843         if((strlen(addr_byte_string_tmp) == 1) && (addr_byte_string_tmp[0] == IPSEC_SA_WILDCARDS_ANY))
844         {
845           for(i = 0; i < 2; i++)
846           {
847             ipv4_address_expanded[cpt] = IPSEC_SA_WILDCARDS_ANY;
848             cpt ++;
849           }
850         }
851         else
852         {
853           sscanf(addr_byte_string_tmp,"%u",&addr_byte);
854           if(addr_byte < 16) g_snprintf(addr_byte_string,4,"0%X",addr_byte);
855           else g_snprintf(addr_byte_string,4,"%X",addr_byte);
856           for(i = 0; i < strlen(addr_byte_string); i++)
857           {
858             ipv4_address_expanded[cpt] = addr_byte_string[i];
859             cpt ++;
860           }
861         }
862         k = 0;
863         j++;
864       }
865       else
866       {
867         if(k >= 3)
868         {
869           /* Incorrect IPv4 Address. Erase previous Values in the Byte. (LRU mechanism) */
870           addr_byte_string_tmp[0] = ipv4_address[j];
871           k = 1;
872           j++;
873         }
874         else
875         {
876           addr_byte_string_tmp[k] = ipv4_address[j];
877           k++;
878           j++;
879         }
880       }
881
882     }
883
884     ipv4_address_expanded[cpt] = '\0';
885   }
886
887   return done_flag;
888 }
889 #endif
890
891 /*
892    Name : static goolean filter_address_match(gchar *addr, gchar *filter, gint len, gint typ)
893    Description : check the matching of an address with a filter
894    Return : Return TRUE if the filter and the address match
895    Params:
896       - gchar *addr : the address to check
897       - gchar *filter : the filter
898       - gint typ : the Address type : either IPv6 or IPv4 (IPSEC_SA_IPV6, IPSEC_SA_IPV4)
899 */
900 static gboolean
901 filter_address_match(gchar *addr, gchar *filter, gint typ)
902 {
903   guint i;
904   guint filter_tmp = 0;
905   guint addr_tmp = 0;
906   char filter_string_tmp[3];
907   char addr_string_tmp[3];
908   guint addr_len;
909   guint filter_len = (guint)strlen(filter);
910
911   if((filter_len == 1) && (filter[0] == IPSEC_SA_WILDCARDS_ANY))
912       return TRUE;
913
914   addr_len = (guint)strlen(addr);
915   if(addr_len != filter_len)
916           return FALSE;
917
918   /* No length specified */
919    if( ((typ == IPSEC_SA_IPV6) && (filter_len > IPSEC_IPV6_ADDR_LEN)) ||
920        ((typ == IPSEC_SA_IPV4) && (filter_len > IPSEC_IPV4_ADDR_LEN)))
921    {
922       /* Filter is longer than address can be... */
923       for(i = 0; i < addr_len; i++)
924       {
925          if((filter[i] != IPSEC_SA_WILDCARDS_ANY) && (filter[i] != addr[i]))
926             return FALSE;
927       }
928       return TRUE;
929    }
930    else
931    {
932       for(i = 0; i < (filter_len/4); i++)
933       {
934          if((filter[i] != IPSEC_SA_WILDCARDS_ANY) && (filter[i] != addr[i]))
935             return FALSE;
936       }
937
938       if(filter[i] == IPSEC_SA_WILDCARDS_ANY)
939          return TRUE;
940       else if (filter_len  % 4 != 0)
941       {
942          /* take the end of the Netmask/Prefixlen into account */
943          filter_string_tmp[0] = filter[i];
944          filter_string_tmp[1] = '\0';
945          addr_string_tmp[0] = addr[i];
946          addr_string_tmp[1] = '\0';
947
948          sscanf(filter_string_tmp,"%x",&filter_tmp);
949          sscanf(addr_string_tmp,"%x",&addr_tmp);
950          for(i = 0; i < (filter_len % 4); i++)
951          {
952             if(((filter_tmp >> (4 -i -1)) & 1) != ((addr_tmp >> (4 -i -1)) & 1))
953                return FALSE;
954          }
955       }
956    }
957
958   return TRUE;
959
960 }
961
962
963 /*
964    Name : static goolean filter_spi_match(gchar *spi, gchar *filter)
965    Description : check the matching of a spi with a filter
966    Return : Return TRUE if the filter matches the spi.
967    Params:
968       - gchar *spi : the spi to check
969       - gchar *filter : the filter
970 */
971 static gboolean
972 filter_spi_match(gchar *spi, gchar *filter)
973 {
974   guint i;
975   guint filter_len = (guint)strlen(filter);
976
977   /* "*" matches against anything */
978   if((filter_len == 1) && (filter[0] == IPSEC_SA_WILDCARDS_ANY))
979     return TRUE;
980   /* Otherwise lengths need to match exactly... */
981   else if(strlen(spi) != filter_len)
982     return FALSE;
983
984   /* ... which means '*' can only appear in the last position of the filter? */
985   /* Start at 2, don't compare "0x" each time */
986   for(i = 2; filter[i]; i++)
987     if((filter[i] != IPSEC_SA_WILDCARDS_ANY) && (filter[i] != spi[i]))
988       return FALSE;
989
990   return TRUE;
991 }
992
993
994 /*
995    Name : static goolean get_esp_sa(g_esp_sa_database *sad, gint protocol_typ, gchar *src,  gchar *dst,  gint spi,
996            gint *encryption_algo,
997            gint *authentication_algo,
998            gchar **encryption_key,
999            guint *encryption_key_len,
1000            gchar **authentication_key,
1001            guint *authentication_key_len,
1002            gcry_cipher_hd_t **cipher_hd,
1003            gboolean **cipher_hd_created
1004
1005    Description : Give Encryption Algo, Key and Authentification Algo for a Packet if a corresponding SA is available in a Security Association database
1006    Return: If the SA is not present, FALSE is then returned.
1007    Params:
1008       - g_esp_sa_database *sad : the Security Association Database
1009       - gint *pt_protocol_typ : the protocol type
1010       - gchar *src : the source address
1011       - gchar *dst : the destination address
1012       - gchar *spi : the spi of the SA
1013       - gint *encryption_algo : the Encryption Algorithm to apply the packet
1014       - gint *authentication_algo : the Authentication Algorithm to apply to the packet
1015       - gchar **encryption_key : the Encryption Key to apply to the packet
1016       - guint *encryption_key_len : the Encryption Key length to apply to the packet
1017       - gchar **authentication_key : the Authentication Key to apply to the packet
1018       - guint *authentication_key_len : the Authentication Key len to apply to the packet
1019       - gcry_cipher_hd_t **cipher_hd : pointer handle to be used for ciphering
1020       - gboolean **cipher_hd_created: points to boolean indicating that cipher handle has
1021                                       been created.  If FALSE, should assign handle to
1022                                       *cipher_hd and set this to TRUE.
1023
1024 */
1025 static gboolean
1026 get_esp_sa(gint protocol_typ, gchar *src,  gchar *dst,  gint spi,
1027            gint *encryption_algo,
1028            gint *authentication_algo,
1029            gchar **encryption_key,
1030            guint *encryption_key_len,
1031            gchar **authentication_key,
1032            guint *authentication_key_len,
1033            gcry_cipher_hd_t **cipher_hd,
1034            gboolean **cipher_hd_created
1035   )
1036 {
1037   gboolean found = FALSE;
1038   guint i, j;
1039   gchar spi_string[IPSEC_SPI_LEN_MAX];
1040
1041   g_snprintf(spi_string, IPSEC_SPI_LEN_MAX,"0x%08x", spi);
1042
1043   *cipher_hd = NULL;
1044   *cipher_hd_created = NULL;
1045
1046   /* Check each known SA in turn */
1047   for (i = 0, j=0; (found == FALSE) && ((i < num_sa_uat) || (j < extra_esp_sa_records.num_records)); )
1048   {
1049     /* Get the next record to try */
1050     uat_esp_sa_record_t *record;
1051     if (j < extra_esp_sa_records.num_records) {
1052       /* Extra ones checked first */
1053       record = &extra_esp_sa_records.records[j++];
1054     }
1055     else {
1056       /* Then UAT ones */
1057       record = &uat_esp_sa_records[i++];
1058     }
1059
1060     if((protocol_typ == record->protocol)
1061        && filter_address_match(src, record->srcIP, protocol_typ)
1062        && filter_address_match(dst, record->dstIP, protocol_typ)
1063        && filter_spi_match(spi_string, record->spi))
1064     {
1065       found = TRUE;
1066
1067       *encryption_algo = record->encryption_algo;
1068       *authentication_algo = record->authentication_algo;
1069       *authentication_key = record->authentication_key;
1070       if (record->authentication_key_length == -1)
1071       {
1072         /* Bad key; XXX - report this */
1073         *authentication_key_len = 0;
1074         found = FALSE;
1075       }
1076       else {
1077         *authentication_key_len = record->authentication_key_length;
1078       }
1079
1080       *encryption_key = record->encryption_key;
1081       if (record->encryption_key_length == -1)
1082       {
1083         /* Bad key; XXX - report this */
1084         *encryption_key_len = 0;
1085         found = FALSE;
1086       }
1087       else {
1088         *encryption_key_len = record->encryption_key_length;
1089       }
1090
1091       /* Tell the caller whether cypher_hd has been created yet and a pointer.
1092          Pass pointer to created flag so that caller can set if/when
1093          it opens the cypher_hd. */
1094       *cipher_hd = &record->cipher_hd;
1095       *cipher_hd_created = &record->cipher_hd_created;
1096     }
1097   }
1098
1099   return found;
1100 }
1101 #endif
1102
1103 static void
1104 export_ipsec_pdu(dissector_handle_t dissector_handle, packet_info *pinfo, tvbuff_t *tvb)
1105 {
1106   if (have_tap_listener(exported_pdu_tap)) {
1107     exp_pdu_data_t *exp_pdu_data;
1108     guint8 tags = EXP_PDU_TAG_IP_SRC_BIT | EXP_PDU_TAG_IP_DST_BIT | EXP_PDU_TAG_SRC_PORT_BIT |
1109                   EXP_PDU_TAG_DST_PORT_BIT | EXP_PDU_TAG_ORIG_FNO_BIT;
1110
1111     exp_pdu_data = load_export_pdu_tags(pinfo, EXP_PDU_TAG_PROTO_NAME,
1112                                         dissector_handle_get_dissector_name(dissector_handle),
1113                                         &tags, 1);
1114
1115     exp_pdu_data->tvb_captured_length = tvb_captured_length(tvb);
1116     exp_pdu_data->tvb_reported_length = tvb_reported_length(tvb);
1117     exp_pdu_data->pdu_tvb = tvb;
1118
1119     tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data);
1120   }
1121 }
1122
1123 static int
1124 dissect_ah_header(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
1125 {
1126   proto_tree *ah_tree;
1127   proto_item *ti;
1128   struct newah ah;
1129   int advance;
1130   struct ah_header_data* header_data;
1131
1132   col_set_str(pinfo->cinfo, COL_PROTOCOL, "AH");
1133   col_clear(pinfo->cinfo, COL_INFO);
1134
1135   tvb_memcpy(tvb, (guint8 *)&ah, 0, sizeof(ah));
1136   advance = (int)sizeof(ah) + ((ah.ah_len - 1) << 2);
1137
1138   col_add_fstr(pinfo->cinfo, COL_INFO, "AH (SPI=0x%08x)",
1139                (guint32)g_ntohl(ah.ah_spi));
1140
1141   header_data = (struct ah_header_data*)p_get_proto_data(pinfo->pool, pinfo, proto_ah, 0 );
1142
1143   if (tree) {
1144     /* !!! specify length */
1145     ti = proto_tree_add_item(tree, proto_ah, tvb, 0, advance, ENC_NA);
1146     ah_tree = proto_item_add_subtree(ti, ett_ah);
1147
1148     proto_tree_add_uint_format_value(ah_tree, hf_ah_next_header, tvb,
1149                         offsetof(struct newah, ah_nxt), 1,
1150                         ah.ah_nxt, "%s (0x%02x)",
1151                         ipprotostr(ah.ah_nxt), ah.ah_nxt);
1152     proto_tree_add_uint(ah_tree, hf_ah_length, tvb,
1153                         offsetof(struct newah, ah_len), 1,
1154                         (ah.ah_len + 2) << 2);
1155     proto_tree_add_uint(ah_tree, hf_ah_spi, tvb,
1156                         offsetof(struct newah, ah_spi), 4,
1157                         (guint32)g_ntohl(ah.ah_spi));
1158     proto_tree_add_uint(ah_tree, hf_ah_sequence, tvb,
1159                         offsetof(struct newah, ah_seq), 4,
1160                         (guint32)g_ntohl(ah.ah_seq));
1161     proto_tree_add_item(ah_tree, hf_ah_iv, tvb,
1162                         sizeof(ah), (ah.ah_len) ? (ah.ah_len - 1) << 2 : 0,
1163                         ENC_NA);
1164
1165     if (header_data != NULL) {
1166       /* Decide where to place next protocol decode */
1167       if (g_ah_payload_in_subtree) {
1168         header_data->next_tree = ah_tree;
1169       }
1170       else {
1171         header_data->next_tree = tree;
1172       }
1173     }
1174   } else {
1175     if (header_data != NULL)
1176       header_data->next_tree = NULL;
1177   }
1178
1179   if (header_data != NULL)
1180     header_data->nxt = ah.ah_nxt;
1181
1182   /* start of the new header (could be a extension header) */
1183   return advance;
1184 }
1185
1186 static int
1187 dissect_ah(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
1188 {
1189   struct ah_header_data header_data = {NULL, 0};
1190   tvbuff_t *next_tvb;
1191   int advance;
1192   dissector_handle_t dissector_handle;
1193   guint32 saved_match_uint;
1194
1195   /* "pass" ah_header_data to header dissector.  This is done
1196      indirectly to prevent conflicts with IPv6 dissector */
1197   p_add_proto_data(pinfo->pool, pinfo, proto_ah, 0, &header_data);
1198
1199   advance = dissect_ah_header(tvb, pinfo, tree, NULL);
1200
1201   p_remove_proto_data(pinfo->pool, pinfo, proto_ah, 0);
1202
1203   next_tvb = tvb_new_subset_remaining(tvb, advance);
1204
1205   if (g_ah_payload_in_subtree) {
1206     col_set_writable(pinfo->cinfo, FALSE);
1207   }
1208
1209   /* do lookup with the subdissector table */
1210   saved_match_uint  = pinfo->match_uint;
1211   dissector_handle = dissector_get_uint_handle(ip_dissector_table, header_data.nxt);
1212   if (dissector_handle) {
1213     pinfo->match_uint = header_data.nxt;
1214   } else {
1215     dissector_handle = data_handle;
1216   }
1217   export_ipsec_pdu(dissector_handle, pinfo, next_tvb);
1218   call_dissector(dissector_handle, next_tvb, pinfo, header_data.next_tree);
1219   pinfo->match_uint = saved_match_uint;
1220   return tvb_captured_length(tvb);
1221 }
1222
1223 /*
1224 Name : dissect_esp_authentication(proto_tree *tree, tvbuff_t *tvb, gint len, gint esp_auth_len, guint8 *authenticator_data_computed,
1225 gboolean authentication_ok, gboolean authentication_checking_ok)
1226 Description : used to print Authenticator field when linked with libgcrypt. Print the expected authenticator value
1227 if requested and if it is wrong.
1228 Return : void
1229 Params:
1230 - proto_tree *tree : the current tree
1231 - tvbuff_t *tvb : the tvbuffer
1232 - gint len : length of the data availabale in tvbuff
1233 - gint esp_auth_len : size of authenticator field
1234 - guint8 *authenticator_data_computed : give the authenticator computed (only needed when authentication_ok and !authentication_checking_ok
1235 - gboolean authentication_ok : set to true if the authentication checking has been run successfully
1236 - gboolean authentication_checking_ok : set to true if the authentication was the one expected
1237 */
1238 #ifdef HAVE_LIBGCRYPT
1239 static void
1240 dissect_esp_authentication(proto_tree *tree, tvbuff_t *tvb, gint len, gint esp_auth_len, guint8 *authenticator_data_computed,
1241                            gboolean authentication_ok, gboolean authentication_checking_ok)
1242 {
1243   proto_item *item;
1244   proto_tree *icv_tree;
1245   gboolean good = FALSE, bad = FALSE;
1246
1247   if(esp_auth_len == 0)
1248   {
1249     icv_tree = proto_tree_add_subtree(tree, tvb, len, 0,
1250                                ett_esp_icv, NULL, "NULL Authentication");
1251     good = TRUE;
1252   }
1253
1254   /* Make sure we have the auth trailer data */
1255   else if(tvb_bytes_exist(tvb, len - esp_auth_len, esp_auth_len))
1256   {
1257     if((authentication_ok) && (authentication_checking_ok))
1258     {
1259       icv_tree = proto_tree_add_subtree(tree, tvb, len - esp_auth_len, esp_auth_len,
1260                                  ett_esp_icv, NULL, "Authentication Data [correct]");
1261       good = TRUE;
1262     }
1263
1264     else if((authentication_ok) && (!authentication_checking_ok))
1265     {
1266       icv_tree = proto_tree_add_subtree_format(tree, tvb, len - esp_auth_len, esp_auth_len,
1267                                  ett_esp_icv, NULL, "Authentication Data [incorrect, should be 0x%s]", authenticator_data_computed);
1268       bad = TRUE;
1269
1270       g_free(authenticator_data_computed);
1271     }
1272
1273     else
1274         icv_tree = proto_tree_add_subtree(tree, tvb, len - esp_auth_len, esp_auth_len,
1275                                     ett_esp_icv, NULL, "Authentication Data");
1276   }
1277   else
1278   {
1279     /* Truncated so just display what we have */
1280     icv_tree = proto_tree_add_subtree(tree, tvb, len - esp_auth_len, esp_auth_len - (len - tvb_captured_length(tvb)),
1281                                ett_esp_icv, NULL, "Authentication Data (truncated)");
1282     bad = TRUE;
1283   }
1284
1285   item = proto_tree_add_boolean(icv_tree, hf_esp_icv_good,
1286                                 tvb, len - esp_auth_len, esp_auth_len, good);
1287   PROTO_ITEM_SET_GENERATED(item);
1288
1289   item = proto_tree_add_boolean(icv_tree, hf_esp_icv_bad,
1290                                 tvb, len - esp_auth_len, esp_auth_len, bad);
1291   PROTO_ITEM_SET_GENERATED(item);
1292 }
1293 #endif
1294
1295 static int
1296 dissect_esp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
1297 {
1298   proto_tree *esp_tree = NULL;
1299   proto_item *ti;
1300   struct newesp esp;
1301
1302   gint len = 0;
1303
1304 #ifdef HAVE_LIBGCRYPT
1305   gint i;
1306
1307   /* Packet Variables related */
1308   gchar *ip_src = NULL;
1309   gchar *ip_dst = NULL;
1310 #endif
1311
1312   guint32 spi = 0;
1313   guint encapsulated_protocol = 0;
1314   gboolean decrypt_dissect_ok = FALSE;
1315   tvbuff_t *next_tvb;
1316   dissector_handle_t dissector_handle;
1317   guint32 saved_match_uint;
1318
1319 #ifdef HAVE_LIBGCRYPT
1320   gboolean null_encryption_decode_heuristic = FALSE;
1321   guint8 *decrypted_data = NULL;
1322   guint8 *authenticator_data = NULL;
1323   guint8 *esp_data = NULL;
1324   tvbuff_t *tvb_decrypted;
1325
1326   /* IPSEC encryption Variables related */
1327   gint protocol_typ = IPSEC_SA_UNKNOWN;
1328   gint esp_crypt_algo = IPSEC_ENCRYPT_NULL;
1329   gint esp_auth_algo = IPSEC_AUTH_NULL;
1330   gchar *esp_crypt_key = NULL;
1331   gchar *esp_auth_key = NULL;
1332   guint esp_crypt_key_len = 0;
1333   guint esp_auth_key_len = 0;
1334   gcry_cipher_hd_t *cipher_hd;
1335   gboolean         *cipher_hd_created;
1336
1337   gint esp_iv_len = 0;
1338   gint esp_auth_len = 0;
1339   gint decrypted_len = 0;
1340   gboolean decrypt_ok = FALSE;
1341   gboolean decrypt_using_libgcrypt = FALSE;
1342   gboolean authentication_check_using_hmac_libgcrypt = FALSE;
1343   gboolean authentication_ok = FALSE;
1344   gboolean authentication_checking_ok = FALSE;
1345   gboolean sad_is_present = FALSE;
1346 #endif
1347   gint esp_pad_len = 0;
1348
1349 #ifdef HAVE_LIBGCRYPT
1350
1351   /* Variables for decryption and authentication checking used for libgrypt */
1352   int decrypted_len_alloc = 0;
1353   gcry_md_hd_t md_hd;
1354   int md_len = 0;
1355   gcry_error_t err = 0;
1356   int crypt_algo_libgcrypt = 0;
1357   int crypt_mode_libgcrypt = 0;
1358   int auth_algo_libgcrypt = 0;
1359   unsigned char *authenticator_data_computed = NULL;
1360   unsigned char *authenticator_data_computed_md;
1361
1362   unsigned char ctr_block[16];
1363
1364 #endif
1365
1366   guint32 sequence_number;
1367
1368   /*
1369    * load the top pane info. This should be overwritten by
1370    * the next protocol in the stack
1371    */
1372
1373   col_set_str(pinfo->cinfo, COL_PROTOCOL, "ESP");
1374   col_clear(pinfo->cinfo, COL_INFO);
1375
1376   tvb_memcpy(tvb, (guint8 *)&esp, 0, sizeof(esp));
1377
1378   col_add_fstr(pinfo->cinfo, COL_INFO, "ESP (SPI=0x%08x)",
1379                (guint32)g_ntohl(esp.esp_spi));
1380
1381
1382   /*
1383    * populate a tree in the second pane with the status of the link layer
1384    * (ie none)
1385    */
1386
1387
1388   spi = (guint32)g_ntohl(esp.esp_spi);
1389   sequence_number = (guint32)g_ntohl(esp.esp_seq);
1390   len = 0, encapsulated_protocol = 0;
1391   decrypt_dissect_ok = FALSE;
1392
1393   ti = proto_tree_add_item(tree, proto_esp, tvb, 0, -1, ENC_NA);
1394   esp_tree = proto_item_add_subtree(ti, ett_esp);
1395   proto_tree_add_uint(esp_tree, hf_esp_spi, tvb,
1396                       offsetof(struct newesp, esp_spi), 4,
1397                       (guint32)g_ntohl(esp.esp_spi));
1398   proto_tree_add_uint(esp_tree, hf_esp_sequence, tvb,
1399                       offsetof(struct newesp, esp_seq), 4,
1400                       sequence_number);
1401
1402   /* Sequence number analysis */
1403   if (g_esp_do_sequence_analysis) {
1404     if (!pinfo->fd->flags.visited) {
1405       check_esp_sequence_info(spi, sequence_number, pinfo);
1406     }
1407     show_esp_sequence_info(spi, sequence_number,
1408                            tvb, esp_tree, pinfo);
1409   }
1410
1411
1412
1413 #ifdef HAVE_LIBGCRYPT
1414   /* The SAD is not activated */
1415   if(g_esp_enable_null_encryption_decode_heuristic &&
1416      !g_esp_enable_encryption_decode)
1417     null_encryption_decode_heuristic = TRUE;
1418
1419   if(g_esp_enable_encryption_decode || g_esp_enable_authentication_check)
1420   {
1421     /* Get Source & Destination Addresses in gchar * with all the bytes available.  */
1422
1423     if (pinfo->src.type == AT_IPv4){
1424       protocol_typ = IPSEC_SA_IPV4;
1425     }else if (pinfo->src.type == AT_IPv6){
1426       protocol_typ = IPSEC_SA_IPV6;
1427     }
1428
1429     /* Create strings for src, dst addresses */
1430     ip_src = address_to_str(wmem_packet_scope(), &pinfo->src);
1431     ip_dst = address_to_str(wmem_packet_scope(), &pinfo->dst);
1432
1433     /* Get the SPI */
1434     if (tvb_captured_length(tvb) >= 4)
1435     {
1436       spi = tvb_get_ntohl(tvb, 0);
1437     }
1438
1439
1440     /*
1441       PARSE the SAD and fill it. It may take some time since it will
1442       be called every times an ESP Payload is found.
1443     */
1444
1445     if((sad_is_present = get_esp_sa(protocol_typ, ip_src, ip_dst, spi,
1446                                     &esp_crypt_algo, &esp_auth_algo,
1447                                     &esp_crypt_key, &esp_crypt_key_len, &esp_auth_key, &esp_auth_key_len,
1448                                     &cipher_hd, &cipher_hd_created)))
1449     {
1450       /* Get length of whole ESP packet. */
1451       len = tvb_reported_length(tvb);
1452
1453       switch(esp_auth_algo)
1454       {
1455       case IPSEC_AUTH_NULL:
1456         esp_auth_len = 0;
1457         break;
1458
1459       case IPSEC_AUTH_ANY_64BIT:
1460         esp_auth_len = 8;
1461         break;
1462
1463       case IPSEC_AUTH_HMAC_SHA256_128:
1464       case IPSEC_AUTH_ANY_128BIT:
1465         esp_auth_len = 16;
1466         break;
1467
1468       case IPSEC_AUTH_HMAC_SHA512_256:
1469       case IPSEC_AUTH_ANY_256BIT:
1470         esp_auth_len = 32;
1471         break;
1472
1473       case IPSEC_AUTH_HMAC_SHA384_192:
1474       case IPSEC_AUTH_ANY_192BIT:
1475         esp_auth_len = 24;
1476         break;
1477
1478       case IPSEC_AUTH_HMAC_SHA1_96:
1479       case IPSEC_AUTH_HMAC_SHA256_96:
1480         /*             case IPSEC_AUTH_AES_XCBC_MAC_96: */
1481       case IPSEC_AUTH_HMAC_MD5_96:
1482       case IPSEC_AUTH_HMAC_RIPEMD160_96:
1483       case IPSEC_AUTH_ANY_96BIT:
1484       default:
1485         esp_auth_len = 12;
1486         break;
1487       }
1488
1489       if(g_esp_enable_authentication_check)
1490       {
1491         switch(esp_auth_algo)
1492         {
1493         case IPSEC_AUTH_HMAC_SHA1_96:
1494           /*
1495             RFC 2404 : HMAC-SHA-1-96 is a secret key algorithm.
1496             While no fixed key length is specified in [RFC-2104],
1497             for use with either ESP or AH a fixed key length of
1498             160-bits MUST be supported.  Key lengths other than
1499             160-bits MUST NOT be supported (i.e. only 160-bit keys
1500             are to be used by HMAC-SHA-1-96).  A key length of
1501             160-bits was chosen based on the recommendations in
1502             [RFC-2104] (i.e. key lengths less than the
1503             authenticator length decrease security strength and
1504             keys longer than the authenticator length do not
1505             significantly increase security strength).
1506           */
1507           auth_algo_libgcrypt = GCRY_MD_SHA1;
1508           authentication_check_using_hmac_libgcrypt = TRUE;
1509           break;
1510
1511         case IPSEC_AUTH_NULL:
1512           authentication_check_using_hmac_libgcrypt = FALSE;
1513           authentication_checking_ok = TRUE;
1514           authentication_ok = TRUE;
1515           break;
1516
1517           /*
1518             case IPSEC_AUTH_AES_XCBC_MAC_96:
1519             auth_algo_libgcrypt =
1520             authentication_check_using_libgcrypt = TRUE;
1521             break;
1522           */
1523
1524         case IPSEC_AUTH_HMAC_SHA256_96:
1525         case IPSEC_AUTH_HMAC_SHA256_128:
1526           auth_algo_libgcrypt = GCRY_MD_SHA256;
1527           authentication_check_using_hmac_libgcrypt = TRUE;
1528           break;
1529
1530         case IPSEC_AUTH_HMAC_SHA384_192:
1531           auth_algo_libgcrypt = GCRY_MD_SHA384;
1532           authentication_check_using_hmac_libgcrypt = TRUE;
1533           break;
1534
1535         case IPSEC_AUTH_HMAC_SHA512_256:
1536           auth_algo_libgcrypt = GCRY_MD_SHA512;
1537           authentication_check_using_hmac_libgcrypt = TRUE;
1538           break;
1539
1540         case IPSEC_AUTH_HMAC_MD5_96:
1541           /*
1542             RFC 2403 : HMAC-MD5-96 is a secret key algorithm.
1543             While no fixed key length is specified in [RFC-2104],
1544             for use with either ESP or AH a fixed key length of
1545             128-bits MUST be supported.  Key lengths other than
1546             128-bits MUST NOT be supported (i.e. only 128-bit keys
1547             are to be used by HMAC-MD5-96).  A key length of
1548             128-bits was chosen based on the recommendations in
1549             [RFC-2104] (i.e. key lengths less than the
1550             authenticator length decrease security strength and
1551             keys longer than the authenticator length do not
1552             significantly increase security strength).
1553           */
1554           auth_algo_libgcrypt = GCRY_MD_MD5;
1555           authentication_check_using_hmac_libgcrypt = TRUE;
1556           break;
1557
1558         case IPSEC_AUTH_HMAC_RIPEMD160_96:
1559           /*
1560             RFC 2857 : HMAC-RIPEMD-160-96 produces a 160-bit
1561             authenticator value.  This 160-bit value can be
1562             truncated as described in RFC2104.  For use with
1563             either ESP or AH, a truncated value using the first
1564             96 bits MUST be supported.
1565           */
1566           auth_algo_libgcrypt = GCRY_MD_RMD160;
1567           authentication_check_using_hmac_libgcrypt = TRUE;
1568           break;
1569
1570         case IPSEC_AUTH_ANY_64BIT:
1571         case IPSEC_AUTH_ANY_96BIT:
1572         case IPSEC_AUTH_ANY_128BIT:
1573         case IPSEC_AUTH_ANY_192BIT:
1574         case IPSEC_AUTH_ANY_256BIT:
1575         default:
1576           authentication_ok = FALSE;
1577           authentication_check_using_hmac_libgcrypt = FALSE;
1578           break;
1579
1580         }
1581
1582         if((authentication_check_using_hmac_libgcrypt) && (!authentication_ok))
1583         {
1584           gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
1585           gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
1586
1587           /* Allocate Buffers for Authenticator Field  */
1588           authenticator_data = (guint8 *) g_malloc0 (( esp_auth_len + 1) * sizeof(guint8));
1589           tvb_memcpy(tvb, authenticator_data, len - esp_auth_len, esp_auth_len);
1590
1591           esp_data = (guint8 *) g_malloc0 (( len - esp_auth_len + 1) * sizeof(guint8));
1592           tvb_memcpy(tvb, esp_data, 0, len - esp_auth_len);
1593
1594           err = gcry_md_open (&md_hd, auth_algo_libgcrypt, GCRY_MD_FLAG_HMAC);
1595           if (err)
1596           {
1597             fprintf (stderr, "<IPsec/ESP Dissector> Error in Algorithm %s, gcry_md_open failed: %s\n",
1598                      gcry_md_algo_name(auth_algo_libgcrypt), gpg_strerror (err));
1599             authentication_ok = FALSE;
1600             g_free(authenticator_data);
1601             g_free(esp_data);
1602           }
1603           else
1604           {
1605             md_len = gcry_md_get_algo_dlen (auth_algo_libgcrypt);
1606             if (md_len < 1 || md_len < esp_auth_len)
1607             {
1608               fprintf (stderr, "<IPsec/ESP Dissector> Error in Algorithm %s, grcy_md_get_algo_dlen failed: %d\n",
1609                        gcry_md_algo_name(auth_algo_libgcrypt), md_len);
1610               authentication_ok = FALSE;
1611             }
1612             else
1613             {
1614               gcry_md_setkey( md_hd, esp_auth_key, esp_auth_key_len );
1615
1616               gcry_md_write (md_hd, esp_data, len - esp_auth_len);
1617
1618               authenticator_data_computed_md = gcry_md_read (md_hd, auth_algo_libgcrypt);
1619               if (authenticator_data_computed_md == 0)
1620               {
1621                 fprintf (stderr, "<IPsec/ESP Dissector> Error in Algorithm %s, gcry_md_read failed\n",
1622                          gcry_md_algo_name(auth_algo_libgcrypt));
1623                 authentication_ok = FALSE;
1624               }
1625               else
1626               {
1627                 if(memcmp (authenticator_data_computed_md, authenticator_data, esp_auth_len))
1628                 {
1629                   unsigned char authenticator_data_computed_car[3];
1630                   authenticator_data_computed = (guint8 *) g_malloc (( esp_auth_len * 2 + 1) * sizeof(guint8));
1631                   for (i = 0; i < esp_auth_len; i++)
1632                   {
1633                     g_snprintf((char *)authenticator_data_computed_car, 3,
1634                                "%02X", authenticator_data_computed_md[i] & 0xFF);
1635                     authenticator_data_computed[i*2] = authenticator_data_computed_car[0];
1636                     authenticator_data_computed[i*2 + 1] = authenticator_data_computed_car[1];
1637                   }
1638
1639                   authenticator_data_computed[esp_auth_len * 2] ='\0';
1640
1641                   authentication_ok = TRUE;
1642                   authentication_checking_ok = FALSE;
1643                 }
1644                 else
1645                 {
1646                   authentication_ok = TRUE;
1647                   authentication_checking_ok = TRUE;
1648                 }
1649               }
1650             }
1651
1652             gcry_md_close (md_hd);
1653             g_free(authenticator_data);
1654             g_free(esp_data);
1655           }
1656         }
1657       }
1658
1659       if(g_esp_enable_encryption_decode)
1660       {
1661         /* Deactivation of the Heuristic to decrypt using the NULL encryption algorithm since the packet is matching a SA */
1662         null_encryption_decode_heuristic = FALSE;
1663
1664         switch(esp_crypt_algo)
1665         {
1666         case IPSEC_ENCRYPT_3DES_CBC :
1667           /* RFC 2451 says :
1668              3DES CBC uses a key of 192 bits.
1669              The first 3DES key is taken from the first 64 bits,
1670              the second from the next 64 bits, and the third
1671              from the last 64 bits.
1672              Implementations MUST take into consideration the
1673              parity bits when initially accepting a new set of
1674              keys.  Each of the three keys is really 56 bits in
1675              length with the extra 8 bits used for parity. */
1676
1677           /* Fix parameters for 3DES-CBC */
1678           esp_iv_len = 8;
1679           crypt_algo_libgcrypt = GCRY_CIPHER_3DES;
1680           crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1681
1682           decrypted_len = len - 8;
1683
1684           if (decrypted_len <= 0)
1685             decrypt_ok = FALSE;
1686           else
1687           {
1688             if(decrypted_len % esp_iv_len  == 0)
1689               decrypted_len_alloc = decrypted_len;
1690             else
1691               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
1692
1693             if (esp_crypt_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
1694             {
1695               fprintf (stderr, "<ESP Preferences> Error in Encryption Algorithm 3DES-CBC : Bad Keylen (got %u Bits, need %lu)\n",
1696                        esp_crypt_key_len * 8,
1697                        (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
1698               decrypt_ok = FALSE;
1699             }
1700             else
1701               decrypt_using_libgcrypt = TRUE;
1702           }
1703           break;
1704
1705         case IPSEC_ENCRYPT_AES_CBC :
1706           /* RFC 3602 says :
1707              AES supports three key sizes: 128 bits, 192 bits,
1708              and 256 bits.  The default key size is 128 bits,
1709              and all implementations MUST support this key size.
1710              Implementations MAY also support key sizes of 192
1711              bits and 256 bits. */
1712
1713           /* Fix parameters for AES-CBC */
1714           esp_iv_len = 16;
1715           crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1716
1717           decrypted_len = len - 8;
1718
1719           if (decrypted_len <= 0)
1720             decrypt_ok = FALSE;
1721           else
1722           {
1723             if(decrypted_len % esp_iv_len  == 0)
1724               decrypted_len_alloc = decrypted_len;
1725             else
1726               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
1727
1728             switch(esp_crypt_key_len * 8)
1729             {
1730             case 128:
1731               crypt_algo_libgcrypt = GCRY_CIPHER_AES128;
1732               decrypt_using_libgcrypt = TRUE;
1733               break;
1734
1735             case 192:
1736               crypt_algo_libgcrypt = GCRY_CIPHER_AES192;
1737               decrypt_using_libgcrypt = TRUE;
1738               break;
1739
1740             case 256:
1741               crypt_algo_libgcrypt = GCRY_CIPHER_AES256;
1742               decrypt_using_libgcrypt = TRUE;
1743               break;
1744
1745             default:
1746               fprintf (stderr, "<ESP Preferences> Error in Encryption Algorithm AES-CBC : Bad Keylen (%u Bits)\n",
1747                        esp_crypt_key_len * 8);
1748               decrypt_ok = FALSE;
1749             }
1750           }
1751           break;
1752
1753         case IPSEC_ENCRYPT_CAST5_CBC :
1754           /* RFC 2144 says :
1755              The CAST-128 encryption algorithm has been designed to allow a key
1756              size that can vary from 40 bits to 128 bits, in 8-bit increments
1757              (that is, the allowable key sizes are 40, 48, 56, 64, ..., 112, 120,
1758              and 128 bits.
1759              We support only 128 bits. */
1760
1761           /* Fix parameters for CAST5-CBC */
1762           esp_iv_len = 8;
1763           crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1764
1765           decrypted_len = len - 8;
1766
1767           if (decrypted_len <= 0)
1768             decrypt_ok = FALSE;
1769           else
1770           {
1771             if(decrypted_len % esp_iv_len  == 0)
1772               decrypted_len_alloc = decrypted_len;
1773             else
1774               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
1775
1776             switch(esp_crypt_key_len * 8)
1777             {
1778             case 128:
1779               crypt_algo_libgcrypt = GCRY_CIPHER_CAST5;
1780               decrypt_using_libgcrypt = TRUE;
1781               break;
1782             default:
1783               fprintf (stderr, "<ESP Preferences> Error in Encryption Algorithm CAST5-CBC : Bad Keylen (%u Bits)\n",
1784                        esp_crypt_key_len * 8);
1785               decrypt_ok = FALSE;
1786             }
1787           }
1788           break;
1789
1790         case IPSEC_ENCRYPT_DES_CBC :
1791           /* RFC 2405 says :
1792              DES-CBC is a symmetric secret key algorithm.
1793              The key size is 64-bits.
1794              [It is commonly known as a 56-bit key as the key
1795              has 56 significant bits; the least significant
1796              bit in every byte is the parity bit.] */
1797
1798           /* Fix parameters for DES-CBC */
1799           esp_iv_len = 8;
1800           crypt_algo_libgcrypt = GCRY_CIPHER_DES;
1801           crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1802           decrypted_len = len - 8;
1803
1804           if (decrypted_len <= 0)
1805             decrypt_ok = FALSE;
1806           else
1807           {
1808             if(decrypted_len % esp_iv_len == 0)
1809               decrypted_len_alloc = decrypted_len;
1810             else
1811               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
1812
1813             if (esp_crypt_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
1814             {
1815               fprintf (stderr, "<ESP Preferences> Error in Encryption Algorithm DES-CBC : Bad Keylen (%u Bits, need %lu)\n",
1816                        esp_crypt_key_len * 8, (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
1817               decrypt_ok = FALSE;
1818             }
1819             else
1820               decrypt_using_libgcrypt = TRUE;
1821           }
1822           break;
1823
1824         case IPSEC_ENCRYPT_AES_CTR :
1825         case IPSEC_ENCRYPT_AES_GCM :
1826           /* RFC 3686 says :
1827              AES supports three key sizes: 128 bits, 192 bits,
1828              and 256 bits.  The default key size is 128 bits,
1829              and all implementations MUST support this key
1830              size.  Implementations MAY also support key sizes
1831              of 192 bits and 256 bits. The remaining 32 bits
1832              will be used as nonce. */
1833
1834           /* Fix parameters for AES-CTR */
1835           esp_iv_len = 8;
1836           crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CTR;
1837
1838           decrypted_len = len - 8;
1839
1840           if (decrypted_len <= 0)
1841             decrypt_ok = FALSE;
1842           else
1843           {
1844             if(decrypted_len % esp_iv_len  == 0)
1845               decrypted_len_alloc = decrypted_len;
1846             else
1847               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
1848
1849             switch(esp_crypt_key_len * 8)
1850             {
1851             case 160:
1852               crypt_algo_libgcrypt = GCRY_CIPHER_AES128;
1853               decrypt_using_libgcrypt = TRUE;
1854               break;
1855
1856             case 224:
1857               crypt_algo_libgcrypt = GCRY_CIPHER_AES192;
1858               decrypt_using_libgcrypt = TRUE;
1859               break;
1860
1861             case 288:
1862               crypt_algo_libgcrypt = GCRY_CIPHER_AES256;
1863               decrypt_using_libgcrypt = TRUE;
1864               break;
1865
1866             default:
1867               fprintf (stderr, "<ESP Preferences> Error in Encryption Algorithm AES-CTR / AES-GCM : Bad Keylen (%u Bits)\n",
1868                        esp_crypt_key_len * 8);
1869               decrypt_ok = FALSE;
1870             }
1871           }
1872           break;
1873
1874         case IPSEC_ENCRYPT_TWOFISH_CBC :
1875           /*  Twofish is a 128-bit block cipher developed by
1876               Counterpane Labs that accepts a variable-length
1877               key up to 256 bits.
1878               We will only accept key sizes of 128 and 256 bits.
1879           */
1880
1881           /* Fix parameters for TWOFISH-CBC */
1882           esp_iv_len = 16;
1883           crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1884
1885           decrypted_len = len - 8;
1886
1887           if (decrypted_len <= 0)
1888             decrypt_ok = FALSE;
1889           else
1890           {
1891             if(decrypted_len % esp_iv_len  == 0)
1892               decrypted_len_alloc = decrypted_len;
1893             else
1894               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
1895
1896             switch(esp_crypt_key_len * 8)
1897             {
1898             case 128:
1899               crypt_algo_libgcrypt = GCRY_CIPHER_TWOFISH128;
1900               decrypt_using_libgcrypt = TRUE;
1901               break;
1902
1903             case 256:
1904               crypt_algo_libgcrypt = GCRY_CIPHER_TWOFISH;
1905               decrypt_using_libgcrypt = TRUE;
1906               break;
1907
1908             default:
1909               fprintf (stderr, "<ESP Preferences> Error in Encryption Algorithm TWOFISH-CBC : Bad Keylen (%u Bits)\n",
1910                        esp_crypt_key_len * 8);
1911               decrypt_ok = FALSE;
1912             }
1913           }
1914
1915           break;
1916
1917         case IPSEC_ENCRYPT_BLOWFISH_CBC :
1918           /* Bruce Schneier of Counterpane Systems developed
1919              the Blowfish block cipher algorithm.
1920              RFC 2451 shows that Blowfish uses key sizes from
1921              40 to 448 bits. The Default size is 128 bits.
1922              We will only accept key sizes of 128 bits, because
1923              libgrypt only accept this key size.
1924           */
1925
1926           /* Fix parameters for BLOWFISH-CBC */
1927           esp_iv_len = 8;
1928           crypt_algo_libgcrypt = GCRY_CIPHER_BLOWFISH;
1929           crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1930
1931           decrypted_len = len - 8;
1932
1933           if (decrypted_len <= 0)
1934             decrypt_ok = FALSE;
1935           else
1936           {
1937             if(decrypted_len % esp_iv_len  == 0)
1938               decrypted_len_alloc = decrypted_len;
1939             else
1940               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
1941
1942             if (esp_crypt_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
1943             {
1944               fprintf (stderr, "<ESP Preferences> Error in Encryption Algorithm BLOWFISH-CBC : Bad Keylen (%u Bits, need %lu)\n",
1945                        esp_crypt_key_len * 8, (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
1946               decrypt_ok = FALSE;
1947             }
1948             else
1949               decrypt_using_libgcrypt = TRUE;
1950           }
1951           break;
1952
1953         case IPSEC_ENCRYPT_NULL :
1954         default :
1955           /* Fix parameters */
1956           esp_iv_len = 0;
1957           decrypted_len = len - 8;
1958
1959           if (decrypted_len <= 0)
1960             decrypt_ok = FALSE;
1961           else
1962           {
1963             /* Allocate Buffers for Encrypted and Decrypted data  */
1964             decrypted_data = (guint8 *) g_malloc ((decrypted_len + 1)* sizeof(guint8));
1965             tvb_memcpy(tvb, decrypted_data , sizeof(struct newesp), decrypted_len);
1966
1967             decrypt_ok = TRUE;
1968           }
1969           break;
1970         }
1971
1972         if (decrypt_using_libgcrypt)
1973         {
1974           /* Allocate Buffers for Encrypted and Decrypted data  */
1975           decrypted_data = (guint8 *) g_malloc ((decrypted_len_alloc + esp_iv_len)* sizeof(guint8));
1976           tvb_memcpy(tvb, decrypted_data, sizeof(struct newesp), decrypted_len);
1977
1978           /* (Lazily) create the cipher_hd */
1979           if (!(*cipher_hd_created)) {
1980             err = gcry_cipher_open(cipher_hd, crypt_algo_libgcrypt, crypt_mode_libgcrypt, 0);
1981             if (err)
1982             {
1983               fprintf(stderr, "<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, grcy_open_cipher failed: %s\n",
1984                       gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gpg_strerror(err));
1985               g_free(decrypted_data);
1986             }
1987             else
1988             {
1989               /* OK, set the key */
1990               if (*cipher_hd_created == FALSE)
1991               {
1992                 if (crypt_mode_libgcrypt == GCRY_CIPHER_MODE_CTR)
1993                 {
1994                   /* Counter mode key includes a 4 byte, (32 bit), nonce following the key */
1995                   err = gcry_cipher_setkey(*cipher_hd, esp_crypt_key, esp_crypt_key_len - 4);
1996                 }
1997                 else
1998                 {
1999                   err = gcry_cipher_setkey(*cipher_hd, esp_crypt_key, esp_crypt_key_len);
2000                 }
2001
2002                 if (err)
2003                 {
2004                   fprintf(stderr, "<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, gcry_cipher_setkey(key_len=%u) failed: %s\n",
2005                           gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, esp_crypt_key_len, gpg_strerror (err));
2006                   gcry_cipher_close(*cipher_hd);
2007                   g_free(decrypted_data);
2008                 }
2009               }
2010
2011               /* Key is created and has its key set now */
2012               *cipher_hd_created = TRUE;
2013             }
2014           }
2015
2016           /* Now try to decrypt */
2017           if (crypt_mode_libgcrypt == GCRY_CIPHER_MODE_CTR)
2018           {
2019             /* Set CTR first */
2020             memset(ctr_block, 0, 16);
2021             memcpy(ctr_block, esp_crypt_key + esp_crypt_key_len - 4, 4);
2022             memcpy(ctr_block + 4, decrypted_data, 8);
2023             ctr_block[15] = 1;
2024             if (esp_crypt_algo == IPSEC_ENCRYPT_AES_GCM) {
2025               ctr_block[15]++;
2026             }
2027             err = gcry_cipher_setctr(*cipher_hd, ctr_block, 16);
2028             if (!err)
2029             {
2030               err = gcry_cipher_decrypt(*cipher_hd, decrypted_data + esp_iv_len, decrypted_len_alloc, NULL, 0);
2031             }
2032           }
2033           else
2034           {
2035             err = gcry_cipher_decrypt(*cipher_hd, decrypted_data, decrypted_len_alloc + esp_iv_len, NULL, 0);
2036           }
2037
2038           if (err)
2039           {
2040             fprintf(stderr, "<IPsec/ESP Dissector> Error in Algorithm %s, Mode %d, gcry_cipher_decrypt failed: %s\n",
2041                     gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gpg_strerror (err));
2042             gcry_cipher_close(*cipher_hd);
2043             g_free(decrypted_data);
2044             decrypt_ok = FALSE;
2045           }
2046           else
2047           {
2048             /* Copy back the Authentication which was not encrypted */
2049             if(decrypted_len >= esp_auth_len)
2050             {
2051               tvb_memcpy(tvb, decrypted_data+decrypted_len-esp_auth_len, (gint)(sizeof(struct newesp)+decrypted_len-esp_auth_len), esp_auth_len);
2052             }
2053
2054             /* Decryption has finished */
2055             decrypt_ok = TRUE;
2056           }
2057         }
2058       }
2059     }
2060     else if(g_esp_enable_null_encryption_decode_heuristic)
2061     {
2062       /* The packet does not belong to a Security Association */
2063       null_encryption_decode_heuristic = TRUE;
2064     }
2065
2066     if(decrypt_ok && (decrypted_len > esp_iv_len))
2067     {
2068       tvb_decrypted = tvb_new_child_real_data(tvb, (guint8 *)g_memdup(decrypted_data+sizeof(guint8)*esp_iv_len,
2069                                                                       decrypted_len - esp_iv_len),
2070                                               decrypted_len - esp_iv_len, decrypted_len - esp_iv_len);
2071       g_free(decrypted_data);
2072
2073       add_new_data_source(pinfo, tvb_decrypted, "Decrypted Data");
2074
2075       /* Handler to free the Decrypted Data Buffer. */
2076       tvb_set_free_cb(tvb_decrypted,g_free);
2077
2078       if(tvb_bytes_exist(tvb, 8, esp_iv_len))
2079       {
2080         if(esp_iv_len > 0)
2081           proto_tree_add_item(esp_tree, hf_esp_iv, tvb, 8, esp_iv_len, ENC_NA);
2082       }
2083       else
2084       {
2085           proto_tree_add_bytes_format(esp_tree, hf_esp_iv, tvb, 8, -1, NULL, "IV (truncated)");
2086       }
2087
2088       /* Make sure the packet is not truncated before the fields
2089        * we need to read to determine the encapsulated protocol */
2090       if(tvb_bytes_exist(tvb_decrypted, decrypted_len - esp_iv_len - esp_auth_len - 2, 2))
2091       {
2092         esp_pad_len = tvb_get_guint8(tvb_decrypted, decrypted_len - esp_iv_len - esp_auth_len - 2);
2093
2094         if(decrypted_len - esp_iv_len - esp_auth_len - esp_pad_len - 2 >= 0)
2095         {
2096           /* Get the encapsulated protocol */
2097           encapsulated_protocol = tvb_get_guint8(tvb_decrypted, decrypted_len - esp_iv_len - esp_auth_len - 1);
2098
2099           dissector_handle = dissector_get_uint_handle(ip_dissector_table, encapsulated_protocol);
2100           if (dissector_handle) {
2101             saved_match_uint  = pinfo->match_uint;
2102             pinfo->match_uint = encapsulated_protocol;
2103             next_tvb = tvb_new_subset_length(tvb_decrypted, 0,
2104                                       decrypted_len - esp_auth_len - esp_pad_len - esp_iv_len - 2);
2105             export_ipsec_pdu(dissector_handle, pinfo, next_tvb);
2106             call_dissector(dissector_handle, next_tvb, pinfo, tree);
2107             pinfo->match_uint = saved_match_uint;
2108             decrypt_dissect_ok = TRUE;
2109           }
2110         }
2111       }
2112
2113       if(decrypt_dissect_ok)
2114       {
2115         if(esp_tree)
2116         {
2117           if(esp_pad_len !=0)
2118             proto_tree_add_item(esp_tree, hf_esp_pad,
2119                                 tvb_decrypted,
2120                                 decrypted_len - esp_iv_len - esp_auth_len - 2 - esp_pad_len,
2121                                 esp_pad_len, ENC_NA);
2122
2123           proto_tree_add_uint(esp_tree, hf_esp_pad_len, tvb_decrypted,
2124                               decrypted_len - esp_iv_len - esp_auth_len - 2, 1,
2125                               esp_pad_len);
2126
2127           proto_tree_add_uint_format(esp_tree, hf_esp_protocol, tvb_decrypted,
2128                                      decrypted_len - esp_iv_len - esp_auth_len - 1, 1,
2129                                      encapsulated_protocol,
2130                                      "Next header: %s (0x%02x)",
2131                                      ipprotostr(encapsulated_protocol), encapsulated_protocol);
2132
2133           dissect_esp_authentication(esp_tree,
2134                                      tvb_decrypted,
2135                                      decrypted_len - esp_iv_len,
2136                                      esp_auth_len,
2137                                      authenticator_data_computed,
2138                                      authentication_ok,
2139                                      authentication_checking_ok );
2140         }
2141       }
2142       else
2143       {
2144         next_tvb = tvb_new_subset_length(tvb_decrypted, 0,
2145                                   decrypted_len - esp_iv_len - esp_auth_len);
2146         export_ipsec_pdu(data_handle, pinfo, next_tvb);
2147         call_dissector(data_handle, next_tvb, pinfo, esp_tree);
2148
2149         if(esp_tree)
2150           dissect_esp_authentication(esp_tree,
2151                                      tvb_decrypted,
2152                                      decrypted_len - esp_iv_len, esp_auth_len,
2153                                      authenticator_data_computed, authentication_ok,
2154                                      authentication_checking_ok );
2155       }
2156     }
2157   }
2158
2159   /*
2160     If the packet is present in the security association database and the field g_esp_enable_authentication_check set.
2161   */
2162   if(!g_esp_enable_encryption_decode && g_esp_enable_authentication_check && sad_is_present)
2163   {
2164     next_tvb = tvb_new_subset(tvb, 8, len - 8 - esp_auth_len, -1);
2165     export_ipsec_pdu(data_handle, pinfo, next_tvb);
2166     call_dissector(data_handle, next_tvb, pinfo, esp_tree);
2167
2168     if(esp_tree)
2169       dissect_esp_authentication(esp_tree, tvb, len ,
2170                                  esp_auth_len, authenticator_data_computed,
2171                                  authentication_ok, authentication_checking_ok );
2172   }
2173
2174   /* The packet does not belong to a security association and the field g_esp_enable_null_encryption_decode_heuristic is set */
2175   else if(null_encryption_decode_heuristic)
2176   {
2177 #endif
2178     if(g_esp_enable_null_encryption_decode_heuristic)
2179     {
2180       /* Get length of whole ESP packet. */
2181       len = tvb_reported_length(tvb);
2182
2183       /* Make sure the packet is not truncated before the fields
2184        * we need to read to determine the encapsulated protocol */
2185       if(tvb_bytes_exist(tvb, len - 14, 2))
2186       {
2187         esp_pad_len = tvb_get_guint8(tvb, len - 14);
2188         encapsulated_protocol = tvb_get_guint8(tvb, len - 13);
2189         dissector_handle = dissector_get_uint_handle(ip_dissector_table, encapsulated_protocol);
2190         if (dissector_handle) {
2191           saved_match_uint  = pinfo->match_uint;
2192           pinfo->match_uint = encapsulated_protocol;
2193           next_tvb = tvb_new_subset_length(tvb, 8, len - 8 - 14 - esp_pad_len);
2194           export_ipsec_pdu(dissector_handle, pinfo, next_tvb);
2195           call_dissector(dissector_handle, next_tvb, pinfo, tree);
2196           pinfo->match_uint = saved_match_uint;
2197           decrypt_dissect_ok = TRUE;
2198         }
2199       }
2200     }
2201
2202     if(decrypt_dissect_ok)
2203     {
2204       if(esp_tree)
2205       {
2206         proto_tree_add_uint(esp_tree, hf_esp_pad_len, tvb,
2207                             len - 14, 1,
2208                             esp_pad_len);
2209
2210         proto_tree_add_uint_format(esp_tree, hf_esp_protocol, tvb,
2211                                    len - 13, 1,
2212                                    encapsulated_protocol,
2213                                    "Next header: %s (0x%02x)",
2214                                    ipprotostr(encapsulated_protocol), encapsulated_protocol);
2215
2216         /* Make sure we have the auth trailer data */
2217         if(tvb_bytes_exist(tvb, len - 12, 12))
2218         {
2219           proto_tree_add_item(esp_tree, hf_esp_authentication_data, tvb, len - 12, 12, ENC_NA);
2220         }
2221         else
2222         {
2223           /* Truncated so just display what we have */
2224           proto_tree_add_bytes_format(esp_tree, hf_esp_authentication_data, tvb, len - 12, 12 - (len - tvb_captured_length(tvb)),
2225                               NULL, "Authentication Data (truncated)");
2226         }
2227       }
2228     }
2229 #ifdef HAVE_LIBGCRYPT
2230   }
2231 #endif
2232   return tvb_captured_length(tvb);
2233 }
2234
2235
2236 static int
2237 dissect_ipcomp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* dissector_data _U_)
2238 {
2239   proto_tree *ipcomp_tree;
2240   proto_item *ti;
2241   struct ipcomp ipcomp;
2242   const char *p;
2243   dissector_handle_t dissector_handle;
2244   guint32 saved_match_uint;
2245   tvbuff_t *data, *decomp;
2246
2247   /*
2248    * load the top pane info. This should be overwritten by
2249    * the next protocol in the stack
2250    */
2251   col_set_str(pinfo->cinfo, COL_PROTOCOL, "IPComp");
2252   col_clear(pinfo->cinfo, COL_INFO);
2253
2254   tvb_memcpy(tvb, (guint8 *)&ipcomp, 0, sizeof(ipcomp));
2255
2256   p = try_val_to_str(g_ntohs(ipcomp.comp_cpi), cpi2val);
2257   if (p == NULL) {
2258     col_add_fstr(pinfo->cinfo, COL_INFO, "IPComp (CPI=0x%04x)", g_ntohs(ipcomp.comp_cpi));
2259   } else {
2260     col_add_fstr(pinfo->cinfo, COL_INFO, "IPComp (CPI=%s)", p);
2261   }
2262
2263   /*
2264    * populate a tree in the second pane with the status of the link layer
2265    * (ie none)
2266    */
2267     ti = proto_tree_add_item(tree, proto_ipcomp, tvb, 0, -1, ENC_NA);
2268     ipcomp_tree = proto_item_add_subtree(ti, ett_ipcomp);
2269
2270     proto_tree_add_uint_format_value(ipcomp_tree, hf_ipcomp_next_header, tvb,
2271                         offsetof(struct ipcomp, comp_nxt), 1,
2272                         ipcomp.comp_nxt, "%s (0x%02x)",
2273                         ipprotostr(ipcomp.comp_nxt), ipcomp.comp_nxt);
2274     proto_tree_add_uint(ipcomp_tree, hf_ipcomp_flags, tvb,
2275                         offsetof(struct ipcomp, comp_flags), 1,
2276                         ipcomp.comp_flags);
2277     proto_tree_add_uint(ipcomp_tree, hf_ipcomp_cpi, tvb,
2278                         offsetof(struct ipcomp, comp_cpi), 2,
2279                         g_ntohs(ipcomp.comp_cpi));
2280
2281     data = tvb_new_subset_remaining(tvb, sizeof(struct ipcomp));
2282     export_ipsec_pdu(data_handle, pinfo, data);
2283     call_dissector(data_handle, data, pinfo, ipcomp_tree);
2284
2285     /*
2286      * try to uncompress as if it were DEFLATEd.  With negotiated
2287      * CPIs, we don't know the algorithm beforehand; if we get it
2288      * wrong, tvb_uncompress() returns NULL and nothing is displayed.
2289      */
2290     decomp = tvb_child_uncompress(data, data, 0, tvb_captured_length(data));
2291     if (decomp) {
2292         add_new_data_source(pinfo, decomp, "IPcomp inflated data");
2293         saved_match_uint  = pinfo->match_uint;
2294         dissector_handle = dissector_get_uint_handle(ip_dissector_table, ipcomp.comp_nxt);
2295         if (dissector_handle) {
2296           pinfo->match_uint = ipcomp.comp_nxt;
2297         } else {
2298           dissector_handle = data_handle;
2299         }
2300         export_ipsec_pdu(dissector_handle, pinfo, decomp);
2301         call_dissector(dissector_handle, decomp, pinfo, tree);
2302         pinfo->match_uint = saved_match_uint;
2303     }
2304
2305         return tvb_captured_length(tvb);
2306 }
2307
2308 static void ipsec_init_protocol(void)
2309 {
2310   esp_sequence_analysis_hash = g_hash_table_new(word_hash_func, word_equal);
2311   esp_sequence_analysis_report_hash = g_hash_table_new(word_hash_func, word_equal);
2312 }
2313
2314 static void ipsec_cleanup_protocol(void)
2315 {
2316 #ifdef HAVE_LIBGCRYPT
2317   /* Free any SA records added by other dissectors */
2318   guint n;
2319   for (n=0; n < extra_esp_sa_records.num_records; n++) {
2320     uat_esp_sa_record_free_cb(&(extra_esp_sa_records.records[n]));
2321   }
2322
2323   /* Free overall block of records */
2324   g_free(extra_esp_sa_records.records);
2325   extra_esp_sa_records.records = NULL;
2326   extra_esp_sa_records.num_records = 0;
2327 #endif
2328
2329   g_hash_table_destroy(esp_sequence_analysis_hash);
2330   g_hash_table_destroy(esp_sequence_analysis_report_hash);
2331 }
2332
2333 void
2334 proto_register_ipsec(void)
2335 {
2336   static hf_register_info hf_ah[] = {
2337     { &hf_ah_next_header,
2338       { "Next header", "ah.next_header", FT_UINT8, BASE_HEX, NULL, 0x0,
2339         NULL, HFILL }},
2340     { &hf_ah_length,
2341       { "Length", "ah.length", FT_UINT8, BASE_HEX, NULL, 0x0,
2342         NULL, HFILL }},
2343     { &hf_ah_spi,
2344       { "AH SPI", "ah.spi", FT_UINT32, BASE_HEX, NULL, 0x0,
2345         "IP Authentication Header Security Parameters Index", HFILL }},
2346     { &hf_ah_iv,
2347       { "AH ICV", "ah.icv", FT_BYTES, BASE_NONE, NULL, 0x0,
2348         "IP Authentication Header Integrity Check Value", HFILL }},
2349     { &hf_ah_sequence,
2350       { "AH Sequence", "ah.sequence", FT_UINT32, BASE_DEC, NULL, 0x0,
2351         "IP Authentication Header Sequence Number", HFILL }}
2352   };
2353
2354   static hf_register_info hf_esp[] = {
2355     { &hf_esp_spi,
2356       { "ESP SPI", "esp.spi", FT_UINT32, BASE_HEX_DEC, NULL, 0x0,
2357         "IP Encapsulating Security Payload Security Parameters Index", HFILL }},
2358     { &hf_esp_sequence,
2359       { "ESP Sequence", "esp.sequence", FT_UINT32, BASE_DEC, NULL, 0x0,
2360         "IP Encapsulating Security Payload Sequence Number", HFILL }},
2361     { &hf_esp_pad,
2362       { "Pad", "esp.pad", FT_BYTES, BASE_NONE, NULL, 0x0,
2363         NULL, HFILL }},
2364     { &hf_esp_pad_len,
2365       { "ESP Pad Length", "esp.pad_len", FT_UINT8, BASE_DEC, NULL, 0x0,
2366         "IP Encapsulating Security Payload Pad Length", HFILL }},
2367     { &hf_esp_protocol,
2368       { "ESP Next Header", "esp.protocol", FT_UINT8, BASE_HEX, NULL, 0x0,
2369         "IP Encapsulating Security Payload Next Header", HFILL }},
2370     { &hf_esp_authentication_data,
2371       { "Authentication Data", "esp.authentication_data", FT_BYTES, BASE_NONE, NULL, 0x0,
2372         NULL, HFILL }},
2373     { &hf_esp_iv,
2374       { "ESP IV", "esp.iv", FT_BYTES, BASE_NONE, NULL, 0x0,
2375         "IP Encapsulating Security Payload", HFILL }},
2376
2377     { &hf_esp_icv_good,
2378       { "Good", "esp.icv_good", FT_BOOLEAN, BASE_NONE,  NULL, 0x0,
2379         "True: ICV matches packet content; False: doesn't match content or not checked", HFILL }},
2380     { &hf_esp_icv_bad,
2381       { "Bad", "esp.icv_bad", FT_BOOLEAN, BASE_NONE,  NULL, 0x0,
2382         "True: ICV doesn't match packet content; False: matches content or not checked", HFILL }},
2383     { &hf_esp_sequence_analysis_expected_sn,
2384       { "Expected SN", "esp.sequence-analysis.expected-sn", FT_UINT32, BASE_DEC,  NULL, 0x0,
2385         NULL, HFILL }},
2386     { &hf_esp_sequence_analysis_previous_frame,
2387       { "Previous Frame", "esp.sequence-analysis.previous-frame", FT_FRAMENUM, BASE_NONE,  NULL, 0x0,
2388         NULL, HFILL }},
2389   };
2390
2391   static hf_register_info hf_ipcomp[] = {
2392     { &hf_ipcomp_next_header,
2393       { "Next Header", "ipcomp.next_header", FT_UINT8, BASE_HEX, NULL, 0x0,
2394         NULL, HFILL }},
2395     { &hf_ipcomp_flags,
2396       { "IPComp Flags", "ipcomp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
2397         "IP Payload Compression Protocol Flags", HFILL }},
2398     { &hf_ipcomp_cpi,
2399       { "IPComp CPI", "ipcomp.cpi", FT_UINT16, BASE_HEX, VALS(cpi2val), 0x0,
2400         "IP Payload Compression Protocol Compression Parameter Index", HFILL }},
2401   };
2402
2403   static gint *ett[] = {
2404     &ett_ah,
2405     &ett_esp,
2406     &ett_esp_icv,
2407     &ett_ipcomp,
2408   };
2409
2410   static ei_register_info ei[] = {
2411     { &ei_esp_sequence_analysis_wrong_sequence_number, { "esp.sequence-analysis.wrong-sequence-number", PI_SEQUENCE, PI_WARN, "Wrong Sequence Number", EXPFILL }}
2412   };
2413
2414 #ifdef HAVE_LIBGCRYPT
2415
2416   static const value_string esp_proto_type_vals[] = {
2417     { IPSEC_SA_IPV4, "IPv4" },
2418     { IPSEC_SA_IPV6, "IPv6" },
2419     { 0x00, NULL }
2420   };
2421
2422   static const value_string esp_encryption_type_vals[] = {
2423     { IPSEC_ENCRYPT_NULL, "NULL" },
2424     { IPSEC_ENCRYPT_3DES_CBC, "TripleDES-CBC [RFC2451]" },
2425     { IPSEC_ENCRYPT_AES_CBC, "AES-CBC [RFC3602]" },
2426     { IPSEC_ENCRYPT_AES_CTR, "AES-CTR [RFC3686]" },
2427     { IPSEC_ENCRYPT_DES_CBC, "DES-CBC [RFC2405]" },
2428     { IPSEC_ENCRYPT_CAST5_CBC, "CAST5-CBC [RFC2144]" },
2429     { IPSEC_ENCRYPT_BLOWFISH_CBC, "BLOWFISH-CBC [RFC2451]" },
2430     { IPSEC_ENCRYPT_TWOFISH_CBC, "TWOFISH-CBC" },
2431     { IPSEC_ENCRYPT_AES_GCM, "AES-GCM [RFC4106]" },
2432     { 0x00, NULL }
2433   };
2434
2435   static const value_string esp_authentication_type_vals[] = {
2436     { IPSEC_AUTH_NULL, "NULL" },
2437     { IPSEC_AUTH_HMAC_SHA1_96, "HMAC-SHA-1-96 [RFC2404]" },
2438     { IPSEC_AUTH_HMAC_SHA256_96, "HMAC-SHA-256-96 [draft-ietf-ipsec-ciph-sha-256-00]" },
2439     { IPSEC_AUTH_HMAC_SHA256_128, "HMAC-SHA-256-128 [RFC4868]" },
2440     { IPSEC_AUTH_HMAC_SHA384_192, "HMAC-SHA-384-192 [RFC4868]" },
2441     { IPSEC_AUTH_HMAC_SHA512_256, "HMAC-SHA-512-256 [RFC4868]" },
2442     { IPSEC_AUTH_HMAC_MD5_96, "HMAC-MD5-96 [RFC2403]" },
2443     { IPSEC_AUTH_HMAC_RIPEMD160_96, "MAC-RIPEMD-160-96 [RFC2857]" },
2444 /*    { IPSEC_AUTH_AES_XCBC_MAC_96, "AES-XCBC-MAC-96 [RFC3566]" }, */
2445     { IPSEC_AUTH_ANY_64BIT, "ANY 64 bit authentication [no checking]" },
2446     { IPSEC_AUTH_ANY_96BIT, "ANY 96 bit authentication [no checking]" },
2447     { IPSEC_AUTH_ANY_128BIT, "ANY 128 bit authentication [no checking]" },
2448     { IPSEC_AUTH_ANY_192BIT, "ANY 192 bit authentication [no checking]" },
2449     { IPSEC_AUTH_ANY_256BIT, "ANY 256 bit authentication [no checking]" },
2450     { 0x00, NULL }
2451   };
2452
2453   static uat_field_t esp_uat_flds[] = {
2454       UAT_FLD_VS(uat_esp_sa_records, protocol, "Protocol", esp_proto_type_vals, "Protocol used"),
2455       UAT_FLD_CSTRING(uat_esp_sa_records, srcIP, "Src IP", "Source Address"),
2456       UAT_FLD_CSTRING(uat_esp_sa_records, dstIP, "Dest IP", "Destination Address"),
2457       UAT_FLD_CSTRING(uat_esp_sa_records, spi, "SPI", "SPI"),
2458       UAT_FLD_VS(uat_esp_sa_records, encryption_algo, "Encryption", esp_encryption_type_vals, "Encryption algorithm"),
2459       UAT_FLD_CSTRING(uat_esp_sa_records, encryption_key_string, "Encryption Key", "Encryption Key"),
2460       UAT_FLD_VS(uat_esp_sa_records, authentication_algo, "Authentication", esp_authentication_type_vals, "Authentication algorithm"),
2461       UAT_FLD_CSTRING(uat_esp_sa_records, authentication_key_string, "Authentication Key", "Authentication Key"),
2462       UAT_END_FIELDS
2463     };
2464 #endif
2465
2466   module_t *ah_module;
2467   module_t *esp_module;
2468
2469   expert_module_t* expert_esp;
2470
2471   proto_ah = proto_register_protocol("Authentication Header", "AH", "ah");
2472   proto_register_field_array(proto_ah, hf_ah, array_length(hf_ah));
2473
2474   proto_esp = proto_register_protocol("Encapsulating Security Payload",
2475                                       "ESP", "esp");
2476   proto_register_field_array(proto_esp, hf_esp, array_length(hf_esp));
2477
2478   proto_ipcomp = proto_register_protocol("IP Payload Compression",
2479                                          "IPComp", "ipcomp");
2480   proto_register_field_array(proto_ipcomp, hf_ipcomp, array_length(hf_ipcomp));
2481
2482   proto_register_subtree_array(ett, array_length(ett));
2483
2484   expert_esp = expert_register_protocol(proto_esp);
2485   expert_register_field_array(expert_esp, ei, array_length(ei));
2486
2487   /* Register a configuration option for placement of AH payload dissection */
2488   ah_module = prefs_register_protocol(proto_ah, NULL);
2489   prefs_register_bool_preference(ah_module, "place_ah_payload_in_subtree",
2490                                  "Place AH payload in subtree",
2491                                  "Whether the AH payload decode should be placed in a subtree",
2492                                  &g_ah_payload_in_subtree);
2493   esp_module = prefs_register_protocol(proto_esp, NULL);
2494
2495   prefs_register_bool_preference(esp_module, "enable_null_encryption_decode_heuristic",
2496                                  "Attempt to detect/decode NULL encrypted ESP payloads",
2497                                  "This is done only if the Decoding is not SET or the packet does not belong to a SA. "
2498                                  "Assumes a 12 byte auth (HMAC-SHA1-96/HMAC-MD5-96/AES-XCBC-MAC-96) "
2499                                  "and attempts decode based on the ethertype 13 bytes from packet end",
2500                                  &g_esp_enable_null_encryption_decode_heuristic);
2501
2502   prefs_register_bool_preference(esp_module, "do_esp_sequence_analysis",
2503                                  "Check sequence numbers of ESP frames",
2504                                  "Check that successive frames increase sequence number by 1 within an SPI.  This should work OK when only one host is sending frames on an SPI",
2505                                  &g_esp_do_sequence_analysis);
2506
2507 #ifdef HAVE_LIBGCRYPT
2508   prefs_register_bool_preference(esp_module, "enable_encryption_decode",
2509                                  "Attempt to detect/decode encrypted ESP payloads",
2510                                  "Attempt to decode based on the SAD described hereafter.",
2511                                  &g_esp_enable_encryption_decode);
2512
2513   prefs_register_bool_preference(esp_module, "enable_authentication_check",
2514                                  "Attempt to Check ESP Authentication",
2515                                  "Attempt to Check ESP Authentication based on the SAD described hereafter.",
2516                                  &g_esp_enable_authentication_check);
2517
2518   esp_uat = uat_new("ESP SAs",
2519             sizeof(uat_esp_sa_record_t),    /* record size */
2520             "esp_sa",                       /* filename */
2521             TRUE,                           /* from_profile */
2522             &uat_esp_sa_records,            /* data_ptr */
2523             &num_sa_uat,                    /* numitems_ptr */
2524             UAT_AFFECTS_DISSECTION,         /* affects dissection of packets, but not set of named fields */
2525             NULL,                           /* help */
2526             uat_esp_sa_record_copy_cb,      /* copy callback */
2527             uat_esp_sa_record_update_cb,    /* update callback */
2528             uat_esp_sa_record_free_cb,      /* free callback */
2529             NULL,                           /* post update callback */
2530             esp_uat_flds);                  /* UAT field definitions */
2531
2532   prefs_register_uat_preference(esp_module,
2533                                 "sa_table",
2534                                 "ESP SAs",
2535                                 "Preconfigured ESP Security Associations",
2536                                 esp_uat);
2537 #endif
2538
2539   register_init_routine(&ipsec_init_protocol);
2540   register_cleanup_routine(&ipsec_cleanup_protocol);
2541
2542   new_register_dissector("esp", dissect_esp, proto_esp);
2543   new_register_dissector("ah", dissect_ah, proto_ah);
2544 }
2545
2546 void
2547 proto_reg_handoff_ipsec(void)
2548 {
2549   dissector_handle_t esp_handle, ah_handle, ipv6_ah_handle, ipcomp_handle;
2550
2551   data_handle = find_dissector("data");
2552   ah_handle = find_dissector("ah");
2553   dissector_add_uint("ip.proto", IP_PROTO_AH, ah_handle);
2554   esp_handle = find_dissector("esp");
2555   dissector_add_uint("ip.proto", IP_PROTO_ESP, esp_handle);
2556   ipcomp_handle = new_create_dissector_handle(dissect_ipcomp, proto_ipcomp);
2557   dissector_add_uint("ip.proto", IP_PROTO_IPCOMP, ipcomp_handle);
2558   ipv6_ah_handle = new_create_dissector_handle(dissect_ah_header, proto_ah );
2559   dissector_add_uint("ipv6.nxt", IP_PROTO_AH, ipv6_ah_handle);
2560
2561   ip_dissector_table = find_dissector_table("ip.proto");
2562
2563   exported_pdu_tap = find_tap_id(EXPORT_PDU_TAP_NAME_LAYER_3);
2564 }
2565
2566 /*
2567  * Editor modelines
2568  *
2569  * Local Variables:
2570  * c-basic-offset: 2
2571  * tab-width: 8
2572  * indent-tabs-mode: nil
2573  * End:
2574  *
2575  * ex: set shiftwidth=2 tabstop=8 expandtab:
2576  * :indentSize=2:tabSize=8:noTabs=true:
2577  */