TODO drsuapi compressed
[wireshark-sm.git] / epan / dissectors / packet-ipsec.c
blob4c4042b7ed8249701ec0cab90e721832ea1252b1
1 /* packet-ipsec.c
2 * Routines for IPsec/IPComp packet disassembly
4 * Wireshark - Network traffic analyzer
5 * By Gerald Combs <gerald@wireshark.org>
6 * Copyright 1998 Gerald Combs
8 * SPDX-License-Identifier: GPL-2.0-or-later
9 */
14 Addon: ESP Decryption and Authentication Checking
16 Frederic ROUDAUT (frederic.roudaut@free.fr)
17 Copyright 2006 Frederic ROUDAUT
19 - Decrypt ESP Payload for the following Algorithms defined in RFC 4305:
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
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
34 - Check ESP Authentication for the following Algorithms defined in RFC 4305:
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.
43 - Add ESP Authentication checking for the following Authentication Algorithm :
44 HMAC-SHA256 : any keylen
45 HMAC-RIPEMD160-96 [RFC2857] : any keylen
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.
58 #include "config.h"
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>
72 #include <stdio.h> /* for sscanf() */
73 #include <epan/uat.h>
74 #include <wsutil/str_util.h>
75 #include <wsutil/wsgcrypt.h>
76 #include <wsutil/pint.h>
78 #include "packet-ipsec.h"
79 #include "packet-ip.h"
81 void proto_register_ipsec(void);
82 void proto_reg_handoff_ipsec(void);
84 static int proto_ah;
85 static int hf_ah_next_header;
86 static int hf_ah_length;
87 static int hf_ah_reserved;
88 static int hf_ah_spi;
89 static int hf_ah_iv;
90 static int hf_ah_sequence;
91 static int proto_esp;
92 static int hf_esp_spi;
93 static int hf_esp_iv;
94 static int hf_esp_icv;
95 static int hf_esp_icv_good;
96 static int hf_esp_icv_bad;
97 static int hf_esp_sequence;
98 static int hf_esp_encrypted_data;
99 static int hf_esp_decrypted_data;
100 static int hf_esp_contained_data;
101 static int hf_esp_pad;
102 static int hf_esp_pad_len;
103 static int hf_esp_protocol;
104 static int hf_esp_sequence_analysis_expected_sn;
105 static int hf_esp_sequence_analysis_previous_frame;
107 static int proto_ipcomp;
108 static int hf_ipcomp_next_header;
109 static int hf_ipcomp_flags;
110 static int hf_ipcomp_cpi;
112 static int ett_ah;
113 static int ett_esp;
114 static int ett_esp_icv;
115 static int ett_esp_decrypted_data;
116 static int ett_ipcomp;
118 static expert_field ei_esp_sequence_analysis_wrong_sequence_number;
119 static expert_field ei_esp_pad_bogus;
122 static int exported_pdu_tap = -1;
124 static dissector_handle_t ipcomp_handle;
125 static capture_dissector_handle_t ah_cap_handle;
127 static dissector_handle_t data_handle;
129 static dissector_table_t ip_dissector_table;
131 /* Encryption algorithms defined in RFC 4305 */
132 #define IPSEC_ENCRYPT_NULL 0
133 #define IPSEC_ENCRYPT_3DES_CBC 1
134 #define IPSEC_ENCRYPT_AES_CBC 2
135 #define IPSEC_ENCRYPT_AES_CTR 3
136 #define IPSEC_ENCRYPT_DES_CBC 4
137 #define IPSEC_ENCRYPT_BLOWFISH_CBC 5
138 #define IPSEC_ENCRYPT_TWOFISH_CBC 6
140 /* Encryption algorithm defined in RFC 2144 */
141 #define IPSEC_ENCRYPT_CAST5_CBC 7
143 /* Encryption algorithms defined in RFC 4106 */
144 #define IPSEC_ENCRYPT_AES_GCM 8
145 #define IPSEC_ENCRYPT_AES_GCM_8 9
146 #define IPSEC_ENCRYPT_AES_GCM_12 10
147 #define IPSEC_ENCRYPT_AES_GCM_16 11
149 /* Encryption algorithm defined in RFC 4106 & RFC 8750 */
150 #define IPSEC_ENCRYPT_AES_GCM_16_IIV 12
152 /* Encryption algorithm defined in RFC 7634 */
153 #define IPSEC_ENCRYPT_CHACHA20_POLY1305 13
155 /* Encryption algorithm defined in RFC 7634 & RFC 8750 */
156 #define IPSEC_ENCRYPT_CHACHA20_POLY1305_IIV 14
158 /* Authentication algorithms defined in RFC 4305 */
159 #define IPSEC_AUTH_NULL 0
160 #define IPSEC_AUTH_HMAC_SHA1_96 1
161 #define IPSEC_AUTH_HMAC_SHA256_96 2
162 #define IPSEC_AUTH_HMAC_SHA256_128 3
163 #define IPSEC_AUTH_HMAC_SHA384_192 4
164 #define IPSEC_AUTH_HMAC_SHA512_256 5
165 #define IPSEC_AUTH_HMAC_MD5_96 6
166 #define IPSEC_AUTH_HMAC_RIPEMD160_96 7
167 /* define IPSEC_AUTH_AES_XCBC_MAC_96 6 */
168 #define IPSEC_AUTH_ANY_64BIT 8
169 #define IPSEC_AUTH_ANY_96BIT 9
170 #define IPSEC_AUTH_ANY_128BIT 10
171 #define IPSEC_AUTH_ANY_192BIT 11
172 #define IPSEC_AUTH_ANY_256BIT 12
174 /* ICV types (not an RFC classification) */
175 #define ICV_TYPE_UNCHECKED 0 /* ICV is not verified */
176 #define ICV_TYPE_HMAC 1 /* ICV is verified before decryption using an HMAC */
177 #define ICV_TYPE_AEAD 2 /* ICV is verified during decryption using an AEAD cipher */
179 #define IPSEC_IPV6_ADDR_LEN 128
180 #define IPSEC_IPV4_ADDR_LEN 32
181 #define IPSEC_STRLEN_IPV6 32
182 #define IPSEC_STRLEN_IPV4 8
183 #define IPSEC_SA_IPV4 1
184 #define IPSEC_SA_IPV6 2
185 #define IPSEC_SA_ANY 3
186 #define IPSEC_SA_UNKNOWN -1
187 #define IPSEC_SA_WILDCARDS_ANY '*'
188 /* the maximum number of bytes (10)(including the terminating nul character(11)) */
189 #define IPSEC_SPI_LEN_MAX 11
190 #define IPSEC_SA_SN 32
191 #define IPSEC_SA_ESN 64
194 /* well-known algorithm number (in CPI), from RFC2409 */
195 #define IPCOMP_OUI 1 /* vendor specific */
196 #define IPCOMP_DEFLATE 2 /* RFC2394 */
197 #define IPCOMP_LZS 3 /* RFC2395 */
198 #define IPCOMP_MAX 4
201 static const value_string cpi2val[] = {
202 { IPCOMP_OUI, "OUI" },
203 { IPCOMP_DEFLATE, "DEFLATE" },
204 { IPCOMP_LZS, "LZS" },
205 { 0, NULL },
208 /* The length of the two fields (SPI and Sequence Number) preceding the Payload Data */
209 #define ESP_HEADER_LEN 8
212 static const value_string esp_encryption_type_vals[] = {
213 { IPSEC_ENCRYPT_NULL, "NULL" },
214 { IPSEC_ENCRYPT_3DES_CBC, "TripleDES-CBC [RFC2451]" },
215 { IPSEC_ENCRYPT_AES_CBC, "AES-CBC [RFC3602]" },
216 { IPSEC_ENCRYPT_AES_CTR, "AES-CTR [RFC3686]" },
217 { IPSEC_ENCRYPT_DES_CBC, "DES-CBC [RFC2405]" },
218 { IPSEC_ENCRYPT_CAST5_CBC, "CAST5-CBC [RFC2144]" },
219 { IPSEC_ENCRYPT_BLOWFISH_CBC, "BLOWFISH-CBC [RFC2451]" },
220 { IPSEC_ENCRYPT_TWOFISH_CBC, "TWOFISH-CBC" },
221 { IPSEC_ENCRYPT_AES_GCM, "AES-GCM [RFC4106]" }, /* deprecated; (no ICV length specified) */
222 { IPSEC_ENCRYPT_AES_GCM_8, "AES-GCM with 8 octet ICV [RFC4106]" },
223 { IPSEC_ENCRYPT_AES_GCM_12, "AES-GCM with 12 octet ICV [RFC4106]" },
224 { IPSEC_ENCRYPT_AES_GCM_16, "AES-GCM with 16 octet ICV [RFC4106]" },
225 { IPSEC_ENCRYPT_AES_GCM_16_IIV, "AES-GCM with IIV and 16 octet ICV [RFC4106 & RFC8750]" },
226 { IPSEC_ENCRYPT_CHACHA20_POLY1305, "ChaCha20 with Poly1305 [RFC7634]" },
227 { IPSEC_ENCRYPT_CHACHA20_POLY1305_IIV, "ChaCha20 with Poly1305 and IIV [RFC7634 & RFC8750]" },
228 { 0x00, NULL }
231 static const char *
232 esp_get_encr_algo_name(int esp_encr_algo)
234 return esp_encryption_type_vals[esp_encr_algo].strptr;
238 static const value_string esp_authentication_type_vals[] = {
239 { IPSEC_AUTH_NULL, "NULL" },
240 { IPSEC_AUTH_HMAC_SHA1_96, "HMAC-SHA-1-96 [RFC2404]" },
241 { IPSEC_AUTH_HMAC_SHA256_96, "HMAC-SHA-256-96 [draft-ietf-ipsec-ciph-sha-256-00]" },
242 { IPSEC_AUTH_HMAC_SHA256_128, "HMAC-SHA-256-128 [RFC4868]" },
243 { IPSEC_AUTH_HMAC_SHA384_192, "HMAC-SHA-384-192 [RFC4868]" },
244 { IPSEC_AUTH_HMAC_SHA512_256, "HMAC-SHA-512-256 [RFC4868]" },
245 { IPSEC_AUTH_HMAC_MD5_96, "HMAC-MD5-96 [RFC2403]" },
246 { IPSEC_AUTH_HMAC_RIPEMD160_96, "MAC-RIPEMD-160-96 [RFC2857]" },
247 /* { IPSEC_AUTH_AES_XCBC_MAC_96, "AES-XCBC-MAC-96 [RFC3566]" }, */
248 { IPSEC_AUTH_ANY_64BIT, "ANY 64 bit authentication [no checking]" },
249 { IPSEC_AUTH_ANY_96BIT, "ANY 96 bit authentication [no checking]" },
250 { IPSEC_AUTH_ANY_128BIT, "ANY 128 bit authentication [no checking]" },
251 { IPSEC_AUTH_ANY_192BIT, "ANY 192 bit authentication [no checking]" },
252 { IPSEC_AUTH_ANY_256BIT, "ANY 256 bit authentication [no checking]" },
253 { 0x00, NULL }
256 static const char *
257 esp_get_auth_algo_name(int esp_auth_algo)
259 return esp_authentication_type_vals[esp_auth_algo].strptr;
263 /*-------------------------------------
264 * UAT for ESP
265 *-------------------------------------
267 /* UAT entry structure. */
268 typedef struct {
269 uint8_t protocol;
270 char *srcIP;
271 char *dstIP;
272 char *spi;
274 uint8_t encryption_algo; /* see values in esp_encryption_type_vals */
275 char *encryption_key_string;
276 char *encryption_key;
277 int encryption_key_length;
278 bool cipher_hd_created;
279 gcry_cipher_hd_t cipher_hd; /* Key is stored here and closed with the SA */
281 uint8_t authentication_algo; /* see values in esp_authentication_type_vals */
282 char *authentication_key_string;
283 char *authentication_key;
284 int authentication_key_length;
286 uint8_t sn_length;
287 uint32_t sn_upper;
288 } uat_esp_sa_record_t;
290 static uat_esp_sa_record_t *uat_esp_sa_records;
292 /* Extra SA records that may be set programmatically */
293 /* 'records' array is now allocated on the heap */
294 #define MAX_EXTRA_SA_RECORDS 16
295 typedef struct extra_esp_sa_records_t {
296 unsigned num_records;
297 uat_esp_sa_record_t *records;
298 } extra_esp_sa_records_t;
299 static extra_esp_sa_records_t extra_esp_sa_records;
301 static uat_t * esp_uat;
302 static unsigned num_sa_uat;
305 Name : static int compute_ascii_key(char **ascii_key, char *key)
306 Description : Allocate memory for the key and transform the key if it is hexadecimal
307 Return : Return the key length
308 Params:
309 - char **ascii_key : the resulting ascii key allocated here
310 - char *key : the key to compute
311 - char **err : an error string to report if the input is found to be invalid
313 static int
314 compute_ascii_key(char **ascii_key, const char *key, char **err)
316 unsigned key_len = 0, raw_key_len;
317 int hex_digit;
318 unsigned char key_byte;
319 unsigned i, j;
321 if(key != NULL)
323 raw_key_len = (unsigned)strlen(key);
324 if((raw_key_len > 2) && (key[0] == '0') && ((key[1] == 'x') || (key[1] == 'X')))
327 * Key begins with "0x" or "0X"; skip that and treat the rest
328 * as a sequence of hex digits.
330 i = 2; /* first character after "0[Xx]" */
331 j = 0;
332 if(raw_key_len %2 == 1)
335 * Key has an odd number of characters; we act as if the
336 * first character had a 0 in front of it, making the
337 * number of characters even.
339 key_len = (raw_key_len - 2) / 2 + 1;
340 *ascii_key = (char *) g_malloc ((key_len + 1)* sizeof(char));
341 hex_digit = g_ascii_xdigit_value(key[i]);
342 if (hex_digit == -1)
344 g_free(*ascii_key);
345 *ascii_key = NULL;
346 *err = ws_strdup_printf("Key %s begins with an invalid hex char (%c)", key, key[i]);
347 return -1; /* not a valid hex digit */
349 (*ascii_key)[j] = (unsigned char)hex_digit;
350 j++;
351 i++;
353 else
356 * Key has an even number of characters, so we treat each
357 * pair of hex digits as a single byte value.
359 key_len = (raw_key_len - 2) / 2;
360 *ascii_key = (char *) g_malloc ((key_len + 1)* sizeof(char));
363 while(i < (raw_key_len -1))
365 hex_digit = g_ascii_xdigit_value(key[i]);
366 i++;
367 if (hex_digit == -1)
369 g_free(*ascii_key);
370 *ascii_key = NULL;
371 *err = ws_strdup_printf("Key %s has an invalid hex char (%c)",
372 key, key[i-1]);
373 return -1; /* not a valid hex digit */
375 key_byte = ((unsigned char)hex_digit) << 4;
376 hex_digit = g_ascii_xdigit_value(key[i]);
377 i++;
378 if (hex_digit == -1)
380 g_free(*ascii_key);
381 *ascii_key = NULL;
382 *err = ws_strdup_printf("Key %s has an invalid hex char (%c)", key, key[i-1]);
383 return -1; /* not a valid hex digit */
385 key_byte |= (unsigned char)hex_digit;
386 (*ascii_key)[j] = key_byte;
387 j++;
389 (*ascii_key)[j] = '\0';
392 else if((raw_key_len == 2) && (key[0] == '0') && ((key[1] == 'x') || (key[1] == 'X')))
394 /* A valid null key */
395 *ascii_key = NULL;
396 return 0;
398 else
400 /* Doesn't begin with 0X or 0x... */
401 key_len = raw_key_len;
402 *ascii_key = g_strdup(key);
406 return key_len;
410 static bool uat_esp_sa_record_update_cb(void* r, char** err) {
411 uat_esp_sa_record_t* rec = (uat_esp_sa_record_t *)r;
413 /* Compute keys & lengths once and for all */
414 g_free(rec->encryption_key);
415 if (rec->cipher_hd_created) {
416 gcry_cipher_close(rec->cipher_hd);
417 rec->cipher_hd_created = false;
419 if (rec->encryption_key_string) {
420 rec->encryption_key_length = compute_ascii_key(&rec->encryption_key, rec->encryption_key_string, err);
422 else {
423 rec->encryption_key_length = 0;
424 rec->encryption_key = NULL;
427 g_free(rec->authentication_key);
428 if (rec->authentication_key_string) {
429 rec->authentication_key_length = compute_ascii_key(&rec->authentication_key, rec->authentication_key_string, err);
431 else {
432 rec->authentication_key_length = 0;
433 rec->authentication_key = NULL;
436 /* TODO: Make sure IP addresses have a valid conversion */
437 /* Unfortunately, return value of get_full_ipv4_addr() or get_full_ipv6_addr() (depending upon rec->protocol)
438 is not sufficient */
440 /* TODO: check format of spi */
442 /* Return true only if *err has not been set by checking code. */
443 return *err == NULL;
446 static void* uat_esp_sa_record_copy_cb(void* n, const void* o, size_t siz _U_) {
447 uat_esp_sa_record_t* new_rec = (uat_esp_sa_record_t *)n;
448 const uat_esp_sa_record_t* old_rec = (const uat_esp_sa_record_t *)o;
450 /* Copy UAT fields */
451 new_rec->protocol = old_rec->protocol;
452 new_rec->srcIP = g_strdup(old_rec->srcIP);
453 new_rec->dstIP = g_strdup(old_rec->dstIP);
454 new_rec->spi = g_strdup(old_rec->spi);
455 new_rec->encryption_algo = old_rec->encryption_algo;
456 new_rec->encryption_key_string = g_strdup(old_rec->encryption_key_string);
457 new_rec->encryption_key = NULL;
458 new_rec->cipher_hd_created = false;
459 new_rec->authentication_algo = old_rec->authentication_algo;
460 new_rec->authentication_key_string = g_strdup(old_rec->authentication_key_string);
461 new_rec->authentication_key = NULL;
462 new_rec->sn_length = old_rec->sn_length;
463 new_rec->sn_upper = old_rec->sn_upper;
465 /* Parse keys as in an update */
466 char *err = NULL;
467 uat_esp_sa_record_update_cb(new_rec, &err);
468 if (err) {
469 g_free(err);
472 return new_rec;
475 static void uat_esp_sa_record_free_cb(void*r) {
476 uat_esp_sa_record_t* rec = (uat_esp_sa_record_t*)r;
478 g_free(rec->srcIP);
479 g_free(rec->dstIP);
480 g_free(rec->spi);
481 g_free(rec->encryption_key_string);
482 g_free(rec->encryption_key);
483 g_free(rec->authentication_key_string);
484 g_free(rec->authentication_key);
486 if (rec->cipher_hd_created) {
487 gcry_cipher_close(rec->cipher_hd);
488 rec->cipher_hd_created = false;
492 UAT_VS_DEF(uat_esp_sa_records, protocol, uat_esp_sa_record_t, uint8_t, IPSEC_SA_IPV4, "IPv4")
493 UAT_CSTRING_CB_DEF(uat_esp_sa_records, srcIP, uat_esp_sa_record_t)
494 UAT_CSTRING_CB_DEF(uat_esp_sa_records, dstIP, uat_esp_sa_record_t)
495 UAT_CSTRING_CB_DEF(uat_esp_sa_records, spi, uat_esp_sa_record_t)
496 UAT_VS_DEF(uat_esp_sa_records, encryption_algo, uat_esp_sa_record_t, uint8_t, 0, "FIXX")
497 UAT_CSTRING_CB_DEF(uat_esp_sa_records, encryption_key_string, uat_esp_sa_record_t)
498 UAT_VS_DEF(uat_esp_sa_records, authentication_algo, uat_esp_sa_record_t, uint8_t, 0, "FIXX")
499 UAT_CSTRING_CB_DEF(uat_esp_sa_records, authentication_key_string, uat_esp_sa_record_t)
500 UAT_VS_DEF(uat_esp_sa_records, sn_length, uat_esp_sa_record_t, uint8_t, IPSEC_SA_SN, "32-bit")
501 UAT_HEX_CB_DEF(uat_esp_sa_records, sn_upper, uat_esp_sa_record_t)
504 /* Configure a new SA (programmatically, most likely from a private dissector).
505 The arguments here are deliberately in the same string formats as the UAT fields
506 in order to keep code paths common.
507 Note that an attempt to match with these entries will be made *before* entries
508 added through the UAT entry interface/file. */
509 void esp_sa_record_add_from_dissector(uint8_t protocol, const char *srcIP, const char *dstIP,
510 char *spi,
511 uint8_t encryption_algo, /* values from esp_encryption_type_vals */
512 const char *encryption_key,
513 uint8_t authentication_algo, /* values from esp_authentication_type_vals */
514 const char *authentication_key)
516 uat_esp_sa_record_t* record = NULL;
517 if (extra_esp_sa_records.num_records == 0) {
518 extra_esp_sa_records.records = g_new(uat_esp_sa_record_t, MAX_EXTRA_SA_RECORDS);
520 /* Add new entry */
521 if (extra_esp_sa_records.num_records < MAX_EXTRA_SA_RECORDS) {
522 record = &extra_esp_sa_records.records[extra_esp_sa_records.num_records++];
524 else {
525 /* No room left!! */
526 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Failed to add UE as already have max (%d) configured\n",
527 MAX_EXTRA_SA_RECORDS);
528 return;
531 /* Copy key fields */
532 record->protocol = protocol;
533 record->srcIP = g_strdup(srcIP);
534 record->dstIP = g_strdup(dstIP);
535 record->spi = g_strdup(spi);
537 /* Encryption */
538 record->encryption_algo = encryption_algo;
539 record->encryption_key_string = g_strdup(encryption_key);
540 record->encryption_key = NULL;
541 record->cipher_hd_created = false;
543 /* Authentication */
544 record->authentication_algo = authentication_algo;
545 record->authentication_key_string = g_strdup(authentication_key);
546 record->authentication_key = NULL;
548 /* XXX - Should we change the function so private dissectors pass this in? */
549 record->sn_length = IPSEC_SA_SN;
550 record->sn_upper = 0;
552 /* Parse keys */
553 char *err = NULL;
554 uat_esp_sa_record_update_cb(record, &err);
555 if (err) {
556 /* Free (but ignore) any error string set */
557 g_free(err);
561 /*************************************/
562 /* Preference settings */
564 /* Default ESP payload decode to off */
565 static bool g_esp_enable_encryption_decode;
567 /* Default ESP payload Authentication Checking to off */
568 static bool g_esp_enable_authentication_check;
570 /**************************************************/
571 /* Sequence number analysis */
573 /* SPI state, key is just 32-bit SPI */
574 typedef struct
576 uint32_t firstValidSN;
577 uint32_t previousSequenceNumber;
578 uint32_t previousFrameNum;
579 } spi_status;
581 /* The sequence analysis SPI hash table.
582 Maps SPI -> spi_status */
583 static wmem_map_t *esp_sequence_analysis_hash;
585 /* Results are stored here: framenum -> spi_status */
586 /* N.B. only store entries for out-of-order frames, if there is no entry for
587 a given frame, it was found to be in-order */
588 static wmem_map_t *esp_sequence_analysis_report_hash;
590 /* During the first pass, update the SPI state. If the sequence numbers
591 are out of order, add an entry to the report table */
592 static void check_esp_sequence_info(uint32_t spi, uint32_t sequence_number, packet_info *pinfo)
594 /* Do the table lookup */
595 spi_status *status = (spi_status*)wmem_map_lookup(esp_sequence_analysis_hash,
596 GUINT_TO_POINTER((unsigned)spi));
597 if (status == NULL) {
598 /* Create an entry for this SPI */
599 status = wmem_new0(wmem_file_scope(), spi_status);
600 status->previousSequenceNumber = sequence_number;
601 status->previousFrameNum = pinfo->num;
603 /* And add it to the table */
604 wmem_map_insert(esp_sequence_analysis_hash, GUINT_TO_POINTER((unsigned)spi), status);
606 else {
607 spi_status *frame_status;
609 /* Entry already existed, so check that we got the sequence number we expected. */
610 if (sequence_number != status->previousSequenceNumber+1) {
611 /* Create report entry */
612 frame_status = wmem_new0(wmem_file_scope(), spi_status);
613 /* Copy what was expected */
614 *frame_status = *status;
615 /* And add it into the report table */
616 wmem_map_insert(esp_sequence_analysis_report_hash, GUINT_TO_POINTER(pinfo->num), frame_status);
618 /* Adopt this setting as 'current' regardless of whether expected */
619 status->previousSequenceNumber = sequence_number;
620 status->previousFrameNum = pinfo->num;
624 /* Check to see if there is a report stored for this frame. If there is,
625 add it to the tree and report using expert info */
626 static void show_esp_sequence_info(uint32_t spi, uint32_t sequence_number,
627 tvbuff_t *tvb, proto_tree *tree, packet_info *pinfo)
629 /* Look up this frame in the report table. */
630 spi_status *status = (spi_status*)wmem_map_lookup(esp_sequence_analysis_report_hash,
631 GUINT_TO_POINTER(pinfo->num));
632 if (status != NULL) {
633 proto_item *sn_ti, *frame_ti;
635 /* Expected sequence number */
636 sn_ti = proto_tree_add_uint(tree, hf_esp_sequence_analysis_expected_sn,
637 tvb, 0, 0, status->previousSequenceNumber+1);
638 if (sequence_number > (status->previousSequenceNumber+1)) {
639 proto_item_append_text(sn_ti, " (%u SNs missing)",
640 sequence_number - (status->previousSequenceNumber+1));
642 proto_item_set_generated(sn_ti);
644 /* Link back to previous frame for SPI */
645 frame_ti = proto_tree_add_uint(tree, hf_esp_sequence_analysis_previous_frame,
646 tvb, 0, 0, status->previousFrameNum);
647 proto_item_set_generated(frame_ti);
649 /* Expert info */
650 if (sequence_number == status->previousSequenceNumber) {
651 expert_add_info_format(pinfo, sn_ti, &ei_esp_sequence_analysis_wrong_sequence_number,
652 "Wrong Sequence Number for SPI %08x - %u repeated",
653 spi, sequence_number);
655 else if (sequence_number > status->previousSequenceNumber+1) {
656 expert_add_info_format(pinfo, sn_ti, &ei_esp_sequence_analysis_wrong_sequence_number,
657 "Wrong Sequence Number for SPI %08x - %u missing",
658 spi,
659 sequence_number - (status->previousSequenceNumber+1));
661 else {
662 expert_add_info_format(pinfo, sn_ti, &ei_esp_sequence_analysis_wrong_sequence_number,
663 "Wrong Sequence Number for SPI %08x - %u less than expected",
664 spi,
665 (status->previousSequenceNumber+1) - sequence_number);
671 Default ESP payload heuristic decode to off
672 (only works if payload is NULL encrypted and ESP payload decode is off or payload is NULL encrypted
673 and the packet does not match a Security Association).
675 static bool g_esp_enable_null_encryption_decode_heuristic;
677 #define PADDING_RFC 0
678 #define PADDING_ZERO 1
679 #define PADDING_ANY 2
681 /* PADDING_RFC is chosen as 0 to be the default */
682 static int g_esp_padding_type;
684 static const enum_val_t esp_padding_vals[] = {
685 { "rfc", "RFC compliant padding only", PADDING_RFC },
686 { "zero", "All-zero padding also permitted", PADDING_ZERO },
687 { "any", "Any padding permitted", PADDING_ANY },
688 { NULL, NULL, 0 }
691 /* Default to doing ESP sequence analysis */
692 static bool g_esp_do_sequence_analysis = true;
697 Name : static int get_ipv6_suffix(char* ipv6_suffix, char *ipv6_address)
698 Description : Get the extended IPv6 Suffix of an IPv6 Address
699 Return : Return the number of char of the IPv6 address suffix parsed
700 Params:
701 - char *ipv6_address : the valid ipv6 address to parse in char *
702 - char *ipv6_suffix : the ipv6 suffix associated in char *
704 ex: if IPv6 address is "3ffe::1" the IPv6 suffix will be "0001" and the function will return 3
706 static int get_ipv6_suffix(char* ipv6_suffix, char *ipv6_address)
708 char suffix[IPSEC_STRLEN_IPV6 + 1];
709 int cpt = 0;
710 int cpt_suffix = 0;
711 int cpt_seg = 0;
712 int j =0;
713 int ipv6_len = 0;
714 bool found = false;
716 ipv6_len = (int) strlen(ipv6_address);
717 if(ipv6_len != 0)
719 while ( (cpt_suffix < IPSEC_STRLEN_IPV6) && (ipv6_len - cpt -1 >= 0) && (found == false))
721 if(ipv6_address[ipv6_len - cpt - 1] == ':')
723 /* Add some 0 to the prefix; */
724 for(j = cpt_seg; j < 4; j++)
726 suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = '0';
727 cpt_suffix ++;
729 cpt_seg = 0;
731 if(ipv6_len - cpt - 1 == 0)
733 /* Found a suffix */
734 found = true;
736 else
737 if(ipv6_address[ipv6_len - cpt - 2] == ':')
739 /* found a suffix */
740 cpt +=2;
741 found = true;
744 else
746 cpt++;
749 else
751 suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = g_ascii_toupper(ipv6_address[ipv6_len - cpt - 1]);
752 cpt_seg ++;
753 cpt_suffix ++;
754 cpt++;
758 if(cpt_suffix % 4 != 0)
760 for(j = cpt_seg; j < 4; j++)
762 suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = '0';
763 cpt_suffix ++;
769 for(j = 0 ; j < cpt_suffix ; j ++)
771 suffix[j] = suffix[j + IPSEC_STRLEN_IPV6 - cpt_suffix] ;
774 suffix[j] = '\0';
775 memcpy(ipv6_suffix,suffix,j + 1);
776 return cpt;
780 Name : static int get_full_ipv6_addr(char* ipv6_addr_expanded, char *ipv6_addr)
781 Description : Get the extended IPv6 Address of an IPv6 Address
782 Return : Return the remaining number of char of the IPv6 address parsed
783 Params:
784 - char *ipv6_addr : the valid ipv6 address to parse in char *
785 - char *ipv6_addr_expanded : the expanded ipv6 address associated in char *
787 ex: if IPv6 address is "3ffe::1" the IPv6 expanded address
788 will be "3FFE0000000000000000000000000001" and the function will return 0
789 if IPV6 address is "3ffe::*" the IPv6 expanded address
790 will be "3FFE000000000000000000000000****" and the function will return 0
792 static int
793 get_full_ipv6_addr(char* ipv6_addr_expanded, char *ipv6_addr)
795 char suffix[IPSEC_STRLEN_IPV6 + 1];
796 char prefix[IPSEC_STRLEN_IPV6 + 1];
797 char *prefix_addr;
799 int suffix_cpt = 0;
800 int suffix_len = 0;
801 int prefix_remaining = 0;
802 int prefix_len = 0;
803 int j = 0;
804 unsigned i = 0;
805 unsigned addr_byte = 0;
806 unsigned mask = IPSEC_IPV6_ADDR_LEN;
807 char* mask_begin = NULL;
810 if((ipv6_addr == NULL) || (strcmp(ipv6_addr, "") == 0)) return -1;
812 memset(ipv6_addr_expanded, 0x0, IPSEC_STRLEN_IPV6);
814 mask_begin = strchr(ipv6_addr, '/');
815 if(mask_begin)
817 if(sscanf(mask_begin, "/%u", &mask) == EOF)
818 mask = IPSEC_IPV6_ADDR_LEN;
819 mask_begin[0] = '\0';
822 if((strlen(ipv6_addr) == 1) && (ipv6_addr[0] == IPSEC_SA_WILDCARDS_ANY))
824 for(j = 0; j < IPSEC_STRLEN_IPV6; j++)
826 ipv6_addr_expanded[j] = IPSEC_SA_WILDCARDS_ANY;
828 ipv6_addr_expanded[IPSEC_STRLEN_IPV6] = '\0';
829 return 0;
832 suffix_cpt = get_ipv6_suffix(suffix,ipv6_addr);
833 suffix_len = (int) strlen(suffix);
835 if(suffix_len < IPSEC_STRLEN_IPV6)
837 prefix_addr = wmem_strndup(wmem_packet_scope(), ipv6_addr,strlen(ipv6_addr) - suffix_cpt);
838 prefix_remaining = get_ipv6_suffix(prefix,prefix_addr);
839 prefix_len = (int) strlen(prefix);
840 memcpy(ipv6_addr_expanded,prefix,prefix_len);
844 for(j = 0; j <= IPSEC_STRLEN_IPV6 - prefix_len - suffix_len; j++)
846 ipv6_addr_expanded[j + prefix_len] = '0';
849 memcpy(ipv6_addr_expanded + IPSEC_STRLEN_IPV6 - suffix_len, suffix,suffix_len + 1);
851 for(i = 0; i < IPSEC_STRLEN_IPV6; i++)
853 if(4 * (i + 1) > mask)
855 if(mask <= 4 * i || ipv6_addr_expanded[i] == '*')
856 ipv6_addr_expanded[i] = '*';
857 else {
858 if(sscanf(ipv6_addr_expanded + i, "%X", &addr_byte) == EOF)
859 break;
860 addr_byte &= (0x0F << (4 * (i + 1) - mask));
861 addr_byte &= 0x0F;
862 snprintf(ipv6_addr_expanded + i, 4, "%X", addr_byte);
867 if(suffix_len < IPSEC_STRLEN_IPV6)
868 return (int) strlen(ipv6_addr) - suffix_cpt - prefix_remaining;
869 else
870 return (int) strlen(ipv6_addr) - suffix_cpt;
875 Name : static bool get_full_ipv4_addr(char* ipv4_addr_expanded, char *ipv4_addr)
876 Description : Get the extended IPv4 Address of an IPv4 Address
877 Return : Return true if it can derive an IPv4 address. It does not mean that
878 the previous one was valid.
879 Params:
880 - char *ipv4_addr : the valid ipv4 address to parse in char *
881 - char *ipv4_addr_expanded : the expanded ipv4 address associated in char *
883 ex: if IPv4 address is "190.*.*.1" the IPv4 expanded address will be "BE****01" and
884 the function will return 0
885 if IPv4 address is "*" the IPv4 expanded address will be "********" and
886 the function will return 0
888 static bool
889 get_full_ipv4_addr(char* ipv4_address_expanded, char *ipv4_address)
891 char addr_byte_string_tmp[4];
892 char addr_byte_string[4];
894 unsigned addr_byte = 0;
895 unsigned i = 0;
896 unsigned j = 0;
897 unsigned k = 0;
898 unsigned cpt = 0;
899 bool done_flag = false;
900 unsigned mask = IPSEC_IPV4_ADDR_LEN;
901 char* mask_begin = NULL;
903 if((ipv4_address == NULL) || (strcmp(ipv4_address, "") == 0)) return done_flag;
905 mask_begin = strchr(ipv4_address, '/');
906 if(mask_begin)
908 if(sscanf(mask_begin, "/%u", &mask) == EOF)
909 mask = IPSEC_IPV4_ADDR_LEN;
910 mask_begin[0] = '\0';
913 if((strlen(ipv4_address) == 1) && (ipv4_address[0] == IPSEC_SA_WILDCARDS_ANY))
915 for(i = 0; i <= IPSEC_STRLEN_IPV4; i++)
917 ipv4_address_expanded[i] = IPSEC_SA_WILDCARDS_ANY;
919 ipv4_address_expanded[IPSEC_STRLEN_IPV4] = '\0';
920 done_flag = true;
923 else {
924 j = 0;
925 cpt = 0;
926 k = 0;
927 while((done_flag == false) && (j <= strlen(ipv4_address)) && (cpt < IPSEC_STRLEN_IPV4))
929 if(j == strlen(ipv4_address))
931 addr_byte_string_tmp[k] = '\0';
932 if((strlen(addr_byte_string_tmp) == 1) && (addr_byte_string_tmp[0] == IPSEC_SA_WILDCARDS_ANY))
934 for(i = 0; i < 2; i++)
936 ipv4_address_expanded[cpt] = IPSEC_SA_WILDCARDS_ANY;
937 cpt ++;
940 else
942 if (sscanf(addr_byte_string_tmp,"%u",&addr_byte) == EOF)
943 return false;
945 if(addr_byte < 16)
946 snprintf(addr_byte_string,4,"0%X",addr_byte);
947 else
948 snprintf(addr_byte_string,4,"%X",addr_byte);
949 for(i = 0; i < strlen(addr_byte_string); i++)
951 ipv4_address_expanded[cpt] = addr_byte_string[i];
952 cpt ++;
955 done_flag = true;
958 else if(ipv4_address[j] == '.')
960 addr_byte_string_tmp[k] = '\0';
961 if((strlen(addr_byte_string_tmp) == 1) && (addr_byte_string_tmp[0] == IPSEC_SA_WILDCARDS_ANY))
963 for(i = 0; i < 2; i++)
965 ipv4_address_expanded[cpt] = IPSEC_SA_WILDCARDS_ANY;
966 cpt ++;
969 else
971 if (sscanf(addr_byte_string_tmp,"%u",&addr_byte) == EOF)
972 return false;
974 if(addr_byte < 16)
975 snprintf(addr_byte_string,4,"0%X",addr_byte);
976 else
977 snprintf(addr_byte_string,4,"%X",addr_byte);
978 for(i = 0; i < strlen(addr_byte_string); i++)
980 ipv4_address_expanded[cpt] = addr_byte_string[i];
981 cpt ++;
984 k = 0;
985 j++;
987 else
989 if(k >= 3)
991 /* Incorrect IPv4 Address. Erase previous Values in the Byte. (LRU mechanism) */
992 addr_byte_string_tmp[0] = ipv4_address[j];
993 k = 1;
994 j++;
996 else
998 addr_byte_string_tmp[k] = ipv4_address[j];
999 k++;
1000 j++;
1006 for(i = 0; i < IPSEC_STRLEN_IPV4; i++)
1008 if(4 * (i + 1) > mask)
1010 if(mask <= 4 * i || ipv4_address_expanded[i] == '*')
1011 ipv4_address_expanded[i] = '*';
1012 else {
1013 if(sscanf(ipv4_address_expanded + i, "%X", &addr_byte) == EOF)
1014 return false;
1015 addr_byte &= (0x0F << (4 * (i + 1) - mask));
1016 addr_byte &= 0x0F;
1017 snprintf(ipv4_address_expanded + i, 4, "%X", addr_byte);
1021 ipv4_address_expanded[cpt] = '\0';
1024 return done_flag;
1028 Name : static goolean filter_address_match(char *addr, char *filter, int len, int typ)
1029 Description : check the matching of an address with a filter
1030 Return : Return true if the filter and the address match
1031 Params:
1032 - char *addr : the address to check
1033 - char *filter : the filter
1034 - int typ : the Address type : either IPv6 or IPv4 (IPSEC_SA_IPV6, IPSEC_SA_IPV4)
1036 static bool
1037 filter_address_match(char *addr, char *filter, int typ)
1039 unsigned i;
1040 char addr_hex[IPSEC_STRLEN_IPV6 + 1];
1041 char filter_hex[IPSEC_STRLEN_IPV6 + 1];
1042 unsigned addr_len;
1043 unsigned filter_len;
1045 switch(typ) {
1046 case IPSEC_SA_ANY:
1047 return true;
1048 case IPSEC_SA_IPV4:
1049 if (!get_full_ipv4_addr(addr_hex, addr))
1050 return false;
1051 if (!get_full_ipv4_addr(filter_hex, filter))
1052 return false;
1053 break;
1054 case IPSEC_SA_IPV6:
1055 if (get_full_ipv6_addr(addr_hex, addr))
1056 return false;
1057 if (get_full_ipv6_addr(filter_hex, filter))
1058 return false;
1059 break;
1060 case IPSEC_SA_UNKNOWN:
1061 default:
1062 return false;
1065 addr_len = (unsigned)strlen(addr_hex);
1066 filter_len = (unsigned)strlen(filter_hex);
1068 if((filter_len == 1) && (filter[0] == IPSEC_SA_WILDCARDS_ANY)){
1069 return true;
1072 if(addr_len != filter_len)
1073 return false;
1075 /* No length specified */
1076 if( ((typ == IPSEC_SA_IPV6) && (filter_len == IPSEC_STRLEN_IPV6)) ||
1077 ((typ == IPSEC_SA_IPV4) && (filter_len == IPSEC_STRLEN_IPV4)))
1079 /* Check byte by byte ... */
1080 for(i = 0; i < addr_len; i++)
1082 if((filter_hex[i] != IPSEC_SA_WILDCARDS_ANY) && (filter_hex[i] != addr_hex[i]))
1083 return false;
1085 return true;
1087 else
1088 return false;
1089 return true;
1095 Name : static goolean filter_spi_match(char *spi, char *filter)
1096 Description : check the matching of a spi with a filter
1097 Return : Return true if the filter matches the spi.
1098 Params:
1099 - unsigned spi : the spi to check
1100 - char *filter : the filter
1102 static bool
1103 filter_spi_match(unsigned spi, char *filter)
1105 unsigned i;
1106 unsigned filter_len = (unsigned)strlen(filter);
1108 /* "*" matches against anything */
1109 if((filter_len == 1) && (filter[0] == IPSEC_SA_WILDCARDS_ANY))
1110 return true;
1112 /* If the filter has a wildcard, treat SPI as a string */
1113 if (strchr(filter, IPSEC_SA_WILDCARDS_ANY) != NULL) {
1114 char spi_string[IPSEC_SPI_LEN_MAX];
1116 snprintf(spi_string, IPSEC_SPI_LEN_MAX,"0x%08x", spi);
1118 /* Lengths need to match exactly... */
1119 if(strlen(spi_string) != filter_len)
1120 return false;
1122 /* ... which means '*' can only appear in the last position of the filter? */
1123 /* Start at 2, don't compare "0x" each time */
1124 for(i = 2; filter[i]; i++)
1125 if((filter[i] != IPSEC_SA_WILDCARDS_ANY) && (filter[i] != spi_string[i]))
1126 return false;
1127 } else if (strtoul(filter, NULL, 0) != spi) {
1128 return false;
1130 return true;
1135 Name : static goolean get_esp_sa(g_esp_sa_database *sad, int protocol_typ, char *src, char *dst, unsigned spi,
1136 int *encryption_algo,
1137 int *authentication_algo,
1138 char **encryption_key,
1139 unsigned *encryption_key_len,
1140 char **authentication_key,
1141 unsigned *authentication_key_len,
1142 gcry_cipher_hd_t **cipher_hd,
1143 bool **cipher_hd_created
1145 Description : Give Encryption Algo, Key and Authentication Algo for a Packet if a corresponding SA is available in a Security Association database
1146 Return: If the SA is not present, false is then returned.
1147 Params:
1148 - g_esp_sa_database *sad : the Security Association Database
1149 - int *pt_protocol_typ : the protocol type
1150 - char *src : the source address
1151 - char *dst : the destination address
1152 - char *spi : the spi of the SA
1153 - int *encryption_algo : the Encryption Algorithm to apply the packet
1154 - int *authentication_algo : the Authentication Algorithm to apply to the packet
1155 - char **encryption_key : the Encryption Key to apply to the packet
1156 - unsigned *encryption_key_len : the Encryption Key length to apply to the packet
1157 - char **authentication_key : the Authentication Key to apply to the packet
1158 - unsigned *authentication_key_len : the Authentication Key len to apply to the packet
1159 - gcry_cipher_hd_t **cipher_hd : pointer handle to be used for ciphering
1160 - bool **cipher_hd_created: points to boolean indicating that cipher handle has
1161 been created. If false, should assign handle to
1162 *cipher_hd and set this to true.
1165 static bool
1166 get_esp_sa(int protocol_typ, char *src, char *dst, unsigned spi,
1167 int *encryption_algo,
1168 int *authentication_algo,
1169 char **encryption_key,
1170 unsigned *encryption_key_len,
1171 char **authentication_key,
1172 unsigned *authentication_key_len,
1173 gcry_cipher_hd_t **cipher_hd,
1174 bool **cipher_hd_created,
1175 uint8_t *sn_length,
1176 uint32_t *sn_upper
1179 bool found = false;
1180 unsigned i, j;
1182 *cipher_hd = NULL;
1183 *cipher_hd_created = NULL;
1185 /* Check each known SA in turn */
1186 for (i = 0, j=0; (found == false) && ((i < num_sa_uat) || (j < extra_esp_sa_records.num_records)); )
1188 /* Get the next record to try */
1189 uat_esp_sa_record_t *record;
1190 if (j < extra_esp_sa_records.num_records) {
1191 /* Extra ones checked first */
1192 record = &extra_esp_sa_records.records[j++];
1194 else {
1195 /* Then UAT ones */
1196 record = &uat_esp_sa_records[i++];
1199 if((protocol_typ == record->protocol || record->protocol == IPSEC_SA_ANY)
1200 && (filter_address_match(src, record->srcIP, protocol_typ) || record->protocol == IPSEC_SA_ANY)
1201 && (filter_address_match(dst, record->dstIP, protocol_typ) || record->protocol == IPSEC_SA_ANY)
1202 && filter_spi_match(spi, record->spi))
1204 found = true;
1206 *encryption_algo = record->encryption_algo;
1207 *authentication_algo = record->authentication_algo;
1208 *authentication_key = record->authentication_key;
1209 if (record->authentication_key_length == -1)
1211 /* Bad key; XXX - report this */
1212 *authentication_key_len = 0;
1213 found = false;
1215 else {
1216 *authentication_key_len = record->authentication_key_length;
1219 *encryption_key = record->encryption_key;
1220 if (record->encryption_key_length == -1)
1222 /* Bad key; XXX - report this */
1223 *encryption_key_len = 0;
1224 found = false;
1226 else {
1227 *encryption_key_len = record->encryption_key_length;
1230 /* Tell the caller whether cipher_hd has been created yet and a pointer.
1231 Pass pointer to created flag so that caller can set if/when
1232 it opens the cipher_hd. */
1233 *cipher_hd = &record->cipher_hd;
1234 *cipher_hd_created = &record->cipher_hd_created;
1236 *sn_length = record->sn_length;
1237 *sn_upper = record->sn_upper;
1241 return found;
1244 static void ah_prompt(packet_info *pinfo, char *result)
1246 snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "IP protocol %u as",
1247 GPOINTER_TO_UINT(p_get_proto_data(pinfo->pool, pinfo, proto_ah, pinfo->curr_layer_num)));
1250 static void *ah_value(packet_info *pinfo)
1252 return p_get_proto_data(pinfo->pool, pinfo, proto_ah, pinfo->curr_layer_num);
1255 static void
1256 export_ipsec_pdu(dissector_handle_t dissector_handle, packet_info *pinfo, tvbuff_t *tvb)
1258 if (have_tap_listener(exported_pdu_tap)) {
1259 exp_pdu_data_t *exp_pdu_data = export_pdu_create_common_tags(pinfo, dissector_handle_get_dissector_name(dissector_handle), EXP_PDU_TAG_DISSECTOR_NAME);
1261 exp_pdu_data->tvb_captured_length = tvb_captured_length(tvb);
1262 exp_pdu_data->tvb_reported_length = tvb_reported_length(tvb);
1263 exp_pdu_data->pdu_tvb = tvb;
1265 tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data);
1270 * Implements much of RFC 5879, "Heuristics for Detecting ESP-NULL Packets"
1272 * Does NOT attempt to properly detect ENCR_NULL_AUTH_AES_GMAC.
1274 static int
1275 esp_null_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *esp_tree)
1277 int esp_packet_len, esp_pad_len, esp_icv_len, offset;
1278 unsigned encapsulated_protocol;
1279 uint32_t saved_match_uint;
1280 bool heur_ok;
1282 proto_item *ti;
1283 tvbuff_t *next_tvb;
1284 dissector_handle_t dissector_handle;
1286 /* Possible ICV lengths to try. Per RFC 5879, smallest to largest.
1288 static const int icv_lengths[] = {
1296 esp_packet_len = tvb_reported_length(tvb);
1298 for (int i = 0; (esp_icv_len = icv_lengths[i]) != -1; i++) {
1300 /* Make sure the packet is not truncated before the fields
1301 * we need to read to determine the encapsulated protocol.
1303 if (tvb_bytes_exist(tvb, -(esp_icv_len + 2), 2))
1305 offset = esp_packet_len - (esp_icv_len + 2);
1306 esp_pad_len = tvb_get_uint8(tvb, offset);
1307 encapsulated_protocol = tvb_get_uint8(tvb, offset + 1);
1308 dissector_handle = dissector_get_uint_handle(ip_dissector_table, encapsulated_protocol);
1309 if (dissector_handle == NULL) {
1310 continue;
1312 if (ESP_HEADER_LEN + esp_pad_len > offset) {
1313 continue;
1315 heur_ok = true;
1316 for (int j=0; j < esp_pad_len; j++) {
1317 if (tvb_get_uint8(tvb, offset - (j + 1)) != (esp_pad_len - j)) {
1318 heur_ok = false;
1319 break;
1322 if (!heur_ok) {
1323 switch (g_esp_padding_type) {
1324 case PADDING_RFC:
1325 continue;
1326 case PADDING_ZERO:
1327 for (int j=0; j < esp_pad_len; j++) {
1328 if (tvb_get_uint8(tvb, offset - (j + 1)) != 0) {
1329 continue;
1332 /* FALLTHROUGH */
1333 case PADDING_ANY:
1334 break;
1335 default:
1336 continue;
1340 saved_match_uint = pinfo->match_uint;
1341 pinfo->match_uint = encapsulated_protocol;
1342 next_tvb = tvb_new_subset_length(tvb, ESP_HEADER_LEN, offset - ESP_HEADER_LEN - esp_pad_len);
1343 /* If the matching dissector has been disabled or rejects the packet,
1344 * consider the heuristic failed.
1345 * XXX: Should we also catch exceptions and consider those failures too?
1347 * Note that the case of ENCR_NULL_AUTH_AES_GMAC will find the correct
1348 * padding and encapsulated protocol using a 16 byte ICV, but needs to
1349 * skip over the 8 bytes of IV.
1351 if (call_dissector_only(dissector_handle, next_tvb, pinfo, proto_tree_get_parent_tree(esp_tree), NULL) == 0) {
1352 pinfo->match_uint = saved_match_uint;
1353 continue;
1355 export_ipsec_pdu(dissector_handle, pinfo, next_tvb);
1356 pinfo->match_uint = saved_match_uint;
1358 if (esp_tree) {
1359 if (esp_pad_len !=0) {
1360 ti = proto_tree_add_item(esp_tree, hf_esp_pad,
1361 tvb, offset - esp_pad_len,
1362 esp_pad_len, ENC_NA);
1363 if (!heur_ok) {
1364 expert_add_info(pinfo, ti, &ei_esp_pad_bogus);
1368 proto_tree_add_uint(esp_tree, hf_esp_pad_len, tvb,
1369 offset, 1,
1370 esp_pad_len);
1372 proto_tree_add_uint_format(esp_tree, hf_esp_protocol, tvb,
1373 offset + 1, 1,
1374 encapsulated_protocol,
1375 "Next header: %s (0x%02x)",
1376 ipprotostr(encapsulated_protocol), encapsulated_protocol);
1379 return esp_icv_len;
1382 return esp_icv_len;
1385 static bool
1386 capture_ah(const unsigned char *pd, int offset, int len, capture_packet_info_t *cpinfo, const union wtap_pseudo_header *pseudo_header)
1388 uint8_t nxt;
1389 int advance;
1391 if (!BYTES_ARE_IN_FRAME(offset, len, 2))
1392 return false;
1393 nxt = pd[offset];
1394 advance = 8 + ((pd[offset+1] - 1) << 2);
1395 if (!BYTES_ARE_IN_FRAME(offset, len, advance))
1396 return false;
1397 offset += advance;
1399 return try_capture_dissector("ip.proto", nxt, pd, offset, len, cpinfo, pseudo_header);
1402 static int
1403 dissect_ah(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data)
1405 proto_tree *ah_tree, *root_tree;
1406 proto_item *pi, *ti;
1407 unsigned ah_nxt; /* Next header */
1408 uint8_t ah_len; /* Length of header in 32bit words minus 2 */
1409 unsigned ah_hdr_len; /* Length of header in octets */
1410 unsigned ah_icv_len; /* Length of ICV header field in octets */
1411 uint32_t ah_spi; /* Security parameter index */
1412 tvbuff_t *next_tvb;
1413 dissector_handle_t dissector_handle;
1414 uint32_t saved_match_uint;
1416 col_set_str(pinfo->cinfo, COL_PROTOCOL, "AH");
1417 col_clear(pinfo->cinfo, COL_INFO);
1419 ah_nxt = tvb_get_uint8(tvb, 0);
1420 ah_len = tvb_get_uint8(tvb, 1);
1421 ah_hdr_len = (ah_len + 2) * 4;
1422 ah_icv_len = ah_len ? (ah_len - 1) * 4 : 0;
1424 root_tree = p_ipv6_pinfo_select_root(pinfo, tree);
1425 p_ipv6_pinfo_add_len(pinfo, ah_hdr_len);
1427 pi = proto_tree_add_item(root_tree, proto_ah, tvb, 0, -1, ENC_NA);
1428 ah_tree = proto_item_add_subtree(pi, ett_ah);
1430 proto_tree_add_item(ah_tree, hf_ah_next_header, tvb, 0, 1, ENC_BIG_ENDIAN);
1431 ti = proto_tree_add_item(ah_tree, hf_ah_length, tvb, 1, 1, ENC_BIG_ENDIAN);
1432 proto_item_append_text(ti, " (%u bytes)", ah_hdr_len);
1433 proto_tree_add_item(ah_tree, hf_ah_reserved, tvb, 2, 2, ENC_NA);
1434 proto_tree_add_item_ret_uint(ah_tree, hf_ah_spi, tvb, 4, 4, ENC_BIG_ENDIAN, &ah_spi);
1436 col_add_fstr(pinfo->cinfo, COL_INFO, "AH (SPI=0x%08x)", ah_spi);
1438 proto_tree_add_item(ah_tree, hf_ah_sequence, tvb, 8, 4, ENC_BIG_ENDIAN);
1439 proto_tree_add_item(ah_tree, hf_ah_iv, tvb, 12, ah_icv_len, ENC_NA);
1441 proto_item_set_len(pi, ah_hdr_len);
1443 /* Save next header value for Decode As dialog */
1444 p_add_proto_data(pinfo->pool, pinfo, proto_ah,
1445 pinfo->curr_layer_num, GUINT_TO_POINTER(ah_nxt));
1447 next_tvb = tvb_new_subset_remaining(tvb, ah_hdr_len);
1449 if (pinfo->dst.type == AT_IPv6) {
1450 ipv6_dissect_next(ah_nxt, next_tvb, pinfo, tree, (ws_ip6 *)data);
1451 } else {
1452 /* do lookup with the subdissector table */
1453 saved_match_uint = pinfo->match_uint;
1454 dissector_handle = dissector_get_uint_handle(ip_dissector_table, ah_nxt);
1455 if (dissector_handle) {
1456 pinfo->match_uint = ah_nxt;
1457 } else {
1458 dissector_handle = data_handle;
1460 export_ipsec_pdu(dissector_handle, pinfo, next_tvb);
1461 call_dissector(dissector_handle, next_tvb, pinfo, tree);
1462 pinfo->match_uint = saved_match_uint;
1464 return tvb_captured_length(tvb);
1467 static int
1468 dissect_esp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
1470 proto_tree *esp_tree = NULL, *decr_tree = NULL, *icv_tree = NULL;
1471 proto_item *item = NULL;
1472 proto_item *iv_item = NULL, *encr_data_item = NULL, *icv_item = NULL;
1474 /* Packet Variables related */
1475 char *ip_src = NULL;
1476 char *ip_dst = NULL;
1478 uint32_t spi = 0;
1479 unsigned encapsulated_protocol = 0;
1480 bool decrypt_dissect_ok = false;
1481 tvbuff_t *next_tvb;
1482 dissector_handle_t dissector_handle;
1483 uint32_t saved_match_uint;
1485 bool null_encryption_decode_heuristic = false;
1486 uint8_t *esp_iv = NULL;
1487 uint8_t *esp_encr_data = NULL;
1488 uint8_t *esp_decr_data = NULL;
1489 uint8_t *esp_icv = NULL;
1490 tvbuff_t *tvb_decrypted = NULL;
1492 /* IPSEC encryption Variables related */
1493 int protocol_typ = IPSEC_SA_UNKNOWN;
1494 int esp_encr_algo = IPSEC_ENCRYPT_NULL;
1495 int esp_auth_algo = IPSEC_AUTH_NULL;
1496 int icv_type = ICV_TYPE_UNCHECKED;
1497 char *esp_encr_key = NULL;
1498 char *esp_auth_key = NULL;
1499 unsigned esp_encr_key_len = 0;
1500 unsigned esp_auth_key_len = 0;
1501 gcry_cipher_hd_t *cipher_hd;
1502 bool *cipher_hd_created;
1504 int offset = 0;
1505 int esp_packet_len = 0;
1506 int esp_iv_len = 0;
1507 int esp_block_len = 0;
1508 int esp_encr_data_len = 0;
1509 int esp_decr_data_len = 0;
1510 int esp_icv_len = 0;
1511 int esp_salt_len = 0;
1512 bool decrypt_ok = false;
1513 bool decrypt_using_libgcrypt = false;
1514 bool icv_checked = false;
1515 bool icv_correct = false;
1516 bool sad_is_present = false;
1517 int esp_pad_len = 0;
1520 /* Variables for decryption and authentication checking used for libgrypt */
1521 gcry_md_hd_t md_hd;
1522 int md_len = 0;
1523 gcry_error_t err = 0;
1524 int crypt_algo_libgcrypt = 0;
1525 int crypt_mode_libgcrypt = 0;
1526 int auth_algo_libgcrypt = 0;
1527 char *esp_icv_expected = NULL; /* as readable hex string, for error messages */
1528 unsigned char ctr_block[16];
1529 unsigned char nonce[12]; /* nonce for decrypting ChaCha20-Poly1305 */
1532 uint32_t sequence_number;
1533 uint8_t sn_length = IPSEC_SA_SN;
1534 uint32_t sn_upper = 0;
1537 * load the top pane info. This should be overwritten by
1538 * the next protocol in the stack
1541 col_set_str(pinfo->cinfo, COL_PROTOCOL, "ESP");
1542 col_clear(pinfo->cinfo, COL_INFO);
1545 * populate a tree in the second pane with the status of the link layer
1546 * (ie none)
1548 item = proto_tree_add_item(tree, proto_esp, tvb, 0, -1, ENC_NA);
1549 esp_tree = proto_item_add_subtree(item, ett_esp);
1550 proto_tree_add_item_ret_uint(esp_tree, hf_esp_spi, tvb,
1551 0, 4, ENC_BIG_ENDIAN, &spi);
1552 proto_tree_add_item_ret_uint(esp_tree, hf_esp_sequence, tvb,
1553 4, 4, ENC_BIG_ENDIAN, &sequence_number);
1555 col_add_fstr(pinfo->cinfo, COL_INFO, "ESP (SPI=0x%08x)", spi);
1557 /* Sequence number analysis */
1558 if (g_esp_do_sequence_analysis) {
1559 if (!pinfo->fd->visited) {
1560 check_esp_sequence_info(spi, sequence_number, pinfo);
1562 show_esp_sequence_info(spi, sequence_number,
1563 tvb, esp_tree, pinfo);
1566 esp_packet_len = tvb_reported_length(tvb);
1568 /* Get length of remaining ESP packet (without the header) */
1569 esp_encr_data_len = esp_packet_len - ESP_HEADER_LEN;
1570 if (esp_encr_data_len <= 0)
1571 return tvb_captured_length(tvb);
1573 offset = ESP_HEADER_LEN;
1575 /* The SAD is not activated */
1576 if(g_esp_enable_null_encryption_decode_heuristic &&
1577 !g_esp_enable_encryption_decode)
1578 null_encryption_decode_heuristic = true;
1580 if(g_esp_enable_encryption_decode || g_esp_enable_authentication_check)
1582 /* Get Source & Destination Addresses in char * with all the bytes available. */
1584 if (pinfo->src.type == AT_IPv4){
1585 protocol_typ = IPSEC_SA_IPV4;
1586 }else if (pinfo->src.type == AT_IPv6){
1587 protocol_typ = IPSEC_SA_IPV6;
1590 /* Create strings for src, dst addresses */
1591 ip_src = address_to_str(pinfo->pool, &pinfo->src);
1592 ip_dst = address_to_str(pinfo->pool, &pinfo->dst);
1594 /* Get the SPI */
1595 if (tvb_captured_length(tvb) >= 4)
1597 spi = tvb_get_ntohl(tvb, 0);
1602 PARSE the SAD and fill it. It may take some time since it will
1603 be called every times an ESP Payload is found.
1606 if((sad_is_present = get_esp_sa(protocol_typ, ip_src, ip_dst, spi,
1607 &esp_encr_algo, &esp_auth_algo,
1608 &esp_encr_key, &esp_encr_key_len, &esp_auth_key, &esp_auth_key_len,
1609 &cipher_hd, &cipher_hd_created, &sn_length, &sn_upper)))
1612 switch(esp_auth_algo)
1614 case IPSEC_AUTH_NULL:
1615 esp_icv_len = 0;
1616 break;
1618 case IPSEC_AUTH_ANY_64BIT:
1619 esp_icv_len = 8;
1620 break;
1622 case IPSEC_AUTH_HMAC_SHA256_128:
1623 case IPSEC_AUTH_ANY_128BIT:
1624 esp_icv_len = 16;
1625 break;
1627 case IPSEC_AUTH_HMAC_SHA512_256:
1628 case IPSEC_AUTH_ANY_256BIT:
1629 esp_icv_len = 32;
1630 break;
1632 case IPSEC_AUTH_HMAC_SHA384_192:
1633 case IPSEC_AUTH_ANY_192BIT:
1634 esp_icv_len = 24;
1635 break;
1637 case IPSEC_AUTH_HMAC_SHA1_96:
1638 case IPSEC_AUTH_HMAC_SHA256_96:
1639 /* case IPSEC_AUTH_AES_XCBC_MAC_96: */
1640 case IPSEC_AUTH_HMAC_MD5_96:
1641 case IPSEC_AUTH_HMAC_RIPEMD160_96:
1642 case IPSEC_AUTH_ANY_96BIT:
1643 default:
1644 esp_icv_len = 12;
1645 break;
1648 switch(esp_encr_algo)
1650 case IPSEC_ENCRYPT_AES_GCM_8:
1651 esp_encr_algo = IPSEC_ENCRYPT_AES_GCM;
1652 esp_icv_len = 8;
1653 break;
1655 case IPSEC_ENCRYPT_AES_GCM_12:
1656 esp_encr_algo = IPSEC_ENCRYPT_AES_GCM;
1657 esp_icv_len = 12;
1658 break;
1660 case IPSEC_ENCRYPT_AES_GCM_16:
1661 esp_encr_algo = IPSEC_ENCRYPT_AES_GCM;
1662 esp_icv_len = 16;
1663 break;
1665 case IPSEC_ENCRYPT_AES_GCM:
1666 esp_icv_len = 0;
1669 if(g_esp_enable_authentication_check)
1671 if (sn_length == IPSEC_SA_ESN && g_esp_do_sequence_analysis) {
1672 spi_status *status = (spi_status*)wmem_map_lookup(esp_sequence_analysis_hash,
1673 GUINT_TO_POINTER((unsigned)spi));
1674 /* We only support 2^32 - 1 frames (and only 2^31 - 1 in the Qt packet
1675 * list), so at most we can overflow once. In a normal capture we
1676 * expect half the frames to be from each direction, too. The proper
1677 * method in RFC 4303 Appendix A involves storing valid sequence
1678 * numbers at multiple points for subsequent passes to slide the window,
1679 * but we shouldn't need to. */
1680 if (status && status->firstValidSN) {
1681 const uint32_t window = 0x8000U;
1682 if (status->firstValidSN >= window) {
1683 if (sequence_number < (status->firstValidSN - window)) {
1684 sn_upper++;
1686 } else {
1687 if (sequence_number >= (status->firstValidSN - window)) {
1688 sn_upper--;
1694 switch(esp_auth_algo)
1696 case IPSEC_AUTH_HMAC_SHA1_96:
1698 RFC 2404 : HMAC-SHA-1-96 is a secret key algorithm.
1699 While no fixed key length is specified in [RFC-2104],
1700 for use with either ESP or AH a fixed key length of
1701 160-bits MUST be supported. Key lengths other than
1702 160-bits MUST NOT be supported (i.e. only 160-bit keys
1703 are to be used by HMAC-SHA-1-96). A key length of
1704 160-bits was chosen based on the recommendations in
1705 [RFC-2104] (i.e. key lengths less than the
1706 authentication length decrease security strength and
1707 keys longer than the authentication length do not
1708 significantly increase security strength).
1710 auth_algo_libgcrypt = GCRY_MD_SHA1;
1711 icv_type = ICV_TYPE_HMAC;
1712 break;
1714 case IPSEC_AUTH_NULL:
1715 break;
1718 case IPSEC_AUTH_AES_XCBC_MAC_96:
1719 auth_algo_libgcrypt =
1720 authentication_check_using_libgcrypt = true;
1721 break;
1724 case IPSEC_AUTH_HMAC_SHA256_96:
1725 case IPSEC_AUTH_HMAC_SHA256_128:
1726 auth_algo_libgcrypt = GCRY_MD_SHA256;
1727 icv_type = ICV_TYPE_HMAC;
1728 break;
1730 case IPSEC_AUTH_HMAC_SHA384_192:
1731 auth_algo_libgcrypt = GCRY_MD_SHA384;
1732 icv_type = ICV_TYPE_HMAC;
1733 break;
1735 case IPSEC_AUTH_HMAC_SHA512_256:
1736 auth_algo_libgcrypt = GCRY_MD_SHA512;
1737 icv_type = ICV_TYPE_HMAC;
1738 break;
1740 case IPSEC_AUTH_HMAC_MD5_96:
1742 RFC 2403 : HMAC-MD5-96 is a secret key algorithm.
1743 While no fixed key length is specified in [RFC-2104],
1744 for use with either ESP or AH a fixed key length of
1745 128-bits MUST be supported. Key lengths other than
1746 128-bits MUST NOT be supported (i.e. only 128-bit keys
1747 are to be used by HMAC-MD5-96). A key length of
1748 128-bits was chosen based on the recommendations in
1749 [RFC-2104] (i.e. key lengths less than the
1750 authentication code length decrease security strength and
1751 keys longer than the authentication code length do not
1752 significantly increase security strength).
1754 auth_algo_libgcrypt = GCRY_MD_MD5;
1755 icv_type = ICV_TYPE_HMAC;
1756 break;
1758 case IPSEC_AUTH_HMAC_RIPEMD160_96:
1760 RFC 2857 : HMAC-RIPEMD-160-96 produces a 160-bit
1761 authentication code. This 160-bit value can be
1762 truncated as described in RFC2104. For use with
1763 either ESP or AH, a truncated value using the first
1764 96 bits MUST be supported.
1766 auth_algo_libgcrypt = GCRY_MD_RMD160;
1767 icv_type = ICV_TYPE_HMAC;
1768 break;
1770 case IPSEC_AUTH_ANY_64BIT:
1771 case IPSEC_AUTH_ANY_96BIT:
1772 case IPSEC_AUTH_ANY_128BIT:
1773 case IPSEC_AUTH_ANY_192BIT:
1774 case IPSEC_AUTH_ANY_256BIT:
1775 default:
1776 break;
1779 if(icv_type == ICV_TYPE_HMAC)
1781 /* Allocate buffer for ICV */
1782 esp_icv = (uint8_t *)tvb_memdup(pinfo->pool, tvb, esp_packet_len - esp_icv_len, esp_icv_len);
1784 err = gcry_md_open (&md_hd, auth_algo_libgcrypt, GCRY_MD_FLAG_HMAC);
1785 if (err)
1787 gcry_md_close(md_hd);
1788 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s, gcry_md_open failed: %s\n",
1789 gcry_md_algo_name(auth_algo_libgcrypt), gcry_strerror(err));
1791 else
1793 md_len = gcry_md_get_algo_dlen (auth_algo_libgcrypt);
1794 if (md_len < 1 || md_len < esp_icv_len)
1796 gcry_md_close(md_hd);
1797 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s, grcy_md_get_algo_dlen failed: %d\n",
1798 gcry_md_algo_name(auth_algo_libgcrypt), md_len);
1800 else
1802 unsigned char *esp_icv_computed;
1804 gcry_md_setkey( md_hd, esp_auth_key, esp_auth_key_len );
1806 gcry_md_write (md_hd, tvb_get_ptr(tvb, 0, esp_packet_len - esp_icv_len), esp_packet_len - esp_icv_len);
1808 if (sn_length == IPSEC_SA_ESN) {
1809 uint8_t sn_bytes[4];
1810 phton32(sn_bytes, sn_upper);
1811 for (int i = 0; i < 4; i++) {
1812 gcry_md_putc(md_hd, sn_bytes[i]);
1816 esp_icv_computed = gcry_md_read (md_hd, auth_algo_libgcrypt);
1817 if (esp_icv_computed == 0)
1819 gcry_md_close(md_hd);
1820 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s, gcry_md_read failed\n",
1821 gcry_md_algo_name(auth_algo_libgcrypt));
1824 if(memcmp (esp_icv_computed, esp_icv, esp_icv_len) == 0) {
1825 icv_checked = true;
1826 icv_correct = true;
1827 } else {
1828 icv_checked = true;
1829 icv_correct = false;
1830 esp_icv_expected = bytes_to_str(pinfo->pool, esp_icv_computed, esp_icv_len);
1834 gcry_md_close(md_hd);
1839 if(g_esp_enable_encryption_decode)
1841 /* Deactivation of the Heuristic to decrypt using the NULL encryption algorithm since the packet is matching a SA */
1842 null_encryption_decode_heuristic = false;
1844 switch(esp_encr_algo)
1846 case IPSEC_ENCRYPT_3DES_CBC :
1847 /* RFC 2451 says :
1848 3DES CBC uses a key of 192 bits.
1849 The first 3DES key is taken from the first 64 bits,
1850 the second from the next 64 bits, and the third
1851 from the last 64 bits.
1852 Implementations MUST take into consideration the
1853 parity bits when initially accepting a new set of
1854 keys. Each of the three keys is really 56 bits in
1855 length with the extra 8 bits used for parity. */
1857 /* Fix parameters for 3DES-CBC */
1858 esp_iv_len = esp_block_len = 8;
1859 crypt_algo_libgcrypt = GCRY_CIPHER_3DES;
1860 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1862 if (esp_encr_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
1864 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm 3DES-CBC : Bad Keylen (got %u Bits, need %lu)\n",
1865 esp_encr_key_len * 8,
1866 (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
1867 decrypt_ok = false;
1869 else
1870 decrypt_using_libgcrypt = true;
1872 break;
1874 case IPSEC_ENCRYPT_AES_CBC :
1875 /* RFC 3602 says :
1876 AES supports three key sizes: 128 bits, 192 bits,
1877 and 256 bits. The default key size is 128 bits,
1878 and all implementations MUST support this key size.
1879 Implementations MAY also support key sizes of 192
1880 bits and 256 bits. */
1882 /* Fix parameters for AES-CBC */
1883 esp_iv_len = esp_block_len = 16;
1884 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1886 switch(esp_encr_key_len * 8)
1888 case 128:
1889 crypt_algo_libgcrypt = GCRY_CIPHER_AES128;
1890 decrypt_using_libgcrypt = true;
1891 break;
1893 case 192:
1894 crypt_algo_libgcrypt = GCRY_CIPHER_AES192;
1895 decrypt_using_libgcrypt = true;
1896 break;
1898 case 256:
1899 crypt_algo_libgcrypt = GCRY_CIPHER_AES256;
1900 decrypt_using_libgcrypt = true;
1901 break;
1903 default:
1904 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm AES-CBC : Bad Keylen (%u Bits)\n",
1905 esp_encr_key_len * 8);
1906 decrypt_ok = false;
1909 break;
1911 case IPSEC_ENCRYPT_CAST5_CBC :
1912 /* RFC 2144 says :
1913 The CAST-128 encryption algorithm has been designed to allow a key
1914 size that can vary from 40 bits to 128 bits, in 8-bit increments
1915 (that is, the allowable key sizes are 40, 48, 56, 64, ..., 112, 120,
1916 and 128 bits.)
1917 We support only 128 bits. */
1919 /* Fix parameters for CAST5-CBC */
1920 esp_iv_len = esp_block_len = 8;
1921 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1923 switch(esp_encr_key_len * 8)
1925 case 128:
1926 crypt_algo_libgcrypt = GCRY_CIPHER_CAST5;
1927 decrypt_using_libgcrypt = true;
1928 break;
1929 default:
1930 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm CAST5-CBC : Bad Keylen (%u Bits)\n",
1931 esp_encr_key_len * 8);
1932 decrypt_ok = false;
1934 break;
1936 case IPSEC_ENCRYPT_DES_CBC :
1937 /* RFC 2405 says :
1938 DES-CBC is a symmetric secret key algorithm.
1939 The key size is 64-bits.
1940 [It is commonly known as a 56-bit key as the key
1941 has 56 significant bits; the least significant
1942 bit in every byte is the parity bit.] */
1944 /* Fix parameters for DES-CBC */
1945 esp_iv_len = esp_block_len = 8;
1946 crypt_algo_libgcrypt = GCRY_CIPHER_DES;
1947 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
1949 if (esp_encr_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
1951 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm DES-CBC : Bad Keylen (%u Bits, need %lu)\n",
1952 esp_encr_key_len * 8, (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
1953 decrypt_ok = false;
1955 else
1956 decrypt_using_libgcrypt = true;
1958 break;
1960 case IPSEC_ENCRYPT_AES_CTR :
1961 case IPSEC_ENCRYPT_AES_GCM :
1962 /* RFC 3686 says :
1963 AES supports three key sizes: 128 bits, 192 bits,
1964 and 256 bits. The default key size is 128 bits,
1965 and all implementations MUST support this key
1966 size. Implementations MAY also support key sizes
1967 of 192 bits and 256 bits. The remaining 32 bits
1968 will be used as nonce. */
1970 /* Fix parameters for AES-CTR/AES-GCM */
1971 esp_iv_len = 8;
1972 esp_block_len = 1;
1973 /* The counter mode key includes a 4 byte nonce following the key, which is used as the salt */
1974 esp_salt_len = 4;
1975 esp_encr_key_len -= esp_salt_len;
1977 crypt_mode_libgcrypt =
1978 (esp_encr_algo == IPSEC_ENCRYPT_AES_CTR) ? GCRY_CIPHER_MODE_CTR : GCRY_CIPHER_MODE_GCM;
1979 switch(esp_encr_key_len * 8)
1981 case 128:
1982 crypt_algo_libgcrypt = GCRY_CIPHER_AES128;
1983 decrypt_using_libgcrypt = true;
1984 break;
1986 case 192:
1987 crypt_algo_libgcrypt = GCRY_CIPHER_AES192;
1988 decrypt_using_libgcrypt = true;
1989 break;
1991 case 256:
1992 crypt_algo_libgcrypt = GCRY_CIPHER_AES256;
1993 decrypt_using_libgcrypt = true;
1994 break;
1996 default:
1997 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm %s : Bad Keylen (%u Bits)\n",
1998 (esp_encr_algo == IPSEC_ENCRYPT_AES_CTR) ? "AES-CTR" : "AES-GCM",
1999 esp_encr_key_len * 8);
2000 decrypt_ok = false;
2003 if (esp_encr_algo == IPSEC_ENCRYPT_AES_GCM) {
2004 if (esp_auth_algo != IPSEC_AUTH_NULL) {
2005 REPORT_DISSECTOR_BUG("<ESP Preferences> Error: AES-GCM encryption can only be used with NULL authentication\n");
2007 icv_type = ICV_TYPE_AEAD;
2010 break;
2012 case IPSEC_ENCRYPT_TWOFISH_CBC :
2013 /* Twofish is a 128-bit block cipher developed by
2014 Counterpane Labs that accepts a variable-length
2015 key up to 256 bits.
2016 We will only accept key sizes of 128 and 256 bits.
2019 /* Fix parameters for TWOFISH-CBC */
2020 esp_iv_len = 16;
2021 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2023 switch(esp_encr_key_len * 8)
2025 case 128:
2026 crypt_algo_libgcrypt = GCRY_CIPHER_TWOFISH128;
2027 decrypt_using_libgcrypt = true;
2028 break;
2030 case 256:
2031 crypt_algo_libgcrypt = GCRY_CIPHER_TWOFISH;
2032 decrypt_using_libgcrypt = true;
2033 break;
2035 default:
2036 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm TWOFISH-CBC : Bad Keylen (%u Bits)\n",
2037 esp_encr_key_len * 8);
2038 decrypt_ok = false;
2041 break;
2043 case IPSEC_ENCRYPT_BLOWFISH_CBC :
2044 /* Bruce Schneier of Counterpane Systems developed
2045 the Blowfish block cipher algorithm.
2046 RFC 2451 shows that Blowfish uses key sizes from
2047 40 to 448 bits. The Default size is 128 bits.
2048 We will only accept key sizes of 128 bits, because
2049 libgrypt only accept this key size.
2052 /* Fix parameters for BLOWFISH-CBC */
2053 esp_iv_len = esp_block_len = 8;
2054 crypt_algo_libgcrypt = GCRY_CIPHER_BLOWFISH;
2055 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2057 if (esp_encr_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
2059 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm BLOWFISH-CBC : Bad Keylen (%u Bits, need %lu)\n",
2060 esp_encr_key_len * 8, (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
2061 decrypt_ok = false;
2063 else
2064 decrypt_using_libgcrypt = true;
2066 break;
2068 case IPSEC_ENCRYPT_AES_GCM_16_IIV:
2069 esp_iv_len = 0; // Implicit IV - First Byte after SEQ is Data
2070 esp_icv_len = 16; // ICV is 16 bytes long
2071 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_GCM;
2073 /* The key includes a 4 byte nonce following the key, which is used as the salt */
2074 esp_salt_len = 4;
2075 esp_encr_key_len -= esp_salt_len;
2077 switch(esp_encr_key_len * 8)
2079 case 128:
2080 crypt_algo_libgcrypt = GCRY_CIPHER_AES128;
2081 decrypt_using_libgcrypt = true;
2082 break;
2084 case 192:
2085 crypt_algo_libgcrypt = GCRY_CIPHER_AES192;
2086 decrypt_using_libgcrypt = true;
2087 break;
2089 case 256:
2090 crypt_algo_libgcrypt = GCRY_CIPHER_AES256;
2091 decrypt_using_libgcrypt = true;
2092 break;
2094 default:
2095 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm AES_GCM16: Bad Keylen (%u Bits)\n",
2096 esp_encr_key_len * 8);
2097 decrypt_ok = false;
2100 break;
2102 case IPSEC_ENCRYPT_CHACHA20_POLY1305:
2103 esp_iv_len = 8; // IV is 8 byte long
2104 esp_icv_len = 16; // AEAD Mode - ICV is Associated Data
2105 crypt_algo_libgcrypt = GCRY_CIPHER_CHACHA20;
2106 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_POLY1305;
2107 icv_type = ICV_TYPE_AEAD;
2108 auth_algo_libgcrypt = GCRY_MAC_POLY1305;
2110 /* The key includes a 4 byte nonce following the key, which is used as the salt */
2111 esp_salt_len = 4;
2112 esp_encr_key_len -= esp_salt_len;
2114 if (esp_encr_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
2116 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm CHACHA20_POLY1305: Bad Keylen (%u Bits, need %lu)\n",
2117 esp_encr_key_len * 8, (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
2118 decrypt_ok = false;
2120 else
2121 decrypt_using_libgcrypt = true;
2123 break;
2125 case IPSEC_ENCRYPT_CHACHA20_POLY1305_IIV:
2126 esp_iv_len = 0; // Implicit IV - First Byte after SEQ is Data
2127 esp_icv_len = 16; // AEAD Mode - ICV is Associated Data
2128 crypt_algo_libgcrypt = GCRY_CIPHER_CHACHA20;
2129 crypt_mode_libgcrypt = GCRY_CIPHER_MODE_POLY1305;
2130 icv_type = ICV_TYPE_AEAD;
2131 auth_algo_libgcrypt = GCRY_MAC_POLY1305;
2133 /* The counter mode key includes a 4 byte nonce following the key, which is used as the salt */
2134 esp_salt_len = 4;
2135 esp_encr_key_len -= esp_salt_len;
2137 if (esp_encr_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
2139 REPORT_DISSECTOR_BUG("<ESP Preferences> Error in Encryption Algorithm CHACHA20_POLY1305_IIV: Bad Keylen (%u Bits, need %lu)\n",
2140 esp_encr_key_len * 8, (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
2141 decrypt_ok = false;
2143 else
2144 decrypt_using_libgcrypt = true;
2146 break;
2148 case IPSEC_ENCRYPT_NULL :
2149 default :
2150 /* Fix parameters */
2151 esp_iv_len = 0;
2152 esp_block_len = 1;
2154 /* Allocate buffer for decrypted data */
2155 esp_decr_data_len = esp_encr_data_len - esp_icv_len;
2156 esp_decr_data = (uint8_t *)wmem_alloc(pinfo->pool, esp_decr_data_len);
2158 tvb_memcpy(tvb, esp_decr_data, ESP_HEADER_LEN, esp_decr_data_len);
2160 decrypt_ok = true;
2162 break;
2165 esp_encr_data_len -= (esp_iv_len + esp_icv_len);
2168 * Zero or negative length of encrypted data shows that the user specified
2169 * wrong encryption algorithm and/or authentication algorithm.
2171 if (esp_encr_data_len <= 0) {
2172 return esp_packet_len;
2176 * Add the IV to the tree and store it in a packet scope buffer for later decryption
2177 * if the specified encryption algorithm uses IV.
2179 if (esp_iv_len) {
2180 tvb_ensure_bytes_exist(tvb, offset, esp_iv_len);
2182 iv_item = proto_tree_add_item(esp_tree, hf_esp_iv, tvb, offset, esp_iv_len, ENC_NA);
2183 proto_item_append_text(iv_item, " (%d bytes)", esp_iv_len);
2184 esp_iv = (unsigned char *)tvb_memdup(pinfo->pool, tvb, offset, esp_iv_len);
2186 offset += esp_iv_len;
2190 * Add the encrypted portion to the tree and store it in a packet scope buffer for later decryption.
2192 if (esp_encr_data_len) {
2193 encr_data_item = proto_tree_add_item(esp_tree, hf_esp_encrypted_data, tvb, offset, esp_encr_data_len, ENC_NA);
2194 proto_item_append_text(encr_data_item, " (%d bytes) <%s>",
2195 esp_encr_data_len,
2196 esp_get_encr_algo_name(esp_encr_algo));
2198 esp_encr_data = (unsigned char *)tvb_memdup(pinfo->pool, tvb, offset, esp_encr_data_len);
2199 offset += esp_encr_data_len;
2202 * Verify that the encrypted payload data is properly aligned: The ciphertext length
2203 * needs to be a multiple of the of block size (which equals 1 for 'stream ciphers'
2204 * like AES-GCM and AES-CTR) and the ciphertext needs to terminate on a 4-byte boundary,
2205 * according to RFC 2406, section 2.4. Given the fact that all current block sizes are
2206 * powers of 2, only the stricter alignment requirement needs to be checked:
2208 if (esp_block_len > 4 && esp_encr_data_len % esp_block_len != 0) {
2209 proto_item_append_text(encr_data_item, "[Invalid length, ciphertext should be a multiple of block size (%u)]",
2210 esp_block_len);
2211 decrypt_using_libgcrypt = false;
2212 } else if (esp_encr_data_len % 4 != 0) {
2213 proto_item_append_text(encr_data_item, "[Invalid length, ciphertext should terminate at 4-byte boundary]");
2214 decrypt_using_libgcrypt = false;
2220 * Add the ICV (Integrity Check Value) to the tree before decryption to ensure
2221 * the ICV be displayed even if the decryption fails.
2224 if (esp_icv_len) {
2225 icv_item = proto_tree_add_item(esp_tree, hf_esp_icv, tvb, offset, esp_icv_len, ENC_NA);
2226 proto_item_append_text(icv_item, " (%d bytes) <%s>",
2227 esp_icv_len,
2228 icv_type == ICV_TYPE_AEAD ?
2229 esp_get_encr_algo_name(esp_encr_algo) :
2230 esp_get_auth_algo_name(esp_auth_algo));
2234 if (decrypt_using_libgcrypt)
2237 * Allocate buffer for decrypted data.
2239 esp_decr_data = (unsigned char*)wmem_alloc(pinfo->pool, esp_encr_data_len);
2240 esp_decr_data_len = esp_encr_data_len;
2242 tvb_memcpy(tvb, esp_decr_data, ESP_HEADER_LEN, esp_encr_data_len);
2244 /* (Lazily) create the cipher_hd */
2245 if (!(*cipher_hd_created)) {
2246 err = gcry_cipher_open(cipher_hd, crypt_algo_libgcrypt, crypt_mode_libgcrypt, 0);
2247 if (err) {
2248 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, grcy_open_cipher failed: %s\n",
2249 gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gcry_strerror(err));
2251 else
2253 /* OK, set the key */
2254 if (*cipher_hd_created == false)
2256 err = gcry_cipher_setkey(*cipher_hd, esp_encr_key, esp_encr_key_len);
2258 if (err) {
2259 gcry_cipher_close(*cipher_hd);
2260 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, gcry_cipher_setkey(key_len=%u) failed: %s\n",
2261 gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, esp_encr_key_len, gcry_strerror(err));
2265 /* Key is created and has its key set now */
2266 *cipher_hd_created = true;
2270 /* Now try to decrypt */
2271 if (esp_encr_algo == IPSEC_ENCRYPT_AES_CTR || esp_encr_algo == IPSEC_ENCRYPT_AES_GCM)
2273 unsigned int ctr_block_size = sizeof(ctr_block);
2275 /* Set CTR first */
2276 memset(ctr_block, 0, ctr_block_size);
2277 memcpy(ctr_block, esp_encr_key + esp_encr_key_len, esp_salt_len);
2278 memcpy(ctr_block + esp_salt_len, esp_iv, esp_iv_len);
2280 if (crypt_mode_libgcrypt == GCRY_CIPHER_MODE_CTR) {
2281 ctr_block[ctr_block_size-1] = 1;
2282 if (esp_encr_algo == IPSEC_ENCRYPT_AES_GCM) {
2283 /* AES-CTR is used as fallback for AES-GCM (only) if gcrypt does not have AEAD ciphers.
2284 * The extra increment is necessary because AES-GCM reserves counter 0 for the final
2285 * step to create the authentication tag and starts encryption with counter 1.
2287 ctr_block[ctr_block_size-1]++;
2289 err = gcry_cipher_setctr(*cipher_hd, ctr_block, 16);
2290 } else {
2291 err = gcry_cipher_setiv(*cipher_hd, ctr_block, esp_salt_len + esp_iv_len);
2294 else if (esp_encr_algo == IPSEC_ENCRYPT_CHACHA20_POLY1305_IIV || esp_encr_algo == IPSEC_ENCRYPT_AES_GCM_16_IIV)
2296 // Implicit IV, see https://www.rfc-editor.org/rfc/rfc8750.html
2297 unsigned int nonce_size = sizeof(nonce);
2298 memset(nonce, 0, nonce_size);
2299 memcpy(nonce, esp_encr_key + esp_encr_key_len, esp_salt_len);
2300 nonce[8] = (sequence_number >> 24) & 0xff;
2301 nonce[9] = (sequence_number >> 16) & 0xff;
2302 nonce[10] = (sequence_number >> 8) & 0xff;
2303 nonce[11] = sequence_number & 0xff;
2304 err = gcry_cipher_setiv(*cipher_hd, nonce, 12);
2306 else if (esp_encr_algo == IPSEC_ENCRYPT_CHACHA20_POLY1305)
2308 // see https://www.rfc-editor.org/rfc/rfc7634.html
2309 unsigned int nonce_size = sizeof(nonce);
2311 memset(nonce, 0, nonce_size);
2312 memcpy(nonce, esp_encr_key + esp_encr_key_len, esp_salt_len);
2313 memcpy(nonce + esp_salt_len, esp_iv, esp_iv_len);
2315 err = gcry_cipher_setiv(*cipher_hd, nonce, esp_salt_len + esp_iv_len);
2317 else
2319 err = gcry_cipher_setiv(*cipher_hd, esp_iv, esp_iv_len);
2322 if (err) {
2323 gcry_cipher_close(*cipher_hd);
2324 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, gcry_cipher_set%s() failed: %s\n",
2325 gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt,
2326 (crypt_mode_libgcrypt == GCRY_CIPHER_MODE_CTR) ? "ctr" : "iv",
2327 gcry_strerror(err));
2331 if (g_esp_enable_authentication_check && icv_type == ICV_TYPE_AEAD) {
2332 /* Allocate buffer for ICV */
2333 esp_icv = (uint8_t *)tvb_memdup(pinfo->pool, tvb, esp_packet_len - esp_icv_len, esp_icv_len);
2335 if (sn_length == IPSEC_SA_SN) {
2336 err = gcry_cipher_authenticate(*cipher_hd, tvb_get_ptr(tvb, 0, ESP_HEADER_LEN), ESP_HEADER_LEN);
2337 } else {
2338 uint8_t *aad = wmem_alloc(pinfo->pool, ESP_HEADER_LEN + 4);
2339 tvb_memcpy(tvb, aad, 0, 4);
2340 phton32(&aad[4], sn_upper);
2341 tvb_memcpy(tvb, &aad[ESP_HEADER_LEN], 4, ESP_HEADER_LEN);
2342 err = gcry_cipher_authenticate(*cipher_hd, aad, ESP_HEADER_LEN + 4);
2345 if (err) {
2346 gcry_cipher_close(*cipher_hd);
2347 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, gcry_cipher_authenticate() failed: %s\n",
2348 gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gcry_strerror(err));
2352 if (!err)
2354 err = gcry_cipher_decrypt(*cipher_hd, esp_decr_data, esp_decr_data_len, esp_encr_data, esp_encr_data_len);
2357 if (err)
2359 gcry_cipher_close(*cipher_hd);
2360 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s, Mode %d, gcry_cipher_decrypt failed: %s\n",
2361 gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gcry_strerror(err));
2363 else
2365 /* Decryption has finished */
2366 decrypt_ok = true;
2368 if (g_esp_enable_authentication_check && icv_type == ICV_TYPE_AEAD) {
2369 unsigned char *esp_icv_computed;
2370 int tag_len;
2372 tag_len = (auth_algo_libgcrypt == GCRY_MAC_POLY1305) ? 16 : (int)gcry_cipher_get_algo_blklen(crypt_algo_libgcrypt);
2374 if (tag_len < esp_icv_len) {
2375 fprintf (stderr, "<IPsec/ESP Dissector> Error in Algorithm %s, tag length (%d) is less than icv length (%d)\n",
2376 gcry_md_algo_name(crypt_algo_libgcrypt), tag_len, esp_icv_len);
2379 esp_icv_computed = (unsigned char *)wmem_alloc(pinfo->pool, tag_len);
2380 err = gcry_cipher_gettag(*cipher_hd, esp_icv_computed, tag_len);
2381 if (err) {
2382 gcry_cipher_close(*cipher_hd);
2383 REPORT_DISSECTOR_BUG("<IPsec/ESP Dissector> Error in Algorithm %s: gcry_cipher_gettag failed: %s",
2384 gcry_md_algo_name(crypt_algo_libgcrypt), gcry_strerror(err));
2387 if (memcmp(esp_icv_computed, esp_icv, esp_icv_len) == 0) {
2388 icv_checked = true;
2389 icv_correct = true;
2390 } else {
2391 icv_checked = true;
2392 icv_correct = false;
2393 esp_icv_expected = bytes_to_str(pinfo->pool, esp_icv_computed, esp_icv_len);
2400 else if(g_esp_enable_null_encryption_decode_heuristic)
2402 /* The packet does not belong to a Security Association */
2403 null_encryption_decode_heuristic = true;
2406 if(decrypt_ok)
2408 tvb_decrypted = tvb_new_child_real_data(tvb, (uint8_t *)wmem_memdup(pinfo->pool, esp_decr_data, esp_decr_data_len),
2409 esp_decr_data_len, esp_decr_data_len);
2411 add_new_data_source(pinfo, tvb_decrypted, "Decrypted Data");
2412 item = proto_tree_add_item(esp_tree, hf_esp_decrypted_data, tvb_decrypted, 0, esp_decr_data_len, ENC_NA);
2413 proto_item_append_text(item, " (%d byte%s)", esp_decr_data_len, plurality(esp_decr_data_len, "", "s"));
2415 decr_tree = proto_item_add_subtree(item, ett_esp_decrypted_data);
2417 /* Make sure the packet is not truncated before the fields
2418 * we need to read to determine the encapsulated protocol */
2419 if(tvb_bytes_exist(tvb_decrypted, esp_decr_data_len - 2, 2))
2421 int esp_contained_data_len;
2423 esp_pad_len = tvb_get_uint8(tvb_decrypted, esp_decr_data_len - 2);
2424 esp_contained_data_len = esp_decr_data_len - esp_pad_len - 2;
2426 if(esp_contained_data_len > 0)
2428 item = proto_tree_add_item(decr_tree, hf_esp_contained_data, tvb_decrypted, 0, esp_contained_data_len, ENC_NA);
2429 proto_item_append_text(item, " (%d byte%s)", esp_contained_data_len, plurality(esp_contained_data_len, "", "s"));
2431 /* Get the encapsulated protocol */
2432 encapsulated_protocol = tvb_get_uint8(tvb_decrypted, esp_decr_data_len - 1);
2434 dissector_handle = dissector_get_uint_handle(ip_dissector_table, encapsulated_protocol);
2435 if (dissector_handle) {
2437 * Recursively dissect the decrypted frame
2439 * Note that the dissection restarts at the top level 'tree' here, not
2440 * at 'decr_tree', which is hidden inside the ESP subtree. This has
2441 * the effect that the protocol layers of the decrypted packet show up
2442 * in the protocol stack of the Packet Details Pane immediately below
2443 * the ESP layer, which is more intuitive and practical for the user.
2445 saved_match_uint = pinfo->match_uint;
2446 pinfo->match_uint = encapsulated_protocol;
2447 next_tvb = tvb_new_subset_length(tvb_decrypted, 0, esp_contained_data_len);
2448 export_ipsec_pdu(dissector_handle, pinfo, next_tvb);
2449 call_dissector(dissector_handle, next_tvb, pinfo, tree);
2450 pinfo->match_uint = saved_match_uint;
2451 decrypt_dissect_ok = true;
2456 if(decrypt_dissect_ok)
2458 if(decr_tree)
2460 if(esp_pad_len !=0)
2461 proto_tree_add_item(decr_tree, hf_esp_pad,
2462 tvb_decrypted,
2463 esp_decr_data_len - esp_pad_len - 2,
2464 esp_pad_len, ENC_NA);
2466 proto_tree_add_uint(decr_tree, hf_esp_pad_len, tvb_decrypted,
2467 esp_decr_data_len - 2, 1,
2468 esp_pad_len);
2470 proto_tree_add_uint_format(decr_tree, hf_esp_protocol, tvb_decrypted,
2471 esp_decr_data_len - 1, 1,
2472 encapsulated_protocol,
2473 "Next header: %s (0x%02x)",
2474 ipprotostr(encapsulated_protocol), encapsulated_protocol);
2477 else
2479 next_tvb = tvb_new_subset_length(tvb_decrypted, 0,
2480 esp_decr_data_len);
2481 export_ipsec_pdu(data_handle, pinfo, next_tvb);
2482 call_dissector(data_handle, next_tvb, pinfo, decr_tree);
2488 If the packet is present in the security association database and the field g_esp_enable_authentication_check set.
2490 if(!g_esp_enable_encryption_decode && g_esp_enable_authentication_check && sad_is_present)
2492 next_tvb = tvb_new_subset_length_caplen(tvb, ESP_HEADER_LEN, esp_packet_len - ESP_HEADER_LEN - esp_icv_len, -1);
2493 export_ipsec_pdu(data_handle, pinfo, next_tvb);
2494 call_dissector(data_handle, next_tvb, pinfo, esp_tree);
2496 /* The packet does not belong to a security association and the field g_esp_enable_null_encryption_decode_heuristic is set */
2497 else if(null_encryption_decode_heuristic)
2499 if(g_esp_enable_null_encryption_decode_heuristic)
2501 esp_icv_len = esp_null_heur(tvb, pinfo, esp_tree);
2504 if(esp_icv_len != -1)
2506 offset = esp_packet_len - esp_icv_len;
2507 if(esp_tree)
2509 /* Make sure we have the auth trailer data */
2510 if(tvb_bytes_exist(tvb, offset, esp_icv_len))
2512 icv_item = proto_tree_add_item(esp_tree, hf_esp_icv, tvb, offset, esp_icv_len, ENC_NA);
2514 else
2516 /* Truncated so just display what we have */
2517 icv_item = proto_tree_add_bytes_format(esp_tree, hf_esp_icv, tvb, offset,
2518 esp_icv_len - (esp_packet_len - tvb_captured_length(tvb)),
2519 NULL, "Integrity Check Value (truncated)");
2525 if(icv_item != NULL) {
2527 bool good = false, bad = false;
2529 icv_tree = proto_item_add_subtree(icv_item, ett_esp_icv);
2531 if(icv_checked) {
2532 if (icv_correct) {
2533 proto_item_append_text(icv_item, " [correct]");
2534 good = true;
2535 if (sn_length == IPSEC_SA_ESN && g_esp_do_sequence_analysis) {
2536 spi_status *status = (spi_status*)wmem_map_lookup(esp_sequence_analysis_hash,
2537 GUINT_TO_POINTER((unsigned)spi));
2538 if (status && !status->firstValidSN) {
2539 status->firstValidSN = sequence_number;
2542 } else {
2543 proto_item_append_text(icv_item, " [incorrect, should be %s]", esp_icv_expected);
2544 bad = true;
2546 } else {
2547 proto_item_append_text(icv_item, " [unchecked]");
2550 item = proto_tree_add_boolean(icv_tree, hf_esp_icv_good,
2551 tvb, offset, esp_icv_len, good);
2552 proto_item_set_generated(item);
2554 item = proto_tree_add_boolean(icv_tree, hf_esp_icv_bad,
2555 tvb, offset, esp_icv_len, bad);
2556 proto_item_set_generated(item);
2559 return tvb_captured_length(tvb);
2563 static int
2564 dissect_ipcomp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* dissector_data _U_)
2566 proto_tree *ipcomp_tree;
2567 proto_item *ti;
2568 uint8_t comp_nxt; /* Next Header */
2569 uint32_t comp_cpi; /* Compression parameter index */
2570 dissector_handle_t dissector_handle;
2571 uint32_t saved_match_uint;
2572 tvbuff_t *data, *decomp;
2575 * load the top pane info. This should be overwritten by
2576 * the next protocol in the stack
2578 col_set_str(pinfo->cinfo, COL_PROTOCOL, "IPComp");
2579 col_clear(pinfo->cinfo, COL_INFO);
2581 comp_nxt = tvb_get_uint8(tvb, 0);
2584 * populate a tree in the second pane with the status of the link layer
2585 * (ie none)
2587 ti = proto_tree_add_item(tree, proto_ipcomp, tvb, 0, -1, ENC_NA);
2588 ipcomp_tree = proto_item_add_subtree(ti, ett_ipcomp);
2590 proto_tree_add_uint_format_value(ipcomp_tree, hf_ipcomp_next_header, tvb,
2591 0, 1, comp_nxt, "%s (0x%02x)", ipprotostr(comp_nxt), comp_nxt);
2592 proto_tree_add_item(ipcomp_tree, hf_ipcomp_flags, tvb, 1, 1, ENC_NA);
2593 proto_tree_add_item_ret_uint(ipcomp_tree, hf_ipcomp_cpi, tvb, 2, 2, ENC_BIG_ENDIAN, &comp_cpi);
2595 col_add_fstr(pinfo->cinfo, COL_INFO, "IPComp (CPI=%s)", val_to_str(comp_cpi, cpi2val, "0x%04x"));
2597 data = tvb_new_subset_remaining(tvb, 4);
2598 export_ipsec_pdu(data_handle, pinfo, data);
2599 call_dissector(data_handle, data, pinfo, ipcomp_tree);
2602 * try to uncompress as if it were DEFLATEd. With negotiated
2603 * CPIs, we don't know the algorithm beforehand; if we get it
2604 * wrong, tvb_child_uncompress_zlib() returns NULL and nothing is displayed.
2606 decomp = tvb_child_uncompress_zlib(data, data, 0, tvb_captured_length(data));
2607 if (decomp) {
2608 add_new_data_source(pinfo, decomp, "IPcomp inflated data");
2609 saved_match_uint = pinfo->match_uint;
2610 dissector_handle = dissector_get_uint_handle(ip_dissector_table, comp_nxt);
2611 if (dissector_handle) {
2612 pinfo->match_uint = comp_nxt;
2613 } else {
2614 dissector_handle = data_handle;
2616 export_ipsec_pdu(dissector_handle, pinfo, decomp);
2617 call_dissector(dissector_handle, decomp, pinfo, tree);
2618 pinfo->match_uint = saved_match_uint;
2621 return tvb_captured_length(tvb);
2624 static void ipsec_cleanup_protocol(void)
2626 /* Free any SA records added by other dissectors */
2627 unsigned n;
2628 for (n=0; n < extra_esp_sa_records.num_records; n++) {
2629 uat_esp_sa_record_free_cb(&(extra_esp_sa_records.records[n]));
2632 /* Free overall block of records */
2633 g_free(extra_esp_sa_records.records);
2634 extra_esp_sa_records.records = NULL;
2635 extra_esp_sa_records.num_records = 0;
2638 void
2639 proto_register_ipsec(void)
2641 static hf_register_info hf_ah[] = {
2642 { &hf_ah_next_header,
2643 { "Next header", "ah.next_header", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &ipproto_val_ext, 0x0,
2644 NULL, HFILL }},
2645 { &hf_ah_length,
2646 { "Length", "ah.length", FT_UINT8, BASE_DEC, NULL, 0x0,
2647 NULL, HFILL }},
2648 { &hf_ah_reserved,
2649 { "Reserved", "ah.reserved", FT_BYTES, BASE_NONE, NULL, 0x0,
2650 NULL, HFILL }},
2651 { &hf_ah_spi,
2652 { "AH SPI", "ah.spi", FT_UINT32, BASE_HEX, NULL, 0x0,
2653 "IP Authentication Header Security Parameters Index", HFILL }},
2654 { &hf_ah_iv,
2655 { "AH ICV", "ah.icv", FT_BYTES, BASE_NONE, NULL, 0x0,
2656 "IP Authentication Header Integrity Check Value", HFILL }},
2657 { &hf_ah_sequence,
2658 { "AH Sequence", "ah.sequence", FT_UINT32, BASE_DEC, NULL, 0x0,
2659 "IP Authentication Header Sequence Number", HFILL }}
2662 static hf_register_info hf_esp[] = {
2663 { &hf_esp_spi,
2664 { "ESP SPI", "esp.spi", FT_UINT32, BASE_HEX_DEC, NULL, 0x0,
2665 "IP Encapsulating Security Payload Security Parameters Index", HFILL }},
2666 { &hf_esp_sequence,
2667 { "ESP Sequence", "esp.sequence", FT_UINT32, BASE_DEC, NULL, 0x0,
2668 "IP Encapsulating Security Payload Sequence Number", HFILL }},
2669 { &hf_esp_pad,
2670 { "Pad", "esp.pad", FT_BYTES, BASE_NONE, NULL, 0x0,
2671 NULL, HFILL }},
2672 { &hf_esp_pad_len,
2673 { "ESP Pad Length", "esp.pad_len", FT_UINT8, BASE_DEC, NULL, 0x0,
2674 "IP Encapsulating Security Payload Pad Length", HFILL }},
2675 { &hf_esp_protocol,
2676 { "ESP Next Header", "esp.protocol", FT_UINT8, BASE_HEX, NULL, 0x0,
2677 "IP Encapsulating Security Payload Next Header", HFILL }},
2678 { &hf_esp_iv,
2679 { "ESP IV", "esp.iv", FT_BYTES, BASE_NONE, NULL, 0x0,
2680 "IP Encapsulating Security Payload Initialization Vector", HFILL }},
2681 { &hf_esp_encrypted_data,
2682 { "ESP Encrypted Data", "esp.encrypted_data", FT_BYTES, BASE_NONE, NULL, 0x0,
2683 "IP Encapsulating Security Payload Encrypted Data", HFILL }},
2684 { &hf_esp_decrypted_data,
2685 { "ESP Decrypted Data", "esp.decrypted_data", FT_BYTES, BASE_NONE, NULL, 0x0,
2686 "IP Encapsulating Security Payload Decrypted Data", HFILL }},
2687 { &hf_esp_contained_data,
2688 { "ESP Contained Data", "esp.contained_data", FT_BYTES, BASE_NONE, NULL, 0x0,
2689 "IP Encapsulating Security Payload Contained Data", HFILL }},
2690 { &hf_esp_icv,
2691 { "ESP ICV", "esp.icv", FT_BYTES, BASE_NONE, NULL, 0x0,
2692 "IP Encapsulating Security Payload Integrity Check Value", HFILL }},
2693 { &hf_esp_icv_good,
2694 { "Good", "esp.icv_good", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2695 "True: ICV matches packet content; False: doesn't match content or not checked", HFILL }},
2696 { &hf_esp_icv_bad,
2697 { "Bad", "esp.icv_bad", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
2698 "True: ICV doesn't match packet content; False: matches content or not checked", HFILL }},
2699 { &hf_esp_sequence_analysis_expected_sn,
2700 { "Expected SN", "esp.sequence-analysis.expected-sn", FT_UINT32, BASE_DEC, NULL, 0x0,
2701 NULL, HFILL }},
2702 { &hf_esp_sequence_analysis_previous_frame,
2703 { "Previous Frame", "esp.sequence-analysis.previous-frame", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
2704 NULL, HFILL }},
2707 static hf_register_info hf_ipcomp[] = {
2708 { &hf_ipcomp_next_header,
2709 { "Next Header", "ipcomp.next_header", FT_UINT8, BASE_HEX, NULL, 0x0,
2710 NULL, HFILL }},
2711 { &hf_ipcomp_flags,
2712 { "IPComp Flags", "ipcomp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
2713 "IP Payload Compression Protocol Flags", HFILL }},
2714 { &hf_ipcomp_cpi,
2715 { "IPComp CPI", "ipcomp.cpi", FT_UINT16, BASE_HEX, VALS(cpi2val), 0x0,
2716 "IP Payload Compression Protocol Compression Parameter Index", HFILL }},
2719 static int *ett[] = {
2720 &ett_ah,
2721 &ett_esp,
2722 &ett_esp_icv,
2723 &ett_esp_decrypted_data,
2724 &ett_ipcomp,
2727 static ei_register_info ei[] = {
2728 { &ei_esp_sequence_analysis_wrong_sequence_number, { "esp.sequence-analysis.wrong-sequence-number", PI_SEQUENCE, PI_WARN, "Wrong Sequence Number", EXPFILL }},
2729 { &ei_esp_pad_bogus, { "esp.pad.bogus", PI_PROTOCOL, PI_WARN, "Padding MUST increment starting with 1 [RFC 4303 2.4]", EXPFILL }}
2732 static const value_string esp_proto_type_vals[] = {
2733 { IPSEC_SA_IPV4, "IPv4" },
2734 { IPSEC_SA_IPV6, "IPv6" },
2735 { IPSEC_SA_ANY, "Any" },
2736 { 0x00, NULL }
2739 static const value_string esp_sn_length_vals[] = {
2740 { IPSEC_SA_SN, "32-bit" },
2741 { IPSEC_SA_ESN, "64-bit" },
2742 { 0x00, NULL }
2745 static uat_field_t esp_uat_flds[] = {
2746 UAT_FLD_VS(uat_esp_sa_records, protocol, "Protocol", esp_proto_type_vals, "Protocol used"),
2747 UAT_FLD_CSTRING(uat_esp_sa_records, srcIP, "Src IP", "Source Address"),
2748 UAT_FLD_CSTRING(uat_esp_sa_records, dstIP, "Dest IP", "Destination Address"),
2749 UAT_FLD_CSTRING(uat_esp_sa_records, spi, "SPI", "SPI"),
2750 UAT_FLD_VS(uat_esp_sa_records, encryption_algo, "Encryption", esp_encryption_type_vals, "Encryption algorithm"),
2751 UAT_FLD_CSTRING(uat_esp_sa_records, encryption_key_string, "Encryption Key", "Encryption Key"),
2752 UAT_FLD_VS(uat_esp_sa_records, authentication_algo, "Authentication", esp_authentication_type_vals, "Authentication algorithm"),
2753 UAT_FLD_CSTRING(uat_esp_sa_records, authentication_key_string, "Authentication Key", "Authentication Key"),
2754 UAT_FLD_VS(uat_esp_sa_records, sn_length, "SN", esp_sn_length_vals, "Sequence Number length"),
2755 UAT_FLD_HEX(uat_esp_sa_records, sn_upper, "ESN High Bits", "Extended Sequence Number upper 32 bits (hex)"),
2756 UAT_END_FIELDS
2759 static build_valid_func ah_da_build_value[1] = {ah_value};
2760 static decode_as_value_t ah_da_values = {ah_prompt, 1, ah_da_build_value};
2761 static decode_as_t ah_da = {"ah", "ip.proto", 1, 0, &ah_da_values, NULL, NULL,
2762 decode_as_default_populate_list, decode_as_default_reset, decode_as_default_change, NULL};
2764 module_t *ah_module;
2765 module_t *esp_module;
2767 expert_module_t* expert_esp;
2769 proto_ah = proto_register_protocol("Authentication Header", "AH", "ah");
2770 proto_register_field_array(proto_ah, hf_ah, array_length(hf_ah));
2772 proto_esp = proto_register_protocol("Encapsulating Security Payload", "ESP", "esp");
2773 proto_register_field_array(proto_esp, hf_esp, array_length(hf_esp));
2775 proto_ipcomp = proto_register_protocol("IP Payload Compression", "IPComp", "ipcomp");
2776 proto_register_field_array(proto_ipcomp, hf_ipcomp, array_length(hf_ipcomp));
2778 proto_register_subtree_array(ett, array_length(ett));
2780 expert_esp = expert_register_protocol(proto_esp);
2781 expert_register_field_array(expert_esp, ei, array_length(ei));
2783 ah_module = prefs_register_protocol_obsolete(proto_ah);
2785 prefs_register_obsolete_preference(ah_module, "place_ah_payload_in_subtree");
2787 esp_module = prefs_register_protocol(proto_esp, NULL);
2789 prefs_register_bool_preference(esp_module, "enable_null_encryption_decode_heuristic",
2790 "Attempt to detect/decode NULL encrypted ESP payloads",
2791 "This is done only if the Decoding is not SET or the packet does not belong to a SA. "
2792 "Tries ICV lengths of 12, 16, 24, and 32 bytes, checks for valid padding, "
2793 "and attempts to decode based on the derived Next Header field. "
2794 "Does not detect ENCR_NULL_AUTH_AES_GMAC (i.e. assumes 0 length IV)",
2795 &g_esp_enable_null_encryption_decode_heuristic);
2797 prefs_register_enum_preference(esp_module, "padding",
2798 "Padding type accepted",
2799 "RFC 4303 2.4 requires that padding bytes, if present, MUST "
2800 "be the monotonically increasing sequence 1, 2, 3, …. "
2801 "Some implementations add non-compliant padding. "
2802 "This option determines what, if any, non-compliant padding "
2803 "the NULL encryption heuristic will allow. "
2804 "WARNING: Allowing non-compliant padding can lead to "
2805 "significant false positives.",
2806 &g_esp_padding_type, esp_padding_vals, false);
2808 prefs_register_bool_preference(esp_module, "do_esp_sequence_analysis",
2809 "Check sequence numbers of ESP frames",
2810 "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",
2811 &g_esp_do_sequence_analysis);
2813 prefs_register_bool_preference(esp_module, "enable_encryption_decode",
2814 "Attempt to detect/decode encrypted ESP payloads",
2815 "Attempt to decode based on the SAD described hereafter.",
2816 &g_esp_enable_encryption_decode);
2818 prefs_register_bool_preference(esp_module, "enable_authentication_check",
2819 "Attempt to Check ESP Authentication",
2820 "Attempt to Check ESP Authentication based on the SAD described hereafter.",
2821 &g_esp_enable_authentication_check);
2823 esp_uat = uat_new("ESP SAs",
2824 sizeof(uat_esp_sa_record_t), /* record size */
2825 "esp_sa", /* filename */
2826 true, /* from_profile */
2827 &uat_esp_sa_records, /* data_ptr */
2828 &num_sa_uat, /* numitems_ptr */
2829 UAT_AFFECTS_DISSECTION, /* affects dissection of packets, but not set of named fields */
2830 NULL, /* help */
2831 uat_esp_sa_record_copy_cb, /* copy callback */
2832 uat_esp_sa_record_update_cb, /* update callback */
2833 uat_esp_sa_record_free_cb, /* free callback */
2834 NULL, /* post update callback */
2835 NULL, /* reset callback */
2836 esp_uat_flds); /* UAT field definitions */
2838 static const char *esp_uat_defaults_[] = {
2839 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "32-bit", "0" };
2840 uat_set_default_values(esp_uat, esp_uat_defaults_);
2842 prefs_register_uat_preference(esp_module,
2843 "sa_table",
2844 "ESP SAs",
2845 "Preconfigured ESP Security Associations",
2846 esp_uat);
2848 esp_sequence_analysis_hash = wmem_map_new_autoreset(wmem_epan_scope(), wmem_file_scope(), g_direct_hash, g_direct_equal);
2849 esp_sequence_analysis_report_hash = wmem_map_new_autoreset(wmem_epan_scope(), wmem_file_scope(), g_direct_hash, g_direct_equal);
2850 register_cleanup_routine(&ipsec_cleanup_protocol);
2852 register_dissector("esp", dissect_esp, proto_esp);
2853 register_dissector("ah", dissect_ah, proto_ah);
2855 ipcomp_handle = register_dissector("ipcomp", dissect_ipcomp, proto_ipcomp);
2856 ah_cap_handle = register_capture_dissector("ah", capture_ah, proto_ah);
2858 register_decode_as(&ah_da);
2861 void
2862 proto_reg_handoff_ipsec(void)
2864 dissector_handle_t esp_handle, ah_handle;
2866 data_handle = find_dissector("data");
2867 ah_handle = find_dissector("ah");
2868 dissector_add_uint("ip.proto", IP_PROTO_AH, ah_handle);
2869 esp_handle = find_dissector("esp");
2870 dissector_add_uint("ip.proto", IP_PROTO_ESP, esp_handle);
2871 dissector_add_uint("ip.proto", IP_PROTO_IPCOMP, ipcomp_handle);
2873 ip_dissector_table = find_dissector_table("ip.proto");
2875 capture_dissector_add_uint("ip.proto", IP_PROTO_AH, ah_cap_handle);
2877 exported_pdu_tap = find_tap_id(EXPORT_PDU_TAP_NAME_LAYER_3);
2881 * Editor modelines
2883 * Local Variables:
2884 * c-basic-offset: 2
2885 * tab-width: 8
2886 * indent-tabs-mode: nil
2887 * End:
2889 * ex: set shiftwidth=2 tabstop=8 expandtab:
2890 * :indentSize=2:tabSize=8:noTabs=true: