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