1 /* Instantiate a public key crypto key from an X.509 Certificate
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/module.h>
14 #include <linux/kernel.h>
15 #include <linux/slab.h>
16 #include <linux/err.h>
17 #include <linux/mpi.h>
18 #include <linux/asn1_decoder.h>
19 #include <keys/asymmetric-subtype.h>
20 #include <keys/asymmetric-parser.h>
21 #include <keys/system_keyring.h>
22 #include <crypto/hash.h>
23 #include "asymmetric_keys.h"
24 #include "public_key.h"
25 #include "x509_parser.h"
26 
27 static bool use_builtin_keys;
28 static struct asymmetric_key_id *ca_keyid;
29 
30 #ifndef MODULE
31 static int __init ca_keys_setup(char *str)
32 {
33 	if (!str)		/* default system keyring */
34 		return 1;
35 
36 	if (strncmp(str, "id:", 3) == 0) {
37 		struct asymmetric_key_id *p;
38 		p = asymmetric_key_hex_to_key_id(str + 3);
39 		if (p == ERR_PTR(-EINVAL))
40 			pr_err("Unparsable hex string in ca_keys\n");
41 		else if (!IS_ERR(p))
42 			ca_keyid = p;	/* owner key 'id:xxxxxx' */
43 	} else if (strcmp(str, "builtin") == 0) {
44 		use_builtin_keys = true;
45 	}
46 
47 	return 1;
48 }
49 __setup("ca_keys=", ca_keys_setup);
50 #endif
51 
52 /**
53  * x509_request_asymmetric_key - Request a key by X.509 certificate params.
54  * @keyring: The keys to search.
55  * @kid: The key ID.
56  * @partial: Use partial match if true, exact if false.
57  *
58  * Find a key in the given keyring by subject name and key ID.  These might,
59  * for instance, be the issuer name and the authority key ID of an X.509
60  * certificate that needs to be verified.
61  */
62 struct key *x509_request_asymmetric_key(struct key *keyring,
63 					const struct asymmetric_key_id *kid,
64 					bool partial)
65 {
66 	key_ref_t key;
67 	char *id, *p;
68 
69 	/* Construct an identifier "id:<keyid>". */
70 	p = id = kmalloc(2 + 1 + kid->len * 2 + 1, GFP_KERNEL);
71 	if (!id)
72 		return ERR_PTR(-ENOMEM);
73 
74 	if (partial) {
75 		*p++ = 'i';
76 		*p++ = 'd';
77 	} else {
78 		*p++ = 'e';
79 		*p++ = 'x';
80 	}
81 	*p++ = ':';
82 	p = bin2hex(p, kid->data, kid->len);
83 	*p = 0;
84 
85 	pr_debug("Look up: \"%s\"\n", id);
86 
87 	key = keyring_search(make_key_ref(keyring, 1),
88 			     &key_type_asymmetric, id);
89 	if (IS_ERR(key))
90 		pr_debug("Request for key '%s' err %ld\n", id, PTR_ERR(key));
91 	kfree(id);
92 
93 	if (IS_ERR(key)) {
94 		switch (PTR_ERR(key)) {
95 			/* Hide some search errors */
96 		case -EACCES:
97 		case -ENOTDIR:
98 		case -EAGAIN:
99 			return ERR_PTR(-ENOKEY);
100 		default:
101 			return ERR_CAST(key);
102 		}
103 	}
104 
105 	pr_devel("<==%s() = 0 [%x]\n", __func__,
106 		 key_serial(key_ref_to_ptr(key)));
107 	return key_ref_to_ptr(key);
108 }
109 EXPORT_SYMBOL_GPL(x509_request_asymmetric_key);
110 
111 /*
112  * Set up the signature parameters in an X.509 certificate.  This involves
113  * digesting the signed data and extracting the signature.
114  */
115 int x509_get_sig_params(struct x509_certificate *cert)
116 {
117 	struct crypto_shash *tfm;
118 	struct shash_desc *desc;
119 	size_t digest_size, desc_size;
120 	void *digest;
121 	int ret;
122 
123 	pr_devel("==>%s()\n", __func__);
124 
125 	if (cert->unsupported_crypto)
126 		return -ENOPKG;
127 	if (cert->sig.rsa.s)
128 		return 0;
129 
130 	cert->sig.rsa.s = mpi_read_raw_data(cert->raw_sig, cert->raw_sig_size);
131 	if (!cert->sig.rsa.s)
132 		return -ENOMEM;
133 	cert->sig.nr_mpi = 1;
134 
135 	/* Allocate the hashing algorithm we're going to need and find out how
136 	 * big the hash operational data will be.
137 	 */
138 	tfm = crypto_alloc_shash(hash_algo_name[cert->sig.pkey_hash_algo], 0, 0);
139 	if (IS_ERR(tfm)) {
140 		if (PTR_ERR(tfm) == -ENOENT) {
141 			cert->unsupported_crypto = true;
142 			return -ENOPKG;
143 		}
144 		return PTR_ERR(tfm);
145 	}
146 
147 	desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
148 	digest_size = crypto_shash_digestsize(tfm);
149 
150 	/* We allocate the hash operational data storage on the end of the
151 	 * digest storage space.
152 	 */
153 	ret = -ENOMEM;
154 	digest = kzalloc(digest_size + desc_size, GFP_KERNEL);
155 	if (!digest)
156 		goto error;
157 
158 	cert->sig.digest = digest;
159 	cert->sig.digest_size = digest_size;
160 
161 	desc = digest + digest_size;
162 	desc->tfm = tfm;
163 	desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
164 
165 	ret = crypto_shash_init(desc);
166 	if (ret < 0)
167 		goto error;
168 	might_sleep();
169 	ret = crypto_shash_finup(desc, cert->tbs, cert->tbs_size, digest);
170 error:
171 	crypto_free_shash(tfm);
172 	pr_devel("<==%s() = %d\n", __func__, ret);
173 	return ret;
174 }
175 EXPORT_SYMBOL_GPL(x509_get_sig_params);
176 
177 /*
178  * Check the signature on a certificate using the provided public key
179  */
180 int x509_check_signature(const struct public_key *pub,
181 			 struct x509_certificate *cert)
182 {
183 	int ret;
184 
185 	pr_devel("==>%s()\n", __func__);
186 
187 	ret = x509_get_sig_params(cert);
188 	if (ret < 0)
189 		return ret;
190 
191 	ret = public_key_verify_signature(pub, &cert->sig);
192 	if (ret == -ENOPKG)
193 		cert->unsupported_crypto = true;
194 	pr_debug("Cert Verification: %d\n", ret);
195 	return ret;
196 }
197 EXPORT_SYMBOL_GPL(x509_check_signature);
198 
199 /*
200  * Check the new certificate against the ones in the trust keyring.  If one of
201  * those is the signing key and validates the new certificate, then mark the
202  * new certificate as being trusted.
203  *
204  * Return 0 if the new certificate was successfully validated, 1 if we couldn't
205  * find a matching parent certificate in the trusted list and an error if there
206  * is a matching certificate but the signature check fails.
207  */
208 static int x509_validate_trust(struct x509_certificate *cert,
209 			       struct key *trust_keyring)
210 {
211 	struct key *key;
212 	int ret = 1;
213 
214 	if (!trust_keyring)
215 		return -EOPNOTSUPP;
216 
217 	if (ca_keyid && !asymmetric_key_id_partial(cert->authority, ca_keyid))
218 		return -EPERM;
219 
220 	key = x509_request_asymmetric_key(trust_keyring, cert->authority,
221 					  false);
222 	if (!IS_ERR(key))  {
223 		if (!use_builtin_keys
224 		    || test_bit(KEY_FLAG_BUILTIN, &key->flags))
225 			ret = x509_check_signature(key->payload.data, cert);
226 		key_put(key);
227 	}
228 	return ret;
229 }
230 
231 /*
232  * Attempt to parse a data blob for a key as an X509 certificate.
233  */
234 static int x509_key_preparse(struct key_preparsed_payload *prep)
235 {
236 	struct asymmetric_key_ids *kids;
237 	struct x509_certificate *cert;
238 	const char *q;
239 	size_t srlen, sulen;
240 	char *desc = NULL, *p;
241 	int ret;
242 
243 	cert = x509_cert_parse(prep->data, prep->datalen);
244 	if (IS_ERR(cert))
245 		return PTR_ERR(cert);
246 
247 	pr_devel("Cert Issuer: %s\n", cert->issuer);
248 	pr_devel("Cert Subject: %s\n", cert->subject);
249 
250 	if (cert->pub->pkey_algo >= PKEY_ALGO__LAST ||
251 	    cert->sig.pkey_algo >= PKEY_ALGO__LAST ||
252 	    cert->sig.pkey_hash_algo >= PKEY_HASH__LAST ||
253 	    !pkey_algo[cert->pub->pkey_algo] ||
254 	    !pkey_algo[cert->sig.pkey_algo] ||
255 	    !hash_algo_name[cert->sig.pkey_hash_algo]) {
256 		ret = -ENOPKG;
257 		goto error_free_cert;
258 	}
259 
260 	pr_devel("Cert Key Algo: %s\n", pkey_algo_name[cert->pub->pkey_algo]);
261 	pr_devel("Cert Valid From: %04ld-%02d-%02d %02d:%02d:%02d\n",
262 		 cert->valid_from.tm_year + 1900, cert->valid_from.tm_mon + 1,
263 		 cert->valid_from.tm_mday, cert->valid_from.tm_hour,
264 		 cert->valid_from.tm_min,  cert->valid_from.tm_sec);
265 	pr_devel("Cert Valid To: %04ld-%02d-%02d %02d:%02d:%02d\n",
266 		 cert->valid_to.tm_year + 1900, cert->valid_to.tm_mon + 1,
267 		 cert->valid_to.tm_mday, cert->valid_to.tm_hour,
268 		 cert->valid_to.tm_min,  cert->valid_to.tm_sec);
269 	pr_devel("Cert Signature: %s + %s\n",
270 		 pkey_algo_name[cert->sig.pkey_algo],
271 		 hash_algo_name[cert->sig.pkey_hash_algo]);
272 
273 	cert->pub->algo = pkey_algo[cert->pub->pkey_algo];
274 	cert->pub->id_type = PKEY_ID_X509;
275 
276 	/* Check the signature on the key if it appears to be self-signed */
277 	if (!cert->authority ||
278 	    asymmetric_key_id_same(cert->skid, cert->authority)) {
279 		ret = x509_check_signature(cert->pub, cert); /* self-signed */
280 		if (ret < 0)
281 			goto error_free_cert;
282 	} else if (!prep->trusted) {
283 		ret = x509_validate_trust(cert, get_system_trusted_keyring());
284 		if (!ret)
285 			prep->trusted = 1;
286 	}
287 
288 	/* Propose a description */
289 	sulen = strlen(cert->subject);
290 	if (cert->raw_skid) {
291 		srlen = cert->raw_skid_size;
292 		q = cert->raw_skid;
293 	} else {
294 		srlen = cert->raw_serial_size;
295 		q = cert->raw_serial;
296 	}
297 	if (srlen > 1 && *q == 0) {
298 		srlen--;
299 		q++;
300 	}
301 
302 	ret = -ENOMEM;
303 	desc = kmalloc(sulen + 2 + srlen * 2 + 1, GFP_KERNEL);
304 	if (!desc)
305 		goto error_free_cert;
306 	p = memcpy(desc, cert->subject, sulen);
307 	p += sulen;
308 	*p++ = ':';
309 	*p++ = ' ';
310 	p = bin2hex(p, q, srlen);
311 	*p = 0;
312 
313 	kids = kmalloc(sizeof(struct asymmetric_key_ids), GFP_KERNEL);
314 	if (!kids)
315 		goto error_free_desc;
316 	kids->id[0] = cert->id;
317 	kids->id[1] = cert->skid;
318 
319 	/* We're pinning the module by being linked against it */
320 	__module_get(public_key_subtype.owner);
321 	prep->type_data[0] = &public_key_subtype;
322 	prep->type_data[1] = kids;
323 	prep->payload[0] = cert->pub;
324 	prep->description = desc;
325 	prep->quotalen = 100;
326 
327 	/* We've finished with the certificate */
328 	cert->pub = NULL;
329 	cert->id = NULL;
330 	cert->skid = NULL;
331 	desc = NULL;
332 	ret = 0;
333 
334 error_free_desc:
335 	kfree(desc);
336 error_free_cert:
337 	x509_free_certificate(cert);
338 	return ret;
339 }
340 
341 static struct asymmetric_key_parser x509_key_parser = {
342 	.owner	= THIS_MODULE,
343 	.name	= "x509",
344 	.parse	= x509_key_preparse,
345 };
346 
347 /*
348  * Module stuff
349  */
350 static int __init x509_key_init(void)
351 {
352 	return register_asymmetric_key_parser(&x509_key_parser);
353 }
354 
355 static void __exit x509_key_exit(void)
356 {
357 	unregister_asymmetric_key_parser(&x509_key_parser);
358 }
359 
360 module_init(x509_key_init);
361 module_exit(x509_key_exit);
362 
363 MODULE_DESCRIPTION("X.509 certificate parser");
364 MODULE_LICENSE("GPL");
365