Merge tag 'media/v4.7-1' of git://git.kernel.org/pub/scm/linux/kernel/git/mchehab...
[cascardo/linux.git] / crypto / asymmetric_keys / pkcs7_parser.c
1 /* PKCS#7 parser
2  *
3  * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
4  * Written by David Howells (dhowells@redhat.com)
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public Licence
8  * as published by the Free Software Foundation; either version
9  * 2 of the Licence, or (at your option) any later version.
10  */
11
12 #define pr_fmt(fmt) "PKCS7: "fmt
13 #include <linux/kernel.h>
14 #include <linux/export.h>
15 #include <linux/slab.h>
16 #include <linux/err.h>
17 #include <linux/oid_registry.h>
18 #include <crypto/public_key.h>
19 #include "pkcs7_parser.h"
20 #include "pkcs7-asn1.h"
21
22 struct pkcs7_parse_context {
23         struct pkcs7_message    *msg;           /* Message being constructed */
24         struct pkcs7_signed_info *sinfo;        /* SignedInfo being constructed */
25         struct pkcs7_signed_info **ppsinfo;
26         struct x509_certificate *certs;         /* Certificate cache */
27         struct x509_certificate **ppcerts;
28         unsigned long   data;                   /* Start of data */
29         enum OID        last_oid;               /* Last OID encountered */
30         unsigned        x509_index;
31         unsigned        sinfo_index;
32         const void      *raw_serial;
33         unsigned        raw_serial_size;
34         unsigned        raw_issuer_size;
35         const void      *raw_issuer;
36         const void      *raw_skid;
37         unsigned        raw_skid_size;
38         bool            expect_skid;
39 };
40
41 /*
42  * Free a signed information block.
43  */
44 static void pkcs7_free_signed_info(struct pkcs7_signed_info *sinfo)
45 {
46         if (sinfo) {
47                 kfree(sinfo->sig.s);
48                 kfree(sinfo->sig.digest);
49                 kfree(sinfo->signing_cert_id);
50                 kfree(sinfo);
51         }
52 }
53
54 /**
55  * pkcs7_free_message - Free a PKCS#7 message
56  * @pkcs7: The PKCS#7 message to free
57  */
58 void pkcs7_free_message(struct pkcs7_message *pkcs7)
59 {
60         struct x509_certificate *cert;
61         struct pkcs7_signed_info *sinfo;
62
63         if (pkcs7) {
64                 while (pkcs7->certs) {
65                         cert = pkcs7->certs;
66                         pkcs7->certs = cert->next;
67                         x509_free_certificate(cert);
68                 }
69                 while (pkcs7->crl) {
70                         cert = pkcs7->crl;
71                         pkcs7->crl = cert->next;
72                         x509_free_certificate(cert);
73                 }
74                 while (pkcs7->signed_infos) {
75                         sinfo = pkcs7->signed_infos;
76                         pkcs7->signed_infos = sinfo->next;
77                         pkcs7_free_signed_info(sinfo);
78                 }
79                 kfree(pkcs7);
80         }
81 }
82 EXPORT_SYMBOL_GPL(pkcs7_free_message);
83
84 /*
85  * Check authenticatedAttributes are provided or not provided consistently.
86  */
87 static int pkcs7_check_authattrs(struct pkcs7_message *msg)
88 {
89         struct pkcs7_signed_info *sinfo;
90         bool want = false;
91
92         sinfo = msg->signed_infos;
93         if (sinfo->authattrs) {
94                 want = true;
95                 msg->have_authattrs = true;
96         }
97
98         for (sinfo = sinfo->next; sinfo; sinfo = sinfo->next)
99                 if (!!sinfo->authattrs != want)
100                         goto inconsistent;
101         return 0;
102
103 inconsistent:
104         pr_warn("Inconsistently supplied authAttrs\n");
105         return -EINVAL;
106 }
107
108 /**
109  * pkcs7_parse_message - Parse a PKCS#7 message
110  * @data: The raw binary ASN.1 encoded message to be parsed
111  * @datalen: The size of the encoded message
112  */
113 struct pkcs7_message *pkcs7_parse_message(const void *data, size_t datalen)
114 {
115         struct pkcs7_parse_context *ctx;
116         struct pkcs7_message *msg = ERR_PTR(-ENOMEM);
117         int ret;
118
119         ctx = kzalloc(sizeof(struct pkcs7_parse_context), GFP_KERNEL);
120         if (!ctx)
121                 goto out_no_ctx;
122         ctx->msg = kzalloc(sizeof(struct pkcs7_message), GFP_KERNEL);
123         if (!ctx->msg)
124                 goto out_no_msg;
125         ctx->sinfo = kzalloc(sizeof(struct pkcs7_signed_info), GFP_KERNEL);
126         if (!ctx->sinfo)
127                 goto out_no_sinfo;
128
129         ctx->data = (unsigned long)data;
130         ctx->ppcerts = &ctx->certs;
131         ctx->ppsinfo = &ctx->msg->signed_infos;
132
133         /* Attempt to decode the signature */
134         ret = asn1_ber_decoder(&pkcs7_decoder, ctx, data, datalen);
135         if (ret < 0) {
136                 msg = ERR_PTR(ret);
137                 goto out;
138         }
139
140         ret = pkcs7_check_authattrs(ctx->msg);
141         if (ret < 0)
142                 goto out;
143
144         msg = ctx->msg;
145         ctx->msg = NULL;
146
147 out:
148         while (ctx->certs) {
149                 struct x509_certificate *cert = ctx->certs;
150                 ctx->certs = cert->next;
151                 x509_free_certificate(cert);
152         }
153         pkcs7_free_signed_info(ctx->sinfo);
154 out_no_sinfo:
155         pkcs7_free_message(ctx->msg);
156 out_no_msg:
157         kfree(ctx);
158 out_no_ctx:
159         return msg;
160 }
161 EXPORT_SYMBOL_GPL(pkcs7_parse_message);
162
163 /**
164  * pkcs7_get_content_data - Get access to the PKCS#7 content
165  * @pkcs7: The preparsed PKCS#7 message to access
166  * @_data: Place to return a pointer to the data
167  * @_data_len: Place to return the data length
168  * @want_wrapper: True if the ASN.1 object header should be included in the data
169  *
170  * Get access to the data content of the PKCS#7 message, including, optionally,
171  * the header of the ASN.1 object that contains it.  Returns -ENODATA if the
172  * data object was missing from the message.
173  */
174 int pkcs7_get_content_data(const struct pkcs7_message *pkcs7,
175                            const void **_data, size_t *_data_len,
176                            bool want_wrapper)
177 {
178         size_t wrapper;
179
180         if (!pkcs7->data)
181                 return -ENODATA;
182
183         wrapper = want_wrapper ? pkcs7->data_hdrlen : 0;
184         *_data = pkcs7->data - wrapper;
185         *_data_len = pkcs7->data_len + wrapper;
186         return 0;
187 }
188 EXPORT_SYMBOL_GPL(pkcs7_get_content_data);
189
190 /*
191  * Note an OID when we find one for later processing when we know how
192  * to interpret it.
193  */
194 int pkcs7_note_OID(void *context, size_t hdrlen,
195                    unsigned char tag,
196                    const void *value, size_t vlen)
197 {
198         struct pkcs7_parse_context *ctx = context;
199
200         ctx->last_oid = look_up_OID(value, vlen);
201         if (ctx->last_oid == OID__NR) {
202                 char buffer[50];
203                 sprint_oid(value, vlen, buffer, sizeof(buffer));
204                 printk("PKCS7: Unknown OID: [%lu] %s\n",
205                        (unsigned long)value - ctx->data, buffer);
206         }
207         return 0;
208 }
209
210 /*
211  * Note the digest algorithm for the signature.
212  */
213 int pkcs7_sig_note_digest_algo(void *context, size_t hdrlen,
214                                unsigned char tag,
215                                const void *value, size_t vlen)
216 {
217         struct pkcs7_parse_context *ctx = context;
218
219         switch (ctx->last_oid) {
220         case OID_md4:
221                 ctx->sinfo->sig.hash_algo = "md4";
222                 break;
223         case OID_md5:
224                 ctx->sinfo->sig.hash_algo = "md5";
225                 break;
226         case OID_sha1:
227                 ctx->sinfo->sig.hash_algo = "sha1";
228                 break;
229         case OID_sha256:
230                 ctx->sinfo->sig.hash_algo = "sha256";
231                 break;
232         case OID_sha384:
233                 ctx->sinfo->sig.hash_algo = "sha384";
234                 break;
235         case OID_sha512:
236                 ctx->sinfo->sig.hash_algo = "sha512";
237                 break;
238         case OID_sha224:
239                 ctx->sinfo->sig.hash_algo = "sha224";
240                 break;
241         default:
242                 printk("Unsupported digest algo: %u\n", ctx->last_oid);
243                 return -ENOPKG;
244         }
245         return 0;
246 }
247
248 /*
249  * Note the public key algorithm for the signature.
250  */
251 int pkcs7_sig_note_pkey_algo(void *context, size_t hdrlen,
252                              unsigned char tag,
253                              const void *value, size_t vlen)
254 {
255         struct pkcs7_parse_context *ctx = context;
256
257         switch (ctx->last_oid) {
258         case OID_rsaEncryption:
259                 ctx->sinfo->sig.pkey_algo = "rsa";
260                 break;
261         default:
262                 printk("Unsupported pkey algo: %u\n", ctx->last_oid);
263                 return -ENOPKG;
264         }
265         return 0;
266 }
267
268 /*
269  * We only support signed data [RFC2315 sec 9].
270  */
271 int pkcs7_check_content_type(void *context, size_t hdrlen,
272                              unsigned char tag,
273                              const void *value, size_t vlen)
274 {
275         struct pkcs7_parse_context *ctx = context;
276
277         if (ctx->last_oid != OID_signed_data) {
278                 pr_warn("Only support pkcs7_signedData type\n");
279                 return -EINVAL;
280         }
281
282         return 0;
283 }
284
285 /*
286  * Note the SignedData version
287  */
288 int pkcs7_note_signeddata_version(void *context, size_t hdrlen,
289                                   unsigned char tag,
290                                   const void *value, size_t vlen)
291 {
292         struct pkcs7_parse_context *ctx = context;
293         unsigned version;
294
295         if (vlen != 1)
296                 goto unsupported;
297
298         ctx->msg->version = version = *(const u8 *)value;
299         switch (version) {
300         case 1:
301                 /* PKCS#7 SignedData [RFC2315 sec 9.1]
302                  * CMS ver 1 SignedData [RFC5652 sec 5.1]
303                  */
304                 break;
305         case 3:
306                 /* CMS ver 3 SignedData [RFC2315 sec 5.1] */
307                 break;
308         default:
309                 goto unsupported;
310         }
311
312         return 0;
313
314 unsupported:
315         pr_warn("Unsupported SignedData version\n");
316         return -EINVAL;
317 }
318
319 /*
320  * Note the SignerInfo version
321  */
322 int pkcs7_note_signerinfo_version(void *context, size_t hdrlen,
323                                   unsigned char tag,
324                                   const void *value, size_t vlen)
325 {
326         struct pkcs7_parse_context *ctx = context;
327         unsigned version;
328
329         if (vlen != 1)
330                 goto unsupported;
331
332         version = *(const u8 *)value;
333         switch (version) {
334         case 1:
335                 /* PKCS#7 SignerInfo [RFC2315 sec 9.2]
336                  * CMS ver 1 SignerInfo [RFC5652 sec 5.3]
337                  */
338                 if (ctx->msg->version != 1)
339                         goto version_mismatch;
340                 ctx->expect_skid = false;
341                 break;
342         case 3:
343                 /* CMS ver 3 SignerInfo [RFC2315 sec 5.3] */
344                 if (ctx->msg->version == 1)
345                         goto version_mismatch;
346                 ctx->expect_skid = true;
347                 break;
348         default:
349                 goto unsupported;
350         }
351
352         return 0;
353
354 unsupported:
355         pr_warn("Unsupported SignerInfo version\n");
356         return -EINVAL;
357 version_mismatch:
358         pr_warn("SignedData-SignerInfo version mismatch\n");
359         return -EBADMSG;
360 }
361
362 /*
363  * Extract a certificate and store it in the context.
364  */
365 int pkcs7_extract_cert(void *context, size_t hdrlen,
366                        unsigned char tag,
367                        const void *value, size_t vlen)
368 {
369         struct pkcs7_parse_context *ctx = context;
370         struct x509_certificate *x509;
371
372         if (tag != ((ASN1_UNIV << 6) | ASN1_CONS_BIT | ASN1_SEQ)) {
373                 pr_debug("Cert began with tag %02x at %lu\n",
374                          tag, (unsigned long)ctx - ctx->data);
375                 return -EBADMSG;
376         }
377
378         /* We have to correct for the header so that the X.509 parser can start
379          * from the beginning.  Note that since X.509 stipulates DER, there
380          * probably shouldn't be an EOC trailer - but it is in PKCS#7 (which
381          * stipulates BER).
382          */
383         value -= hdrlen;
384         vlen += hdrlen;
385
386         if (((u8*)value)[1] == 0x80)
387                 vlen += 2; /* Indefinite length - there should be an EOC */
388
389         x509 = x509_cert_parse(value, vlen);
390         if (IS_ERR(x509))
391                 return PTR_ERR(x509);
392
393         x509->index = ++ctx->x509_index;
394         pr_debug("Got cert %u for %s\n", x509->index, x509->subject);
395         pr_debug("- fingerprint %*phN\n", x509->id->len, x509->id->data);
396
397         *ctx->ppcerts = x509;
398         ctx->ppcerts = &x509->next;
399         return 0;
400 }
401
402 /*
403  * Save the certificate list
404  */
405 int pkcs7_note_certificate_list(void *context, size_t hdrlen,
406                                 unsigned char tag,
407                                 const void *value, size_t vlen)
408 {
409         struct pkcs7_parse_context *ctx = context;
410
411         pr_devel("Got cert list (%02x)\n", tag);
412
413         *ctx->ppcerts = ctx->msg->certs;
414         ctx->msg->certs = ctx->certs;
415         ctx->certs = NULL;
416         ctx->ppcerts = &ctx->certs;
417         return 0;
418 }
419
420 /*
421  * Note the content type.
422  */
423 int pkcs7_note_content(void *context, size_t hdrlen,
424                        unsigned char tag,
425                        const void *value, size_t vlen)
426 {
427         struct pkcs7_parse_context *ctx = context;
428
429         if (ctx->last_oid != OID_data &&
430             ctx->last_oid != OID_msIndirectData) {
431                 pr_warn("Unsupported data type %d\n", ctx->last_oid);
432                 return -EINVAL;
433         }
434
435         ctx->msg->data_type = ctx->last_oid;
436         return 0;
437 }
438
439 /*
440  * Extract the data from the message and store that and its content type OID in
441  * the context.
442  */
443 int pkcs7_note_data(void *context, size_t hdrlen,
444                     unsigned char tag,
445                     const void *value, size_t vlen)
446 {
447         struct pkcs7_parse_context *ctx = context;
448
449         pr_debug("Got data\n");
450
451         ctx->msg->data = value;
452         ctx->msg->data_len = vlen;
453         ctx->msg->data_hdrlen = hdrlen;
454         return 0;
455 }
456
457 /*
458  * Parse authenticated attributes.
459  */
460 int pkcs7_sig_note_authenticated_attr(void *context, size_t hdrlen,
461                                       unsigned char tag,
462                                       const void *value, size_t vlen)
463 {
464         struct pkcs7_parse_context *ctx = context;
465         struct pkcs7_signed_info *sinfo = ctx->sinfo;
466         enum OID content_type;
467
468         pr_devel("AuthAttr: %02x %zu [%*ph]\n", tag, vlen, (unsigned)vlen, value);
469
470         switch (ctx->last_oid) {
471         case OID_contentType:
472                 if (__test_and_set_bit(sinfo_has_content_type, &sinfo->aa_set))
473                         goto repeated;
474                 content_type = look_up_OID(value, vlen);
475                 if (content_type != ctx->msg->data_type) {
476                         pr_warn("Mismatch between global data type (%d) and sinfo %u (%d)\n",
477                                 ctx->msg->data_type, sinfo->index,
478                                 content_type);
479                         return -EBADMSG;
480                 }
481                 return 0;
482
483         case OID_signingTime:
484                 if (__test_and_set_bit(sinfo_has_signing_time, &sinfo->aa_set))
485                         goto repeated;
486                 /* Should we check that the signing time is consistent
487                  * with the signer's X.509 cert?
488                  */
489                 return x509_decode_time(&sinfo->signing_time,
490                                         hdrlen, tag, value, vlen);
491
492         case OID_messageDigest:
493                 if (__test_and_set_bit(sinfo_has_message_digest, &sinfo->aa_set))
494                         goto repeated;
495                 if (tag != ASN1_OTS)
496                         return -EBADMSG;
497                 sinfo->msgdigest = value;
498                 sinfo->msgdigest_len = vlen;
499                 return 0;
500
501         case OID_smimeCapabilites:
502                 if (__test_and_set_bit(sinfo_has_smime_caps, &sinfo->aa_set))
503                         goto repeated;
504                 if (ctx->msg->data_type != OID_msIndirectData) {
505                         pr_warn("S/MIME Caps only allowed with Authenticode\n");
506                         return -EKEYREJECTED;
507                 }
508                 return 0;
509
510                 /* Microsoft SpOpusInfo seems to be contain cont[0] 16-bit BE
511                  * char URLs and cont[1] 8-bit char URLs.
512                  *
513                  * Microsoft StatementType seems to contain a list of OIDs that
514                  * are also used as extendedKeyUsage types in X.509 certs.
515                  */
516         case OID_msSpOpusInfo:
517                 if (__test_and_set_bit(sinfo_has_ms_opus_info, &sinfo->aa_set))
518                         goto repeated;
519                 goto authenticode_check;
520         case OID_msStatementType:
521                 if (__test_and_set_bit(sinfo_has_ms_statement_type, &sinfo->aa_set))
522                         goto repeated;
523         authenticode_check:
524                 if (ctx->msg->data_type != OID_msIndirectData) {
525                         pr_warn("Authenticode AuthAttrs only allowed with Authenticode\n");
526                         return -EKEYREJECTED;
527                 }
528                 /* I'm not sure how to validate these */
529                 return 0;
530         default:
531                 return 0;
532         }
533
534 repeated:
535         /* We permit max one item per AuthenticatedAttribute and no repeats */
536         pr_warn("Repeated/multivalue AuthAttrs not permitted\n");
537         return -EKEYREJECTED;
538 }
539
540 /*
541  * Note the set of auth attributes for digestion purposes [RFC2315 sec 9.3]
542  */
543 int pkcs7_sig_note_set_of_authattrs(void *context, size_t hdrlen,
544                                     unsigned char tag,
545                                     const void *value, size_t vlen)
546 {
547         struct pkcs7_parse_context *ctx = context;
548         struct pkcs7_signed_info *sinfo = ctx->sinfo;
549
550         if (!test_bit(sinfo_has_content_type, &sinfo->aa_set) ||
551             !test_bit(sinfo_has_message_digest, &sinfo->aa_set)) {
552                 pr_warn("Missing required AuthAttr\n");
553                 return -EBADMSG;
554         }
555
556         if (ctx->msg->data_type != OID_msIndirectData &&
557             test_bit(sinfo_has_ms_opus_info, &sinfo->aa_set)) {
558                 pr_warn("Unexpected Authenticode AuthAttr\n");
559                 return -EBADMSG;
560         }
561
562         /* We need to switch the 'CONT 0' to a 'SET OF' when we digest */
563         sinfo->authattrs = value - (hdrlen - 1);
564         sinfo->authattrs_len = vlen + (hdrlen - 1);
565         return 0;
566 }
567
568 /*
569  * Note the issuing certificate serial number
570  */
571 int pkcs7_sig_note_serial(void *context, size_t hdrlen,
572                           unsigned char tag,
573                           const void *value, size_t vlen)
574 {
575         struct pkcs7_parse_context *ctx = context;
576         ctx->raw_serial = value;
577         ctx->raw_serial_size = vlen;
578         return 0;
579 }
580
581 /*
582  * Note the issuer's name
583  */
584 int pkcs7_sig_note_issuer(void *context, size_t hdrlen,
585                           unsigned char tag,
586                           const void *value, size_t vlen)
587 {
588         struct pkcs7_parse_context *ctx = context;
589         ctx->raw_issuer = value;
590         ctx->raw_issuer_size = vlen;
591         return 0;
592 }
593
594 /*
595  * Note the issuing cert's subjectKeyIdentifier
596  */
597 int pkcs7_sig_note_skid(void *context, size_t hdrlen,
598                         unsigned char tag,
599                         const void *value, size_t vlen)
600 {
601         struct pkcs7_parse_context *ctx = context;
602
603         pr_devel("SKID: %02x %zu [%*ph]\n", tag, vlen, (unsigned)vlen, value);
604
605         ctx->raw_skid = value;
606         ctx->raw_skid_size = vlen;
607         return 0;
608 }
609
610 /*
611  * Note the signature data
612  */
613 int pkcs7_sig_note_signature(void *context, size_t hdrlen,
614                              unsigned char tag,
615                              const void *value, size_t vlen)
616 {
617         struct pkcs7_parse_context *ctx = context;
618
619         ctx->sinfo->sig.s = kmemdup(value, vlen, GFP_KERNEL);
620         if (!ctx->sinfo->sig.s)
621                 return -ENOMEM;
622
623         ctx->sinfo->sig.s_size = vlen;
624         return 0;
625 }
626
627 /*
628  * Note a signature information block
629  */
630 int pkcs7_note_signed_info(void *context, size_t hdrlen,
631                            unsigned char tag,
632                            const void *value, size_t vlen)
633 {
634         struct pkcs7_parse_context *ctx = context;
635         struct pkcs7_signed_info *sinfo = ctx->sinfo;
636         struct asymmetric_key_id *kid;
637
638         if (ctx->msg->data_type == OID_msIndirectData && !sinfo->authattrs) {
639                 pr_warn("Authenticode requires AuthAttrs\n");
640                 return -EBADMSG;
641         }
642
643         /* Generate cert issuer + serial number key ID */
644         if (!ctx->expect_skid) {
645                 kid = asymmetric_key_generate_id(ctx->raw_serial,
646                                                  ctx->raw_serial_size,
647                                                  ctx->raw_issuer,
648                                                  ctx->raw_issuer_size);
649         } else {
650                 kid = asymmetric_key_generate_id(ctx->raw_skid,
651                                                  ctx->raw_skid_size,
652                                                  "", 0);
653         }
654         if (IS_ERR(kid))
655                 return PTR_ERR(kid);
656
657         pr_devel("SINFO KID: %u [%*phN]\n", kid->len, kid->len, kid->data);
658
659         sinfo->signing_cert_id = kid;
660         sinfo->index = ++ctx->sinfo_index;
661         *ctx->ppsinfo = sinfo;
662         ctx->ppsinfo = &sinfo->next;
663         ctx->sinfo = kzalloc(sizeof(struct pkcs7_signed_info), GFP_KERNEL);
664         if (!ctx->sinfo)
665                 return -ENOMEM;
666         return 0;
667 }