x509_public_key.c 9.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Instantiate a public key crypto key from an X.509 Certificate
 *
 * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
 * Written by David Howells (dhowells@redhat.com)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public Licence
 * as published by the Free Software Foundation; either version
 * 2 of the Licence, or (at your option) any later version.
 */

#define pr_fmt(fmt) "X.509: "fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <keys/asymmetric-subtype.h>
#include <keys/asymmetric-parser.h>
18
#include <keys/system_keyring.h>
19 20 21 22
#include <crypto/hash.h>
#include "asymmetric_keys.h"
#include "x509_parser.h"

23
static bool use_builtin_keys;
24
static struct asymmetric_key_id *ca_keyid;
25 26

#ifndef MODULE
27 28 29 30 31
static struct {
	struct asymmetric_key_id id;
	unsigned char data[10];
} cakey;

32 33 34 35 36
static int __init ca_keys_setup(char *str)
{
	if (!str)		/* default system keyring */
		return 1;

37
	if (strncmp(str, "id:", 3) == 0) {
38 39 40 41 42 43 44 45 46 47 48 49 50
		struct asymmetric_key_id *p = &cakey.id;
		size_t hexlen = (strlen(str) - 3) / 2;
		int ret;

		if (hexlen == 0 || hexlen > sizeof(cakey.data)) {
			pr_err("Missing or invalid ca_keys id\n");
			return 1;
		}

		ret = __asymmetric_key_hex_to_key_id(str + 3, p, hexlen);
		if (ret < 0)
			pr_err("Unparsable ca_keys id hex string\n");
		else
51 52
			ca_keyid = p;	/* owner key 'id:xxxxxx' */
	} else if (strcmp(str, "builtin") == 0) {
53
		use_builtin_keys = true;
54
	}
55 56 57 58 59 60

	return 1;
}
__setup("ca_keys=", ca_keys_setup);
#endif

61 62 63
/**
 * x509_request_asymmetric_key - Request a key by X.509 certificate params.
 * @keyring: The keys to search.
64 65
 * @id: The issuer & serialNumber to look for or NULL.
 * @skid: The subjectKeyIdentifier to look for or NULL.
66
 * @partial: Use partial match if true, exact if false.
67
 *
68 69 70 71
 * Find a key in the given keyring by identifier.  The preferred identifier is
 * the issuer + serialNumber and the fallback identifier is the
 * subjectKeyIdentifier.  If both are given, the lookup is by the former, but
 * the latter must also match.
72
 */
73
struct key *x509_request_asymmetric_key(struct key *keyring,
74 75
					const struct asymmetric_key_id *id,
					const struct asymmetric_key_id *skid,
76
					bool partial)
77
{
78 79 80 81 82 83 84 85 86 87 88 89 90 91
	struct key *key;
	key_ref_t ref;
	const char *lookup;
	char *req, *p;
	int len;

	if (id) {
		lookup = id->data;
		len = id->len;
	} else {
		lookup = skid->data;
		len = skid->len;
	}
	
92
	/* Construct an identifier "id:<keyid>". */
93 94
	p = req = kmalloc(2 + 1 + len * 2 + 1, GFP_KERNEL);
	if (!req)
95 96
		return ERR_PTR(-ENOMEM);

97 98 99 100 101 102 103
	if (partial) {
		*p++ = 'i';
		*p++ = 'd';
	} else {
		*p++ = 'e';
		*p++ = 'x';
	}
104
	*p++ = ':';
105
	p = bin2hex(p, lookup, len);
106
	*p = 0;
107

108
	pr_debug("Look up: \"%s\"\n", req);
109

110 111 112 113 114
	ref = keyring_search(make_key_ref(keyring, 1),
			     &key_type_asymmetric, req);
	if (IS_ERR(ref))
		pr_debug("Request for key '%s' err %ld\n", req, PTR_ERR(ref));
	kfree(req);
115

116 117
	if (IS_ERR(ref)) {
		switch (PTR_ERR(ref)) {
118 119 120 121 122 123
			/* Hide some search errors */
		case -EACCES:
		case -ENOTDIR:
		case -EAGAIN:
			return ERR_PTR(-ENOKEY);
		default:
124 125 126 127 128 129 130 131 132 133 134 135 136 137
			return ERR_CAST(ref);
		}
	}

	key = key_ref_to_ptr(ref);
	if (id && skid) {
		const struct asymmetric_key_ids *kids = asymmetric_key_ids(key);
		if (!kids->id[1]) {
			pr_debug("issuer+serial match, but expected SKID missing\n");
			goto reject;
		}
		if (!asymmetric_key_id_same(skid, kids->id[1])) {
			pr_debug("issuer+serial match, but SKID does not\n");
			goto reject;
138 139
		}
	}
140 141 142
	
	pr_devel("<==%s() = 0 [%x]\n", __func__, key_serial(key));
	return key;
143

144 145 146
reject:
	key_put(key);
	return ERR_PTR(-EKEYREJECTED);
147
}
148
EXPORT_SYMBOL_GPL(x509_request_asymmetric_key);
149

