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