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 "public_key.h"
19 #include "x509_parser.h"
20 #include "x509-asn1.h"
21 #include "x509_rsakey-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 };
39 
40 /*
41  * Free an X.509 certificate
42  */
43 void x509_free_certificate(struct x509_certificate *cert)
44 {
45 	if (cert) {
46 		public_key_destroy(cert->pub);
47 		kfree(cert->issuer);
48 		kfree(cert->subject);
49 		kfree(cert->id);
50 		kfree(cert->skid);
51 		kfree(cert->authority);
52 		kfree(cert->sig.digest);
53 		mpi_free(cert->sig.rsa.s);
54 		kfree(cert);
55 	}
56 }
57 EXPORT_SYMBOL_GPL(x509_free_certificate);
58 
59 /*
60  * Parse an X.509 certificate
61  */
62 struct x509_certificate *x509_cert_parse(const void *data, size_t datalen)
63 {
64 	struct x509_certificate *cert;
65 	struct x509_parse_context *ctx;
66 	struct asymmetric_key_id *kid;
67 	long ret;
68 
69 	ret = -ENOMEM;
70 	cert = kzalloc(sizeof(struct x509_certificate), GFP_KERNEL);
71 	if (!cert)
72 		goto error_no_cert;
73 	cert->pub = kzalloc(sizeof(struct public_key), GFP_KERNEL);
74 	if (!cert->pub)
75 		goto error_no_ctx;
76 	ctx = kzalloc(sizeof(struct x509_parse_context), GFP_KERNEL);
77 	if (!ctx)
78 		goto error_no_ctx;
79 
80 	ctx->cert = cert;
81 	ctx->data = (unsigned long)data;
82 
83 	/* Attempt to decode the certificate */
84 	ret = asn1_ber_decoder(&x509_decoder, ctx, data, datalen);
85 	if (ret < 0)
86 		goto error_decode;
87 
88 	/* Decode the public key */
89 	ret = asn1_ber_decoder(&x509_rsakey_decoder, ctx,
90 			       ctx->key, ctx->key_size);
91 	if (ret < 0)
92 		goto error_decode;
93 
94 	/* Generate cert issuer + serial number key ID */
95 	kid = asymmetric_key_generate_id(cert->raw_serial,
96 					 cert->raw_serial_size,
97 					 cert->raw_issuer,
98 					 cert->raw_issuer_size);
99 	if (IS_ERR(kid)) {
100 		ret = PTR_ERR(kid);
101 		goto error_decode;
102 	}
103 	cert->id = kid;
104 
105 	kfree(ctx);
106 	return cert;
107 
108 error_decode:
109 	kfree(ctx);
110 error_no_ctx:
111 	x509_free_certificate(cert);
112 error_no_cert:
113 	return ERR_PTR(ret);
114 }
115 EXPORT_SYMBOL_GPL(x509_cert_parse);
116 
117 /*
118  * Note an OID when we find one for later processing when we know how
119  * to interpret it.
120  */
121 int x509_note_OID(void *context, size_t hdrlen,
122 	     unsigned char tag,
123 	     const void *value, size_t vlen)
124 {
125 	struct x509_parse_context *ctx = context;
126 
127 	ctx->last_oid = look_up_OID(value, vlen);
128 	if (ctx->last_oid == OID__NR) {
129 		char buffer[50];
130 		sprint_oid(value, vlen, buffer, sizeof(buffer));
131 		pr_debug("Unknown OID: [%lu] %s\n",
132 			 (unsigned long)value - ctx->data, buffer);
133 	}
134 	return 0;
135 }
136 
137 /*
138  * Save the position of the TBS data so that we can check the signature over it
139  * later.
140  */
141 int x509_note_tbs_certificate(void *context, size_t hdrlen,
142 			      unsigned char tag,
143 			      const void *value, size_t vlen)
144 {
145 	struct x509_parse_context *ctx = context;
146 
147 	pr_debug("x509_note_tbs_certificate(,%zu,%02x,%ld,%zu)!\n",
148 		 hdrlen, tag, (unsigned long)value - ctx->data, vlen);
149 
150 	ctx->cert->tbs = value - hdrlen;
151 	ctx->cert->tbs_size = vlen + hdrlen;
152 	return 0;
153 }
154 
155 /*
156  * Record the public key algorithm
157  */
158 int x509_note_pkey_algo(void *context, size_t hdrlen,
159 			unsigned char tag,
160 			const void *value, size_t vlen)
161 {
162 	struct x509_parse_context *ctx = context;
163 
164 	pr_debug("PubKey Algo: %u\n", ctx->last_oid);
165 
166 	switch (ctx->last_oid) {
167 	case OID_md2WithRSAEncryption:
168 	case OID_md3WithRSAEncryption:
169 	default:
170 		return -ENOPKG; /* Unsupported combination */
171 
172 	case OID_md4WithRSAEncryption:
173 		ctx->cert->sig.pkey_hash_algo = HASH_ALGO_MD5;
174 		ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA;
175 		break;
176 
177 	case OID_sha1WithRSAEncryption:
178 		ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA1;
179 		ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA;
180 		break;
181 
182 	case OID_sha256WithRSAEncryption:
183 		ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA256;
184 		ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA;
185 		break;
186 
187 	case OID_sha384WithRSAEncryption:
188 		ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA384;
189 		ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA;
190 		break;
191 
192 	case OID_sha512WithRSAEncryption:
193 		ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA512;
194 		ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA;
195 		break;
196 
197 	case OID_sha224WithRSAEncryption:
198 		ctx->cert->sig.pkey_hash_algo = HASH_ALGO_SHA224;
199 		ctx->cert->sig.pkey_algo = PKEY_ALGO_RSA;
200 		break;
201 	}
202 
203 	ctx->algo_oid = ctx->last_oid;
204 	return 0;
205 }
206 
207 /*
208  * Note the whereabouts and type of the signature.
209  */
210 int x509_note_signature(void *context, size_t hdrlen,
211 			unsigned char tag,
212 			const void *value, size_t vlen)
213 {
214 	struct x509_parse_context *ctx = context;
215 
216 	pr_debug("Signature type: %u size %zu\n", ctx->last_oid, vlen);
217 
218 	if (ctx->last_oid != ctx->algo_oid) {
219 		pr_warn("Got cert with pkey (%u) and sig (%u) algorithm OIDs\n",
220 			ctx->algo_oid, ctx->last_oid);
221 		return -EINVAL;
222 	}
223 
224 	ctx->cert->raw_sig = value;
225 	ctx->cert->raw_sig_size = vlen;
226 	return 0;
227 }
228 
229 /*
230  * Note the certificate serial number
231  */
232 int x509_note_serial(void *context, size_t hdrlen,
233 		     unsigned char tag,
234 		     const void *value, size_t vlen)
235 {
236 	struct x509_parse_context *ctx = context;
237 	ctx->cert->raw_serial = value;
238 	ctx->cert->raw_serial_size = vlen;
239 	return 0;
240 }
241 
242 /*
243  * Note some of the name segments from which we'll fabricate a name.
244  */
245 int x509_extract_name_segment(void *context, size_t hdrlen,
246 			      unsigned char tag,
247 			      const void *value, size_t vlen)
248 {
249 	struct x509_parse_context *ctx = context;
250 
251 	switch (ctx->last_oid) {
252 	case OID_commonName:
253 		ctx->cn_size = vlen;
254 		ctx->cn_offset = (unsigned long)value - ctx->data;
255 		break;
256 	case OID_organizationName:
257 		ctx->o_size = vlen;
258 		ctx->o_offset = (unsigned long)value - ctx->data;
259 		break;
260 	case OID_email_address:
261 		ctx->email_size = vlen;
262 		ctx->email_offset = (unsigned long)value - ctx->data;
263 		break;
264 	default:
265 		break;
266 	}
267 
268 	return 0;
269 }
270 
271 /*
272  * Fabricate and save the issuer and subject names
273  */
274 static int x509_fabricate_name(struct x509_parse_context *ctx, size_t hdrlen,
275 			       unsigned char tag,
276 			       char **_name, size_t vlen)
277 {
278 	const void *name, *data = (const void *)ctx->data;
279 	size_t namesize;
280 	char *buffer;
281 
282 	if (*_name)
283 		return -EINVAL;
284 
285 	/* Empty name string if no material */
286 	if (!ctx->cn_size && !ctx->o_size && !ctx->email_size) {
287 		buffer = kmalloc(1, GFP_KERNEL);
288 		if (!buffer)
289 			return -ENOMEM;
290 		buffer[0] = 0;
291 		goto done;
292 	}
293 
294 	if (ctx->cn_size && ctx->o_size) {
295 		/* Consider combining O and CN, but use only the CN if it is
296 		 * prefixed by the O, or a significant portion thereof.
297 		 */
298 		namesize = ctx->cn_size;
299 		name = data + ctx->cn_offset;
300 		if (ctx->cn_size >= ctx->o_size &&
301 		    memcmp(data + ctx->cn_offset, data + ctx->o_offset,
302 			   ctx->o_size) == 0)
303 			goto single_component;
304 		if (ctx->cn_size >= 7 &&
305 		    ctx->o_size >= 7 &&
306 		    memcmp(data + ctx->cn_offset, data + ctx->o_offset, 7) == 0)
307 			goto single_component;
308 
309 		buffer = kmalloc(ctx->o_size + 2 + ctx->cn_size + 1,
310 				 GFP_KERNEL);
311 		if (!buffer)
312 			return -ENOMEM;
313 
314 		memcpy(buffer,
315 		       data + ctx->o_offset, ctx->o_size);
316 		buffer[ctx->o_size + 0] = ':';
317 		buffer[ctx->o_size + 1] = ' ';
318 		memcpy(buffer + ctx->o_size + 2,
319 		       data + ctx->cn_offset, ctx->cn_size);
320 		buffer[ctx->o_size + 2 + ctx->cn_size] = 0;
321 		goto done;
322 
323 	} else if (ctx->cn_size) {
324 		namesize = ctx->cn_size;
325 		name = data + ctx->cn_offset;
326 	} else if (ctx->o_size) {
327 		namesize = ctx->o_size;
328 		name = data + ctx->o_offset;
329 	} else {
330 		namesize = ctx->email_size;
331 		name = data + ctx->email_offset;
332 	}
333 
334 single_component:
335 	buffer = kmalloc(namesize + 1, GFP_KERNEL);
336 	if (!buffer)
337 		return -ENOMEM;
338 	memcpy(buffer, name, namesize);
339 	buffer[namesize] = 0;
340 
341 done:
342 	*_name = buffer;
343 	ctx->cn_size = 0;
344 	ctx->o_size = 0;
345 	ctx->email_size = 0;
346 	return 0;
347 }
348 
349 int x509_note_issuer(void *context, size_t hdrlen,
350 		     unsigned char tag,
351 		     const void *value, size_t vlen)
352 {
353 	struct x509_parse_context *ctx = context;
354 	ctx->cert->raw_issuer = value;
355 	ctx->cert->raw_issuer_size = vlen;
356 	return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->issuer, vlen);
357 }
358 
359 int x509_note_subject(void *context, size_t hdrlen,
360 		      unsigned char tag,
361 		      const void *value, size_t vlen)
362 {
363 	struct x509_parse_context *ctx = context;
364 	ctx->cert->raw_subject = value;
365 	ctx->cert->raw_subject_size = vlen;
366 	return x509_fabricate_name(ctx, hdrlen, tag, &ctx->cert->subject, vlen);
367 }
368 
369 /*
370  * Extract the data for the public key algorithm
371  */
372 int x509_extract_key_data(void *context, size_t hdrlen,
373 			  unsigned char tag,
374 			  const void *value, size_t vlen)
375 {
376 	struct x509_parse_context *ctx = context;
377 
378 	if (ctx->last_oid != OID_rsaEncryption)
379 		return -ENOPKG;
380 
381 	ctx->cert->pub->pkey_algo = PKEY_ALGO_RSA;
382 
383 	/* Discard the BIT STRING metadata */
384 	ctx->key = value + 1;
385 	ctx->key_size = vlen - 1;
386 	return 0;
387 }
388 
389 /*
390  * Extract a RSA public key value
391  */
392 int rsa_extract_mpi(void *context, size_t hdrlen,
393 		    unsigned char tag,
394 		    const void *value, size_t vlen)
395 {
396 	struct x509_parse_context *ctx = context;
397 	MPI mpi;
398 
399 	if (ctx->nr_mpi >= ARRAY_SIZE(ctx->cert->pub->mpi)) {
400 		pr_err("Too many public key MPIs in certificate\n");
401 		return -EBADMSG;
402 	}
403 
404 	mpi = mpi_read_raw_data(value, vlen);
405 	if (!mpi)
406 		return -ENOMEM;
407 
408 	ctx->cert->pub->mpi[ctx->nr_mpi++] = mpi;
409 	return 0;
410 }
411 
412 /* The keyIdentifier in AuthorityKeyIdentifier SEQUENCE is tag(CONT,PRIM,0) */
413 #define SEQ_TAG_KEYID (ASN1_CONT << 6)
414 
415 /*
416  * Process certificate extensions that are used to qualify the certificate.
417  */
418 int x509_process_extension(void *context, size_t hdrlen,
419 			   unsigned char tag,
420 			   const void *value, size_t vlen)
421 {
422 	struct x509_parse_context *ctx = context;
423 	struct asymmetric_key_id *kid;
424 	const unsigned char *v = value;
425 	int i;
426 
427 	pr_debug("Extension: %u\n", ctx->last_oid);
428 
429 	if (ctx->last_oid == OID_subjectKeyIdentifier) {
430 		/* Get hold of the key fingerprint */
431 		if (ctx->cert->skid || vlen < 3)
432 			return -EBADMSG;
433 		if (v[0] != ASN1_OTS || v[1] != vlen - 2)
434 			return -EBADMSG;
435 		v += 2;
436 		vlen -= 2;
437 
438 		ctx->cert->raw_skid_size = vlen;
439 		ctx->cert->raw_skid = v;
440 		kid = asymmetric_key_generate_id(ctx->cert->raw_subject,
441 						 ctx->cert->raw_subject_size,
442 						 v, vlen);
443 		if (IS_ERR(kid))
444 			return PTR_ERR(kid);
445 		ctx->cert->skid = kid;
446 		pr_debug("subjkeyid %*phN\n", kid->len, kid->data);
447 		return 0;
448 	}
449 
450 	if (ctx->last_oid == OID_authorityKeyIdentifier) {
451 		/* Get hold of the CA key fingerprint */
452 		if (ctx->cert->authority || vlen < 5)
453 			return -EBADMSG;
454 
455 		/* Authority Key Identifier must be a Constructed SEQUENCE */
456 		if (v[0] != (ASN1_SEQ | (ASN1_CONS << 5)))
457 			return -EBADMSG;
458 
459 		/* Authority Key Identifier is not indefinite length */
460 		if (unlikely(vlen == ASN1_INDEFINITE_LENGTH))
461 			return -EBADMSG;
462 
463 		if (vlen < ASN1_INDEFINITE_LENGTH) {
464 			/* Short Form length */
465 			if (v[1] != vlen - 2 ||
466 			    v[2] != SEQ_TAG_KEYID ||
467 			    v[3] > vlen - 4)
468 				return -EBADMSG;
469 
470 			vlen = v[3];
471 			v += 4;
472 		} else {
473 			/* Long Form length */
474 			size_t seq_len = 0;
475 			size_t sub = v[1] - ASN1_INDEFINITE_LENGTH;
476 
477 			if (sub > 2)
478 				return -EBADMSG;
479 
480 			/* calculate the length from subsequent octets */
481 			v += 2;
482 			for (i = 0; i < sub; i++) {
483 				seq_len <<= 8;
484 				seq_len |= v[i];
485 			}
486 
487 			if (seq_len != vlen - 2 - sub ||
488 			    v[sub] != SEQ_TAG_KEYID ||
489 			    v[sub + 1] > vlen - 4 - sub)
490 				return -EBADMSG;
491 
492 			vlen = v[sub + 1];
493 			v += (sub + 2);
494 		}
495 
496 		kid = asymmetric_key_generate_id(ctx->cert->raw_issuer,
497 						 ctx->cert->raw_issuer_size,
498 						 v, vlen);
499 		if (IS_ERR(kid))
500 			return PTR_ERR(kid);
501 		pr_debug("authkeyid %*phN\n", kid->len, kid->data);
502 		ctx->cert->authority = kid;
503 		return 0;
504 	}
505 
506 	return 0;
507 }
508 
509 /*
510  * Record a certificate time.
511  */
512 static int x509_note_time(struct tm *tm,  size_t hdrlen,
513 			  unsigned char tag,
514 			  const unsigned char *value, size_t vlen)
515 {
516 	const unsigned char *p = value;
517 
518 #define dec2bin(X) ((X) - '0')
519 #define DD2bin(P) ({ unsigned x = dec2bin(P[0]) * 10 + dec2bin(P[1]); P += 2; x; })
520 
521 	if (tag == ASN1_UNITIM) {
522 		/* UTCTime: YYMMDDHHMMSSZ */
523 		if (vlen != 13)
524 			goto unsupported_time;
525 		tm->tm_year = DD2bin(p);
526 		if (tm->tm_year >= 50)
527 			tm->tm_year += 1900;
528 		else
529 			tm->tm_year += 2000;
530 	} else if (tag == ASN1_GENTIM) {
531 		/* GenTime: YYYYMMDDHHMMSSZ */
532 		if (vlen != 15)
533 			goto unsupported_time;
534 		tm->tm_year = DD2bin(p) * 100 + DD2bin(p);
535 	} else {
536 		goto unsupported_time;
537 	}
538 
539 	tm->tm_year -= 1900;
540 	tm->tm_mon  = DD2bin(p) - 1;
541 	tm->tm_mday = DD2bin(p);
542 	tm->tm_hour = DD2bin(p);
543 	tm->tm_min  = DD2bin(p);
544 	tm->tm_sec  = DD2bin(p);
545 
546 	if (*p != 'Z')
547 		goto unsupported_time;
548 
549 	return 0;
550 
551 unsupported_time:
552 	pr_debug("Got unsupported time [tag %02x]: '%*.*s'\n",
553 		 tag, (int)vlen, (int)vlen, value);
554 	return -EBADMSG;
555 }
556 
557 int x509_note_not_before(void *context, size_t hdrlen,
558 			 unsigned char tag,
559 			 const void *value, size_t vlen)
560 {
561 	struct x509_parse_context *ctx = context;
562 	return x509_note_time(&ctx->cert->valid_from, hdrlen, tag, value, vlen);
563 }
564 
565 int x509_note_not_after(void *context, size_t hdrlen,
566 			unsigned char tag,
567 			const void *value, size_t vlen)
568 {
569 	struct x509_parse_context *ctx = context;
570 	return x509_note_time(&ctx->cert->valid_to, hdrlen, tag, value, vlen);
571 }
572