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