s4:heimdal: import lorikeet-heimdal-200906080040 (commit 904d0124b46eed7a8ad6e5b73e89...
[sfrench/samba-autobuild/.git] / source4 / heimdal / lib / hx509 / ks_p12.c
1 /*
2  * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #include "hx_locl.h"
35
36 struct ks_pkcs12 {
37     hx509_certs certs;
38     char *fn;
39 };
40
41 typedef int (*collector_func)(hx509_context,
42                               struct hx509_collector *,
43                               const void *, size_t,
44                               const PKCS12_Attributes *);
45
46 struct type {
47     const heim_oid *oid;
48     collector_func func;
49 };
50
51 static void
52 parse_pkcs12_type(hx509_context, struct hx509_collector *, const heim_oid *,
53                   const void *, size_t, const PKCS12_Attributes *);
54
55
56 static const PKCS12_Attribute *
57 find_attribute(const PKCS12_Attributes *attrs, const heim_oid *oid)
58 {
59     int i;
60     if (attrs == NULL)
61         return NULL;
62     for (i = 0; i < attrs->len; i++)
63         if (der_heim_oid_cmp(oid, &attrs->val[i].attrId) == 0)
64             return &attrs->val[i];
65     return NULL;
66 }
67
68 static int
69 keyBag_parser(hx509_context context,
70               struct hx509_collector *c,
71               const void *data, size_t length,
72               const PKCS12_Attributes *attrs)
73 {
74     const PKCS12_Attribute *attr;
75     PKCS8PrivateKeyInfo ki;
76     const heim_octet_string *os = NULL;
77     int ret;
78
79     attr = find_attribute(attrs, &asn1_oid_id_pkcs_9_at_localKeyId);
80     if (attr)
81         os = &attr->attrValues;
82
83     ret = decode_PKCS8PrivateKeyInfo(data, length, &ki, NULL);
84     if (ret)
85         return ret;
86
87     _hx509_collector_private_key_add(context,
88                                      c,
89                                      &ki.privateKeyAlgorithm,
90                                      NULL,
91                                      &ki.privateKey,
92                                      os);
93     free_PKCS8PrivateKeyInfo(&ki);
94     return 0;
95 }
96
97 static int
98 ShroudedKeyBag_parser(hx509_context context,
99                       struct hx509_collector *c,
100                       const void *data, size_t length,
101                       const PKCS12_Attributes *attrs)
102 {
103     PKCS8EncryptedPrivateKeyInfo pk;
104     heim_octet_string content;
105     int ret;
106
107     memset(&pk, 0, sizeof(pk));
108
109     ret = decode_PKCS8EncryptedPrivateKeyInfo(data, length, &pk, NULL);
110     if (ret)
111         return ret;
112
113     ret = _hx509_pbe_decrypt(context,
114                              _hx509_collector_get_lock(c),
115                              &pk.encryptionAlgorithm,
116                              &pk.encryptedData,
117                              &content);
118     free_PKCS8EncryptedPrivateKeyInfo(&pk);
119     if (ret)
120         return ret;
121
122     ret = keyBag_parser(context, c, content.data, content.length, attrs);
123     der_free_octet_string(&content);
124     return ret;
125 }
126
127 static int
128 certBag_parser(hx509_context context,
129                struct hx509_collector *c,
130                const void *data, size_t length,
131                const PKCS12_Attributes *attrs)
132 {
133     heim_octet_string os;
134     hx509_cert cert;
135     PKCS12_CertBag cb;
136     int ret;
137
138     ret = decode_PKCS12_CertBag(data, length, &cb, NULL);
139     if (ret)
140         return ret;
141
142     if (der_heim_oid_cmp(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certType)) {
143         free_PKCS12_CertBag(&cb);
144         return 0;
145     }
146
147     ret = decode_PKCS12_OctetString(cb.certValue.data,
148                                     cb.certValue.length,
149                                     &os,
150                                     NULL);
151     free_PKCS12_CertBag(&cb);
152     if (ret)
153         return ret;
154
155     ret = hx509_cert_init_data(context, os.data, os.length, &cert);
156     der_free_octet_string(&os);
157     if (ret)
158         return ret;
159
160     ret = _hx509_collector_certs_add(context, c, cert);
161     if (ret) {
162         hx509_cert_free(cert);
163         return ret;
164     }
165
166     {
167         const PKCS12_Attribute *attr;
168         const heim_oid *oids[] = {
169             &asn1_oid_id_pkcs_9_at_localKeyId, &asn1_oid_id_pkcs_9_at_friendlyName
170         };
171         int i;
172
173         for  (i = 0; i < sizeof(oids)/sizeof(oids[0]); i++) {
174             const heim_oid *oid = oids[i];
175             attr = find_attribute(attrs, oid);
176             if (attr)
177                 _hx509_set_cert_attribute(context, cert, oid,
178                                           &attr->attrValues);
179         }       
180     }
181
182     hx509_cert_free(cert);
183
184     return 0;
185 }
186
187 static int
188 parse_safe_content(hx509_context context,
189                    struct hx509_collector *c,
190                    const unsigned char *p, size_t len)
191 {
192     PKCS12_SafeContents sc;
193     int ret, i;
194
195     memset(&sc, 0, sizeof(sc));
196
197     ret = decode_PKCS12_SafeContents(p, len, &sc, NULL);
198     if (ret)
199         return ret;
200
201     for (i = 0; i < sc.len ; i++)
202         parse_pkcs12_type(context,
203                           c,
204                           &sc.val[i].bagId,
205                           sc.val[i].bagValue.data,
206                           sc.val[i].bagValue.length,
207                           sc.val[i].bagAttributes);
208
209     free_PKCS12_SafeContents(&sc);
210     return 0;
211 }
212
213 static int
214 safeContent_parser(hx509_context context,
215                    struct hx509_collector *c,
216                    const void *data, size_t length,
217                    const PKCS12_Attributes *attrs)
218 {
219     heim_octet_string os;
220     int ret;
221
222     ret = decode_PKCS12_OctetString(data, length, &os, NULL);
223     if (ret)
224         return ret;
225     ret = parse_safe_content(context, c, os.data, os.length);
226     der_free_octet_string(&os);
227     return ret;
228 }
229
230 static int
231 encryptedData_parser(hx509_context context,
232                      struct hx509_collector *c,
233                      const void *data, size_t length,
234                      const PKCS12_Attributes *attrs)
235 {
236     heim_octet_string content;
237     heim_oid contentType;
238     int ret;
239                 
240     memset(&contentType, 0, sizeof(contentType));
241
242     ret = hx509_cms_decrypt_encrypted(context,
243                                       _hx509_collector_get_lock(c),
244                                       data, length,
245                                       &contentType,
246                                       &content);
247     if (ret)
248         return ret;
249
250     if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) == 0)
251         ret = parse_safe_content(context, c, content.data, content.length);
252
253     der_free_octet_string(&content);
254     der_free_oid(&contentType);
255     return ret;
256 }
257
258 static int
259 envelopedData_parser(hx509_context context,
260                      struct hx509_collector *c,
261                      const void *data, size_t length,
262                      const PKCS12_Attributes *attrs)
263 {
264     heim_octet_string content;
265     heim_oid contentType;
266     hx509_lock lock;
267     int ret;
268                 
269     memset(&contentType, 0, sizeof(contentType));
270
271     lock = _hx509_collector_get_lock(c);
272
273     ret = hx509_cms_unenvelope(context,
274                                _hx509_lock_unlock_certs(lock),
275                                0,
276                                data, length,
277                                NULL,
278                                0,
279                                &contentType,
280                                &content);
281     if (ret) {
282         hx509_set_error_string(context, HX509_ERROR_APPEND, ret,
283                                "PKCS12 failed to unenvelope");
284         return ret;
285     }
286
287     if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) == 0)
288         ret = parse_safe_content(context, c, content.data, content.length);
289
290     der_free_octet_string(&content);
291     der_free_oid(&contentType);
292
293     return ret;
294 }
295
296
297 struct type bagtypes[] = {
298     { &asn1_oid_id_pkcs12_keyBag, keyBag_parser },
299     { &asn1_oid_id_pkcs12_pkcs8ShroudedKeyBag, ShroudedKeyBag_parser },
300     { &asn1_oid_id_pkcs12_certBag, certBag_parser },
301     { &asn1_oid_id_pkcs7_data, safeContent_parser },
302     { &asn1_oid_id_pkcs7_encryptedData, encryptedData_parser },
303     { &asn1_oid_id_pkcs7_envelopedData, envelopedData_parser }
304 };
305
306 static void
307 parse_pkcs12_type(hx509_context context,
308                   struct hx509_collector *c,
309                   const heim_oid *oid,
310                   const void *data, size_t length,
311                   const PKCS12_Attributes *attrs)
312 {
313     int i;
314
315     for (i = 0; i < sizeof(bagtypes)/sizeof(bagtypes[0]); i++)
316         if (der_heim_oid_cmp(bagtypes[i].oid, oid) == 0)
317             (*bagtypes[i].func)(context, c, data, length, attrs);
318 }
319
320 static int
321 p12_init(hx509_context context,
322          hx509_certs certs, void **data, int flags,
323          const char *residue, hx509_lock lock)
324 {
325     struct ks_pkcs12 *p12;
326     size_t len;
327     void *buf;
328     PKCS12_PFX pfx;
329     PKCS12_AuthenticatedSafe as;
330     int ret, i;
331     struct hx509_collector *c;
332
333     *data = NULL;
334
335     if (lock == NULL)
336         lock = _hx509_empty_lock;
337
338     ret = _hx509_collector_alloc(context, lock, &c);
339     if (ret)
340         return ret;
341
342     p12 = calloc(1, sizeof(*p12));
343     if (p12 == NULL) {
344         ret = ENOMEM;
345         hx509_set_error_string(context, 0, ret, "out of memory");
346         goto out;
347     }
348
349     p12->fn = strdup(residue);
350     if (p12->fn == NULL) {
351         ret = ENOMEM;
352         hx509_set_error_string(context, 0, ret, "out of memory");
353         goto out;
354     }
355
356     if (flags & HX509_CERTS_CREATE) {
357         ret = hx509_certs_init(context, "MEMORY:ks-file-create",
358                                0, lock, &p12->certs);
359         if (ret == 0)
360             *data = p12;
361         goto out;
362     }
363
364     ret = rk_undumpdata(residue, &buf, &len);
365     if (ret) {
366         hx509_clear_error_string(context);
367         goto out;
368     }
369
370     ret = decode_PKCS12_PFX(buf, len, &pfx, NULL);
371     rk_xfree(buf);
372     if (ret) {
373         hx509_set_error_string(context, 0, ret,
374                                "Failed to decode the PFX in %s", residue);
375         goto out;
376     }
377
378     if (der_heim_oid_cmp(&pfx.authSafe.contentType, &asn1_oid_id_pkcs7_data) != 0) {
379         free_PKCS12_PFX(&pfx);
380         ret = EINVAL;
381         hx509_set_error_string(context, 0, ret,
382                                "PKCS PFX isn't a pkcs7-data container");
383         goto out;
384     }
385
386     if (pfx.authSafe.content == NULL) {
387         free_PKCS12_PFX(&pfx);
388         ret = EINVAL;
389         hx509_set_error_string(context, 0, ret,
390                                "PKCS PFX missing data");
391         goto out;
392     }
393
394     {
395         heim_octet_string asdata;
396
397         ret = decode_PKCS12_OctetString(pfx.authSafe.content->data,
398                                         pfx.authSafe.content->length,
399                                         &asdata,
400                                         NULL);
401         free_PKCS12_PFX(&pfx);
402         if (ret) {
403             hx509_clear_error_string(context);
404             goto out;
405         }
406         ret = decode_PKCS12_AuthenticatedSafe(asdata.data,
407                                               asdata.length,
408                                               &as,
409                                               NULL);
410         der_free_octet_string(&asdata);
411         if (ret) {
412             hx509_clear_error_string(context);
413             goto out;
414         }
415     }
416
417     for (i = 0; i < as.len; i++)
418         parse_pkcs12_type(context,
419                           c,
420                           &as.val[i].contentType,
421                           as.val[i].content->data,
422                           as.val[i].content->length,
423                           NULL);
424
425     free_PKCS12_AuthenticatedSafe(&as);
426
427     ret = _hx509_collector_collect_certs(context, c, &p12->certs);
428     if (ret == 0)
429         *data = p12;
430
431 out:
432     _hx509_collector_free(c);
433
434     if (ret && p12) {
435         if (p12->fn)
436             free(p12->fn);
437         if (p12->certs)
438             hx509_certs_free(&p12->certs);
439         free(p12);
440     }
441
442     return ret;
443 }
444
445 static int
446 addBag(hx509_context context,
447        PKCS12_AuthenticatedSafe *as,
448        const heim_oid *oid,
449        void *data,
450        size_t length)
451 {
452     void *ptr;
453     int ret;
454
455     ptr = realloc(as->val, sizeof(as->val[0]) * (as->len + 1));
456     if (ptr == NULL) {
457         hx509_set_error_string(context, 0, ENOMEM, "out of memory");
458         return ENOMEM;
459     }
460     as->val = ptr;
461
462     ret = der_copy_oid(oid, &as->val[as->len].contentType);
463     if (ret) {
464         hx509_set_error_string(context, 0, ret, "out of memory");
465         return ret;
466     }
467
468     as->val[as->len].content = calloc(1, sizeof(*as->val[0].content));
469     if (as->val[as->len].content == NULL) {
470         der_free_oid(&as->val[as->len].contentType);
471         hx509_set_error_string(context, 0, ENOMEM, "malloc out of memory");
472         return ENOMEM;
473     }
474
475     as->val[as->len].content->data = data;
476     as->val[as->len].content->length = length;
477
478     as->len++;
479
480     return 0;
481 }
482
483 static int
484 store_func(hx509_context context, void *ctx, hx509_cert c)
485 {
486     PKCS12_AuthenticatedSafe *as = ctx;
487     PKCS12_OctetString os;
488     PKCS12_CertBag cb;
489     size_t size;
490     int ret;
491
492     memset(&os, 0, sizeof(os));
493     memset(&cb, 0, sizeof(cb));
494
495     os.data = NULL;
496     os.length = 0;
497
498     ret = hx509_cert_binary(context, c, &os);
499     if (ret)
500         return ret;
501
502     ASN1_MALLOC_ENCODE(PKCS12_OctetString,
503                        cb.certValue.data,cb.certValue.length,
504                        &os, &size, ret);
505     free(os.data);
506     if (ret)
507         goto out;
508     ret = der_copy_oid(&asn1_oid_id_pkcs_9_at_certTypes_x509, &cb.certType);
509     if (ret) {
510         free_PKCS12_CertBag(&cb);
511         goto out;
512     }
513     ASN1_MALLOC_ENCODE(PKCS12_CertBag, os.data, os.length,
514                        &cb, &size, ret);
515     free_PKCS12_CertBag(&cb);
516     if (ret)
517         goto out;
518
519     ret = addBag(context, as, &asn1_oid_id_pkcs12_certBag, os.data, os.length);
520
521     if (_hx509_cert_private_key_exportable(c)) {
522         hx509_private_key key = _hx509_cert_private_key(c);
523         PKCS8PrivateKeyInfo pki;
524
525         memset(&pki, 0, sizeof(pki));
526
527         ret = der_parse_hex_heim_integer("00", &pki.version);
528         if (ret)
529             return ret;
530         ret = _hx509_private_key_oid(context, key,
531                                      &pki.privateKeyAlgorithm.algorithm);
532         if (ret) {
533             free_PKCS8PrivateKeyInfo(&pki);
534             return ret;
535         }
536         ret = _hx509_private_key_export(context,
537                                         _hx509_cert_private_key(c),
538                                         &pki.privateKey);
539         if (ret) {
540             free_PKCS8PrivateKeyInfo(&pki);
541             return ret;
542         }
543         /* set attribute, asn1_oid_id_pkcs_9_at_localKeyId */
544
545         ASN1_MALLOC_ENCODE(PKCS8PrivateKeyInfo, os.data, os.length,
546                            &pki, &size, ret);
547         free_PKCS8PrivateKeyInfo(&pki);
548         if (ret)
549             return ret;
550
551         ret = addBag(context, as, &asn1_oid_id_pkcs12_keyBag, os.data, os.length);
552         if (ret)
553             return ret;
554     }
555
556 out:
557     return ret;
558 }
559
560 static int
561 p12_store(hx509_context context,
562           hx509_certs certs, void *data, int flags, hx509_lock lock)
563 {
564     struct ks_pkcs12 *p12 = data;
565     PKCS12_PFX pfx;
566     PKCS12_AuthenticatedSafe as;
567     PKCS12_OctetString asdata;
568     size_t size;
569     int ret;
570
571     memset(&as, 0, sizeof(as));
572     memset(&pfx, 0, sizeof(pfx));
573
574     ret = hx509_certs_iter(context, p12->certs, store_func, &as);
575     if (ret)
576         goto out;
577
578     ASN1_MALLOC_ENCODE(PKCS12_AuthenticatedSafe, asdata.data, asdata.length,
579                        &as, &size, ret);
580     free_PKCS12_AuthenticatedSafe(&as);
581     if (ret)
582         return ret;
583                 
584     ret = der_parse_hex_heim_integer("03", &pfx.version);
585     if (ret) {
586         free(asdata.data);
587         goto out;
588     }
589
590     pfx.authSafe.content = calloc(1, sizeof(*pfx.authSafe.content));
591
592     ASN1_MALLOC_ENCODE(PKCS12_OctetString,
593                        pfx.authSafe.content->data,
594                        pfx.authSafe.content->length,
595                        &asdata, &size, ret);
596     free(asdata.data);
597     if (ret)
598         goto out;
599
600     ret = der_copy_oid(&asn1_oid_id_pkcs7_data, &pfx.authSafe.contentType);
601     if (ret)
602         goto out;
603
604     ASN1_MALLOC_ENCODE(PKCS12_PFX, asdata.data, asdata.length,
605                        &pfx, &size, ret);
606     if (ret)
607         goto out;
608
609 #if 0
610     const struct _hx509_password *pw;
611
612     pw = _hx509_lock_get_passwords(lock);
613     if (pw != NULL) {
614         pfx.macData = calloc(1, sizeof(*pfx.macData));
615         if (pfx.macData == NULL) {
616             ret = ENOMEM;
617             hx509_set_error_string(context, 0, ret, "malloc out of memory");
618             return ret;
619         }
620         if (pfx.macData == NULL) {
621             free(asdata.data);
622             goto out;
623         }
624     }
625     ret = calculate_hash(&aspath, pw, pfx.macData);
626 #endif
627
628     rk_dumpdata(p12->fn, asdata.data, asdata.length);
629     free(asdata.data);
630
631 out:
632     free_PKCS12_AuthenticatedSafe(&as);
633     free_PKCS12_PFX(&pfx);
634
635     return ret;
636 }
637
638
639 static int
640 p12_free(hx509_certs certs, void *data)
641 {
642     struct ks_pkcs12 *p12 = data;
643     hx509_certs_free(&p12->certs);
644     free(p12->fn);
645     free(p12);
646     return 0;
647 }
648
649 static int
650 p12_add(hx509_context context, hx509_certs certs, void *data, hx509_cert c)
651 {
652     struct ks_pkcs12 *p12 = data;
653     return hx509_certs_add(context, p12->certs, c);
654 }
655
656 static int
657 p12_iter_start(hx509_context context,
658                hx509_certs certs,
659                void *data,
660                void **cursor)
661 {
662     struct ks_pkcs12 *p12 = data;
663     return hx509_certs_start_seq(context, p12->certs, cursor);
664 }
665
666 static int
667 p12_iter(hx509_context context,
668          hx509_certs certs,
669          void *data,
670          void *cursor,
671          hx509_cert *cert)
672 {
673     struct ks_pkcs12 *p12 = data;
674     return hx509_certs_next_cert(context, p12->certs, cursor, cert);
675 }
676
677 static int
678 p12_iter_end(hx509_context context,
679              hx509_certs certs,
680              void *data,
681              void *cursor)
682 {
683     struct ks_pkcs12 *p12 = data;
684     return hx509_certs_end_seq(context, p12->certs, cursor);
685 }
686
687 static struct hx509_keyset_ops keyset_pkcs12 = {
688     "PKCS12",
689     0,
690     p12_init,
691     p12_store,
692     p12_free,
693     p12_add,
694     NULL,
695     p12_iter_start,
696     p12_iter,
697     p12_iter_end
698 };
699
700 void
701 _hx509_ks_pkcs12_register(hx509_context context)
702 {
703     _hx509_ks_register(context, &keyset_pkcs12);
704 }