150
/*
151 152
 * Set up the signature parameters in an X.509 certificate.  This involves
 * digesting the signed data and extracting the signature.
153
 */
154
int x509_get_sig_params(struct x509_certificate *cert)
155 156 157 158
{
	struct crypto_shash *tfm;
	struct shash_desc *desc;
	size_t digest_size, desc_size;
159
	void *digest;
160 161 162
	int ret;

	pr_devel("==>%s()\n", __func__);
163

164 165
	if (cert->unsupported_crypto)
		return -ENOPKG;
166
	if (cert->sig.s)
167 168
		return 0;

169 170 171
	cert->sig.s = kmemdup(cert->raw_sig, cert->raw_sig_size,
			      GFP_KERNEL);
	if (!cert->sig.s)
172
		return -ENOMEM;
173 174

	cert->sig.s_size = cert->raw_sig_size;
175

176 177 178
	/* Allocate the hashing algorithm we're going to need and find out how
	 * big the hash operational data will be.
	 */
179
	tfm = crypto_alloc_shash(hash_algo_name[cert->sig.pkey_hash_algo], 0, 0);
180 181 182 183 184 185 186
	if (IS_ERR(tfm)) {
		if (PTR_ERR(tfm) == -ENOENT) {
			cert->unsupported_crypto = true;
			return -ENOPKG;
		}
		return PTR_ERR(tfm);
	}
187 188 189 190

	desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
	digest_size = crypto_shash_digestsize(tfm);

191 192
	/* We allocate the hash operational data storage on the end of the
	 * digest storage space.
193 194
	 */
	ret = -ENOMEM;
195 196
	digest = kzalloc(ALIGN(digest_size, __alignof__(*desc)) + desc_size,
			 GFP_KERNEL);
197 198
	if (!digest)
		goto error;
199

200 201
	cert->sig.digest = digest;
	cert->sig.digest_size = digest_size;
202

203
	desc = PTR_ALIGN(digest + digest_size, __alignof__(*desc));
204 205
	desc->tfm = tfm;
	desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
206 207 208 209

	ret = crypto_shash_init(desc);
	if (ret < 0)
		goto error;
210 211 212 213 214 215 216 217
	might_sleep();
	ret = crypto_shash_finup(desc, cert->tbs, cert->tbs_size, digest);
error:
	crypto_free_shash(tfm);
	pr_devel("<==%s() = %d\n", __func__, ret);
	return ret;
}
EXPORT_SYMBOL_GPL(x509_get_sig_params);
218

219 220 221 222 223 224 225
/*
 * Check the signature on a certificate using the provided public key
 */
int x509_check_signature(const struct public_key *pub,
			 struct x509_certificate *cert)
{
	int ret;
226

227
	pr_devel("==>%s()\n", __func__);
228

229 230 231
	ret = x509_get_sig_params(cert);
	if (ret < 0)
		return ret;
232

233
	ret = public_key_verify_signature(pub, &cert->sig);
234 235
	if (ret == -ENOPKG)
		cert->unsupported_crypto = true;
236 237 238
	pr_debug("Cert Verification: %d\n", ret);
	return ret;
}
239
EXPORT_SYMBOL_GPL(x509_check_signature);
240

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
/*
 * Check the new certificate against the ones in the trust keyring.  If one of
 * those is the signing key and validates the new certificate, then mark the
 * new certificate as being trusted.
 *
 * Return 0 if the new certificate was successfully validated, 1 if we couldn't
 * find a matching parent certificate in the trusted list and an error if there
 * is a matching certificate but the signature check fails.
 */
static int x509_validate_trust(struct x509_certificate *cert,
			       struct key *trust_keyring)
{
	struct key *key;
	int ret = 1;

	if (!trust_keyring)
		return -EOPNOTSUPP;

259
	if (ca_keyid && !asymmetric_key_id_partial(cert->akid_skid, ca_keyid))
260 261
		return -EPERM;

262 263
	key = x509_request_asymmetric_key(trust_keyring,
					  cert->akid_id, cert->akid_skid,
264
					  false);
265
	if (!IS_ERR(key))  {
266 267
		if (!use_builtin_keys
		    || test_bit(KEY_FLAG_BUILTIN, &key->flags))
268 269
			ret = x509_check_signature(key->payload.data[asym_crypto],
						   cert);
270 271 272 273 274
		key_put(key);
	}
	return ret;
}

