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