blob: 4e41cffd2301dc1d906556b447e297fd51393dce [file] [log] [blame]
AKASHI Takahiro591535c2019-11-13 09:45:00 +09001// SPDX-License-Identifier: GPL-2.0-or-later
2/* X.509 certificate parser
3 *
4 * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
6 */
7
8#define pr_fmt(fmt) "X.509: "fmt
Simon Glassd66c5f72020-02-03 07:36:15 -07009#include <dm/devres.h>
AKASHI Takahiro591535c2019-11-13 09:45:00 +090010#include <linux/kernel.h>
11#ifndef __UBOOT__
12#include <linux/export.h>
13#include <linux/slab.h>
14#endif
15#include <linux/err.h>
16#include <linux/oid_registry.h>
17#ifdef __UBOOT__
18#include <linux/string.h>
19#endif
20#include <crypto/public_key.h>
21#include "x509_parser.h"
22#include "x509.asn1.h"
23#include "x509_akid.asn1.h"
24
25struct x509_parse_context {
26 struct x509_certificate *cert; /* Certificate being constructed */
27 unsigned long data; /* Start of data */
28 const void *cert_start; /* Start of cert content */
29 const void *key; /* Key data */
30 size_t key_size; /* Size of key data */
31 const void *params; /* Key parameters */
32 size_t params_size; /* Size of key parameters */
33 enum OID key_algo; /* Public key algorithm */
34 enum OID last_oid; /* Last OID encountered */
35 enum OID algo_oid; /* Algorithm OID */
36 unsigned char nr_mpi; /* Number of MPIs stored */
37 u8 o_size; /* Size of organizationName (O) */
38 u8 cn_size; /* Size of commonName (CN) */
39 u8 email_size; /* Size of emailAddress */
40 u16 o_offset; /* Offset of organizationName (O) */
41 u16 cn_offset; /* Offset of commonName (CN) */
42 u16 email_offset; /* Offset of emailAddress */
43 unsigned raw_akid_size;
44 const void *raw_akid; /* Raw authorityKeyId in ASN.1 */
45 const void *akid_raw_issuer; /* Raw directoryName in authorityKeyId */
46 unsigned akid_raw_issuer_size;
47};
48
49/*
50 * Free an X.509 certificate
51 */
52void x509_free_certificate(struct x509_certificate *cert)
53{
54 if (cert) {
55 public_key_free(cert->pub);
56 public_key_signature_free(cert->sig);
57 kfree(cert->issuer);
58 kfree(cert->subject);
59 kfree(cert->id);
60 kfree(cert->skid);
61 kfree(cert);
62 }
63}
64EXPORT_SYMBOL_GPL(x509_free_certificate);
65
66/*
67 * Parse an X.509 certificate
68 */
69struct x509_certificate *x509_cert_parse(const void *data, size_t datalen)
70{
71 struct x509_certificate *cert;
72 struct x509_parse_context *ctx;
73 struct asymmetric_key_id *kid;
74 long ret;
75
76 ret = -ENOMEM;
77 cert = kzalloc(sizeof(struct x509_certificate), GFP_KERNEL);
78 if (!cert)
79 goto error_no_cert;
80 cert->pub = kzalloc(sizeof(struct public_key), GFP_KERNEL);
81 if (!cert->pub)
82 goto error_no_ctx;
83 cert->sig = kzalloc(sizeof(struct public_key_signature), GFP_KERNEL);
84 if (!cert->sig)
85 goto error_no_ctx;
86 ctx = kzalloc(sizeof(struct x509_parse_context), GFP_KERNEL);
87 if (!ctx)
88 goto error_no_ctx;
89
90 ctx->cert = cert;
91 ctx->data = (unsigned long)data;
92
93 /* Attempt to decode the certificate */
94 ret = asn1_ber_decoder(&x509_decoder, ctx, data, datalen);
95 if (ret < 0)
96 goto error_decode;
97
98 /* Decode the AuthorityKeyIdentifier */
99 if (ctx->raw_akid) {
100 pr_devel("AKID: %u %*phN\n",
101 ctx->raw_akid_size, ctx->raw_akid_size, ctx->raw_akid);
102 ret = asn1_ber_decoder(&x509_akid_decoder, ctx,
103 ctx->raw_akid, ctx->raw_akid_size);
104 if (ret < 0) {
105 pr_warn("Couldn't decode AuthKeyIdentifier\n");
106 goto error_decode;
107 }
108 }
109
110 ret = -ENOMEM;
111 cert->pub->key = kmemdup(ctx->key, ctx->key_size, GFP_KERNEL);
112 if (!cert->pub->key)
113 goto error_decode;
114
115 cert->pub->keylen = ctx->key_size;
116
117 cert->pub->params = kmemdup(ctx->params, ctx->params_size, GFP_KERNEL);
118 if (!cert->pub->params)
119 goto error_decode;
120
121 cert->pub->paramlen = ctx->params_size;
122 cert->pub->algo = ctx->key_algo;
123
124 /* Grab the signature bits */
125 ret = x509_get_sig_params(cert);
126 if (ret < 0)
127 goto error_decode;
128
129 /* Generate cert issuer + serial number key ID */
130 kid = asymmetric_key_generate_id(cert->raw_serial,
131 cert->raw_serial_size,
132 cert->raw_issuer,
133 cert->raw_issuer_size);
134 if (IS_ERR(kid)) {
135 ret = PTR_ERR(kid);
136 goto error_decode;
137 }
138 cert->id = kid;
139
140#ifndef __UBOOT__
141 /* Detect self-signed certificates */
142 ret = x509_check_for_self_signed(cert);
143 if (ret < 0)
144 goto error_decode;
145#endif
146
147 kfree(ctx);
148 return cert;
149
150error_decode:
151 kfree(ctx);
152error_no_ctx:
153 x509_free_certificate(cert);
154error_no_cert:
155 return ERR_PTR(ret);
156}
157EXPORT_SYMBOL_GPL(x509_cert_parse);
158
159/*
160 * Note an OID when we find one for later processing when we know how
161 * to interpret it.
162 */
163int x509_note_OID(void *context, size_t hdrlen,
164 unsigned char tag,
165 const void *value, size_t vlen)
166{
167 struct x509_parse_context *ctx = context;
168
169 ctx->last_oid = look_up_OID(value, vlen);
170 if (ctx->last_oid == OID__NR) {
171 char buffer[50];
172 sprint_oid(value, vlen, buffer, sizeof(buffer));
173 pr_debug("Unknown OID: [%lu] %s\n",
174 (unsigned long)value - ctx->data, buffer);
175 }
176 return 0;
177}
178
179/*
180 * Save the position of the TBS data so that we can check the signature over it
181 * later.
182 */
183int x509_note_tbs_certificate(void *context, size_t hdrlen,
184 unsigned char tag,
185 const void *value, size_t vlen)
186{
187 struct x509_parse_context *ctx = context;
188
189 pr_debug("x509_note_tbs_certificate(,%zu,%02x,%ld,%zu)!\n",
190 hdrlen, tag, (unsigned long)value - ctx->data, vlen);
191
192 ctx->cert->tbs = value - hdrlen;
193 ctx->cert->tbs_size = vlen + hdrlen;
194 return 0;
195}
196
197/*
198 * Record the public key algorithm
199 */
200int x509_note_pkey_algo(void *context, size_t hdrlen,
201 unsigned char tag,
202 const void *value, size_t vlen)
203{
204 struct x509_parse_context *ctx = context;
205
206 pr_debug("PubKey Algo: %u\n", ctx->last_oid);
207
208 switch (ctx->last_oid) {
209 case OID_md2WithRSAEncryption:
210 case OID_md3WithRSAEncryption:
211 default:
212 return -ENOPKG; /* Unsupported combination */
213
214 case OID_md4WithRSAEncryption:
215 ctx->cert->sig->hash_algo = "md4";
216 goto rsa_pkcs1;
217
218 case OID_sha1WithRSAEncryption:
219 ctx->cert->sig->hash_algo = "sha1";
220 goto rsa_pkcs1;
221
222 case OID_sha256WithRSAEncryption:
223 ctx->cert->sig->hash_algo = "sha256";
224 goto rsa_pkcs1;
225
226 case OID_sha384WithRSAEncryption:
227 ctx->cert->sig->hash_algo = "sha384";
228 goto rsa_pkcs1;
229
230 case OID_sha512WithRSAEncryption:
231 ctx->cert->sig->hash_algo = "sha512";
232 goto rsa_pkcs1;
233
234 case OID_sha224WithRSAEncryption:
235 ctx->cert->sig->hash_algo = "sha224";
236 goto rsa_pkcs1;
237
238 case OID_gost2012Signature256:
239 ctx->cert->sig->hash_algo = "streebog256";
240 goto ecrdsa;
241
242 case OID_gost2012Signature512:
243 ctx->cert->sig->hash_algo = "streebog512";
244 goto ecrdsa;
245 }
246
247rsa_pkcs1:
248 ctx->cert->sig->pkey_algo = "rsa";
249 ctx->cert->sig->encoding = "pkcs1";
250 ctx->algo_oid = ctx->last_oid;
251 return 0;
252ecrdsa:
253 ctx->cert->sig->pkey_algo = "ecrdsa";
254 ctx->cert->sig->encoding = "raw";
255 ctx->algo_oid = ctx->last_oid;
256 return 0;
257}
258
259/*
260 * Note the whereabouts and type of the signature.
261 */
262int x509_note_signature(void *context, size_t hdrlen,
263 unsigned char tag,
264 const void *value, size_t vlen)
265{
266 struct x509_parse_context *ctx = context;
267
268 pr_debug("Signature type: %u size %zu\n", ctx->last_oid, vlen);
269
270 if (ctx->last_oid != ctx->algo_oid) {
271 pr_warn("Got cert with pkey (%u) and sig (%u) algorithm OIDs\n",
272 ctx->algo_oid, ctx->last_oid);
273 return -EINVAL;
274 }
275
276 if (strcmp(ctx->cert->sig->pkey_algo, "rsa") == 0 ||
277 strcmp(ctx->cert->sig->pkey_algo, "ecrdsa") == 0) {
278 /* Discard the BIT STRING metadata */
279 if (vlen < 1 || *(const u8 *)value != 0)
280 return -EBADMSG;
281
282 value++;
283 vlen--;
284 }
285
286 ctx->cert->raw_sig = value;
287 ctx->cert->raw_sig_size = vlen;
288 return 0;
289}
290
291/*
292 * Note the certificate serial number
293 */
294int x509_note_serial(void *context, size_t hdrlen,
295 unsigned char tag,
296 const void *value, size_t vlen)
297{
298 struct x509_parse_context *ctx = context;
299 ctx->cert->raw_serial = value;
300 ctx->cert->raw_serial_size = vlen;
301 return 0;
302}
303
304/*
305 * Note some of the name segments from which we'll fabricate a name.
306 */
307int x509_extract_name_segment(void *context, size_t hdrlen,
308 unsigned char tag,
309 const void *value, size_t vlen)
310{
311 struct x509_parse_context *ctx = context;
312
313 switch (ctx->last_oid) {
314 case OID_commonName:
315 ctx->cn_size = vlen;
316 ctx->cn_offset = (unsigned long)value - ctx->data;
317 break;
318 case OID_organizationName:
319 ctx->o_size = vlen;
320 ctx->o_offset = (unsigned long)value - ctx->data;
321 break;
322 case OID_email_address:
323 ctx->email_size = vlen;
324 ctx->email_offset = (unsigned long)value - ctx->data;
325 break;
326 default:
327 break;
328 }
329
330 return 0;
331}
332
333/*
334 * Fabricate and save the issuer and subject names
335 */
336static int x509_fabricate_name(struct x509_parse_context *ctx, size_t hdrlen,
337 unsigned char tag,
338 char **_name, size_t vlen)
339{
340 const void *name, *data = (const void *)ctx->data;
341 size_t namesize;
342 char *buffer;
343
344 if (*_name)
345 return -EINVAL;
346
347 /* Empty name string if no material */
348 if (!ctx->cn_size && !ctx->o_size && !ctx->email_size) {
349 buffer = kmalloc(1, GFP_KERNEL);
350 if (!buffer)
351 return -ENOMEM;
352 buffer[0] = 0;
353 goto done;
354 }
355
356 if (ctx->cn_size && ctx->o_size) {
357 /* Consider combining O and CN, but use only the CN if it is
358 * prefixed by the O, or a significant portion thereof.
359 */
360 namesize = ctx->cn_size;
361 name = data + ctx->cn_offset;
362 if (ctx->cn_size >= ctx->o_size &&
363 memcmp(data + ctx->cn_offset, data + ctx->o_offset,
364 ctx->o_size) == 0)
365 goto single_component;
366 if (ctx->cn_size >= 7 &&
367 ctx->o_size >= 7 &&
368 memcmp(data + ctx->cn_offset, data + ctx->o_offset, 7) == 0)
369 goto single_component;
370
371 buffer = kmalloc(ctx->o_size + 2 + ctx->cn_size + 1,
372 GFP_KERNEL);
373 if (!buffer)
374 return -ENOMEM;
375
376 memcpy(buffer,
377 data + ctx->o_offset, ctx->o_size);
378 buffer[ctx->o_size + 0] = ':';
379 buffer[ctx->o_size + 1] = ' ';
380 memcpy(buffer + ctx->o_size + 2,
381 data + ctx->cn_offset, ctx->cn_size);
382 buffer[ctx->o_size + 2 + ctx->cn_size] = 0;
383 goto done;
384
385 } else if (ctx->cn_size) {
386 namesize = ctx->cn_size;
387 name = data + ctx->cn_offset;
388 } else if (ctx->o_size) {
389 namesize = ctx->o_size;
390 name = data + ctx->o_offset;
391 } else {
392 namesize = ctx->email_size;
393 name = data + ctx->email_offset;
394 }
395
396single_component:
397 buffer = kmalloc(namesize + 1, GFP_KERNEL);
398 if (!buffer)
399 return -ENOMEM;
400 memcpy(buffer, name, namesize);
401 buffer[namesize] = 0;
402
403done:
404 *_name = buffer;
405 ctx->cn_size = 0;
406 ctx->o_size = 0;
407 ctx->email_size = 0;
408 return 0;
409}
410
411int x509_note_issuer(void *context, size_t hdrlen,
412 unsigned char tag,
413 const void *value, size_t vlen)
414{
415 struct x509_parse_context *ctx = context;
416 ctx->cert->raw_issuer = value;
417 ctx->cert->raw_issuer_size = vlen;
418 return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->issuer, vlen);
419}
420
421int x509_note_subject(void *context, size_t hdrlen,
422 unsigned char tag,
423 const void *value, size_t vlen)
424{
425 struct x509_parse_context *ctx = context;
426 ctx->cert->raw_subject = value;
427 ctx->cert->raw_subject_size = vlen;
428 return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->subject, vlen);
429}
430
431/*
432 * Extract the parameters for the public key
433 */
434int x509_note_params(void *context, size_t hdrlen,
435 unsigned char tag,
436 const void *value, size_t vlen)
437{
438 struct x509_parse_context *ctx = context;
439
440 /*
441 * AlgorithmIdentifier is used three times in the x509, we should skip
442 * first and ignore third, using second one which is after subject and
443 * before subjectPublicKey.
444 */
445 if (!ctx->cert->raw_subject || ctx->key)
446 return 0;
447 ctx->params = value - hdrlen;
448 ctx->params_size = vlen + hdrlen;
449 return 0;
450}
451
452/*
453 * Extract the data for the public key algorithm
454 */
455int x509_extract_key_data(void *context, size_t hdrlen,
456 unsigned char tag,
457 const void *value, size_t vlen)
458{
459 struct x509_parse_context *ctx = context;
460
461 ctx->key_algo = ctx->last_oid;
462 if (ctx->last_oid == OID_rsaEncryption)
463 ctx->cert->pub->pkey_algo = "rsa";
464 else if (ctx->last_oid == OID_gost2012PKey256 ||
465 ctx->last_oid == OID_gost2012PKey512)
466 ctx->cert->pub->pkey_algo = "ecrdsa";
467 else
468 return -ENOPKG;
469
470 /* Discard the BIT STRING metadata */
471 if (vlen < 1 || *(const u8 *)value != 0)
472 return -EBADMSG;
473 ctx->key = value + 1;
474 ctx->key_size = vlen - 1;
475 return 0;
476}
477
478/* The keyIdentifier in AuthorityKeyIdentifier SEQUENCE is tag(CONT,PRIM,0) */
479#define SEQ_TAG_KEYID (ASN1_CONT << 6)
480
481/*
482 * Process certificate extensions that are used to qualify the certificate.
483 */
484int x509_process_extension(void *context, size_t hdrlen,
485 unsigned char tag,
486 const void *value, size_t vlen)
487{
488 struct x509_parse_context *ctx = context;
489 struct asymmetric_key_id *kid;
490 const unsigned char *v = value;
491
492 pr_debug("Extension: %u\n", ctx->last_oid);
493
494 if (ctx->last_oid == OID_subjectKeyIdentifier) {
495 /* Get hold of the key fingerprint */
496 if (ctx->cert->skid || vlen < 3)
497 return -EBADMSG;
498 if (v[0] != ASN1_OTS || v[1] != vlen - 2)
499 return -EBADMSG;
500 v += 2;
501 vlen -= 2;
502
503 ctx->cert->raw_skid_size = vlen;
504 ctx->cert->raw_skid = v;
505 kid = asymmetric_key_generate_id(v, vlen, "", 0);
506 if (IS_ERR(kid))
507 return PTR_ERR(kid);
508 ctx->cert->skid = kid;
509 pr_debug("subjkeyid %*phN\n", kid->len, kid->data);
510 return 0;
511 }
512
513 if (ctx->last_oid == OID_authorityKeyIdentifier) {
514 /* Get hold of the CA key fingerprint */
515 ctx->raw_akid = v;
516 ctx->raw_akid_size = vlen;
517 return 0;
518 }
519
520 return 0;
521}
522
523/**
524 * x509_decode_time - Decode an X.509 time ASN.1 object
525 * @_t: The time to fill in
526 * @hdrlen: The length of the object header
527 * @tag: The object tag
528 * @value: The object value
529 * @vlen: The size of the object value
530 *
531 * Decode an ASN.1 universal time or generalised time field into a struct the
532 * kernel can handle and check it for validity. The time is decoded thus:
533 *
534 * [RFC5280 §4.1.2.5]
535 * CAs conforming to this profile MUST always encode certificate validity
536 * dates through the year 2049 as UTCTime; certificate validity dates in
537 * 2050 or later MUST be encoded as GeneralizedTime. Conforming
538 * applications MUST be able to process validity dates that are encoded in
539 * either UTCTime or GeneralizedTime.
540 */
541int x509_decode_time(time64_t *_t, size_t hdrlen,
542 unsigned char tag,
543 const unsigned char *value, size_t vlen)
544{
545 static const unsigned char month_lengths[] = { 31, 28, 31, 30, 31, 30,
546 31, 31, 30, 31, 30, 31 };
547 const unsigned char *p = value;
548 unsigned year, mon, day, hour, min, sec, mon_len;
549
550#define dec2bin(X) ({ unsigned char x = (X) - '0'; if (x > 9) goto invalid_time; x; })
551#define DD2bin(P) ({ unsigned x = dec2bin(P[0]) * 10 + dec2bin(P[1]); P += 2; x; })
552
553 if (tag == ASN1_UNITIM) {
554 /* UTCTime: YYMMDDHHMMSSZ */
555 if (vlen != 13)
556 goto unsupported_time;
557 year = DD2bin(p);
558 if (year >= 50)
559 year += 1900;
560 else
561 year += 2000;
562 } else if (tag == ASN1_GENTIM) {
563 /* GenTime: YYYYMMDDHHMMSSZ */
564 if (vlen != 15)
565 goto unsupported_time;
566 year = DD2bin(p) * 100 + DD2bin(p);
567 if (year >= 1950 && year <= 2049)
568 goto invalid_time;
569 } else {
570 goto unsupported_time;
571 }
572
573 mon = DD2bin(p);
574 day = DD2bin(p);
575 hour = DD2bin(p);
576 min = DD2bin(p);
577 sec = DD2bin(p);
578
579 if (*p != 'Z')
580 goto unsupported_time;
581
582 if (year < 1970 ||
583 mon < 1 || mon > 12)
584 goto invalid_time;
585
586 mon_len = month_lengths[mon - 1];
587 if (mon == 2) {
588 if (year % 4 == 0) {
589 mon_len = 29;
590 if (year % 100 == 0) {
591 mon_len = 28;
592 if (year % 400 == 0)
593 mon_len = 29;
594 }
595 }
596 }
597
598 if (day < 1 || day > mon_len ||
599 hour > 24 || /* ISO 8601 permits 24:00:00 as midnight tomorrow */
600 min > 59 ||
601 sec > 60) /* ISO 8601 permits leap seconds [X.680 46.3] */
602 goto invalid_time;
603
604 *_t = mktime64(year, mon, day, hour, min, sec);
605 return 0;
606
607unsupported_time:
608 pr_debug("Got unsupported time [tag %02x]: '%*phN'\n",
609 tag, (int)vlen, value);
610 return -EBADMSG;
611invalid_time:
612 pr_debug("Got invalid time [tag %02x]: '%*phN'\n",
613 tag, (int)vlen, value);
614 return -EBADMSG;
615}
616EXPORT_SYMBOL_GPL(x509_decode_time);
617
618int x509_note_not_before(void *context, size_t hdrlen,
619 unsigned char tag,
620 const void *value, size_t vlen)
621{
622 struct x509_parse_context *ctx = context;
623 return x509_decode_time(&ctx->cert->valid_from, hdrlen, tag, value, vlen);
624}
625
626int x509_note_not_after(void *context, size_t hdrlen,
627 unsigned char tag,
628 const void *value, size_t vlen)
629{
630 struct x509_parse_context *ctx = context;
631 return x509_decode_time(&ctx->cert->valid_to, hdrlen, tag, value, vlen);
632}
633
634/*
635 * Note a key identifier-based AuthorityKeyIdentifier
636 */
637int x509_akid_note_kid(void *context, size_t hdrlen,
638 unsigned char tag,
639 const void *value, size_t vlen)
640{
641 struct x509_parse_context *ctx = context;
642 struct asymmetric_key_id *kid;
643
644 pr_debug("AKID: keyid: %*phN\n", (int)vlen, value);
645
646 if (ctx->cert->sig->auth_ids[1])
647 return 0;
648
649 kid = asymmetric_key_generate_id(value, vlen, "", 0);
650 if (IS_ERR(kid))
651 return PTR_ERR(kid);
652 pr_debug("authkeyid %*phN\n", kid->len, kid->data);
653 ctx->cert->sig->auth_ids[1] = kid;
654 return 0;
655}
656
657/*
658 * Note a directoryName in an AuthorityKeyIdentifier
659 */
660int x509_akid_note_name(void *context, size_t hdrlen,
661 unsigned char tag,
662 const void *value, size_t vlen)
663{
664 struct x509_parse_context *ctx = context;
665
666 pr_debug("AKID: name: %*phN\n", (int)vlen, value);
667
668 ctx->akid_raw_issuer = value;
669 ctx->akid_raw_issuer_size = vlen;
670 return 0;
671}
672
673/*
674 * Note a serial number in an AuthorityKeyIdentifier
675 */
676int x509_akid_note_serial(void *context, size_t hdrlen,
677 unsigned char tag,
678 const void *value, size_t vlen)
679{
680 struct x509_parse_context *ctx = context;
681 struct asymmetric_key_id *kid;
682
683 pr_debug("AKID: serial: %*phN\n", (int)vlen, value);
684
685 if (!ctx->akid_raw_issuer || ctx->cert->sig->auth_ids[0])
686 return 0;
687
688 kid = asymmetric_key_generate_id(value,
689 vlen,
690 ctx->akid_raw_issuer,
691 ctx->akid_raw_issuer_size);
692 if (IS_ERR(kid))
693 return PTR_ERR(kid);
694
695 pr_debug("authkeyid %*phN\n", kid->len, kid->data);
696 ctx->cert->sig->auth_ids[0] = kid;
697 return 0;
698}