ASN1: Register PDU-dissectors as NEW
[metze/wireshark/wip.git] / asn1 / pkcs12 / packet-pkcs12-template.c
1 /* packet-pkcs12.c
2  * Routines for PKCS#12: Personal Information Exchange packet dissection
3  * Graeme Lunt 2006
4  *
5  * See "PKCS #12 v1.1: Personal Information Exchange Syntax":
6  *
7  *    http://www.emc.com/emc-plus/rsa-labs/pkcs/files/h11301-wp-pkcs-12v1-1-personal-information-exchange-syntax.pdf
8  *
9  * Wireshark - Network traffic analyzer
10  * By Gerald Combs <gerald@wireshark.org>
11  * Copyright 1998 Gerald Combs
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26  */
27
28 #include "config.h"
29
30 #include <glib.h>
31 #include <epan/packet.h>
32 #include <epan/expert.h>
33 #include <epan/oids.h>
34 #include <epan/asn1.h>
35 #include <epan/prefs.h>
36 #include <epan/wmem/wmem.h>
37
38 #include "packet-ber.h"
39 #include "packet-pkcs12.h"
40 #include "packet-x509af.h"
41 #include "packet-x509if.h"
42 #include "packet-cms.h"
43
44 #ifdef HAVE_SYS_TIME_H
45 #include <sys/time.h>
46 #endif
47
48 #ifdef HAVE_LIBGCRYPT
49 #include <wsutil/wsgcrypt.h>
50 #endif
51
52 #define PNAME  "PKCS#12: Personal Information Exchange"
53 #define PSNAME "PKCS12"
54 #define PFNAME "pkcs12"
55
56 #define PKCS12_PBE_ARCFOUR_SHA1_OID     "1.2.840.113549.1.12.1.1"
57 #define PKCS12_PBE_3DES_SHA1_OID        "1.2.840.113549.1.12.1.3"
58 #define PKCS12_PBE_RC2_40_SHA1_OID      "1.2.840.113549.1.12.1.6"
59
60 void proto_register_pkcs12(void);
61 void proto_reg_handoff_pkcs12(void);
62
63 /* Initialize the protocol and registered fields */
64 static int proto_pkcs12 = -1;
65
66 static int hf_pkcs12_X509Certificate_PDU = -1;
67 static gint ett_decrypted_pbe = -1;
68
69 static expert_field ei_pkcs12_octet_string_expected = EI_INIT;
70
71
72 static const char *object_identifier_id = NULL;
73 static int iteration_count = 0;
74 static tvbuff_t *salt = NULL;
75 static const char *password = NULL;
76 static gboolean try_null_password = FALSE;
77
78 static void dissect_AuthenticatedSafe_OCTETSTRING_PDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
79 static void dissect_SafeContents_OCTETSTRING_PDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);
80 static int dissect_PrivateKeyInfo_PDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data);
81
82 #include "packet-pkcs12-hf.c"
83
84 /* Initialize the subtree pointers */
85 #include "packet-pkcs12-ett.c"
86
87 static void append_oid(proto_tree *tree, const char *oid)
88 {
89         const char *name = NULL;
90
91         name = oid_resolved_from_string(oid);
92         proto_item_append_text(tree, " (%s)", name ? name : oid);
93 }
94
95 #ifdef HAVE_LIBGCRYPT
96
97 static int
98 generate_key_or_iv(unsigned int id, tvbuff_t *salt_tvb, unsigned int iter,
99                        const char *pw, unsigned int req_keylen, char * keybuf)
100 {
101   int rc;
102   unsigned int i, j;
103   gcry_md_hd_t md;
104   gcry_mpi_t num_b1 = NULL;
105   size_t pwlen;
106   char hash[20], buf_b[64], buf_i[128], *p;
107   char *salt_p;
108   int salt_size;
109   size_t cur_keylen;
110   size_t n;
111   gcry_error_t  err;
112
113   cur_keylen = 0;
114
115   salt_size = tvb_captured_length(salt_tvb);
116   salt_p = (char *)tvb_memdup(wmem_packet_scope(), salt_tvb, 0, salt_size);
117
118   if (pw == NULL)
119     pwlen = 0;
120   else
121     pwlen = strlen (pw);
122
123   if (pwlen > 63 / 2)
124     {
125       return FALSE;
126     }
127
128   /* Store salt and password in BUF_I */
129   p = buf_i;
130   for (i = 0; i < 64; i++)
131     *p++ = salt_p[i % salt_size];
132   if (pw)
133     {
134       for (i = j = 0; i < 64; i += 2)
135         {
136           *p++ = 0;
137           *p++ = pw[j];
138           if (++j > pwlen)      /* Note, that we include the trailing zero */
139             j = 0;
140         }
141     }
142   else
143     memset (p, 0, 64);
144
145   for (;;) {
146       err = gcry_md_open(&md, GCRY_MD_SHA1, 0);
147       if (gcry_err_code(err))
148         {
149           return FALSE;
150         }
151       for (i = 0; i < 64; i++)
152         {
153           unsigned char lid = id & 0xFF;
154           gcry_md_write (md, &lid, 1);
155         }
156
157       gcry_md_write(md, buf_i, pw ? 128 : 64);
158
159       gcry_md_final (md);
160       memcpy (hash, gcry_md_read (md, 0), 20);
161
162       gcry_md_close (md);
163
164       for (i = 1; i < iter; i++)
165         gcry_md_hash_buffer (GCRY_MD_SHA1, hash, hash, 20);
166
167       for (i = 0; i < 20 && cur_keylen < req_keylen; i++)
168         keybuf[cur_keylen++] = hash[i];
169
170       if (cur_keylen == req_keylen)
171       {
172         gcry_mpi_release (num_b1);
173         return TRUE;            /* ready */
174       }
175
176       /* need more bytes. */
177       for (i = 0; i < 64; i++)
178         buf_b[i] = hash[i % 20];
179
180       n = 64;
181
182       rc = gcry_mpi_scan (&num_b1, GCRYMPI_FMT_USG, buf_b, n, &n);
183
184       if (rc != 0)
185         {
186           return FALSE;
187         }
188
189       gcry_mpi_add_ui (num_b1, num_b1, 1);
190
191       for (i = 0; i < 128; i += 64)
192         {
193           gcry_mpi_t num_ij;
194
195           n = 64;
196           rc = gcry_mpi_scan (&num_ij, GCRYMPI_FMT_USG, buf_i + i, n, &n);
197
198           if (rc != 0)
199             {
200               return FALSE;
201             }
202
203           gcry_mpi_add (num_ij, num_ij, num_b1);
204           gcry_mpi_clear_highbit (num_ij, 64 * 8);
205
206           n = 64;
207
208           rc = gcry_mpi_print (GCRYMPI_FMT_USG, buf_i + i, n, &n, num_ij);
209           if (rc != 0)
210             {
211               return FALSE;
212             }
213
214           gcry_mpi_release (num_ij);
215         }
216   }
217 }
218
219 #endif
220
221 void PBE_reset_parameters(void)
222 {
223         iteration_count = 0;
224         salt = NULL;
225 }
226
227 int PBE_decrypt_data(const char *object_identifier_id_param, tvbuff_t *encrypted_tvb, asn1_ctx_t *actx, proto_item *item)
228 {
229 #ifdef HAVE_LIBGCRYPT
230         const char      *encryption_algorithm;
231         gcry_cipher_hd_t cipher;
232         gcry_error_t    err;
233         int             algo;
234         int             mode;
235         int             ivlen = 0;
236         int             keylen = 0;
237         int             datalen = 0;
238         char            *key = NULL;
239         char            *iv = NULL;
240         char            *clear_data = NULL;
241         tvbuff_t        *clear_tvb = NULL;
242         const gchar     *oidname;
243         GString         *name;
244         proto_tree      *tree;
245         char            byte;
246         gboolean        decrypt_ok = TRUE;
247
248         if(((password == NULL) || (*password == '\0')) && (try_null_password == FALSE)) {
249                 /* we are not configured to decrypt */
250                 return FALSE;
251         }
252
253         encryption_algorithm = x509af_get_last_algorithm_id();
254
255         /* these are the only encryption schemes we understand for now */
256         if(!strcmp(encryption_algorithm, PKCS12_PBE_3DES_SHA1_OID)) {
257                 ivlen = 8;
258                 keylen = 24;
259                 algo = GCRY_CIPHER_3DES;
260                 mode = GCRY_CIPHER_MODE_CBC;
261         } else if(!strcmp(encryption_algorithm, PKCS12_PBE_ARCFOUR_SHA1_OID)) {
262                 ivlen = 0;
263                 keylen = 16;
264                 algo = GCRY_CIPHER_ARCFOUR;
265                 mode = GCRY_CIPHER_MODE_NONE;
266         } else if(!strcmp(encryption_algorithm, PKCS12_PBE_RC2_40_SHA1_OID)) {
267                 ivlen = 8;
268                 keylen = 5;
269                 algo = GCRY_CIPHER_RFC2268_40;
270                 mode = GCRY_CIPHER_MODE_CBC;
271         } else {
272                 /* we don't know how to decrypt this */
273
274                 proto_item_append_text(item, " [Unsupported encryption algorithm]");
275                 return FALSE;
276         }
277
278         if((iteration_count == 0) || (salt == NULL)) {
279                 proto_item_append_text(item, " [Insufficient parameters]");
280                 return FALSE;
281         }
282
283         /* allocate buffers */
284         key = (char *)wmem_alloc(wmem_packet_scope(), keylen);
285
286         if(!generate_key_or_iv(1 /*LEY */, salt, iteration_count, password, keylen, key))
287                 return FALSE;
288
289         if(ivlen) {
290
291                 iv = (char *)wmem_alloc(wmem_packet_scope(), ivlen);
292
293                 if(!generate_key_or_iv(2 /* IV */, salt, iteration_count, password, ivlen, iv))
294                         return FALSE;
295         }
296
297         /* now try an internal function */
298         err = gcry_cipher_open(&cipher, algo, mode, 0);
299         if (gcry_err_code (err))
300                         return FALSE;
301
302         err = gcry_cipher_setkey (cipher, key, keylen);
303         if (gcry_err_code (err)) {
304                         gcry_cipher_close (cipher);
305                         return FALSE;
306         }
307
308         if(ivlen) {
309                   err = gcry_cipher_setiv (cipher, iv, ivlen);
310                   if (gcry_err_code (err)) {
311                           gcry_cipher_close (cipher);
312                           return FALSE;
313                   }
314         }
315
316         datalen = tvb_captured_length(encrypted_tvb);
317         clear_data = (char *)g_malloc(datalen);
318
319         err = gcry_cipher_decrypt (cipher, clear_data, datalen, (char *)tvb_memdup(wmem_packet_scope(), encrypted_tvb, 0, datalen), datalen);
320         if (gcry_err_code (err)) {
321
322                 proto_item_append_text(item, " [Failed to decrypt with password preference]");
323
324                 gcry_cipher_close (cipher);
325                 g_free(clear_data);
326                 return FALSE;
327         }
328
329         gcry_cipher_close (cipher);
330
331         /* We don't know if we have successfully decrypted the data or not so we:
332                 a) check the trailing bytes
333                 b) see if we start with a sequence or a set (is this too constraining?
334                 */
335
336         /* first the trailing bytes */
337         byte = clear_data[datalen-1];
338         if(byte <= 0x08) {
339                 int i;
340
341                 for(i = (int)byte; i > 0 ; i--) {
342                         if(clear_data[datalen - i] != byte) {
343                                 decrypt_ok = FALSE;
344                                 break;
345                         }
346                 }
347         } else {
348                 /* XXX: is this a failure? */
349         }
350
351         /* we assume the result is ASN.1 - check it is a SET or SEQUENCE */
352         byte = clear_data[0];
353         if((byte != 0x30) && (byte != 0x31)) { /* do we need more here? OCTET STRING? */
354                 decrypt_ok = FALSE;
355         }
356
357         if(!decrypt_ok) {
358                 g_free(clear_data);
359                 proto_item_append_text(item, " [Failed to decrypt with supplied password]");
360
361                 return FALSE;
362         }
363
364         proto_item_append_text(item, " [Decrypted successfully]");
365
366         tree = proto_item_add_subtree(item, ett_decrypted_pbe);
367
368         /* OK - so now clear_data contains the decrypted data */
369
370         clear_tvb = tvb_new_child_real_data(encrypted_tvb,(const guint8 *)clear_data, datalen, datalen);
371         tvb_set_free_cb(clear_tvb, g_free);
372
373         name = g_string_new("");
374         oidname = oid_resolved_from_string(object_identifier_id_param);
375         g_string_printf(name, "Decrypted %s", oidname ? oidname : object_identifier_id_param);
376
377         /* add it as a new source */
378         add_new_data_source(actx->pinfo, clear_tvb, name->str);
379
380         g_string_free(name, TRUE);
381
382         /* now try and decode it */
383         call_ber_oid_callback(object_identifier_id_param, clear_tvb, 0, actx->pinfo, tree, NULL);
384
385         return TRUE;
386 #else
387         /* we cannot decrypt */
388         return FALSE;
389
390 #endif
391 }
392
393 #include "packet-pkcs12-fn.c"
394
395 static int strip_octet_string(tvbuff_t *tvb)
396 {
397   gint8 ber_class;
398   gboolean pc, ind;
399   gint32 tag;
400   guint32 len;
401   int offset = 0;
402
403   /* PKCS#7 encodes the content as OCTET STRING, whereas CMS is just any ANY */
404   /* if we use CMS (rather than PKCS#7) - which we are - we need to strip the OCTET STRING tag */
405   /* before proceeding */
406
407   offset = get_ber_identifier(tvb, 0, &ber_class, &pc, &tag);
408   offset = get_ber_length(tvb, offset, &len, &ind);
409
410   if((ber_class == BER_CLASS_UNI) && (tag == BER_UNI_TAG_OCTETSTRING))
411     return offset;
412
413   return 0;
414
415 }
416
417 static void dissect_AuthenticatedSafe_OCTETSTRING_PDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) {
418   int offset = 0;
419   asn1_ctx_t asn1_ctx;
420   asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
421
422   if((offset = strip_octet_string(tvb)) > 0)
423     dissect_pkcs12_AuthenticatedSafe(FALSE, tvb, offset, &asn1_ctx, tree, hf_pkcs12_AuthenticatedSafe_PDU);
424   else
425     proto_tree_add_expert(tree, pinfo, &ei_pkcs12_octet_string_expected, tvb, 0, 1);
426 }
427
428 static void dissect_SafeContents_OCTETSTRING_PDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
429 {
430   int offset = 0;
431   asn1_ctx_t asn1_ctx;
432   asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
433
434   offset = strip_octet_string(tvb);
435
436   dissect_pkcs12_SafeContents(FALSE, tvb, offset, &asn1_ctx, tree, hf_pkcs12_SafeContents_PDU);
437 }
438
439 static void dissect_X509Certificate_OCTETSTRING_PDU(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
440 {
441   int offset = 0;
442   asn1_ctx_t asn1_ctx;
443   asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
444
445   if((offset = strip_octet_string(tvb)) > 0)
446         dissect_x509af_Certificate(FALSE, tvb, offset, &asn1_ctx, tree, hf_pkcs12_X509Certificate_PDU);
447   else
448         proto_tree_add_expert(tree, pinfo, &ei_pkcs12_octet_string_expected, tvb, 0, 1);
449 }
450
451 /*--- proto_register_pkcs12 ----------------------------------------------*/
452 void proto_register_pkcs12(void) {
453
454   /* List of fields */
455   static hf_register_info hf[] = {
456     { &hf_pkcs12_X509Certificate_PDU,
457       { "X509Certificate", "pkcs12.X509Certificate",
458         FT_NONE, BASE_NONE, NULL, 0,
459         "pkcs12.X509Certificate", HFILL }},
460 #include "packet-pkcs12-hfarr.c"
461   };
462
463   /* List of subtrees */
464   static gint *ett[] = {
465           &ett_decrypted_pbe,
466 #include "packet-pkcs12-ettarr.c"
467   };
468   static ei_register_info ei[] = {
469       { &ei_pkcs12_octet_string_expected, { "pkcs12.octet_string_expected", PI_PROTOCOL, PI_WARN, "BER Error: OCTET STRING expected", EXPFILL }},
470   };
471
472   module_t *pkcs12_module;
473   expert_module_t* expert_pkcs12;
474
475   /* Register protocol */
476   proto_pkcs12 = proto_register_protocol(PNAME, PSNAME, PFNAME);
477
478   /* Register fields and subtrees */
479   proto_register_field_array(proto_pkcs12, hf, array_length(hf));
480   proto_register_subtree_array(ett, array_length(ett));
481   expert_pkcs12 = expert_register_protocol(proto_pkcs12);
482   expert_register_field_array(expert_pkcs12, ei, array_length(ei));
483
484   /* Register preferences */
485   pkcs12_module = prefs_register_protocol(proto_pkcs12, NULL);
486
487   prefs_register_string_preference(pkcs12_module, "password",
488         "Password to decrypt the file with",
489         "The password to used to decrypt the encrypted elements within"
490         " the PKCS#12 file", &password);
491
492   prefs_register_bool_preference(pkcs12_module, "try_null_password",
493         "Try to decrypt with a empty password",
494         "Whether to try and decrypt the encrypted data within the"
495         " PKCS#12 with a NULL password", &try_null_password);
496
497   new_register_ber_syntax_dissector("PKCS#12", proto_pkcs12, dissect_PFX_PDU);
498   register_ber_oid_syntax(".p12", NULL, "PKCS#12");
499   register_ber_oid_syntax(".pfx", NULL, "PKCS#12");
500 }
501
502
503 /*--- proto_reg_handoff_pkcs12 -------------------------------------------*/
504 void proto_reg_handoff_pkcs12(void) {
505 #include "packet-pkcs12-dis-tab.c"
506
507         register_ber_oid_dissector("1.2.840.113549.1.9.22.1", dissect_X509Certificate_OCTETSTRING_PDU, proto_pkcs12, "x509Certificate");
508
509 }
510