1 /* X.509 certificate parser
3 * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
4 * Written by David Howells (dhowells@redhat.com)
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.
12 #define pr_fmt(fmt) "X.509: "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 "x509_parser.h"
20 #include "x509.asn1.h"
21 #include "x509_akid.asn1.h"
23 struct x509_parse_context {
24 struct x509_certificate *cert; /* Certificate being constructed */
25 unsigned long data; /* Start of data */
26 const void *cert_start; /* Start of cert content */
27 const void *key; /* Key data */
28 size_t key_size; /* Size of key data */
29 const void *params; /* Key parameters */
30 size_t params_size; /* Size of key parameters */
31 enum OID key_algo; /* Public key algorithm */
32 enum OID last_oid; /* Last OID encountered */
33 enum OID algo_oid; /* Algorithm OID */
34 unsigned char nr_mpi; /* Number of MPIs stored */
35 u8 o_size; /* Size of organizationName (O) */
36 u8 cn_size; /* Size of commonName (CN) */
37 u8 email_size; /* Size of emailAddress */
38 u16 o_offset; /* Offset of organizationName (O) */
39 u16 cn_offset; /* Offset of commonName (CN) */
40 u16 email_offset; /* Offset of emailAddress */
41 unsigned raw_akid_size;
42 const void *raw_akid; /* Raw authorityKeyId in ASN.1 */
43 const void *akid_raw_issuer; /* Raw directoryName in authorityKeyId */
44 unsigned akid_raw_issuer_size;
48 * Free an X.509 certificate
50 void x509_free_certificate(struct x509_certificate *cert)
53 public_key_free(cert->pub);
54 public_key_signature_free(cert->sig);
62 EXPORT_SYMBOL_GPL(x509_free_certificate);
65 * Parse an X.509 certificate
67 struct x509_certificate *x509_cert_parse(const void *data, size_t datalen)
69 struct x509_certificate *cert;
70 struct x509_parse_context *ctx;
71 struct asymmetric_key_id *kid;
75 cert = kzalloc(sizeof(struct x509_certificate), GFP_KERNEL);
78 cert->pub = kzalloc(sizeof(struct public_key), GFP_KERNEL);
81 cert->sig = kzalloc(sizeof(struct public_key_signature), GFP_KERNEL);
84 ctx = kzalloc(sizeof(struct x509_parse_context), GFP_KERNEL);
89 ctx->data = (unsigned long)data;
91 /* Attempt to decode the certificate */
92 ret = asn1_ber_decoder(&x509_decoder, ctx, data, datalen);
96 /* Decode the AuthorityKeyIdentifier */
98 pr_devel("AKID: %u %*phN\n",
99 ctx->raw_akid_size, ctx->raw_akid_size, ctx->raw_akid);
100 ret = asn1_ber_decoder(&x509_akid_decoder, ctx,
101 ctx->raw_akid, ctx->raw_akid_size);
103 pr_warn("Couldn't decode AuthKeyIdentifier\n");
109 cert->pub->key = kmemdup(ctx->key, ctx->key_size, GFP_KERNEL);
113 cert->pub->keylen = ctx->key_size;
115 cert->pub->params = kmemdup(ctx->params, ctx->params_size, GFP_KERNEL);
116 if (!cert->pub->params)
119 cert->pub->paramlen = ctx->params_size;
120 cert->pub->algo = ctx->key_algo;
122 /* Grab the signature bits */
123 ret = x509_get_sig_params(cert);
127 /* Generate cert issuer + serial number key ID */
128 kid = asymmetric_key_generate_id(cert->raw_serial,
129 cert->raw_serial_size,
131 cert->raw_issuer_size);
138 /* Detect self-signed certificates */
139 ret = x509_check_for_self_signed(cert);
149 x509_free_certificate(cert);
153 EXPORT_SYMBOL_GPL(x509_cert_parse);
156 * Note an OID when we find one for later processing when we know how
159 int x509_note_OID(void *context, size_t hdrlen,
161 const void *value, size_t vlen)
163 struct x509_parse_context *ctx = context;
165 ctx->last_oid = look_up_OID(value, vlen);
166 if (ctx->last_oid == OID__NR) {
168 sprint_oid(value, vlen, buffer, sizeof(buffer));
169 pr_debug("Unknown OID: [%lu] %s\n",
170 (unsigned long)value - ctx->data, buffer);
176 * Save the position of the TBS data so that we can check the signature over it
179 int x509_note_tbs_certificate(void *context, size_t hdrlen,
181 const void *value, size_t vlen)
183 struct x509_parse_context *ctx = context;
185 pr_debug("x509_note_tbs_certificate(,%zu,%02x,%ld,%zu)!\n",
186 hdrlen, tag, (unsigned long)value - ctx->data, vlen);
188 ctx->cert->tbs = value - hdrlen;
189 ctx->cert->tbs_size = vlen + hdrlen;
194 * Record the public key algorithm
196 int x509_note_pkey_algo(void *context, size_t hdrlen,
198 const void *value, size_t vlen)
200 struct x509_parse_context *ctx = context;
202 pr_debug("PubKey Algo: %u\n", ctx->last_oid);
204 switch (ctx->last_oid) {
205 case OID_md2WithRSAEncryption:
206 case OID_md3WithRSAEncryption:
208 return -ENOPKG; /* Unsupported combination */
210 case OID_md4WithRSAEncryption:
211 ctx->cert->sig->hash_algo = "md4";
214 case OID_sha1WithRSAEncryption:
215 ctx->cert->sig->hash_algo = "sha1";
218 case OID_sha256WithRSAEncryption:
219 ctx->cert->sig->hash_algo = "sha256";
222 case OID_sha384WithRSAEncryption:
223 ctx->cert->sig->hash_algo = "sha384";
226 case OID_sha512WithRSAEncryption:
227 ctx->cert->sig->hash_algo = "sha512";
230 case OID_sha224WithRSAEncryption:
231 ctx->cert->sig->hash_algo = "sha224";
234 case OID_gost2012Signature256:
235 ctx->cert->sig->hash_algo = "streebog256";
238 case OID_gost2012Signature512:
239 ctx->cert->sig->hash_algo = "streebog512";
244 ctx->cert->sig->pkey_algo = "rsa";
245 ctx->cert->sig->encoding = "pkcs1";
246 ctx->algo_oid = ctx->last_oid;
249 ctx->cert->sig->pkey_algo = "ecrdsa";
250 ctx->cert->sig->encoding = "raw";
251 ctx->algo_oid = ctx->last_oid;
256 * Note the whereabouts and type of the signature.
258 int x509_note_signature(void *context, size_t hdrlen,
260 const void *value, size_t vlen)
262 struct x509_parse_context *ctx = context;
264 pr_debug("Signature type: %u size %zu\n", ctx->last_oid, vlen);
266 if (ctx->last_oid != ctx->algo_oid) {
267 pr_warn("Got cert with pkey (%u) and sig (%u) algorithm OIDs\n",
268 ctx->algo_oid, ctx->last_oid);
272 if (strcmp(ctx->cert->sig->pkey_algo, "rsa") == 0 ||
273 strcmp(ctx->cert->sig->pkey_algo, "ecrdsa") == 0) {
274 /* Discard the BIT STRING metadata */
275 if (vlen < 1 || *(const u8 *)value != 0)
282 ctx->cert->raw_sig = value;
283 ctx->cert->raw_sig_size = vlen;
288 * Note the certificate serial number
290 int x509_note_serial(void *context, size_t hdrlen,
292 const void *value, size_t vlen)
294 struct x509_parse_context *ctx = context;
295 ctx->cert->raw_serial = value;
296 ctx->cert->raw_serial_size = vlen;
301 * Note some of the name segments from which we'll fabricate a name.
303 int x509_extract_name_segment(void *context, size_t hdrlen,
305 const void *value, size_t vlen)
307 struct x509_parse_context *ctx = context;
309 switch (ctx->last_oid) {
312 ctx->cn_offset = (unsigned long)value - ctx->data;
314 case OID_organizationName:
316 ctx->o_offset = (unsigned long)value - ctx->data;
318 case OID_email_address:
319 ctx->email_size = vlen;
320 ctx->email_offset = (unsigned long)value - ctx->data;
330 * Fabricate and save the issuer and subject names
332 static int x509_fabricate_name(struct x509_parse_context *ctx, size_t hdrlen,
334 char **_name, size_t vlen)
336 const void *name, *data = (const void *)ctx->data;
343 /* Empty name string if no material */
344 if (!ctx->cn_size && !ctx->o_size && !ctx->email_size) {
345 buffer = kmalloc(1, GFP_KERNEL);
352 if (ctx->cn_size && ctx->o_size) {
353 /* Consider combining O and CN, but use only the CN if it is
354 * prefixed by the O, or a significant portion thereof.
356 namesize = ctx->cn_size;
357 name = data + ctx->cn_offset;
358 if (ctx->cn_size >= ctx->o_size &&
359 memcmp(data + ctx->cn_offset, data + ctx->o_offset,
361 goto single_component;
362 if (ctx->cn_size >= 7 &&
364 memcmp(data + ctx->cn_offset, data + ctx->o_offset, 7) == 0)
365 goto single_component;
367 buffer = kmalloc(ctx->o_size + 2 + ctx->cn_size + 1,
373 data + ctx->o_offset, ctx->o_size);
374 buffer[ctx->o_size + 0] = ':';
375 buffer[ctx->o_size + 1] = ' ';
376 memcpy(buffer + ctx->o_size + 2,
377 data + ctx->cn_offset, ctx->cn_size);
378 buffer[ctx->o_size + 2 + ctx->cn_size] = 0;
381 } else if (ctx->cn_size) {
382 namesize = ctx->cn_size;
383 name = data + ctx->cn_offset;
384 } else if (ctx->o_size) {
385 namesize = ctx->o_size;
386 name = data + ctx->o_offset;
388 namesize = ctx->email_size;
389 name = data + ctx->email_offset;
393 buffer = kmalloc(namesize + 1, GFP_KERNEL);
396 memcpy(buffer, name, namesize);
397 buffer[namesize] = 0;
407 int x509_note_issuer(void *context, size_t hdrlen,
409 const void *value, size_t vlen)
411 struct x509_parse_context *ctx = context;
412 ctx->cert->raw_issuer = value;
413 ctx->cert->raw_issuer_size = vlen;
414 return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->issuer, vlen);
417 int x509_note_subject(void *context, size_t hdrlen,
419 const void *value, size_t vlen)
421 struct x509_parse_context *ctx = context;
422 ctx->cert->raw_subject = value;
423 ctx->cert->raw_subject_size = vlen;
424 return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->subject, vlen);
428 * Extract the parameters for the public key
430 int x509_note_params(void *context, size_t hdrlen,
432 const void *value, size_t vlen)
434 struct x509_parse_context *ctx = context;
437 * AlgorithmIdentifier is used three times in the x509, we should skip
438 * first and ignore third, using second one which is after subject and
439 * before subjectPublicKey.
441 if (!ctx->cert->raw_subject || ctx->key)
443 ctx->params = value - hdrlen;
444 ctx->params_size = vlen + hdrlen;
449 * Extract the data for the public key algorithm
451 int x509_extract_key_data(void *context, size_t hdrlen,
453 const void *value, size_t vlen)
455 struct x509_parse_context *ctx = context;
457 ctx->key_algo = ctx->last_oid;
458 if (ctx->last_oid == OID_rsaEncryption)
459 ctx->cert->pub->pkey_algo = "rsa";
460 else if (ctx->last_oid == OID_gost2012PKey256 ||
461 ctx->last_oid == OID_gost2012PKey512)
462 ctx->cert->pub->pkey_algo = "ecrdsa";
466 /* Discard the BIT STRING metadata */
467 if (vlen < 1 || *(const u8 *)value != 0)
469 ctx->key = value + 1;
470 ctx->key_size = vlen - 1;
474 /* The keyIdentifier in AuthorityKeyIdentifier SEQUENCE is tag(CONT,PRIM,0) */
475 #define SEQ_TAG_KEYID (ASN1_CONT << 6)
478 * Process certificate extensions that are used to qualify the certificate.
480 int x509_process_extension(void *context, size_t hdrlen,
482 const void *value, size_t vlen)
484 struct x509_parse_context *ctx = context;
485 struct asymmetric_key_id *kid;
486 const unsigned char *v = value;
488 pr_debug("Extension: %u\n", ctx->last_oid);
490 if (ctx->last_oid == OID_subjectKeyIdentifier) {
491 /* Get hold of the key fingerprint */
492 if (ctx->cert->skid || vlen < 3)
494 if (v[0] != ASN1_OTS || v[1] != vlen - 2)
499 ctx->cert->raw_skid_size = vlen;
500 ctx->cert->raw_skid = v;
501 kid = asymmetric_key_generate_id(v, vlen, "", 0);
504 ctx->cert->skid = kid;
505 pr_debug("subjkeyid %*phN\n", kid->len, kid->data);
509 if (ctx->last_oid == OID_authorityKeyIdentifier) {
510 /* Get hold of the CA key fingerprint */
512 ctx->raw_akid_size = vlen;
520 * x509_decode_time - Decode an X.509 time ASN.1 object
521 * @_t: The time to fill in
522 * @hdrlen: The length of the object header
523 * @tag: The object tag
524 * @value: The object value
525 * @vlen: The size of the object value
527 * Decode an ASN.1 universal time or generalised time field into a struct the
528 * kernel can handle and check it for validity. The time is decoded thus:
530 * [RFC5280 ยง4.1.2.5]
531 * CAs conforming to this profile MUST always encode certificate validity
532 * dates through the year 2049 as UTCTime; certificate validity dates in
533 * 2050 or later MUST be encoded as GeneralizedTime. Conforming
534 * applications MUST be able to process validity dates that are encoded in
535 * either UTCTime or GeneralizedTime.
537 int x509_decode_time(time64_t *_t, size_t hdrlen,
539 const unsigned char *value, size_t vlen)
541 static const unsigned char month_lengths[] = { 31, 28, 31, 30, 31, 30,
542 31, 31, 30, 31, 30, 31 };
543 const unsigned char *p = value;
544 unsigned year, mon, day, hour, min, sec, mon_len;
546 #define dec2bin(X) ({ unsigned char x = (X) - '0'; if (x > 9) goto invalid_time; x; })
547 #define DD2bin(P) ({ unsigned x = dec2bin(P[0]) * 10 + dec2bin(P[1]); P += 2; x; })
549 if (tag == ASN1_UNITIM) {
550 /* UTCTime: YYMMDDHHMMSSZ */
552 goto unsupported_time;
558 } else if (tag == ASN1_GENTIM) {
559 /* GenTime: YYYYMMDDHHMMSSZ */
561 goto unsupported_time;
562 year = DD2bin(p) * 100 + DD2bin(p);
563 if (year >= 1950 && year <= 2049)
566 goto unsupported_time;
576 goto unsupported_time;
582 mon_len = month_lengths[mon - 1];
586 if (year % 100 == 0) {
594 if (day < 1 || day > mon_len ||
595 hour > 24 || /* ISO 8601 permits 24:00:00 as midnight tomorrow */
597 sec > 60) /* ISO 8601 permits leap seconds [X.680 46.3] */
600 *_t = mktime64(year, mon, day, hour, min, sec);
604 pr_debug("Got unsupported time [tag %02x]: '%*phN'\n",
605 tag, (int)vlen, value);
608 pr_debug("Got invalid time [tag %02x]: '%*phN'\n",
609 tag, (int)vlen, value);
612 EXPORT_SYMBOL_GPL(x509_decode_time);
614 int x509_note_not_before(void *context, size_t hdrlen,
616 const void *value, size_t vlen)
618 struct x509_parse_context *ctx = context;
619 return x509_decode_time(&ctx->cert->valid_from, hdrlen, tag, value, vlen);
622 int x509_note_not_after(void *context, size_t hdrlen,
624 const void *value, size_t vlen)
626 struct x509_parse_context *ctx = context;
627 return x509_decode_time(&ctx->cert->valid_to, hdrlen, tag, value, vlen);
631 * Note a key identifier-based AuthorityKeyIdentifier
633 int x509_akid_note_kid(void *context, size_t hdrlen,
635 const void *value, size_t vlen)
637 struct x509_parse_context *ctx = context;
638 struct asymmetric_key_id *kid;
640 pr_debug("AKID: keyid: %*phN\n", (int)vlen, value);
642 if (ctx->cert->sig->auth_ids[1])
645 kid = asymmetric_key_generate_id(value, vlen, "", 0);
648 pr_debug("authkeyid %*phN\n", kid->len, kid->data);
649 ctx->cert->sig->auth_ids[1] = kid;
654 * Note a directoryName in an AuthorityKeyIdentifier
656 int x509_akid_note_name(void *context, size_t hdrlen,
658 const void *value, size_t vlen)
660 struct x509_parse_context *ctx = context;
662 pr_debug("AKID: name: %*phN\n", (int)vlen, value);
664 ctx->akid_raw_issuer = value;
665 ctx->akid_raw_issuer_size = vlen;
670 * Note a serial number in an AuthorityKeyIdentifier
672 int x509_akid_note_serial(void *context, size_t hdrlen,
674 const void *value, size_t vlen)
676 struct x509_parse_context *ctx = context;
677 struct asymmetric_key_id *kid;
679 pr_debug("AKID: serial: %*phN\n", (int)vlen, value);
681 if (!ctx->akid_raw_issuer || ctx->cert->sig->auth_ids[0])
684 kid = asymmetric_key_generate_id(value,
686 ctx->akid_raw_issuer,
687 ctx->akid_raw_issuer_size);
691 pr_debug("authkeyid %*phN\n", kid->len, kid->data);
692 ctx->cert->sig->auth_ids[0] = kid;