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