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