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