#include <string.h> and/or #include <stdio.h> not needed.
[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
78 #include <string.h>
79 #include <glib.h>
80 #include <epan/packet.h>
81 #include <epan/emem.h>
82 #include "packet-ipsec.h"
83 #include <epan/addr_resolv.h>
84 #include <epan/ipproto.h>
85 #include <epan/prefs.h>
86
87 #include <ctype.h>
88
89 /* If you want to be able to decrypt or Check Authentication of ESP packets you MUST define this : */
90 #ifdef HAVE_LIBGCRYPT
91 #include <gcrypt.h>
92 #endif /* HAVE_LIBGCRYPT */
93
94
95 static int proto_ah = -1;
96 static int hf_ah_spi = -1;
97 static int hf_ah_iv = -1;
98 static int hf_ah_sequence = -1;
99 static int proto_esp = -1;
100 static int hf_esp_spi = -1;
101 static int hf_esp_iv = -1;
102 static int hf_esp_sequence = -1;
103 static int hf_esp_pad_len = -1;
104 static int hf_esp_protocol = -1;
105 static int proto_ipcomp = -1;
106 static int hf_ipcomp_flags = -1;
107 static int hf_ipcomp_cpi = -1;
108
109 static gint ett_ah = -1;
110 static gint ett_esp = -1;
111 static gint ett_ipcomp = -1;
112
113 static dissector_handle_t data_handle;
114
115 static dissector_table_t ip_dissector_table;
116
117 #ifdef  HAVE_LIBGCRYPT
118 /* Encryption algorithms defined in RFC 4305 */
119 #define IPSEC_ENCRYPT_NULL 0
120 #define IPSEC_ENCRYPT_3DES_CBC 1
121 #define IPSEC_ENCRYPT_AES_CBC 2
122 #define IPSEC_ENCRYPT_AES_CTR 3
123 #define IPSEC_ENCRYPT_DES_CBC 4
124 #define IPSEC_ENCRYPT_BLOWFISH_CBC 5
125 #define IPSEC_ENCRYPT_TWOFISH_CBC 6
126
127 /* Encryption algorithm defined in RFC 2144 */
128 #define IPSEC_ENCRYPT_CAST5_CBC 7
129
130 /* Authentication algorithms defined in RFC 4305 */
131 #define IPSEC_AUTH_NULL 0
132 #define IPSEC_AUTH_HMAC_SHA1_96 1
133 #define IPSEC_AUTH_HMAC_SHA256_96 2
134 #define IPSEC_AUTH_HMAC_SHA256_128 3
135 #define IPSEC_AUTH_HMAC_MD5_96 4
136 #define IPSEC_AUTH_HMAC_RIPEMD160_96 5
137 /* define IPSEC_AUTH_AES_XCBC_MAC_96 6 */
138 #define IPSEC_AUTH_ANY_96BIT 7
139 #define IPSEC_AUTH_ANY_128BIT 8
140 #define IPSEC_AUTH_ANY_192BIT 9
141 #define IPSEC_AUTH_ANY_256BIT 10
142 #endif
143
144 /* well-known algorithm number (in CPI), from RFC2409 */
145 #define IPCOMP_OUI      1       /* vendor specific */
146 #define IPCOMP_DEFLATE  2       /* RFC2394 */
147 #define IPCOMP_LZS      3       /* RFC2395 */
148 #define IPCOMP_MAX      4
149
150 #ifdef HAVE_LIBGCRYPT
151 #define IPSEC_IPV6_ADDR_LEN 128
152 #define IPSEC_IPV4_ADDR_LEN 32
153 #define IPSEC_STRLEN_IPV6 32
154 #define IPSEC_STRLEN_IPV4 8
155 #define IPSEC_SA_IPV4 1
156 #define IPSEC_SA_IPV6 2
157 #define IPSEC_SA_UNKNOWN -1
158 #define IPSEC_SA_WILDCARDS_ANY '*'
159 #define IPSEC_SA_SEPARATOR '|'
160 #define IPSEC_SA_ADDR_LEN_SEPARATOR '/'
161 #define IPSEC_IPV6_ADDR_MAX 40
162 #define IPSEC_IPV4_ADDR_MAX 16
163 #define IPSEC_SPI_LEN_MAX 10
164 #define IPSEC_TYP_LEN 4
165 #define IPSEC_ADDR_LEN_MAX 3
166
167 /* Number of Security Associations */
168 #define IPSEC_NB_SA 16
169 #endif
170
171 static const value_string cpi2val[] = {
172   { IPCOMP_OUI, "OUI" },
173   { IPCOMP_DEFLATE, "DEFLATE" },
174   { IPCOMP_LZS, "LZS" },
175   { 0, NULL },
176 };
177
178 struct newah {
179   guint8        ah_nxt;         /* Next Header */
180   guint8        ah_len;         /* Length of data + 1, in 32bit */
181   guint16       ah_reserve;     /* Reserved for future use */
182   guint32       ah_spi;         /* Security parameter index */
183   guint32       ah_seq;         /* Sequence number field */
184   /* variable size, 32bit bound*/       /* Authentication data */
185 };
186
187 struct newesp {
188   guint32       esp_spi;        /* ESP */
189   guint32       esp_seq;        /* Sequence number */
190   /*variable size*/             /* (IV and) Payload data */
191   /*variable size*/             /* padding */
192   /*8bit*/                      /* pad size */
193   /*8bit*/                      /* next header */
194   /*8bit*/                      /* next header */
195   /*variable size, 32bit bound*/        /* Authentication data */
196 };
197
198 struct ipcomp {
199   guint8 comp_nxt;      /* Next Header */
200   guint8 comp_flags;    /* Must be zero */
201   guint16 comp_cpi;     /* Compression parameter index */
202 };
203
204 #ifdef HAVE_LIBGCRYPT
205 /* SA Paramaters and SAD */
206 static guint g_esp_nb_sa = IPSEC_NB_SA;
207 static guint g_max_esp_nb_sa = 100;
208
209 typedef struct  {
210   const gchar *sa;
211   gint typ;
212   gchar *src;
213   gint src_len;
214   gchar *dst;
215   gint dst_len;
216   gchar *spi;
217   gint encryption_algo;
218   gint authentication_algo;
219   const gchar *encryption_key;
220   const gchar *authentication_key;
221   gboolean is_valid;
222 } g_esp_sa;
223
224 typedef struct  {
225   gint nb;
226   g_esp_sa table[IPSEC_NB_SA];
227 } g_esp_sa_database;
228
229 static g_esp_sa_database g_esp_sad;
230
231
232 /* Default ESP payload decode to off */
233 static gboolean g_esp_enable_encryption_decode = FALSE;
234
235 /* Default ESP payload Authentication Checking to off */
236 static gboolean g_esp_enable_authentication_check = FALSE;
237 #endif
238
239 /*
240    Default ESP payload heuristic decode to off
241    (only works if payload is NULL encrypted and ESP payload decode is off or payload is NULL encrypted
242    and the packet does not match a Security Association).
243 */
244 static gboolean g_esp_enable_null_encryption_decode_heuristic = FALSE;
245
246 /* Place AH payload in sub tree */
247 static gboolean g_ah_payload_in_subtree = FALSE;
248
249 #ifndef offsetof
250 #define offsetof(type, member)  ((size_t)(&((type *)0)->member))
251 #endif
252
253
254
255
256 /*
257    Name : static int get_ipv6_suffix(char* ipv6_suffix, char *ipv6_address)
258    Description : Get the extended IPv6 Suffix of an IPv6 Address
259    Return : Return the number of char of the IPv6 address suffix parsed
260    Params:
261       - char *ipv6_address : the valid ipv6 address to parse in char *
262       - char *ipv6_suffix : the ipv6 suffix associated in char *
263
264       ex: if IPv6 address is "3ffe::1" the IPv6 suffix will be "0001" and the function will return 3
265 */
266 #ifdef HAVE_LIBGCRYPT
267 static int get_ipv6_suffix(char* ipv6_suffix, char *ipv6_address)
268 {
269   char suffix[IPSEC_STRLEN_IPV6 + 1];
270   int cpt = 0;
271   int cpt_suffix = 0;
272   int cpt_seg = 0;
273   int j =0;
274   int ipv6_len = 0;
275   gboolean found = FALSE;
276
277   ipv6_len = (int) strlen(ipv6_address);
278   if(ipv6_len  == 0)
279     {
280       /* Found a suffix */
281       found = TRUE;
282     }
283   else
284     {
285       while ( (cpt_suffix < IPSEC_STRLEN_IPV6) && (ipv6_len - cpt -1 >= 0) && (found == FALSE))
286         {
287           if(ipv6_address[ipv6_len - cpt - 1] == ':')
288             {
289               /* Add some 0 to the prefix; */
290               for(j = cpt_seg; j < 4; j++)
291                 {
292                   suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = '0';
293                   cpt_suffix ++;
294                 }
295               cpt_seg = 0;
296
297               if(ipv6_len - cpt - 1 == 0)
298                 {
299                   /* Found a suffix */
300                   found = TRUE;
301                 }
302               else
303                 if(ipv6_address[ipv6_len - cpt - 2] == ':')
304                   {
305                     /* found a suffix */
306                     cpt +=2;
307                     found = TRUE;
308                   }
309
310                 else
311                   {
312                     cpt++;
313                   }
314             }
315           else
316             {
317               suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = toupper(ipv6_address[ipv6_len - cpt - 1]);
318               cpt_seg ++;
319               cpt_suffix ++;
320               cpt++;
321             }
322         }
323
324       if(cpt_suffix % 4 != 0)
325         {
326           for(j = cpt_seg; j < 4; j++)
327             {
328               suffix[IPSEC_STRLEN_IPV6 -1 -cpt_suffix] = '0';
329               cpt_suffix ++;
330             }
331           cpt_seg = 0;
332         }
333
334     }
335
336   for(j = 0 ; j < cpt_suffix ; j ++)
337     {
338       suffix[j] = suffix[j + IPSEC_STRLEN_IPV6 - cpt_suffix] ;
339     }
340
341   suffix[j] = '\0';
342   memcpy(ipv6_suffix,suffix,j + 1);
343   return cpt;
344 }
345 #endif
346
347
348
349 /*
350    Name : static int get_full_ipv6_addr(char* ipv6_addr_expanded, char *ipv6_addr)
351    Description : Get the extended IPv6 Address of an IPv6 Address
352    Return : Return the remaining number of char of the IPv6 address parsed
353    Params:
354       - char *ipv6_addr : the valid ipv6 address to parse in char *
355       - char *ipv6_addr_expansed : the expanded ipv6 address associated in char *
356
357       ex: if IPv6 address is "3ffe::1" the IPv6 expanded address
358             will be "3FFE0000000000000000000000000001" and the function will return 0
359           if IPV6 address is "3ffe::*" the IPv6 expanded address
360             will be "3FFE000000000000000000000000****" and the function will return 0
361 */
362 #ifdef HAVE_LIBGCRYPT
363 static int
364 get_full_ipv6_addr(char* ipv6_addr_expanded, char *ipv6_addr)
365 {
366   char suffix[IPSEC_STRLEN_IPV6 + 1];
367   char prefix[IPSEC_STRLEN_IPV6 + 1];
368   char *prefix_addr;
369
370   int suffix_cpt = 0;
371   int suffix_len = 0;
372   int prefix_remaining = 0;
373   int prefix_len = 0;
374   int j = 0;
375
376
377   if((ipv6_addr == NULL) || (strcmp(ipv6_addr, "") == 0))  return -1;
378   if((strlen(ipv6_addr) == 1) && (ipv6_addr[0] == IPSEC_SA_WILDCARDS_ANY))
379     {
380       for(j = 0; j <= IPSEC_STRLEN_IPV6; j++)
381         {
382           ipv6_addr_expanded[j] = IPSEC_SA_WILDCARDS_ANY;
383         }
384       ipv6_addr_expanded[IPSEC_STRLEN_IPV6] = '\0';
385       return 0;
386     }
387
388   suffix_cpt = get_ipv6_suffix(suffix,ipv6_addr);
389   suffix_len = (int) strlen(suffix);
390
391   if(suffix_len <  IPSEC_STRLEN_IPV6)
392     {
393       prefix_addr = ep_strndup(ipv6_addr,strlen(ipv6_addr) - suffix_cpt);
394       prefix_remaining = get_ipv6_suffix(prefix,prefix_addr);
395       prefix_len = (int) strlen(prefix);
396       memcpy(ipv6_addr_expanded,prefix,prefix_len);
397     }
398
399
400   for(j = 0; j <= IPSEC_STRLEN_IPV6 - prefix_len - suffix_len; j++)
401     {
402       ipv6_addr_expanded[j + prefix_len] = '0';
403     }
404
405   memcpy(ipv6_addr_expanded + IPSEC_STRLEN_IPV6 - suffix_len, suffix,suffix_len + 1);
406
407   if(suffix_len < IPSEC_STRLEN_IPV6)
408     return (prefix_len - prefix_remaining);
409   else
410     return (int) strlen(ipv6_addr) - suffix_cpt;
411 }
412 #endif
413
414
415
416 /*
417    Name : static gboolean get_full_ipv4_addr(char* ipv4_addr_expanded, char *ipv4_addr)
418    Description : Get the extended IPv4 Address of an IPv4 Address
419    Return : Return true if it can derive an IPv4 address. It does not mean that
420             the previous one was valid.
421    Params:
422       - char *ipv4_addr : the valid ipv4 address to parse in char *
423       - char *ipv4_addr_expansed : the expanded ipv4 address associated in char *
424
425       ex: if IPv4 address is "190.*.*.1" the IPv4 expanded address will be "BE****01" and
426             the function will return 0
427           if IPv4 address is "*" the IPv4 expanded address will be "********" and
428             the function will return 0
429 */
430 #ifdef HAVE_LIBGCRYPT
431 static gboolean
432 get_full_ipv4_addr(char* ipv4_address_expanded, char *ipv4_address)
433 {
434   char addr_byte_string_tmp[4];
435   char addr_byte_string[4];
436
437   guint addr_byte = 0;
438   guint i = 0;
439   guint j = 0;
440   guint k = 0;
441   guint cpt = 0;
442   gboolean done_flag = FALSE;
443
444   if((ipv4_address == NULL) || (strcmp(ipv4_address, "") == 0))  return done_flag;
445
446   if((strlen(ipv4_address) == 1) && (ipv4_address[0] == IPSEC_SA_WILDCARDS_ANY))
447     {
448       for(i = 0; i <= IPSEC_STRLEN_IPV4; i++)
449         {
450           ipv4_address_expanded[i] = IPSEC_SA_WILDCARDS_ANY;
451         }
452       ipv4_address_expanded[IPSEC_STRLEN_IPV4] = '\0';
453       done_flag = TRUE;
454     }
455
456   else {
457     j = 0;
458     cpt = 0;
459     k = 0;
460     while((done_flag == FALSE) && (j <= strlen(ipv4_address)) && (cpt < IPSEC_STRLEN_IPV4))
461       {
462         if(j == strlen(ipv4_address))
463           {
464             addr_byte_string_tmp[k] = '\0';
465             if((strlen(addr_byte_string_tmp) == 1) && (addr_byte_string_tmp[0] == IPSEC_SA_WILDCARDS_ANY))
466               {
467                 for(i = 0; i < 2; i++)
468                   {
469                     ipv4_address_expanded[cpt] = IPSEC_SA_WILDCARDS_ANY;
470                     cpt ++;
471                   }
472               }
473             else
474               {
475                 sscanf(addr_byte_string_tmp,"%u",&addr_byte);
476                 if(addr_byte < 16) g_snprintf(addr_byte_string,4,"0%X",addr_byte);
477                 else g_snprintf(addr_byte_string,4,"%X",addr_byte);
478                 for(i = 0; i < strlen(addr_byte_string); i++)
479                   {
480                     ipv4_address_expanded[cpt] = addr_byte_string[i];
481                     cpt ++;
482                   }
483               }
484             done_flag = TRUE;
485           }
486
487         else if(ipv4_address[j] == '.')
488           {
489             addr_byte_string_tmp[k] = '\0';
490             if((strlen(addr_byte_string_tmp) == 1) && (addr_byte_string_tmp[0] == IPSEC_SA_WILDCARDS_ANY))
491               {
492                 for(i = 0; i < 2; i++)
493                   {
494                     ipv4_address_expanded[cpt] = IPSEC_SA_WILDCARDS_ANY;
495                     cpt ++;
496                   }
497               }
498             else
499               {
500                 sscanf(addr_byte_string_tmp,"%u",&addr_byte);
501                 if(addr_byte < 16) g_snprintf(addr_byte_string,4,"0%X",addr_byte);
502                 else g_snprintf(addr_byte_string,4,"%X",addr_byte);
503                 for(i = 0; i < strlen(addr_byte_string); i++)
504                   {
505                     ipv4_address_expanded[cpt] = addr_byte_string[i];
506                     cpt ++;
507                   }
508               }
509             k = 0;
510             j++;
511           }
512         else
513           {
514             if(k >= 3)
515               {
516                 /* Incorrect IPv4 Address. Erase previous Values in the Byte. (LRU mechanism) */
517                 addr_byte_string_tmp[0] = ipv4_address[j];
518                 k = 1;
519                 j++;
520               }
521             else
522               {
523                 addr_byte_string_tmp[k] = ipv4_address[j];
524                 k++;
525                 j++;
526               }
527           }
528
529       }
530
531     ipv4_address_expanded[cpt] = '\0';
532   }
533
534   return done_flag;
535 }
536 #endif
537
538
539
540 /*
541    Name : static gboolean esp_sa_parse_ipv6addr(const gchar *sa, guint index_start, gchar **pt_ipv6addr, guint *index_end)
542    Description : Get the IPv6 address of a Security Association
543    Return : Return true if it can get an address. It does not mean that the address is valid.
544    Params:
545       - char *sa : the Security Association in char *
546       - guint index_start : the index to start to find the address
547       - gchar **pt_ipv6addr : the address found. The Allocation is done here !
548       - guint *index_end : the last index of the address
549 */
550 #ifdef HAVE_LIBGCRYPT
551 static gboolean
552 esp_sa_parse_ipv6addr(const gchar *sa, guint index_start, gchar **pt_ipv6addr, guint *index_end)
553 {
554   guint cpt = 0;
555
556   char addr_string[IPSEC_IPV6_ADDR_MAX + 1];
557   gboolean done_flag = FALSE;
558
559   if((sa == NULL) || (strcmp(sa, "") == 0))
560     return FALSE;
561
562   /* Get Address */
563   while(((cpt + index_start) < strlen(sa)) && (done_flag == FALSE) && (cpt <= IPSEC_IPV6_ADDR_MAX))
564     {
565       if((sa[cpt + index_start] == IPSEC_SA_SEPARATOR)  || (sa[cpt + index_start] == IPSEC_SA_ADDR_LEN_SEPARATOR))
566         {
567           if(cpt == 0) return FALSE;
568           *index_end = cpt + index_start;
569           addr_string[cpt] = '\0';
570           done_flag = TRUE;
571         }
572
573       else
574         {
575           if((cpt >= IPSEC_IPV6_ADDR_MAX - 1) && ((cpt  + index_start) < strlen(sa)) && (sa[cpt + index_start + 1] != IPSEC_SA_ADDR_LEN_SEPARATOR) && (sa[cpt + index_start + 1] != IPSEC_SA_SEPARATOR))
576             return FALSE;
577           addr_string[cpt] = toupper(sa[cpt + index_start]);
578           cpt ++;
579         }
580     }
581
582   if(done_flag)
583     {
584       *pt_ipv6addr = g_strdup(addr_string);
585     }
586
587   return done_flag;
588 }
589 #endif
590
591
592 /*
593    Name : static gboolean esp_sa_parse_ipv4addr(const gchar *sa, guint index_start, gchar **pt_ipv4addr, guint *index_end)
594    Description : Get the IPv4 address of a Security Association
595    Return : Return true if it can get an address. It does not mean that the address is valid.
596    Params:
597       - char *sa : the Security Association in char *
598       - guint index_start : the index to start to find the address
599       - gchar **pt_ipv4addr : the address found. The Allocation is done here !
600       - guint *index_end : the last index of the address
601 */
602 #ifdef HAVE_LIBGCRYPT
603 static gboolean
604 esp_sa_parse_ipv4addr(const gchar *sa, guint index_start, gchar **pt_ipv4addr, guint *index_end)
605 {
606   guint cpt = 0;
607
608   char addr_string[IPSEC_IPV4_ADDR_MAX + 1];
609   gboolean done_flag = FALSE;
610
611   if((sa == NULL) || (strcmp(sa, "") == 0))
612     return FALSE;
613
614   /* Get Address */
615   while(((cpt + index_start) < strlen(sa)) && (done_flag == FALSE) && (cpt <= IPSEC_IPV4_ADDR_MAX))
616     {
617       if((sa[cpt + index_start] == IPSEC_SA_SEPARATOR)  || (sa[cpt + index_start] == IPSEC_SA_ADDR_LEN_SEPARATOR))
618         {
619           if(cpt == 0) return FALSE;
620           *index_end = cpt + index_start;
621           addr_string[cpt] = '\0';
622           done_flag = TRUE;
623         }
624
625       else
626         {
627           if((cpt == IPSEC_IPV4_ADDR_MAX - 1)
628              && ((cpt  + index_start) < strlen(sa))
629              && (sa[cpt + index_start + 1] != IPSEC_SA_ADDR_LEN_SEPARATOR)
630              && (sa[cpt + index_start + 1] != IPSEC_SA_SEPARATOR))
631             return FALSE;
632           addr_string[cpt] = toupper(sa[cpt + index_start]);
633           cpt ++;
634         }
635     }
636
637   if(done_flag)
638     {
639       *pt_ipv4addr = g_strdup(addr_string);
640     }
641
642   return done_flag;
643 }
644 #endif
645
646
647 /*
648    Name : static gboolean esp_sa_parse_spi(const gchar *sa, guint index_start, gchar **pt_spi, guint *index_end)
649    Description : Get the SPI of a Security Association
650    Return : Return true if it can get a SPI. It does not mean that the SPI is valid.
651    Params:
652       - char *sa : the Security Association in char *
653       - guint index_start : the index to start to find the spi
654       - gchar **pt_spi : the spi found. The Allocation is done here !
655       - guint *index_end : the last index of the address
656 */
657 #ifdef HAVE_LIBGCRYPT
658 static gboolean
659 esp_sa_parse_spi(const gchar *sa, guint index_start, gchar **pt_spi, guint *index_end)
660 {
661   guint cpt = 0;
662   guint32 spi = 0;
663   guint i = 0;
664
665   gchar spi_string[IPSEC_SPI_LEN_MAX + 1];
666   gchar spi_string_tmp[IPSEC_SPI_LEN_MAX + 1];
667   gboolean done_flag = FALSE;
668
669   if((sa == NULL) || (strcmp(sa, "") == 0))  return FALSE;
670
671   while(((cpt + index_start) < strlen(sa)) && (cpt < IPSEC_SPI_LEN_MAX))
672     {
673       spi_string[cpt] = toupper(sa[cpt + index_start]);
674       cpt ++;
675     }
676
677   if(cpt == 0)
678     done_flag = FALSE;
679   else
680     {
681       spi_string[cpt] = '\0';
682       if((cpt >= 2) &&
683          (spi_string[0] == '0') &&
684          (spi_string[1] == 'X'))
685         {
686           for(i = 0; i <= cpt - 2; i++) spi_string_tmp[i] = spi_string[i+2];
687           sscanf(spi_string_tmp,"%x",&spi);
688           g_snprintf(spi_string, IPSEC_SPI_LEN_MAX, "%i", spi);
689         }
690
691       *index_end = cpt + index_start - 1;
692       *pt_spi = g_strdup(spi_string);
693
694       done_flag = TRUE;
695     }
696
697   return done_flag;
698 }
699 #endif
700
701
702 /*
703    Name : static gboolean esp_sa_parse_protocol_typ(const gchar *sa, guint index_start, gint *pt_protocol_typ, guint *index_end)
704    Description : Get the Protocol Type of a Security Association
705    Return : Return true if it can get a valid protocol type.
706    Params:
707       - char *sa : the Security Association in char *
708       - guint index_start : the index to start to find the protocol type
709       - gint *pt_protocol_typ : the protocol type found. Either IPv4 or IPv6 (IPSEC_SA_IPV4, IPSEC_SA_IPV6)
710       - guint *index_end : the last index of the protocol type
711 */
712 #ifdef HAVE_LIBGCRYPT
713 static gboolean
714 esp_sa_parse_protocol_typ(const gchar *sa, guint index_start, gint *pt_protocol_typ, guint *index_end)
715 {
716   gboolean done_flag = FALSE;
717
718   *pt_protocol_typ = IPSEC_SA_UNKNOWN;
719   if((sa == NULL) || (strlen(&sa[index_start]) <= IPSEC_TYP_LEN) ||
720       (sa[index_start + IPSEC_TYP_LEN] != IPSEC_SA_SEPARATOR))
721     return FALSE;
722
723   if(g_ascii_strncasecmp(&sa[index_start], "IPV6", IPSEC_TYP_LEN) == 0)
724     {
725       *pt_protocol_typ = IPSEC_SA_IPV6;
726       done_flag = TRUE;
727     }
728   else if (g_ascii_strncasecmp(&sa[index_start], "IPV4", IPSEC_TYP_LEN) == 0)
729     {
730       *pt_protocol_typ = IPSEC_SA_IPV4;
731       done_flag = TRUE;
732     }
733   else
734     {
735       *pt_protocol_typ = IPSEC_SA_UNKNOWN;
736       done_flag = FALSE;
737     }
738
739   *index_end = IPSEC_TYP_LEN + index_start + 1;
740
741 /* g_warning("For %s returning %d, %c, %d", sa, *pt_protocol_typ, sa[*index_end], *index_end); */
742   return done_flag;
743 }
744 #endif
745
746
747 /*
748    Name : static gboolean esp_sa_parse_addr_len(const gchar *sa, guint index_start, guint *len, guint *index_end)
749    Description : Get the Address Length of an address (IPv4/IPv6)
750    Return : Return true if it can get an Address Length. It does not mean that the length is valid
751    Params:
752       - char *sa : the Security Association in char *
753       - guint index_start : the index to start to find the length
754       - guint *len : the address length found. If none -1 is given.
755       - guint *index_end : the last index of the address length in the SA
756 */
757 #ifdef HAVE_LIBGCRYPT
758 static gboolean
759 esp_sa_parse_addr_len(const gchar *sa, guint index_start, gint *len, guint *index_end)
760 {
761   guint cpt = 0;
762   char len_string[IPSEC_ADDR_LEN_MAX + 1];
763   gboolean done_flag = FALSE;
764
765   *len = -1;
766
767   if((sa == NULL) || (strcmp(sa, "") == 0))  return FALSE;
768
769   if(sa[index_start] == IPSEC_SA_SEPARATOR)
770     {
771       *index_end = index_start + 1;
772       *len = -1;
773       done_flag = TRUE;
774     }
775
776   else if(sa[index_start] == IPSEC_SA_ADDR_LEN_SEPARATOR)
777     {
778       cpt ++;
779       while(((cpt + index_start) < strlen(sa)) && (done_flag == FALSE) && (cpt < IPSEC_ADDR_LEN_MAX))
780         {
781           if(sa[cpt + index_start] == IPSEC_SA_SEPARATOR)
782             {
783               if(cpt == 1)
784                 {
785                   *index_end = index_start + cpt + 1;
786                   *len = -1;
787                   done_flag = TRUE;
788
789                 }
790               else
791                 {
792                   *index_end = cpt + index_start + 1;
793                   len_string[cpt - 1] = '\0';
794                   *len = atoi(len_string);
795                   done_flag = TRUE;
796                 }
797             }
798
799           else
800             {
801               if((cpt == IPSEC_ADDR_LEN_MAX)
802                  && ((cpt  + index_start) < strlen(sa))
803                  && (sa[cpt + index_start + 1] != IPSEC_SA_ADDR_LEN_SEPARATOR)
804                  && (sa[cpt + index_start + 1] != IPSEC_SA_SEPARATOR))
805                 return FALSE;
806               len_string[cpt -1] = sa[cpt + index_start];
807               cpt ++;
808             }
809         }
810     }
811
812   return done_flag;
813 }
814 #endif
815
816
817 /*
818    Name : esp_sa_remove_white(const gchar *sa, gchar **sa_bis)
819    Description : Remote White Space in a SA
820                  Parse a Security Association and give the SA without space.
821                  There is no need to allocate memory before the call. All is done !
822
823    Return : Void
824    Params:
825       - char *sa : the Security Association in char *
826       - char **sa_bis : the Security Association in char * without white space
827 */
828
829 #ifdef HAVE_LIBGCRYPT
830 static void
831 esp_sa_remove_white(const gchar *sa, gchar **sa_bis)
832 {
833   guint i = 0;
834   guint cpt = 0;
835   gchar *sa_tmp;
836
837   if((sa == NULL) || (strcmp(sa, "") == 0))
838     {
839       *sa_bis = NULL;
840       return;
841     }
842
843   sa_tmp = ep_alloc(strlen(sa) + 1);
844   for(i = 0; sa[i]; i++)
845     {
846
847       if((sa[i] != ' ') && (sa[i] != '\t'))
848         {
849           sa_tmp[cpt] = sa[i];
850           cpt ++;
851         }
852     }
853   sa_tmp[cpt] = '\0';
854
855   /* XXX - Should this be se_allocated instead? */
856   *sa_bis = g_strdup(sa_tmp);
857 }
858 #endif
859
860
861
862 /*
863    Name : static goolean esp_sa_parse_filter(const gchar *sa, gint *pt_protocol_typ, gchar **pt_src, gint *pt_src_len,  gchar **pt_dst, gint *pt_dst_len,  gchar **pt_spi)
864    Description : Parse a Security Association.
865                  Parse a Security Association and give the correspondings parameter : SPI, Source, Destination, Source Length, Destination Length, Protocol Type
866                  There is no need to allocate memory before the call. All is done !
867                  If the SA is not correct FALSE is returned.
868                  This security association Must have the following format :
869
870                  "Type/Source IPv6 or IPv4/Destination IPv6 or IPv4/SPI"
871
872                  Where Type is either IPv4 either IPv6
873                  - source And destination Must have a correct IPv6/IPv4 Address Format.
874                  - SPI is an integer on 4 bytes.
875                  Any element may use the following wildcard :
876
877                  "*" : for an IPv4 Address, it allows all bytes until the next ".". For IPv6 it is the same until the next ":".
878                  For SPI it allows any SPI.
879
880                  ex:
881                  a) IPV4/131.254.200.* /131.254.*.123/ *
882                  b) IPv6/3ffe:*:1/2001::200:* / 456
883
884    Return : Return true if the parsing is correct.
885    Params:
886       - char *sa : the Security Association in char *
887       - gint *pt_protocol_typ : the protocol type
888       - gchar **pt_src : the source address
889       - gint *pt_src_len : the source address length
890       - gchar **pt_dst : the destination address
891       - gint *pt_dst_len : the destination address length
892       - gchar **pt_spi : the spi of the SA
893 */
894 #ifdef HAVE_LIBGCRYPT
895 static gboolean
896 esp_sa_parse_filter(const gchar *sa_src, gint *pt_protocol_typ, gchar **pt_src, gint *pt_src_len,  gchar **pt_dst, gint *pt_dst_len,  gchar **pt_spi)
897 {
898   gchar *src_string;
899   gchar *dst_string;
900   gchar *spi_string;
901   gint src_len = 0;
902   gint dst_len = 0;
903   gchar *src;
904   gchar *dst;
905   gchar *sa;
906
907   guint index_end1 = 0;
908   guint index_end2 = 0;
909
910   esp_sa_remove_white(sa_src,&sa);
911   if(!esp_sa_parse_protocol_typ(sa, 0, pt_protocol_typ, &index_end1)) return FALSE;
912
913   switch(*pt_protocol_typ)
914     {
915
916     case IPSEC_SA_IPV4 :
917       {
918         if(esp_sa_parse_ipv4addr(sa, index_end1, &src_string, &index_end2))
919           {
920             if(esp_sa_parse_addr_len(sa, index_end2, pt_src_len, &index_end1))
921               {
922                 if(esp_sa_parse_ipv4addr(sa, index_end1, &dst_string, &index_end2))
923                   {
924                     if(esp_sa_parse_addr_len(sa, index_end2, pt_dst_len, &index_end1))
925                       {
926                         if(!esp_sa_parse_spi(sa, index_end1, &spi_string, &index_end2))
927                           {
928                             g_free(src_string);
929                             g_free(dst_string);
930                             g_free(spi_string);
931                             g_free(sa);
932                             return FALSE;
933                           }
934                       }
935                     else
936                       {
937                         g_free(src_string);
938                         g_free(dst_string);
939                         g_free(sa);
940                         return FALSE;
941                       }
942                   }
943                 else
944                   {
945                     g_free(src_string);
946                     g_free(sa);
947                     return FALSE;
948                   }
949               }
950             else
951               {
952                 g_free(src_string);
953                 g_free(sa);
954                 return FALSE;
955               }
956           }
957         else
958           {
959             g_free(sa);
960             return FALSE;
961           }
962
963
964         /* Fill the Source Filter */
965         src = (gchar *)g_malloc((IPSEC_STRLEN_IPV4 + 1) * sizeof(gchar));
966         get_full_ipv4_addr(src, src_string);
967         g_free(src_string);
968
969         /* Fill the Destination Filter */
970         dst = (gchar *)g_malloc((IPSEC_STRLEN_IPV4 + 1) * sizeof(gchar));
971         get_full_ipv4_addr(dst, dst_string);
972         g_free(dst_string);
973
974         g_free(sa);
975         break;
976       }
977
978     case IPSEC_SA_IPV6 :
979       {
980         if(esp_sa_parse_ipv6addr(sa, index_end1, &src_string, &index_end2))
981           {
982             if(esp_sa_parse_addr_len(sa, index_end2, &src_len, &index_end1))
983               {
984                 if(esp_sa_parse_ipv6addr(sa, index_end1, &dst_string, &index_end2))
985                   {
986                     if(esp_sa_parse_addr_len(sa, index_end2, &dst_len, &index_end1))
987                       {
988                         if(!esp_sa_parse_spi(sa, index_end1, &spi_string, &index_end2))
989                           {
990                             g_free(src_string);
991                             g_free(dst_string);
992                             g_free(spi_string);
993                             g_free(sa);
994                             return FALSE;
995                           }
996                       }
997                     else
998                       {
999                         g_free(src_string);
1000                         g_free(dst_string);
1001                         g_free(sa);
1002                         return FALSE;
1003                       }
1004                   }
1005                 else
1006                   {
1007                     g_free(src_string);
1008                     g_free(sa);
1009                     return FALSE;
1010                   }
1011               }
1012             else
1013               {
1014                 g_free(src_string);
1015                 g_free(sa);
1016                 return FALSE;
1017               }
1018           }
1019         else
1020           {
1021             g_free(sa);
1022             return FALSE;
1023           }
1024
1025         /* Fill the Source Filter */
1026         src = (gchar *)g_malloc((IPSEC_STRLEN_IPV6 + 1) * sizeof(gchar));
1027         get_full_ipv6_addr(src, src_string);
1028         g_free(src_string);
1029
1030         /* Fill the Destination Filter */
1031         dst = (gchar *)g_malloc((IPSEC_STRLEN_IPV6 + 1) * sizeof(gchar));
1032         get_full_ipv6_addr(dst, dst_string);
1033         g_free(dst_string);
1034
1035         g_free(sa);
1036         break;
1037       }
1038
1039     default:
1040       {
1041         g_free(sa);
1042         return FALSE;
1043       }
1044     }
1045
1046   *pt_spi = spi_string;
1047   *pt_src = src;
1048   *pt_dst = dst;
1049
1050   return TRUE;
1051 }
1052 #endif
1053
1054
1055 /*
1056    Name : static goolean filter_address_match(gchar *addr, gchar *filter, gint len, gint typ)
1057    Description : check the matching of an address with a filter
1058    Return : Return TRUE if the filter and the address match
1059    Params:
1060       - gchar *addr : the address to check
1061       - gchar *filter : the filter
1062       - gint len : the len of the address that should match the filter
1063       - gint typ : the Address type : either IPv6 or IPv4 (IPSEC_SA_IPV6, IPSEC_SA_IPV4)
1064 */
1065 #ifdef HAVE_LIBGCRYPT
1066 static gboolean
1067 filter_address_match(gchar *addr, gchar *filter, gint len, gint typ)
1068 {
1069   gint i = 0;
1070   guint filter_tmp = 0;
1071   guint addr_tmp = 0;
1072   char filter_string_tmp[3];
1073   char addr_string_tmp[3];
1074
1075   if(strlen(addr) != strlen(filter)) return FALSE;
1076   /* No length specified */
1077   if((len < 0)
1078      || ((typ == IPSEC_SA_IPV6) && (len > IPSEC_IPV6_ADDR_LEN))
1079      || ((typ == IPSEC_SA_IPV4) && (len > IPSEC_IPV4_ADDR_LEN)))
1080     {
1081       for(i = 0; (guint)i < strlen(addr); i++)
1082         {
1083           if((filter[i] != IPSEC_SA_WILDCARDS_ANY) && (filter[i] != addr[i])) return FALSE;
1084         }
1085       return TRUE;
1086     }
1087   else
1088     {
1089       for(i = 0; i < (len/ 4); i++)
1090         {
1091           if((filter[i] != IPSEC_SA_WILDCARDS_ANY) && (filter[i] != addr[i])) return FALSE;
1092         }
1093
1094       if(filter[i] == IPSEC_SA_WILDCARDS_ANY) return TRUE;
1095       else if (len  % 4 != 0)
1096         {
1097           /* take the end of the Netmask/Prefixlen into account */
1098           filter_string_tmp[0] = filter[i];
1099           filter_string_tmp[1] = '\0';
1100           addr_string_tmp[0] = addr[i];
1101           addr_string_tmp[1] = '\0';
1102
1103           sscanf(filter_string_tmp,"%x",&filter_tmp);
1104           sscanf(addr_string_tmp,"%x",&addr_tmp);
1105           for(i = 0; i < (len % 4); i++)
1106             {
1107               if(((filter_tmp >> (4 -i -1)) & 1) != ((addr_tmp >> (4 -i -1)) & 1))
1108                 {
1109                   return FALSE;
1110                 }
1111             }
1112         }
1113     }
1114
1115   return TRUE;
1116
1117 }
1118 #endif
1119
1120
1121
1122 /*
1123    Name : static goolean filter_spi_match(gchar *spi, gchar *filter)
1124    Description : check the matching of a spi with a filter
1125    Return : Return TRUE if the filter match the spi.
1126    Params:
1127       - gchar *spi : the spi to check
1128       - gchar *filter : the filter
1129 */
1130 #ifdef HAVE_LIBGCRYPT
1131 static gboolean
1132 filter_spi_match(gchar *spi, gchar *filter)
1133 {
1134   guint i = 0;
1135
1136   if((strlen(filter) == 1) && (filter[0] == IPSEC_SA_WILDCARDS_ANY)) {
1137     return TRUE;
1138   }
1139
1140   else if(strlen(spi) != strlen(filter)) {
1141     return FALSE;
1142   }
1143
1144   for(i = 0; filter[i]; i++)
1145     {
1146       if((filter[i] != IPSEC_SA_WILDCARDS_ANY) && (filter[i] != spi[i])) return FALSE;
1147     }
1148
1149   return TRUE;
1150 }
1151 #endif
1152
1153
1154 /*
1155    Name : static gint compute_ascii_key(gchar **ascii_key, gchar *key)
1156    Description : Allocate memory for the key and transform the key if it is hexadecimal
1157    Return : Return the key length
1158    Params:
1159       - gchar **ascii_key : the resulting ascii key allocated here
1160       - gchar *key : the key to compute
1161 */
1162 #ifdef HAVE_LIBGCRYPT
1163 static gint
1164 compute_ascii_key(gchar **ascii_key, const gchar *key)
1165 {
1166   guint key_len = 0;
1167   gint hex_digit;
1168   guchar key_byte;
1169   guint i, j;
1170
1171   if(key != NULL)
1172     {
1173       if((strlen(key) > 2) && (key[0] == '0') && ((key[1] == 'x') || (key[1] == 'X')))
1174         {
1175           /*
1176            * Key begins with "0x" or "0X"; skip that and treat the rest
1177            * as a sequence of hex digits.
1178            */
1179           i = 2;        /* first character after "0[Xx]" */
1180           j = 0;
1181           if(strlen(key) %2  == 1)
1182             {
1183               /*
1184                * Key has an odd number of characters; we act as if the
1185                * first character had a 0 in front of it, making the
1186                * number of characters even.
1187                */
1188               key_len = ((guint) strlen(key) - 2) / 2 + 1;
1189               *ascii_key = (gchar *) g_malloc ((key_len + 1)* sizeof(gchar));
1190               hex_digit = g_ascii_xdigit_value(key[i]);
1191               i++;
1192               if (hex_digit == -1)
1193                 {
1194                   g_free(*ascii_key);
1195                   *ascii_key = NULL;
1196                   return -1;    /* not a valid hex digit */
1197                 }
1198               (*ascii_key)[j] = (guchar)hex_digit;
1199               j++;
1200             }
1201           else
1202             {
1203               /*
1204                * Key has an even number of characters, so we treat each
1205                * pair of hex digits as a single byte value.
1206                */
1207               key_len = ((guint) strlen(key) - 2) / 2;
1208               *ascii_key = (gchar *) g_malloc ((key_len + 1)* sizeof(gchar));
1209             }
1210
1211           while(i < (strlen(key) -1))
1212             {
1213               hex_digit = g_ascii_xdigit_value(key[i]);
1214               i++;
1215               if (hex_digit == -1)
1216                 {
1217                   g_free(*ascii_key);
1218                   *ascii_key = NULL;
1219                   return -1;    /* not a valid hex digit */
1220                 }
1221               key_byte = ((guchar)hex_digit) << 4;
1222               hex_digit = g_ascii_xdigit_value(key[i]);
1223               i++;
1224               if (hex_digit == -1)
1225                 {
1226                   g_free(*ascii_key);
1227                   *ascii_key = NULL;
1228                   return -1;    /* not a valid hex digit */
1229                 }
1230               key_byte |= (guchar)hex_digit;
1231               (*ascii_key)[j] = key_byte;
1232               j++;
1233             }
1234           (*ascii_key)[j] = '\0';
1235         }
1236
1237       else if((strlen(key) == 2) && (key[0] == '0') && ((key[1] == 'x') || (key[1] == 'X')))
1238         {
1239           return 0;
1240         }
1241
1242       else
1243         {
1244           key_len = (guint) strlen(key);
1245           *ascii_key = g_strdup(key);
1246         }
1247     }
1248
1249   return key_len;
1250 }
1251 #endif
1252
1253
1254 /*
1255    Name : static goolean get_esp_sa(g_esp_sa_database *sad, gint protocol_typ, gchar *src,  gchar *dst,  gint spi,
1256            gint *entry_index
1257            gint *encryption_algo,
1258            gint *authentication_algo,
1259            gchar **encryption_key,
1260            guint *encryption_key_len,
1261            gchar **authentication_key,
1262            guint *authentication_key_len
1263
1264    Description : Give Encryption Algo, Key and Authentification Algo for a Packet if a corresponding SA is available in a Security Association database
1265    Return: If the SA is not present, FALSE is then returned.
1266    Params:
1267       - g_esp_sa_database *sad : the Security Association Database
1268       - gint *pt_protocol_typ : the protocol type
1269       - gchar *src : the source address
1270       - gchar *dst : the destination address
1271       - gchar *spi : the spi of the SA
1272       - gint *entry_index : the index of the SA that matches
1273       - gint *encryption_algo : the Encryption Algorithm to apply the packet
1274       - gint *authentication_algo : the Authentication Algorithm to apply to the packet
1275       - gchar **encryption_key : the Encryption Key to apply to the packet
1276       - guint *encryption_key_len : the Encryption Key length to apply to the packet
1277       - gchar **authentication_key : the Authentication Key to apply to the packet
1278       - guint *authentication_key_len : the Authentication Key len to apply to the packet
1279
1280 */
1281 #ifdef HAVE_LIBGCRYPT
1282 static gboolean
1283 get_esp_sa(g_esp_sa_database *sad, gint protocol_typ, gchar *src,  gchar *dst,  gint spi, gint *entry_index,
1284            gint *encryption_algo,
1285            gint *authentication_algo,
1286            gchar **encryption_key,
1287            guint *encryption_key_len,
1288            gchar **authentication_key,
1289            guint *authentication_key_len
1290            )
1291
1292 {
1293   gboolean found = FALSE;
1294   gint i = 0;
1295   gchar spi_string[IPSEC_SPI_LEN_MAX];
1296   gint key_len;
1297
1298   *entry_index = -1;
1299
1300   g_snprintf(spi_string, IPSEC_SPI_LEN_MAX,"%i", spi);
1301
1302   while((found == FALSE) && (i < sad -> nb))
1303     {
1304       if(esp_sa_parse_filter(sad -> table[i].sa, &sad -> table[i].typ, &sad -> table[i].src, &sad -> table[i].src_len,
1305                              &sad -> table[i].dst, &sad -> table[i].dst_len, &sad -> table[i].spi))
1306         {
1307           g_esp_sad.table[i].is_valid = TRUE;
1308
1309           /* Debugging Purpose */
1310           /*
1311           fprintf(stderr,
1312                   "VALID SA => <SA : %s> <Filter Source : %s/%i> <Filter Destination : %s/%i> <SPI : %s>\n",
1313                   g_esp_sad.table[i].sa, g_esp_sad.table[i].src, g_esp_sad.table[i].src_len,
1314                   g_esp_sad.table[i].dst, g_esp_sad.table[i].dst_len, g_esp_sad.table[i].spi);
1315           */
1316
1317           if((protocol_typ == sad -> table[i].typ)
1318              && filter_address_match(src,sad -> table[i].src, sad -> table[i].src_len, protocol_typ)
1319              && filter_address_match(dst,sad -> table[i].dst, sad -> table[i].dst_len, protocol_typ)
1320              && filter_spi_match(spi_string, sad -> table[i].spi))
1321             {
1322               found = TRUE;
1323
1324               *entry_index = i;
1325               *encryption_algo = sad -> table[i].encryption_algo;
1326               *authentication_algo = sad -> table[i].authentication_algo;
1327               key_len = compute_ascii_key(authentication_key, (gchar *)sad -> table[i].authentication_key);
1328               if (key_len == -1)
1329                 {
1330                   /* Bad key; XXX - report this */
1331                   *authentication_key_len = 0;
1332                   found = FALSE;
1333                 }
1334               else
1335                 *authentication_key_len = (guint)key_len;
1336               key_len = compute_ascii_key(encryption_key, sad -> table[i].encryption_key);
1337               if (key_len == -1)
1338                 {
1339                   /* Bad key; XXX - report this */
1340                   *encryption_key_len = 0;
1341                   found = FALSE;
1342                 }
1343               else
1344                 *encryption_key_len = key_len;
1345
1346               /* Debugging Purpose */
1347               /*
1348               fprintf(stderr,"MATCHING SA => <IP Source : %s> <IP Destination : %s> <SPI : %s>\n\
1349             => <FILTER Source : %s/%i> <FILTER Destination : %s/%i> <FILTER SPI : %s>\n\
1350             => <Encryption Algo : %i> <Encryption Key: %s> <Authentication Algo : %i>\n",
1351                       src,dst,spi_string,
1352                       sad -> table[i].src, sad -> table[i].src_len,
1353                       sad -> table[i].dst, sad -> table[i].dst_len,
1354                       sad -> table[i].spi,
1355                       *encryption_algo, *encryption_key, *authentication_algo);
1356                       */
1357             }
1358
1359           /* We free the Src, Dst and Spi in the SA, but perhaps to allocate it again with the same value !!! */
1360           g_free(g_esp_sad.table[i].src);
1361           g_free(g_esp_sad.table[i].dst);
1362           g_free(g_esp_sad.table[i].spi);
1363           g_esp_sad.table[i].is_valid = FALSE;
1364
1365         }
1366
1367       else
1368         {
1369           /* Debugging Purpose */
1370           /* fprintf(stderr, "INVALID SA => %s \n", g_esp_sad.table[i].sa); */
1371         }
1372
1373       i++;
1374     }
1375   return found;
1376 }
1377 #endif
1378
1379 static void
1380 dissect_ah(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1381 {
1382   proto_tree *next_tree;
1383   guint8 nxt;
1384   tvbuff_t *next_tvb;
1385   int advance;
1386
1387   advance = dissect_ah_header(tvb, pinfo, tree, &nxt, &next_tree);
1388   next_tvb = tvb_new_subset_remaining(tvb, advance);
1389
1390   if (g_ah_payload_in_subtree) {
1391     col_set_writable(pinfo->cinfo, FALSE);
1392   }
1393
1394   /* do lookup with the subdissector table */
1395   if (!dissector_try_port(ip_dissector_table, nxt, next_tvb, pinfo, tree)) {
1396     call_dissector(data_handle,next_tvb, pinfo, next_tree);
1397   }
1398 }
1399
1400 int
1401 dissect_ah_header(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
1402                   guint8 *nxt_p, proto_tree **next_tree_p)
1403 {
1404   proto_tree *ah_tree;
1405   proto_item *ti;
1406   struct newah ah;
1407   int advance;
1408
1409   col_set_str(pinfo->cinfo, COL_PROTOCOL, "AH");
1410   col_clear(pinfo->cinfo, COL_INFO);
1411
1412   tvb_memcpy(tvb, (guint8 *)&ah, 0, sizeof(ah));
1413   advance = sizeof(ah) + ((ah.ah_len - 1) << 2);
1414
1415   if (check_col(pinfo->cinfo, COL_INFO)) {
1416     col_add_fstr(pinfo->cinfo, COL_INFO, "AH (SPI=0x%08x)",
1417                  (guint32)g_ntohl(ah.ah_spi));
1418   }
1419
1420   if (tree) {
1421     /* !!! specify length */
1422     ti = proto_tree_add_item(tree, proto_ah, tvb, 0, advance, FALSE);
1423     ah_tree = proto_item_add_subtree(ti, ett_ah);
1424
1425     proto_tree_add_text(ah_tree, tvb,
1426                         offsetof(struct newah, ah_nxt), 1,
1427                         "Next Header: %s (0x%02x)",
1428                         ipprotostr(ah.ah_nxt), ah.ah_nxt);
1429     proto_tree_add_text(ah_tree, tvb,
1430                         offsetof(struct newah, ah_len), 1,
1431                         "Length: %u", (ah.ah_len + 2) << 2);
1432     proto_tree_add_uint(ah_tree, hf_ah_spi, tvb,
1433                         offsetof(struct newah, ah_spi), 4,
1434                         (guint32)g_ntohl(ah.ah_spi));
1435     proto_tree_add_uint(ah_tree, hf_ah_sequence, tvb,
1436                         offsetof(struct newah, ah_seq), 4,
1437                         (guint32)g_ntohl(ah.ah_seq));
1438     proto_tree_add_item(ah_tree, hf_ah_iv, tvb,
1439                         sizeof(ah), (ah.ah_len) ? (ah.ah_len - 1) << 2 : 0,
1440                         FALSE);
1441
1442     if (next_tree_p != NULL) {
1443       /* Decide where to place next protocol decode */
1444       if (g_ah_payload_in_subtree) {
1445         *next_tree_p = ah_tree;
1446       }
1447       else {
1448         *next_tree_p = tree;
1449       }
1450     }
1451   } else {
1452     if (next_tree_p != NULL)
1453       *next_tree_p = NULL;
1454   }
1455
1456   if (nxt_p != NULL)
1457     *nxt_p = ah.ah_nxt;
1458
1459   /* start of the new header (could be a extension header) */
1460   return advance;
1461 }
1462
1463
1464 /*
1465    Name : dissect_esp_authentication(proto_tree *tree, tvbuff_t *tvb, gint len, gint esp_auth_len, guint8 *authenticator_data_computed,
1466           gboolean authentication_ok, gboolean authentication_checking_ok)
1467    Description : used to print Authenticator field when linked with libgcrypt. Print the expected authenticator value
1468                  if requested and if it is wrong.
1469    Return : void
1470    Params:
1471       - proto_tree *tree : the current tree
1472       - tvbuff_t *tvb : the tvbuffer
1473       - gint len : length of the data availabale in tvbuff
1474       - gint esp_auth_len : size of authenticator field
1475       - guint8 *authenticator_data_computed : give the authenticator computed (only needed when authentication_ok and !authentication_checking_ok
1476       - gboolean authentication_ok : set to true if the authentication checking has been run successfully
1477       - gboolean authentication_checking_ok : set to true if the authentication was the one expected
1478 */
1479 #ifdef HAVE_LIBGCRYPT
1480 static void
1481 dissect_esp_authentication(proto_tree *tree, tvbuff_t *tvb, gint len, gint esp_auth_len, guint8 *authenticator_data_computed,
1482                           gboolean authentication_ok, gboolean authentication_checking_ok)
1483 {
1484   if(esp_auth_len == 0)
1485     {
1486       proto_tree_add_text(tree, tvb, len, 0,
1487                           "NULL Authentication");
1488     }
1489
1490   /* Make sure we have the auth trailer data */
1491   else if(tvb_bytes_exist(tvb, len - esp_auth_len, esp_auth_len))
1492     {
1493       if((authentication_ok) && (authentication_checking_ok))
1494         {
1495           proto_tree_add_text(tree, tvb, len - esp_auth_len, esp_auth_len,
1496                               "Authentication Data [correct]");
1497         }
1498
1499       else if((authentication_ok) && (!authentication_checking_ok))
1500         {
1501           proto_tree_add_text(tree, tvb, len - esp_auth_len, esp_auth_len,
1502                               "Authentication Data [incorrect, should be 0x%s]", authenticator_data_computed);
1503
1504           g_free(authenticator_data_computed);
1505         }
1506
1507       else proto_tree_add_text(tree, tvb, len - esp_auth_len, esp_auth_len,
1508                                "Authentication Data");
1509     }
1510   else
1511     {
1512       /* Truncated so just display what we have */
1513       proto_tree_add_text(tree, tvb, len - esp_auth_len, esp_auth_len - (len - tvb_length(tvb)),
1514                           "Authentication Data (truncated)");
1515     }
1516 }
1517 #endif
1518
1519 static void
1520 dissect_esp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
1521 {
1522   proto_tree *esp_tree = NULL;
1523   proto_item *ti;
1524   struct newesp esp;
1525
1526   gint len = 0;
1527   gint i = 0;
1528
1529 #ifdef HAVE_LIBGCRYPT
1530   char res[3];
1531
1532   /* Packet Variables related */
1533   gchar *ip_src = NULL;
1534   gchar *ip_dst = NULL;
1535   guint32 spi = 0;
1536 #endif
1537
1538   guint encapsulated_protocol = 0;
1539   gboolean decrypt_dissect_ok = FALSE;
1540
1541 #ifdef HAVE_LIBGCRYPT
1542   gboolean get_address_ok = FALSE;
1543   gboolean null_encryption_decode_heuristic = FALSE;
1544   guint8 *decrypted_data = NULL;
1545   guint8 *encrypted_data = NULL;
1546   guint8 *authenticator_data = NULL;
1547   guint8 *esp_data = NULL;
1548   tvbuff_t *tvb_decrypted;
1549   gint entry_index;
1550
1551   /* IPSEC encryption Variables related */
1552   gint protocol_typ = IPSEC_SA_UNKNOWN;
1553   gint esp_crypt_algo = IPSEC_ENCRYPT_NULL;
1554   gint esp_auth_algo = IPSEC_AUTH_NULL;
1555   gchar *esp_crypt_key = NULL;
1556   gchar *esp_auth_key = NULL;
1557   guint esp_crypt_key_len = 0;
1558   guint esp_auth_key_len = 0;
1559   gint esp_iv_len = 0;
1560   gint esp_auth_len = 0;
1561   gint decrypted_len = 0;
1562   gboolean decrypt_ok = FALSE;
1563   gboolean decrypt_using_libgcrypt = FALSE;
1564   gboolean authentication_check_using_hmac_libgcrypt = FALSE;
1565   gboolean authentication_ok = FALSE;
1566   gboolean authentication_checking_ok = FALSE;
1567   gboolean sad_is_present = FALSE;
1568 #endif
1569   gint esp_pad_len = 0;
1570
1571 #ifdef HAVE_LIBGCRYPT
1572
1573   /* Variables for decryption and authentication checking used for libgrypt */
1574   int decrypted_len_alloc = 0;
1575   gcry_cipher_hd_t cypher_hd;
1576   gcry_md_hd_t md_hd;
1577   int md_len = 0;
1578   gcry_error_t err = 0;
1579   int crypt_algo_libgcrypt = 0;
1580   int crypt_mode_libgcrypt = 0;
1581   int auth_algo_libgcrypt = 0;
1582   unsigned char *authenticator_data_computed = NULL;
1583   unsigned char *authenticator_data_computed_md;
1584
1585
1586   /*
1587    * load the top pane info. This should be overwritten by
1588    * the next protocol in the stack
1589    */
1590
1591 #endif
1592
1593   col_set_str(pinfo->cinfo, COL_PROTOCOL, "ESP");
1594   col_clear(pinfo->cinfo, COL_INFO);
1595
1596   tvb_memcpy(tvb, (guint8 *)&esp, 0, sizeof(esp));
1597
1598   if (check_col(pinfo->cinfo, COL_INFO)) {
1599     col_add_fstr(pinfo->cinfo, COL_INFO, "ESP (SPI=0x%08x)",
1600                  (guint32)g_ntohl(esp.esp_spi));
1601   }
1602
1603
1604   /*
1605    * populate a tree in the second pane with the status of the link layer
1606    * (ie none)
1607    */
1608
1609   if(tree) {
1610     len = 0, encapsulated_protocol = 0;
1611     decrypt_dissect_ok = FALSE;
1612     i = 0;
1613
1614     ti = proto_tree_add_item(tree, proto_esp, tvb, 0, -1, FALSE);
1615     esp_tree = proto_item_add_subtree(ti, ett_esp);
1616     proto_tree_add_uint(esp_tree, hf_esp_spi, tvb,
1617                         offsetof(struct newesp, esp_spi), 4,
1618                         (guint32)g_ntohl(esp.esp_spi));
1619     proto_tree_add_uint(esp_tree, hf_esp_sequence, tvb,
1620                         offsetof(struct newesp, esp_seq), 4,
1621                         (guint32)g_ntohl(esp.esp_seq));
1622   }
1623
1624
1625 #ifdef HAVE_LIBGCRYPT
1626   /* The SAD is not activated */
1627   if(g_esp_enable_null_encryption_decode_heuristic &&
1628     !g_esp_enable_encryption_decode)
1629     null_encryption_decode_heuristic = TRUE;
1630
1631   if(g_esp_enable_encryption_decode || g_esp_enable_authentication_check)
1632     {
1633       /* Get Source & Destination Addresses in gchar * with all the bytes available.  */
1634       switch (pinfo -> src.type)
1635         {
1636
1637         case AT_IPv4 :
1638           {
1639             const guint8 *srcaddr = pinfo -> src.data;
1640             const guint8 *dstaddr = pinfo -> dst.data;
1641
1642             ip_src = (gchar *) g_malloc((IPSEC_STRLEN_IPV4 + 1) * sizeof(gchar));
1643             ip_dst = (gchar *) g_malloc((IPSEC_STRLEN_IPV4 + 1) * sizeof(gchar));
1644             protocol_typ = IPSEC_SA_IPV4;
1645
1646             for(i = 0 ; i < pinfo -> src.len; i++)
1647               {
1648                 if(srcaddr[i] < 16)
1649                   {
1650                     g_snprintf(res,3,"0%X ", srcaddr[i]);
1651                   }
1652                 else
1653                   {
1654                     g_snprintf(res,3,"%X ", srcaddr[i]);
1655                   }
1656                 memcpy(ip_src + i*2, res, 2);
1657               }
1658             ip_src[IPSEC_STRLEN_IPV4] = '\0';
1659
1660             for(i = 0 ; i < pinfo -> dst.len; i++)
1661               {
1662                 if(dstaddr[i] < 16)
1663                   {
1664                     g_snprintf(res,3,"0%X ", dstaddr[i]);
1665                   }
1666                 else
1667                   {
1668                     g_snprintf(res,3,"%X ", dstaddr[i]);
1669                   }
1670                 memcpy(ip_dst + i*2, res, 2);
1671               }
1672             ip_dst[IPSEC_STRLEN_IPV4] = '\0';
1673
1674             get_address_ok = TRUE;
1675           break;
1676           }
1677
1678         case AT_IPv6 :
1679           {
1680             const guint8 *srcaddr = pinfo -> src.data;
1681             const guint8 *dstaddr = pinfo -> dst.data;
1682
1683             ip_src = (gchar *) g_malloc((IPSEC_STRLEN_IPV6 + 1) * sizeof(gchar));
1684             ip_dst = (gchar *) g_malloc((IPSEC_STRLEN_IPV6 + 1) * sizeof(gchar));
1685             protocol_typ = IPSEC_SA_IPV6;
1686
1687             for(i = 0 ; i < pinfo -> src.len; i++)
1688               {
1689                 if(srcaddr[i] < 16)
1690                   {
1691                     g_snprintf(res,3,"0%X ", srcaddr[i]);
1692                   }
1693                 else
1694                   {
1695                     g_snprintf(res,3,"%X ", srcaddr[i]);
1696                   }
1697                 memcpy(ip_src + i*2, res, 2);
1698               }
1699             ip_src[IPSEC_STRLEN_IPV6] = '\0';
1700
1701             for(i = 0 ; i < pinfo -> dst.len; i++)
1702               {
1703                 if(dstaddr[i] < 16)
1704                   {
1705                     g_snprintf(res,3,"0%X ", dstaddr[i]);
1706                   }
1707                 else
1708                   {
1709                     g_snprintf(res,3,"%X ", dstaddr[i]);
1710                   }
1711                 memcpy(ip_dst + i*2, res, 2);
1712               }
1713             ip_dst[IPSEC_STRLEN_IPV6] = '\0';
1714
1715             get_address_ok = TRUE;
1716             break;
1717           }
1718
1719         default :
1720           {
1721             get_address_ok = FALSE;
1722             break;
1723           }
1724         }
1725
1726       /* The packet cannot be decoded using the SAD */
1727       if(g_esp_enable_null_encryption_decode_heuristic && !get_address_ok)
1728         null_encryption_decode_heuristic = TRUE;
1729
1730       if(get_address_ok)
1731         {
1732           /* Get the SPI */
1733           if (tvb_length(tvb) >= 4)
1734             {
1735               spi = tvb_get_ntohl(tvb, 0);
1736             }
1737
1738
1739           /*
1740             PARSE the SAD and fill it. It may take some time since it will
1741             be called every times an ESP Payload is found.
1742           */
1743
1744           if((sad_is_present = get_esp_sa(&g_esp_sad, protocol_typ, ip_src, ip_dst, spi, &entry_index,
1745                                           &esp_crypt_algo, &esp_auth_algo,
1746                                           &esp_crypt_key, &esp_crypt_key_len, &esp_auth_key, &esp_auth_key_len)))
1747             {
1748
1749               /* Get length of whole ESP packet. */
1750               len = tvb_reported_length(tvb);
1751
1752               switch(esp_auth_algo)
1753                 {
1754
1755                 case IPSEC_AUTH_HMAC_SHA1_96:
1756                   {
1757                     esp_auth_len = 12;
1758                     break;
1759                   }
1760
1761                 case IPSEC_AUTH_HMAC_SHA256_96:
1762                   {
1763                     esp_auth_len = 12;
1764                     break;
1765                   }
1766
1767                 case IPSEC_AUTH_HMAC_SHA256_128:
1768                   {
1769                     esp_auth_len = 16;
1770                     break;
1771                   }
1772
1773                 case IPSEC_AUTH_NULL:
1774                   {
1775                     esp_auth_len = 0;
1776                     break;
1777                   }
1778
1779                   /*
1780                     case IPSEC_AUTH_AES_XCBC_MAC_96:
1781                     {
1782                     esp_auth_len = 12;
1783                     break;
1784                     }
1785                   */
1786
1787                 case IPSEC_AUTH_HMAC_MD5_96:
1788                   {
1789                     esp_auth_len = 12;
1790                     break;
1791                   }
1792
1793                 case IPSEC_AUTH_HMAC_RIPEMD160_96:
1794                   {
1795                     esp_auth_len = 12;
1796                     break;
1797                   }
1798
1799                 case IPSEC_AUTH_ANY_256BIT:
1800                   {
1801                     esp_auth_len = 32;
1802                     break;
1803                   }
1804
1805                 case IPSEC_AUTH_ANY_192BIT:
1806                   {
1807                     esp_auth_len = 24;
1808                     break;
1809                   }
1810
1811                 case IPSEC_AUTH_ANY_128BIT:
1812                   {
1813                     esp_auth_len = 16;
1814                     break;
1815                   }
1816
1817                 case IPSEC_AUTH_ANY_96BIT:
1818                 default:
1819                   {
1820                     esp_auth_len = 12;
1821                     break;
1822                   }
1823
1824                 }
1825
1826               if(g_esp_enable_authentication_check)
1827                 {
1828                   switch(esp_auth_algo)
1829                     {
1830
1831                     case IPSEC_AUTH_HMAC_SHA1_96:
1832                       /*
1833                         RFC 2404 : HMAC-SHA-1-96 is a secret key algorithm.
1834                         While no fixed key length is specified in [RFC-2104],
1835                         for use with either ESP or AH a fixed key length of
1836                         160-bits MUST be supported.  Key lengths other than
1837                         160-bits MUST NOT be supported (i.e. only 160-bit keys
1838                         are to be used by HMAC-SHA-1-96).  A key length of
1839                         160-bits was chosen based on the recommendations in
1840                         [RFC-2104] (i.e. key lengths less than the
1841                         authenticator length decrease security strength and
1842                         keys longer than the authenticator length do not
1843                         significantly increase security strength).
1844                       */
1845                       {
1846                         auth_algo_libgcrypt = GCRY_MD_SHA1;
1847                         authentication_check_using_hmac_libgcrypt = TRUE;
1848                         break;
1849                       }
1850
1851                     case IPSEC_AUTH_NULL:
1852                       {
1853                         authentication_check_using_hmac_libgcrypt = FALSE;
1854                         authentication_checking_ok = TRUE;
1855                         authentication_ok = TRUE;
1856                         break;
1857                       }
1858
1859                       /*
1860                         case IPSEC_AUTH_AES_XCBC_MAC_96:
1861                         {
1862                         auth_algo_libgcrypt =
1863                         authentication_check_using_libgcrypt = TRUE;
1864                         break;
1865                         }
1866                       */
1867
1868                     case IPSEC_AUTH_HMAC_SHA256_96:
1869                     case IPSEC_AUTH_HMAC_SHA256_128:
1870                       {
1871                         auth_algo_libgcrypt = GCRY_MD_SHA256;
1872                         authentication_check_using_hmac_libgcrypt = TRUE;
1873                         break;
1874                       }
1875
1876                     case IPSEC_AUTH_HMAC_MD5_96:
1877                       /*
1878                         RFC 2403 : HMAC-MD5-96 is a secret key algorithm.
1879                         While no fixed key length is specified in [RFC-2104],
1880                         for use with either ESP or AH a fixed key length of
1881                         128-bits MUST be supported.  Key lengths other than
1882                         128-bits MUST NOT be supported (i.e. only 128-bit keys
1883                         are to be used by HMAC-MD5-96).  A key length of
1884                         128-bits was chosen based on the recommendations in
1885                         [RFC-2104] (i.e. key lengths less than the
1886                         authenticator length decrease security strength and
1887                         keys longer than the authenticator length do not
1888                         significantly increase security strength).
1889                       */
1890                       {
1891                         auth_algo_libgcrypt = GCRY_MD_MD5;
1892                         authentication_check_using_hmac_libgcrypt = TRUE;
1893                         break;
1894                       }
1895
1896                     case IPSEC_AUTH_HMAC_RIPEMD160_96:
1897                       /*
1898                         RFC 2857 : HMAC-RIPEMD-160-96 produces a 160-bit
1899                         authenticator value.  This 160-bit value can be
1900                         truncated as described in RFC2104.  For use with
1901                         either ESP or AH, a truncated value using the first
1902                         96 bits MUST be supported.
1903                       */
1904                       {
1905                         auth_algo_libgcrypt = GCRY_MD_RMD160;
1906                         authentication_check_using_hmac_libgcrypt = TRUE;
1907                         break;
1908                       }
1909
1910                     case IPSEC_AUTH_ANY_96BIT:
1911                     case IPSEC_AUTH_ANY_128BIT:
1912                     case IPSEC_AUTH_ANY_192BIT:
1913                     case IPSEC_AUTH_ANY_256BIT:
1914                     default:
1915                       {
1916                         authentication_ok = FALSE;
1917                         authentication_check_using_hmac_libgcrypt = FALSE;
1918                         break;
1919                       }
1920
1921                       }
1922
1923                   if((authentication_check_using_hmac_libgcrypt) && (!authentication_ok))
1924                     {
1925                       gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
1926                       gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
1927
1928                       /* Allocate Buffers for Authenticator Field  */
1929                       authenticator_data = (guint8 *) g_malloc0 (( esp_auth_len + 1) * sizeof(guint8));
1930                       tvb_memcpy(tvb, authenticator_data, len - esp_auth_len, esp_auth_len);
1931
1932                       esp_data = (guint8 *) g_malloc0 (( len - esp_auth_len + 1) * sizeof(guint8));
1933                       tvb_memcpy(tvb, esp_data, 0, len - esp_auth_len);
1934
1935                       err = gcry_md_open (&md_hd, auth_algo_libgcrypt, GCRY_MD_FLAG_HMAC);
1936                       if (err)
1937                         {
1938                           fprintf (stderr,
1939                                    "<IPsec/ESP Dissector> Error in Algorithm %s, gcry_md_open failed: %s\n",
1940                                    gcry_md_algo_name(auth_algo_libgcrypt), gpg_strerror (err));
1941                           authentication_ok = FALSE;
1942                           g_free(authenticator_data);
1943                           g_free(esp_data);
1944                         }
1945
1946                       else
1947                         {
1948                           md_len = gcry_md_get_algo_dlen (auth_algo_libgcrypt);
1949                           if (md_len < 1 || md_len < esp_auth_len)
1950                             {
1951                               fprintf (stderr,
1952                                        "<IPsec/ESP Dissector> Error in Algorithm %s, grcy_md_get_algo_dlen failed: %d\n",
1953                                        gcry_md_algo_name(auth_algo_libgcrypt), md_len);
1954                               authentication_ok = FALSE;
1955                             }
1956
1957                           else
1958                             {
1959                               gcry_md_setkey( md_hd, esp_auth_key, esp_auth_key_len );
1960
1961                               gcry_md_write (md_hd, esp_data, len - esp_auth_len);
1962
1963                               authenticator_data_computed_md = gcry_md_read (md_hd, auth_algo_libgcrypt);
1964                               if (authenticator_data_computed_md == 0)
1965                                 {
1966                                   fprintf (stderr,
1967                                            "<IPsec/ESP Dissector> Error in Algorithm %s, gcry_md_read failed\n",
1968                                            gcry_md_algo_name(auth_algo_libgcrypt));
1969                                   authentication_ok = FALSE;
1970                                 }
1971                               else
1972                                 {
1973                                   if(memcmp (authenticator_data_computed_md, authenticator_data, esp_auth_len))
1974                                     {
1975                                       unsigned char authenticator_data_computed_car[3];
1976                                       authenticator_data_computed = (guint8 *) g_malloc (( esp_auth_len * 2 + 1) * sizeof(guint8));
1977                                       for (i = 0; i < esp_auth_len; i++)
1978                                         {
1979                                           g_snprintf((char *)authenticator_data_computed_car, 3,
1980                                                      "%02X", authenticator_data_computed_md[i] & 0xFF);
1981                                           authenticator_data_computed[i*2] = authenticator_data_computed_car[0];
1982                                           authenticator_data_computed[i*2 + 1] = authenticator_data_computed_car[1];
1983                                         }
1984
1985                                       authenticator_data_computed[esp_auth_len * 2] ='\0';
1986
1987                                       authentication_ok = TRUE;
1988                                       authentication_checking_ok = FALSE;
1989                                     }
1990                                   else
1991                                     {
1992
1993                                       authentication_ok = TRUE;
1994                                       authentication_checking_ok = TRUE;
1995                                     }
1996                                 }
1997                             }
1998
1999                             gcry_md_close (md_hd);
2000                             g_free(authenticator_data);
2001                             g_free(esp_data);
2002                           }
2003                       }
2004                   }
2005
2006               if(g_esp_enable_encryption_decode)
2007                 {
2008                   /* Deactivation of the Heuristic to decrypt using the NULL encryption algorithm since the packet is matching a SA */
2009                   null_encryption_decode_heuristic = FALSE;
2010
2011                   switch(esp_crypt_algo)
2012                     {
2013
2014                     case IPSEC_ENCRYPT_3DES_CBC :
2015                       {
2016                         /* RFC 2451 says :
2017                            3DES CBC uses a key of 192 bits.
2018                            The first 3DES key is taken from the first 64 bits,
2019                            the second from the next 64 bits, and the third
2020                            from the last 64 bits.
2021                            Implementations MUST take into consideration the
2022                            parity bits when initially accepting a new set of
2023                            keys.  Each of the three keys is really 56 bits in
2024                            length with the extra 8 bits used for parity. */
2025
2026                         /* Fix parameters for 3DES-CBC */
2027                         esp_iv_len = 8;
2028                         crypt_algo_libgcrypt = GCRY_CIPHER_3DES;
2029                         crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2030
2031                         decrypted_len = len - sizeof(struct newesp);
2032
2033                         if (decrypted_len <= 0)
2034                           decrypt_ok = FALSE;
2035                         else
2036                           {
2037                             if(decrypted_len % esp_iv_len  == 0)
2038                               decrypted_len_alloc = decrypted_len;
2039                             else
2040                               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
2041
2042                             if (esp_crypt_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
2043                               {
2044                                 fprintf (stderr,
2045                                          "<ESP Preferences> Error in Encryption Algorithm 3DES-CBC : Bad Keylen (got %i Bits, need %lu)\n",
2046                                          esp_crypt_key_len * 8,
2047                                          (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
2048                                 decrypt_ok = FALSE;
2049                               }
2050                             else
2051                               decrypt_using_libgcrypt = TRUE;
2052                           }
2053
2054                         break;
2055                       }
2056
2057                     case IPSEC_ENCRYPT_AES_CBC :
2058                       {
2059                         /* RFC 3602 says :
2060                            AES supports three key sizes: 128 bits, 192 bits,
2061                            and 256 bits.  The default key size is 128 bits,
2062                            and all implementations MUST support this key size.
2063                            Implementations MAY also support key sizes of 192
2064                            bits and 256 bits. */
2065
2066                         /* Fix parameters for AES-CBC */
2067                         esp_iv_len = 16;
2068                         crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2069
2070                         decrypted_len = len - sizeof(struct newesp);
2071
2072                         if (decrypted_len <= 0)
2073                           decrypt_ok = FALSE;
2074                         else
2075                           {
2076                             if(decrypted_len % esp_iv_len  == 0)
2077                               decrypted_len_alloc = decrypted_len;
2078                             else
2079                               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
2080
2081                             switch(esp_crypt_key_len * 8)
2082                               {
2083                               case 128:
2084                                 {
2085                                   crypt_algo_libgcrypt = GCRY_CIPHER_AES128;
2086                                   decrypt_using_libgcrypt = TRUE;
2087                                   break;
2088                                 }
2089                               case 192:
2090                                 {
2091                                   crypt_algo_libgcrypt = GCRY_CIPHER_AES192;
2092                                   decrypt_using_libgcrypt = TRUE;
2093                                   break;
2094                                 }
2095                               case 256:
2096                                 {
2097                                   crypt_algo_libgcrypt = GCRY_CIPHER_AES256;
2098                                   decrypt_using_libgcrypt = TRUE;
2099                                   break;
2100                                 }
2101                               default:
2102                                 {
2103                                   fprintf (stderr,
2104                                            "<ESP Preferences> Error in Encryption Algorithm AES-CBC : Bad Keylen (%i Bits)\n",
2105                                            esp_crypt_key_len * 8);
2106                                   decrypt_ok = FALSE;
2107                                 }
2108                               }
2109                           }
2110                         break;
2111                       }
2112
2113
2114                     case IPSEC_ENCRYPT_CAST5_CBC :
2115                       {
2116                         /* RFC 2144 says :
2117                            The CAST-128 encryption algorithm has been designed to allow a key
2118                            size that can vary from 40 bits to 128 bits, in 8-bit increments
2119                            (that is, the allowable key sizes are 40, 48, 56, 64, ..., 112, 120,
2120                            and 128 bits.
2121                            We support only 128 bits. */
2122
2123                         /* Fix parameters for CAST5-CBC */
2124                         esp_iv_len = 8;
2125                         crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2126
2127                         decrypted_len = len - sizeof(struct newesp);
2128
2129                         if (decrypted_len <= 0)
2130                           decrypt_ok = FALSE;
2131                         else
2132                           {
2133                             if(decrypted_len % esp_iv_len  == 0)
2134                               decrypted_len_alloc = decrypted_len;
2135                             else
2136                               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
2137
2138                             switch(esp_crypt_key_len * 8)
2139                               {
2140                               case 128:
2141                                 {
2142                                   crypt_algo_libgcrypt = GCRY_CIPHER_CAST5;
2143                                   decrypt_using_libgcrypt = TRUE;
2144                                   break;
2145                                 }
2146                               default:
2147                                 {
2148                                   fprintf (stderr,
2149                                            "<ESP Preferences> Error in Encryption Algorithm CAST5-CBC : Bad Keylen (%i Bits)\n",
2150                                            esp_crypt_key_len * 8);
2151                                   decrypt_ok = FALSE;
2152                                 }
2153                               }
2154                           }
2155                         break;
2156                       }
2157
2158
2159                     case IPSEC_ENCRYPT_DES_CBC :
2160                       {
2161                         /* RFC 2405 says :
2162                            DES-CBC is a symmetric secret key algorithm.
2163                            The key size is 64-bits.
2164                            [It is commonly known as a 56-bit key as the key
2165                            has 56 significant bits; the least significant
2166                            bit in every byte is the parity bit.] */
2167
2168                         /* Fix parameters for DES-CBC */
2169                         esp_iv_len = 8;
2170                         crypt_algo_libgcrypt = GCRY_CIPHER_DES;
2171                         crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2172                         decrypted_len = len - sizeof(struct newesp);
2173
2174                         if (decrypted_len <= 0)
2175                           decrypt_ok = FALSE;
2176                         else
2177                           {
2178                             if(decrypted_len % esp_iv_len == 0)
2179                               decrypted_len_alloc = decrypted_len;
2180                             else
2181                               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
2182
2183                             if (esp_crypt_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
2184                               {
2185                                 fprintf (stderr,
2186                                          "<ESP Preferences> Error in Encryption Algorithm DES-CBC : Bad Keylen (%i Bits, need %lu)\n",
2187                                          esp_crypt_key_len * 8,
2188                                          (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
2189                                 decrypt_ok = FALSE;
2190                               }
2191                             else
2192                               decrypt_using_libgcrypt = TRUE;
2193                           }
2194
2195                         break;
2196                       }
2197
2198
2199                     case IPSEC_ENCRYPT_AES_CTR :
2200                       {
2201                         /* RFC 3686 says :
2202                            AES supports three key sizes: 128 bits, 192 bits,
2203                            and 256 bits.  The default key size is 128 bits,
2204                            and all implementations MUST support this key
2205                            size.  Implementations MAY also support key sizes
2206                            of 192 bits and 256 bits. The remaining 32 bits
2207                            will be used as nonce. */
2208
2209                         /* Fix parameters for AES-CTR */
2210                         esp_iv_len = 8;
2211                         crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CTR;
2212
2213                         decrypted_len = len - sizeof(struct newesp);
2214
2215                         if (decrypted_len <= 0)
2216                           decrypt_ok = FALSE;
2217                         else
2218                           {
2219                             if(decrypted_len % esp_iv_len  == 0)
2220                               decrypted_len_alloc = decrypted_len;
2221                             else
2222                               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
2223
2224                             switch(esp_crypt_key_len * 8)
2225                               {
2226                               case 160:
2227                                 {
2228                                   crypt_algo_libgcrypt = GCRY_CIPHER_AES128;
2229                                   decrypt_using_libgcrypt = TRUE;
2230                                   break;
2231                                 }
2232                               case 224:
2233                                 {
2234                                   crypt_algo_libgcrypt = GCRY_CIPHER_AES192;
2235                                   decrypt_using_libgcrypt = TRUE;
2236                                   break;
2237                                 }
2238                               case 288:
2239                                 {
2240                                   crypt_algo_libgcrypt = GCRY_CIPHER_AES256;
2241                                   decrypt_using_libgcrypt = TRUE;
2242                                   break;
2243                                 }
2244                               default:
2245                                 {
2246                                   fprintf (stderr,
2247                                            "<ESP Preferences> Error in Encryption Algorithm AES-CTR : Bad Keylen (%i Bits)\n",
2248                                            esp_crypt_key_len * 8);
2249                                   decrypt_ok = FALSE;
2250                                 }
2251                               }
2252                           }
2253
2254                         break;
2255                       }
2256
2257                     case IPSEC_ENCRYPT_TWOFISH_CBC :
2258                       {
2259                         /*  Twofish is a 128-bit block cipher developed by
2260                             Counterpane Labs that accepts a variable-length
2261                             key up to 256 bits.
2262                             We will only accept key sizes of 128 and 256 bits.
2263                         */
2264
2265                         /* Fix parameters for TWOFISH-CBC */
2266                         esp_iv_len = 16;
2267                         crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2268
2269                         decrypted_len = len - sizeof(struct newesp);
2270
2271                         if (decrypted_len <= 0)
2272                           decrypt_ok = FALSE;
2273                         else
2274                           {
2275                             if(decrypted_len % esp_iv_len  == 0)
2276                               decrypted_len_alloc = decrypted_len;
2277                             else
2278                               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
2279
2280                             switch(esp_crypt_key_len * 8)
2281                               {
2282                               case 128:
2283                                 {
2284                                   crypt_algo_libgcrypt = GCRY_CIPHER_TWOFISH128;
2285                                   decrypt_using_libgcrypt = TRUE;
2286                                   break;
2287                                 }
2288                               case 256:
2289                                 {
2290                                   crypt_algo_libgcrypt = GCRY_CIPHER_TWOFISH;
2291                                   decrypt_using_libgcrypt = TRUE;
2292                                   break;
2293                                 }
2294                               default:
2295                                 {
2296                                   fprintf (stderr,
2297                                            "<ESP Preferences> Error in Encryption Algorithm TWOFISH-CBC : Bad Keylen (%i Bits)\n",
2298                                            esp_crypt_key_len * 8);
2299                                   decrypt_ok = FALSE;
2300                                 }
2301                               }
2302                           }
2303
2304                         break;
2305                       }
2306
2307
2308                     case IPSEC_ENCRYPT_BLOWFISH_CBC :
2309                       {
2310                         /* Bruce Schneier of Counterpane Systems developed
2311                            the Blowfish block cipher algorithm.
2312                            RFC 2451 shows that Blowfish uses key sizes from
2313                            40 to 448 bits. The Default size is 128 bits.
2314                            We will only accept key sizes of 128 bits, because
2315                            libgrypt only accept this key size.
2316                         */
2317
2318                         /* Fix parameters for BLOWFISH-CBC */
2319                         esp_iv_len = 8;
2320                         crypt_algo_libgcrypt = GCRY_CIPHER_BLOWFISH;
2321                         crypt_mode_libgcrypt = GCRY_CIPHER_MODE_CBC;
2322
2323                         decrypted_len = len - sizeof(struct newesp);
2324
2325                         if (decrypted_len <= 0)
2326                           decrypt_ok = FALSE;
2327                         else
2328                           {
2329                             if(decrypted_len % esp_iv_len  == 0)
2330                               decrypted_len_alloc = decrypted_len;
2331                             else
2332                               decrypted_len_alloc = (decrypted_len / esp_iv_len) * esp_iv_len + esp_iv_len;
2333
2334                             if (esp_crypt_key_len != gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt))
2335                               {
2336                                 fprintf (stderr,
2337                                          "<ESP Preferences> Error in Encryption Algorithm BLOWFISH-CBC : Bad Keylen (%i Bits, need %lu)\n",
2338                                          esp_crypt_key_len * 8, (unsigned long) gcry_cipher_get_algo_keylen (crypt_algo_libgcrypt) * 8);
2339                                 decrypt_ok = FALSE;
2340                               }
2341                             else
2342                               decrypt_using_libgcrypt = TRUE;
2343                           }
2344
2345                         break;
2346
2347                       }
2348
2349
2350                     case IPSEC_ENCRYPT_NULL :
2351                     default :
2352                       {
2353                         /* Fix parameters */
2354                         esp_iv_len = 0;
2355                         decrypted_len = len - sizeof(struct newesp);
2356
2357                         if (decrypted_len <= 0)
2358                           decrypt_ok = FALSE;
2359                         else
2360                           {
2361                             /* Allocate Buffers for Encrypted and Decrypted data  */
2362                             decrypted_data = (guint8 *) g_malloc ((decrypted_len + 1)* sizeof(guint8));
2363                             tvb_memcpy(tvb, decrypted_data , sizeof(struct newesp), decrypted_len);
2364
2365                             decrypt_ok = TRUE;
2366                           }
2367
2368                         break;
2369                       }
2370                     }
2371
2372                   if(decrypt_using_libgcrypt)
2373                     {
2374                       /* Allocate Buffers for Encrypted and Decrypted data  */
2375                       encrypted_data = (guint8 *) g_malloc0 ((decrypted_len_alloc) * sizeof(guint8));
2376                       decrypted_data = (guint8 *) g_malloc ((decrypted_len_alloc + esp_iv_len)* sizeof(guint8));
2377                       tvb_memcpy(tvb, encrypted_data , sizeof(struct newesp), decrypted_len);
2378
2379                       err = gcry_cipher_open (&cypher_hd, crypt_algo_libgcrypt, crypt_mode_libgcrypt, 0);
2380                       if (err)
2381                         {
2382                           fprintf(stderr,
2383                                   "<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, grcy_open_cipher failed: %s\n",
2384                                   gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gpg_strerror (err));
2385                           g_free(encrypted_data);
2386                           g_free(decrypted_data);
2387                           decrypt_ok = FALSE;
2388                         }
2389
2390                       else
2391                         {
2392                           err = gcry_cipher_setkey (cypher_hd, esp_crypt_key, esp_crypt_key_len);
2393                           if (err)
2394                             {
2395                               fprintf(stderr,
2396                                       "<IPsec/ESP Dissector> Error in Algorithm %s Mode %d, gcry_cipher_setkey failed: %s\n",
2397                                       gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gpg_strerror (err));
2398                               gcry_cipher_close (cypher_hd);
2399                               g_free(encrypted_data);
2400                               g_free(decrypted_data);
2401                               decrypt_ok = FALSE;
2402                             }
2403                           else
2404                             {
2405                               err = gcry_cipher_decrypt (cypher_hd,
2406                                                          decrypted_data,
2407                                                          decrypted_len_alloc + esp_iv_len, encrypted_data, decrypted_len_alloc);
2408                               if (err)
2409                                 {
2410                                   fprintf(stderr,
2411                                           "<IPsec/ESP Dissector> Error in Algorithm %s, Mode %d, gcry_cipher_decrypt failed: %s\n",
2412                                           gcry_cipher_algo_name(crypt_algo_libgcrypt), crypt_mode_libgcrypt, gpg_strerror (err));
2413                                   gcry_cipher_close (cypher_hd);
2414                                   g_free(encrypted_data);
2415                                   g_free(decrypted_data);
2416                                   decrypt_ok = FALSE;
2417                                 }
2418                               else
2419                                 {
2420                                   gcry_cipher_close (cypher_hd);
2421
2422                                   /* Add the Authentication which was not encrypted */
2423                                   if(decrypted_len >= esp_auth_len)
2424                                     {
2425                                       for(i = 0; i <  esp_auth_len; i++)
2426                                         {
2427                                           decrypted_data[i + decrypted_len -esp_auth_len]
2428                                             = encrypted_data[i + decrypted_len - esp_auth_len];
2429                                         }
2430                                     }
2431
2432                                   fprintf(stderr,"\n\n ");
2433                                   g_free(encrypted_data);
2434                                   decrypt_ok = TRUE;
2435                                 }
2436                             }
2437                         }
2438                     }
2439
2440                   if(decrypt_ok && (decrypted_len > esp_iv_len))
2441                     {
2442                       tvb_decrypted = tvb_new_child_real_data(tvb,
2443                                                               g_memdup(decrypted_data+sizeof(guint8)*esp_iv_len,
2444                                                                        (decrypted_len - esp_iv_len)*sizeof(guint8)),
2445                                                               decrypted_len - esp_iv_len, decrypted_len - esp_iv_len);
2446                       g_free(decrypted_data);
2447
2448                       add_new_data_source(pinfo,
2449                                           tvb_decrypted,
2450                                           "Decrypted Data");
2451
2452                       /* Handler to free the Decrypted Data Buffer. */
2453                       tvb_set_free_cb(tvb_decrypted,g_free);
2454
2455                       if(tvb_bytes_exist(tvb, 8, esp_iv_len))
2456                         {
2457                           if(esp_iv_len > 0)
2458                             proto_tree_add_item(esp_tree, hf_esp_iv,
2459                                                 tvb,
2460                                                 8, esp_iv_len,
2461                                                 FALSE);
2462                         }
2463
2464                       else
2465                         proto_tree_add_text(esp_tree, tvb,
2466                                             8, -1,
2467                                             "IV (truncated)");
2468
2469                       /* Make sure the packet is not truncated before the fields
2470                        * we need to read to determine the encapsulated protocol */
2471                       if(tvb_bytes_exist(tvb_decrypted, decrypted_len - esp_iv_len - esp_auth_len - 2, 2))
2472                         {
2473                           esp_pad_len = tvb_get_guint8(tvb_decrypted, decrypted_len - esp_iv_len - esp_auth_len - 2);
2474
2475                           if(decrypted_len - esp_iv_len - esp_auth_len - esp_pad_len - 2 >= 0)
2476                             {
2477                               /* Get the encapsulated protocol */
2478                               encapsulated_protocol = tvb_get_guint8(tvb_decrypted, decrypted_len - esp_iv_len - esp_auth_len - 1);
2479
2480                               if(dissector_try_port(ip_dissector_table,
2481                                                     encapsulated_protocol,
2482                                                     tvb_new_subset(tvb_decrypted, 0,
2483                                                                    decrypted_len - esp_auth_len - esp_pad_len - esp_iv_len - 2,
2484                                                                    decrypted_len - esp_auth_len - esp_pad_len - esp_iv_len - 2),
2485                                                     pinfo,
2486                                                     tree))
2487                                 {
2488                                   decrypt_dissect_ok = TRUE;
2489                                 }
2490                             }
2491
2492                         }
2493
2494                       if(decrypt_dissect_ok)
2495                         {
2496                           if(esp_tree)
2497                             {
2498                               if(esp_pad_len !=0)
2499                                 proto_tree_add_text(esp_tree,
2500                                                     tvb_decrypted,
2501                                                     decrypted_len - esp_iv_len - esp_auth_len - 2 - esp_pad_len,
2502                                                     esp_pad_len,
2503                                                     "Pad");
2504
2505                               proto_tree_add_uint(esp_tree, hf_esp_pad_len, tvb_decrypted,
2506                                                   decrypted_len - esp_iv_len - esp_auth_len - 2, 1,
2507                                                   esp_pad_len);
2508
2509                               proto_tree_add_uint_format(esp_tree, hf_esp_protocol, tvb_decrypted,
2510                                          decrypted_len - esp_iv_len - esp_auth_len - 1, 1,
2511                                          encapsulated_protocol,
2512                                         "Next header: %s (0x%02x)",
2513                                          ipprotostr(encapsulated_protocol), encapsulated_protocol);
2514
2515                               dissect_esp_authentication(esp_tree,
2516                                                          tvb_decrypted,
2517                                                          decrypted_len - esp_iv_len,
2518                                                          esp_auth_len,
2519                                                          authenticator_data_computed,
2520                                                          authentication_ok,
2521                                                          authentication_checking_ok );
2522
2523                             }
2524                         }
2525                       else
2526                         {
2527                           call_dissector(data_handle,
2528                                          tvb_new_subset(tvb_decrypted, 0,
2529                                                         decrypted_len - esp_iv_len - esp_auth_len,
2530                                                         decrypted_len - esp_iv_len - esp_auth_len),
2531                                          pinfo, esp_tree);
2532
2533                           if(esp_tree)
2534                             dissect_esp_authentication(esp_tree,
2535                                                        tvb_decrypted,
2536                                                        decrypted_len - esp_iv_len, esp_auth_len,
2537                                                        authenticator_data_computed, authentication_ok,
2538                                                        authentication_checking_ok );
2539
2540                         }
2541                     }
2542
2543                 }
2544
2545               else
2546                 {
2547                   /* The packet does not belong to a security Association */
2548                   null_encryption_decode_heuristic = g_esp_enable_null_encryption_decode_heuristic;
2549                 }
2550
2551               g_free(ip_src);
2552               g_free(ip_dst);
2553               if(esp_auth_key_len != 0) g_free(esp_auth_key);
2554               if(esp_crypt_key_len != 0) g_free(esp_crypt_key);
2555
2556             }
2557         }
2558     }
2559
2560   /*
2561     If the packet is present in the security association database and the field g_esp_enable_authentication_check set.
2562   */
2563   if(!g_esp_enable_encryption_decode && g_esp_enable_authentication_check && sad_is_present)
2564     {
2565       sad_is_present = FALSE;
2566       call_dissector(data_handle,
2567                      tvb_new_subset(tvb, sizeof(struct newesp), len - sizeof(struct newesp) - esp_auth_len, -1),
2568                      pinfo, esp_tree);
2569
2570       if(esp_tree)
2571         dissect_esp_authentication(esp_tree, tvb, len ,
2572                                    esp_auth_len, authenticator_data_computed,
2573                                    authentication_ok, authentication_checking_ok );
2574
2575     }
2576
2577
2578   /* The packet does not belong to a security association and the field g_esp_enable_null_encryption_decode_heuristic is set */
2579   else if(null_encryption_decode_heuristic)
2580     {
2581 #endif
2582       if(g_esp_enable_null_encryption_decode_heuristic)
2583         {
2584           /* Get length of whole ESP packet. */
2585           len = tvb_reported_length(tvb);
2586
2587           /* Make sure the packet is not truncated before the fields
2588            * we need to read to determine the encapsulated protocol */
2589           if(tvb_bytes_exist(tvb, len - 14, 2))
2590             {
2591               esp_pad_len = tvb_get_guint8(tvb, len - 14);
2592               encapsulated_protocol = tvb_get_guint8(tvb, len - 13);
2593               if(dissector_try_port(ip_dissector_table,
2594                                     encapsulated_protocol,
2595                                     tvb_new_subset(tvb,
2596                                                    sizeof(struct newesp),
2597                                                    -1,
2598                                                    len - sizeof(struct newesp) - 14 - esp_pad_len),
2599                                     pinfo,
2600                                     tree))
2601                 {
2602                   decrypt_dissect_ok = TRUE;
2603                 }
2604             }
2605         }
2606
2607       if(decrypt_dissect_ok)
2608         {
2609           if(esp_tree)
2610             {
2611               proto_tree_add_uint(esp_tree, hf_esp_pad_len, tvb,
2612                                   len - 14, 1,
2613                                   esp_pad_len);
2614
2615               proto_tree_add_uint_format(esp_tree, hf_esp_protocol, tvb,
2616                                   len - 13, 1,
2617                                   encapsulated_protocol,
2618                                  "Next header: %s (0x%02x)",
2619                                   ipprotostr(encapsulated_protocol), encapsulated_protocol);
2620
2621               /* Make sure we have the auth trailer data */
2622               if(tvb_bytes_exist(tvb, len - 12, 12))
2623                 {
2624                   proto_tree_add_text(esp_tree, tvb, len - 12, 12,
2625                                       "Authentication Data");
2626                 }
2627
2628               else
2629                 {
2630                   /* Truncated so just display what we have */
2631                   proto_tree_add_text(esp_tree, tvb, len - 12, 12 - (len - tvb_length(tvb)),
2632                                       "Authentication Data (truncated)");
2633                 }
2634             }
2635         }
2636 #ifdef HAVE_LIBGCRYPT
2637
2638   }
2639
2640 #endif
2641 }
2642
2643
2644 static void
2645 dissect_ipcomp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2646 {
2647   proto_tree *ipcomp_tree;
2648   proto_item *ti;
2649   struct ipcomp ipcomp;
2650   const char *p;
2651
2652   /*
2653    * load the top pane info. This should be overwritten by
2654    * the next protocol in the stack
2655    */
2656   col_set_str(pinfo->cinfo, COL_PROTOCOL, "IPComp");
2657   col_clear(pinfo->cinfo, COL_INFO);
2658
2659   tvb_memcpy(tvb, (guint8 *)&ipcomp, 0, sizeof(ipcomp));
2660
2661   if (check_col(pinfo->cinfo, COL_INFO)) {
2662     p = match_strval(g_ntohs(ipcomp.comp_cpi), cpi2val);
2663     if (p == NULL) {
2664       col_add_fstr(pinfo->cinfo, COL_INFO, "IPComp (CPI=0x%04x)",
2665                    g_ntohs(ipcomp.comp_cpi));
2666     } else
2667       col_add_fstr(pinfo->cinfo, COL_INFO, "IPComp (CPI=%s)", p);
2668   }
2669
2670   /*
2671    * populate a tree in the second pane with the status of the link layer
2672    * (ie none)
2673    */
2674   if (tree) {
2675     ti = proto_tree_add_item(tree, proto_ipcomp, tvb, 0, -1, FALSE);
2676     ipcomp_tree = proto_item_add_subtree(ti, ett_ipcomp);
2677
2678     proto_tree_add_text(ipcomp_tree, tvb,
2679                         offsetof(struct ipcomp, comp_nxt), 1,
2680                         "Next Header: %s (0x%02x)",
2681                         ipprotostr(ipcomp.comp_nxt), ipcomp.comp_nxt);
2682     proto_tree_add_uint(ipcomp_tree, hf_ipcomp_flags, tvb,
2683                         offsetof(struct ipcomp, comp_flags), 1,
2684                         ipcomp.comp_flags);
2685     proto_tree_add_uint(ipcomp_tree, hf_ipcomp_cpi, tvb,
2686                         offsetof(struct ipcomp, comp_cpi), 2,
2687                         g_ntohs(ipcomp.comp_cpi));
2688     call_dissector(data_handle,
2689                    tvb_new_subset(tvb, sizeof(struct ipcomp), -1, -1), pinfo,
2690                    ipcomp_tree);
2691   }
2692 }
2693
2694 void
2695 proto_register_ipsec(void)
2696 {
2697
2698 #ifdef HAVE_LIBGCRYPT
2699   guint i=0;
2700 #endif
2701
2702   static hf_register_info hf_ah[] = {
2703     { &hf_ah_spi,
2704       { "AH SPI", "ah.spi", FT_UINT32, BASE_HEX, NULL, 0x0,
2705         "IP Authentication Header Security Parameters Index", HFILL }},
2706     { &hf_ah_iv,
2707       { "AH ICV", "ah.icv", FT_BYTES, BASE_NONE, NULL, 0x0,
2708         "IP Authentication Header Integrity Check Value", HFILL }},
2709     { &hf_ah_sequence,
2710       { "AH Sequence", "ah.sequence", FT_UINT32, BASE_DEC, NULL, 0x0,
2711         "IP Authentication Header Sequence Number", HFILL }}
2712   };
2713
2714   static hf_register_info hf_esp[] = {
2715     { &hf_esp_spi,
2716       { "ESP SPI", "esp.spi", FT_UINT32, BASE_HEX, NULL, 0x0,
2717         "IP Encapsulating Security Payload Security Parameters Index", HFILL }},
2718     { &hf_esp_sequence,
2719       { "ESP Sequence", "esp.sequence", FT_UINT32, BASE_DEC, NULL, 0x0,
2720         "IP Encapsulating Security Payload Sequence Number", HFILL }},
2721     { &hf_esp_pad_len,
2722       { "ESP Pad Length", "esp.pad_len", FT_UINT8, BASE_DEC, NULL, 0x0,
2723         "IP Encapsulating Security Payload Pad Length", HFILL }},
2724     { &hf_esp_protocol,
2725       { "ESP Next Header", "esp.protocol", FT_UINT8, BASE_HEX, NULL, 0x0,
2726         "IP Encapsulating Security Payload Next Header", HFILL }},
2727     { &hf_esp_iv,
2728       { "ESP IV", "esp.iv", FT_BYTES, BASE_NONE, NULL, 0x0,
2729         "IP Encapsulating Security Payload", HFILL }}
2730   };
2731
2732   static hf_register_info hf_ipcomp[] = {
2733     { &hf_ipcomp_flags,
2734       { "IPComp Flags", "ipcomp.flags", FT_UINT8, BASE_HEX, NULL, 0x0,
2735         "IP Payload Compression Protocol Flags", HFILL }},
2736     { &hf_ipcomp_cpi,
2737       { "IPComp CPI", "ipcomp.cpi", FT_UINT16, BASE_HEX, VALS(cpi2val), 0x0,
2738         "IP Payload Compression Protocol Compression Parameter Index", HFILL }},
2739   };
2740   static gint *ett[] = {
2741     &ett_ah,
2742     &ett_esp,
2743     &ett_ipcomp,
2744   };
2745
2746 #ifdef HAVE_LIBGCRYPT
2747   GString *name_str, *title_str;
2748
2749 #define PREF_STR_INIT() \
2750   name_str = g_string_new(""); \
2751   title_str = g_string_new("")
2752
2753 #define PREF_STR_FREE() \
2754   g_string_free(name_str, FALSE); \
2755   g_string_free(title_str, FALSE)
2756
2757   static enum_val_t esp_encryption_algo[] = {
2758
2759     {"null", "NULL", IPSEC_ENCRYPT_NULL},
2760     {"3descbc", "TripleDES-CBC [RFC2451]", IPSEC_ENCRYPT_3DES_CBC},
2761     {"aescbc", "AES-CBC [RFC3602]", IPSEC_ENCRYPT_AES_CBC},
2762     {"aesctr", "AES-CTR [RFC3686]", IPSEC_ENCRYPT_AES_CTR},
2763     {"descbc", "DES-CBC [RFC2405]", IPSEC_ENCRYPT_DES_CBC},
2764     {"cast5cbc", "CAST5-CBC [RFC2144]", IPSEC_ENCRYPT_CAST5_CBC},
2765     {"blowfishcbc","BLOWFISH-CBC [RFC2451]", IPSEC_ENCRYPT_BLOWFISH_CBC},
2766     {"twofishcbc","TWOFISH-CBC", IPSEC_ENCRYPT_TWOFISH_CBC},
2767     {NULL,NULL,0}
2768   };
2769
2770   static enum_val_t esp_authentication_algo[] = {
2771
2772     {"null", "NULL", IPSEC_AUTH_NULL},
2773     {"hmacsha196", "HMAC-SHA-1-96 [RFC2404]", IPSEC_AUTH_HMAC_SHA1_96},
2774     {"hmacsha25696", "HMAC-SHA-256-96 [draft-ietf-ipsec-ciph-sha-256-00]", IPSEC_AUTH_HMAC_SHA256_96},
2775     {"hmacsha256128", "HMAC-SHA-256-128 [RFC4868]", IPSEC_AUTH_HMAC_SHA256_128},
2776     {"hmacmd596", "HMAC-MD5-96 [RFC2403]", IPSEC_AUTH_HMAC_MD5_96},
2777     {"hmacripemd160", "MAC-RIPEMD-160-96 [RFC2857]", IPSEC_AUTH_HMAC_RIPEMD160_96},
2778     /*    {"aesxcbcmac96", "AES-XCBC-MAC-96 [RFC3566]", IPSEC_AUTH_AES_XCBC_MAC_96}, */
2779     {"any96bit",   "ANY 96 bit authentication [no checking]", IPSEC_AUTH_ANY_96BIT},
2780     {"any128bit", "ANY 128 bit authentication [no checking]", IPSEC_AUTH_ANY_128BIT},
2781     {"any192bit", "ANY 192 bit authentication [no checking]", IPSEC_AUTH_ANY_192BIT},
2782     {"any256bit", "ANY 256 bit authentication [no checking]", IPSEC_AUTH_ANY_256BIT},
2783     {NULL,NULL,0}
2784   };
2785 #endif
2786
2787   module_t *ah_module;
2788   module_t *esp_module;
2789
2790   proto_ah = proto_register_protocol("Authentication Header", "AH", "ah");
2791   proto_register_field_array(proto_ah, hf_ah, array_length(hf_ah));
2792
2793   proto_esp = proto_register_protocol("Encapsulating Security Payload",
2794                                       "ESP", "esp");
2795   proto_register_field_array(proto_esp, hf_esp, array_length(hf_esp));
2796
2797   proto_ipcomp = proto_register_protocol("IP Payload Compression",
2798                                          "IPComp", "ipcomp");
2799   proto_register_field_array(proto_ipcomp, hf_ipcomp, array_length(hf_ipcomp));
2800
2801   proto_register_subtree_array(ett, array_length(ett));
2802
2803   /* Register a configuration option for placement of AH payload dissection */
2804   ah_module = prefs_register_protocol(proto_ah, NULL);
2805   prefs_register_bool_preference(ah_module, "place_ah_payload_in_subtree",
2806                                  "Place AH payload in subtree",
2807                                  "Whether the AH payload decode should be placed in a subtree",
2808                                  &g_ah_payload_in_subtree);
2809   esp_module = prefs_register_protocol(proto_esp, NULL);
2810
2811 #ifdef HAVE_LIBGCRYPT
2812   /* Register SA configuration options for ESP decryption */
2813   g_esp_sad.nb = g_esp_nb_sa;
2814   for(i = 0; i < g_esp_nb_sa; i++)
2815     {
2816       g_esp_sad.table[i].sa = NULL;
2817       g_esp_sad.table[i].typ = IPSEC_SA_UNKNOWN;
2818       g_esp_sad.table[i].src = NULL;
2819       g_esp_sad.table[i].dst = NULL;
2820       g_esp_sad.table[i].spi = NULL;
2821       g_esp_sad.table[i].src_len = -1;
2822       g_esp_sad.table[i].dst_len = -1;
2823       g_esp_sad.table[i].encryption_algo = IPSEC_ENCRYPT_NULL;
2824       g_esp_sad.table[i].authentication_algo = IPSEC_AUTH_NULL;
2825       g_esp_sad.table[i].encryption_key = NULL;
2826       g_esp_sad.table[i].authentication_key = NULL;
2827       g_esp_sad.table[i].is_valid = FALSE;
2828     }
2829 #endif
2830
2831   prefs_register_bool_preference(esp_module, "enable_null_encryption_decode_heuristic",
2832                                  "Attempt to detect/decode NULL encrypted ESP payloads",
2833                                  "This is done only if the Decoding is not SET or the packet does not belong to a SA. "
2834                                  "Assumes a 12 byte auth (HMAC-SHA1-96/HMAC-MD5-96/AES-XCBC-MAC-96) "
2835                                  "and attempts decode based on the ethertype 13 bytes from packet end",
2836                                  &g_esp_enable_null_encryption_decode_heuristic);
2837
2838
2839 #ifdef HAVE_LIBGCRYPT
2840   prefs_register_bool_preference(esp_module, "enable_encryption_decode",
2841                                  "Attempt to detect/decode encrypted ESP payloads",
2842                                  "Attempt to decode based on the SAD described hereafter.",
2843                                  &g_esp_enable_encryption_decode);
2844
2845   prefs_register_bool_preference(esp_module, "enable_authentication_check",
2846                                  "Attempt to Check ESP Authentication",
2847                                  "Attempt to Check ESP Authentication based on the SAD described hereafter.",
2848                                  &g_esp_enable_authentication_check);
2849
2850
2851   /* prefs_register_uint_preference(esp_module, "nb_sa",
2852      "Number of Security Associations",
2853      "Number of Security Associations in the SAD",
2854      10, &g_esp_nb_sa); */
2855
2856   for (i = 0; i < g_esp_nb_sa; i++)
2857     {
2858
2859       if (i >=  g_max_esp_nb_sa)
2860         {
2861           break;
2862         }
2863
2864       PREF_STR_INIT();
2865       g_string_printf(name_str,"sa_%d", i + 1);
2866       g_string_printf(title_str,"SA #%d", i + 1);
2867
2868       prefs_register_string_preference(esp_module, name_str->str, title_str->str,
2869                         "SA identifier.  Must have the form "
2870                         "\"Protocol|Source Address|Destination Address|SPI\". "
2871                         "Example: \"IPv4|192.168.0.45|10.1.2.7|*\" "
2872                         "See the ESP Preferences page on the Wireshark wiki "
2873                         "(http://wiki.wireshark.org/ESP_Preferences) for "
2874                         "more details.",
2875                         &g_esp_sad.table[i].sa);
2876       PREF_STR_FREE();
2877
2878
2879       PREF_STR_INIT();
2880       g_string_printf(name_str, "encryption_algorithm_%d", i + 1);
2881       g_string_printf(title_str, "Encryption Algorithm #%d", i + 1);
2882
2883       prefs_register_enum_preference(esp_module, name_str->str, title_str->str,
2884                         "Encryption algorithm",
2885                         &g_esp_sad.table[i].encryption_algo, esp_encryption_algo, FALSE);
2886       PREF_STR_FREE();
2887
2888       PREF_STR_INIT();
2889       g_string_printf(name_str, "authentication_algorithm_%d", i + 1);
2890       g_string_printf(title_str, "Authentication Algorithm #%d", i + 1);
2891
2892       prefs_register_enum_preference(esp_module, name_str->str, title_str->str,
2893                         "Authentication algorithm",
2894                         &g_esp_sad.table[i].authentication_algo, esp_authentication_algo, FALSE);
2895       PREF_STR_FREE();
2896
2897
2898       PREF_STR_INIT();
2899       g_string_printf(name_str, "encryption_key_%d", i + 1);
2900       g_string_printf(title_str, "Encryption Key #%d", i + 1);
2901
2902       prefs_register_string_preference(esp_module, name_str->str, title_str->str,
2903                         "Encryption key. May be ASCII or hexadecimal (if "
2904                         "prepended with 0x)."
2905                         "See the ESP Preferences page on the Wireshark wiki "
2906                         "(http://wiki.wireshark.org/ESP_Preferences) for "
2907                         "supported sizes.",
2908                         &g_esp_sad.table[i].encryption_key);
2909       PREF_STR_FREE();
2910
2911
2912       PREF_STR_INIT();
2913       g_string_printf(name_str, "authentication_key_%d", i + 1);
2914       g_string_printf(title_str, "Authentication Key #%d", i + 1);
2915
2916       prefs_register_string_preference(esp_module, name_str->str, title_str->str,
2917                         "Authentication key. May be ASCII or hexadecimal (if "
2918                         "prepended with 0x)."
2919                         "See the ESP Preferences page on the Wireshark wiki "
2920                         "(http://wiki.wireshark.org/ESP_Preferences) for "
2921                         "supported sizes.",
2922                         &g_esp_sad.table[i].authentication_key);
2923       PREF_STR_FREE();
2924
2925     }
2926
2927
2928 #endif
2929
2930   register_dissector("esp", dissect_esp, proto_esp);
2931   register_dissector("ah", dissect_ah, proto_ah);
2932
2933 }
2934
2935 void
2936 proto_reg_handoff_ipsec(void)
2937 {
2938   dissector_handle_t esp_handle, ah_handle, ipcomp_handle;
2939
2940   data_handle = find_dissector("data");
2941   ah_handle = find_dissector("ah");
2942   dissector_add("ip.proto", IP_PROTO_AH, ah_handle);
2943   esp_handle = find_dissector("esp");
2944   dissector_add("ip.proto", IP_PROTO_ESP, esp_handle);
2945   ipcomp_handle = create_dissector_handle(dissect_ipcomp, proto_ipcomp);
2946   dissector_add("ip.proto", IP_PROTO_IPCOMP, ipcomp_handle);
2947
2948   ip_dissector_table = find_dissector_table("ip.proto");
2949 }
2950
2951
2952