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