275 276 277 278 279
/*
 * Attempt to parse a data blob for a key as an X509 certificate.
 */
static int x509_key_preparse(struct key_preparsed_payload *prep)
{
280
	struct asymmetric_key_ids *kids;
281
	struct x509_certificate *cert;
282
	const char *q;
283
	size_t srlen, sulen;
284
	char *desc = NULL, *p;
285 286 287 288 289 290 291 292
	int ret;

	cert = x509_cert_parse(prep->data, prep->datalen);
	if (IS_ERR(cert))
		return PTR_ERR(cert);

	pr_devel("Cert Issuer: %s\n", cert->issuer);
	pr_devel("Cert Subject: %s\n", cert->subject);
293 294 295 296

	if (cert->pub->pkey_algo >= PKEY_ALGO__LAST ||
	    cert->sig.pkey_algo >= PKEY_ALGO__LAST ||
	    cert->sig.pkey_hash_algo >= PKEY_HASH__LAST ||
297
	    !hash_algo_name[cert->sig.pkey_hash_algo]) {
298 299 300 301
		ret = -ENOPKG;
		goto error_free_cert;
	}

302
	pr_devel("Cert Key Algo: %s\n", pkey_algo_name[cert->pub->pkey_algo]);
303
	pr_devel("Cert Valid period: %lld-%lld\n", cert->valid_from, cert->valid_to);
304 305
	pr_devel("Cert Signature: %s + %s\n",
		 pkey_algo_name[cert->sig.pkey_algo],
306
		 hash_algo_name[cert->sig.pkey_hash_algo]);
307 308 309

	cert->pub->id_type = PKEY_ID_X509;

310
	/* Check the signature on the key if it appears to be self-signed */
311 312 313
	if ((!cert->akid_skid && !cert->akid_id) ||
	    asymmetric_key_id_same(cert->skid, cert->akid_skid) ||
	    asymmetric_key_id_same(cert->id, cert->akid_id)) {
314
		ret = x509_check_signature(cert->pub, cert); /* self-signed */
315 316
		if (ret < 0)
			goto error_free_cert;
317 318
	} else if (!prep->trusted) {
		ret = x509_validate_trust(cert, get_system_trusted_keyring());
319 320
		if (ret)
			ret = x509_validate_trust(cert, get_ima_mok_keyring());
321 322
		if (!ret)
			prep->trusted = 1;
323 324 325 326
	}

	/* Propose a description */
	sulen = strlen(cert->subject);
327 328 329 330 331 332 333
	if (cert->raw_skid) {
		srlen = cert->raw_skid_size;
		q = cert->raw_skid;
	} else {
		srlen = cert->raw_serial_size;
		q = cert->raw_serial;
	}
334

335
	ret = -ENOMEM;
336
	desc = kmalloc(sulen + 2 + srlen * 2 + 1, GFP_KERNEL);
337 338
	if (!desc)
		goto error_free_cert;
339 340 341 342 343 344 345 346 347 348 349 350
	p = memcpy(desc, cert->subject, sulen);
	p += sulen;
	*p++ = ':';
	*p++ = ' ';
	p = bin2hex(p, q, srlen);
	*p = 0;

	kids = kmalloc(sizeof(struct asymmetric_key_ids), GFP_KERNEL);
	if (!kids)
		goto error_free_desc;
	kids->id[0] = cert->id;
	kids->id[1] = cert->skid;
351 352 353

	/* We're pinning the module by being linked against it */
	__module_get(public_key_subtype.owner);
354 355 356
	prep->payload.data[asym_subtype] = &public_key_subtype;
	prep->payload.data[asym_key_ids] = kids;
	prep->payload.data[asym_crypto] = cert->pub;
357 358 359 360 361
	prep->description = desc;
	prep->quotalen = 100;

	/* We've finished with the certificate */
	cert->pub = NULL;
362 363
	cert->id = NULL;
	cert->skid = NULL;
364 365 366
	desc = NULL;
	ret = 0;

367 368
error_free_desc:
	kfree(desc);
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
error_free_cert:
	x509_free_certificate(cert);
	return ret;
}

static struct asymmetric_key_parser x509_key_parser = {
	.owner	= THIS_MODULE,
	.name	= "x509",
	.parse	= x509_key_preparse,
};

/*
 * Module stuff
 */
static int __init x509_key_init(void)
{
	return register_asymmetric_key_parser(&x509_key_parser);
}

static void __exit x509_key_exit(void)
{
	unregister_asymmetric_key_parser(&x509_key_parser);
}

module_init(x509_key_init);
module_exit(x509_key_exit);
395 396 397

MODULE_DESCRIPTION("X.509 certificate parser");
MODULE_LICENSE("GPL");