x509_public_key.c 9.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* 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 <linux/err.h>
#include <linux/mpi.h>
#include <linux/asn1_decoder.h>
#include <keys/asymmetric-subtype.h>
#include <keys/asymmetric-parser.h>
21
#include <keys/system_keyring.h>
22 23 24 25 26
#include <crypto/hash.h>
#include "asymmetric_keys.h"
#include "public_key.h"
#include "x509_parser.h"

27
static bool use_builtin_keys;
28
static struct asymmetric_key_id *ca_keyid;
29 30

#ifndef MODULE
31 32 33 34 35
static struct {
	struct asymmetric_key_id id;
	unsigned char data[10];
} cakey;

36 37 38 39 40
static int __init ca_keys_setup(char *str)
{
	if (!str)		/* default system keyring */
		return 1;

41
	if (strncmp(str, "id:", 3) == 0) {
42 43 44 45 46 47 48 49 50 51 52 53 54
		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
55 56
			ca_keyid = p;	/* owner key 'id:xxxxxx' */
	} else if (strcmp(str, "builtin") == 0) {
57
		use_builtin_keys = true;
58
	}
59 60 61 62 63 64

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

65 66 67
/**
 * x509_request_asymmetric_key - Request a key by X.509 certificate params.
 * @keyring: The keys to search.
68
 * @kid: The key ID.
69
 * @partial: Use partial match if true, exact if false.
70 71 72 73
 *
 * Find a key in the given keyring by subject name and key ID.  These might,
 * for instance, be the issuer name and the authority key ID of an X.509
 * certificate that needs to be verified.
74
 */
75
struct key *x509_request_asymmetric_key(struct key *keyring,
76 77
					const struct asymmetric_key_id *kid,
					bool partial)
78 79
{
	key_ref_t key;
80
	char *id, *p;
81

82 83
	/* Construct an identifier "id:<keyid>". */
	p = id = kmalloc(2 + 1 + kid->len * 2 + 1, GFP_KERNEL);
84 85 86
	if (!id)
		return ERR_PTR(-ENOMEM);

87 88 89 90 91 92 93
	if (partial) {
		*p++ = 'i';
		*p++ = 'd';
	} else {
		*p++ = 'e';
		*p++ = 'x';
	}
94 95 96
	*p++ = ':';
	p = bin2hex(p, kid->data, kid->len);
	*p = 0;
97 98 99 100 101 102

	pr_debug("Look up: \"%s\"\n", id);

	key = keyring_search(make_key_ref(keyring, 1),
			     &key_type_asymmetric, id);
	if (IS_ERR(key))
103
		pr_debug("Request for key '%s' err %ld\n", id, PTR_ERR(key));
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
	kfree(id);

	if (IS_ERR(key)) {
		switch (PTR_ERR(key)) {
			/* Hide some search errors */
		case -EACCES:
		case -ENOTDIR:
		case -EAGAIN:
			return ERR_PTR(-ENOKEY);
		default:
			return ERR_CAST(key);
		}
	}

	pr_devel("<==%s() = 0 [%x]\n", __func__,
		 key_serial(key_ref_to_ptr(key)));
	return key_ref_to_ptr(key);
}
122
EXPORT_SYMBOL_GPL(x509_request_asymmetric_key);
123

124
/*
125 126
 * Set up the signature parameters in an X.509 certificate.  This involves
 * digesting the signed data and extracting the signature.
127
 */
128
int x509_get_sig_params(struct x509_certificate *cert)
129 130 131 132
{
	struct crypto_shash *tfm;
	struct shash_desc *desc;
	size_t digest_size, desc_size;
133
	void *digest;
134 135 136
	int ret;

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

138 139
	if (cert->unsupported_crypto)
		return -ENOPKG;
140 141 142 143 144 145 146 147
	if (cert->sig.rsa.s)
		return 0;

	cert->sig.rsa.s = mpi_read_raw_data(cert->raw_sig, cert->raw_sig_size);
	if (!cert->sig.rsa.s)
		return -ENOMEM;
	cert->sig.nr_mpi = 1;

148 149 150
	/* Allocate the hashing algorithm we're going to need and find out how
	 * big the hash operational data will be.
	 */
151
	tfm = crypto_alloc_shash(hash_algo_name[cert->sig.pkey_hash_algo], 0, 0);
152 153 154 155 156 157 158
	if (IS_ERR(tfm)) {
		if (PTR_ERR(tfm) == -ENOENT) {
			cert->unsupported_crypto = true;
			return -ENOPKG;
		}
		return PTR_ERR(tfm);
	}
159 160 161 162

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

163 164
	/* We allocate the hash operational data storage on the end of the
	 * digest storage space.
165 166
	 */
	ret = -ENOMEM;
167 168 169
	digest = kzalloc(digest_size + desc_size, GFP_KERNEL);
	if (!digest)
		goto error;
170

171 172
	cert->sig.digest = digest;
	cert->sig.digest_size = digest_size;
173

174 175 176
	desc = digest + digest_size;
	desc->tfm = tfm;
	desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
177 178 179 180

	ret = crypto_shash_init(desc);
	if (ret < 0)
		goto error;
181 182 183 184 185 186 187 188
	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);
189

190 191 192 193 194 195 196
/*
 * 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;
197

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

200 201 202
	ret = x509_get_sig_params(cert);
	if (ret < 0)
		return ret;
203

204
	ret = public_key_verify_signature(pub, &cert->sig);
205 206
	if (ret == -ENOPKG)
		cert->unsupported_crypto = true;
207 208 209
	pr_debug("Cert Verification: %d\n", ret);
	return ret;
}
210
EXPORT_SYMBOL_GPL(x509_check_signature);
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/*
 * 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;

230
	if (ca_keyid && !asymmetric_key_id_partial(cert->authority, ca_keyid))
231 232
		return -EPERM;

233 234
	key = x509_request_asymmetric_key(trust_keyring, cert->authority,
					  false);
235
	if (!IS_ERR(key))  {
236 237 238
		if (!use_builtin_keys
		    || test_bit(KEY_FLAG_BUILTIN, &key->flags))
			ret = x509_check_signature(key->payload.data, cert);
239 240 241 242 243
		key_put(key);
	}
	return ret;
}

244 245 246 247 248
/*
 * Attempt to parse a data blob for a key as an X509 certificate.
 */
static int x509_key_preparse(struct key_preparsed_payload *prep)
{
249
	struct asymmetric_key_ids *kids;
250
	struct x509_certificate *cert;
251
	const char *q;
252
	size_t srlen, sulen;
253
	char *desc = NULL, *p;
254 255 256 257 258 259 260 261
	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);
262 263 264 265 266 267

	if (cert->pub->pkey_algo >= PKEY_ALGO__LAST ||
	    cert->sig.pkey_algo >= PKEY_ALGO__LAST ||
	    cert->sig.pkey_hash_algo >= PKEY_HASH__LAST ||
	    !pkey_algo[cert->pub->pkey_algo] ||
	    !pkey_algo[cert->sig.pkey_algo] ||
268
	    !hash_algo_name[cert->sig.pkey_hash_algo]) {
269 270 271 272
		ret = -ENOPKG;
		goto error_free_cert;
	}

273
	pr_devel("Cert Key Algo: %s\n", pkey_algo_name[cert->pub->pkey_algo]);
274
	pr_devel("Cert Valid From: %04ld-%02d-%02d %02d:%02d:%02d\n",
275 276 277
		 cert->valid_from.tm_year + 1900, cert->valid_from.tm_mon + 1,
		 cert->valid_from.tm_mday, cert->valid_from.tm_hour,
		 cert->valid_from.tm_min,  cert->valid_from.tm_sec);
278
	pr_devel("Cert Valid To: %04ld-%02d-%02d %02d:%02d:%02d\n",
279 280 281
		 cert->valid_to.tm_year + 1900, cert->valid_to.tm_mon + 1,
		 cert->valid_to.tm_mday, cert->valid_to.tm_hour,
		 cert->valid_to.tm_min,  cert->valid_to.tm_sec);
282 283
	pr_devel("Cert Signature: %s + %s\n",
		 pkey_algo_name[cert->sig.pkey_algo],
284
		 hash_algo_name[cert->sig.pkey_hash_algo]);
285

286
	cert->pub->algo = pkey_algo[cert->pub->pkey_algo];
287 288
	cert->pub->id_type = PKEY_ID_X509;

289 290
	/* Check the signature on the key if it appears to be self-signed */
	if (!cert->authority ||
291
	    asymmetric_key_id_same(cert->skid, cert->authority)) {
292
		ret = x509_check_signature(cert->pub, cert); /* self-signed */
293 294
		if (ret < 0)
			goto error_free_cert;
295 296 297 298
	} else if (!prep->trusted) {
		ret = x509_validate_trust(cert, get_system_trusted_keyring());
		if (!ret)
			prep->trusted = 1;
299 300 301 302
	}

	/* Propose a description */
	sulen = strlen(cert->subject);
303 304 305 306 307 308 309
	if (cert->raw_skid) {
		srlen = cert->raw_skid_size;
		q = cert->raw_skid;
	} else {
		srlen = cert->raw_serial_size;
		q = cert->raw_serial;
	}
310 311 312 313 314
	if (srlen > 1 && *q == 0) {
		srlen--;
		q++;
	}

315
	ret = -ENOMEM;
316
	desc = kmalloc(sulen + 2 + srlen * 2 + 1, GFP_KERNEL);
317 318
	if (!desc)
		goto error_free_cert;
319 320 321 322 323 324 325 326 327 328 329 330
	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;
331 332 333 334

	/* We're pinning the module by being linked against it */
	__module_get(public_key_subtype.owner);
	prep->type_data[0] = &public_key_subtype;
335
	prep->type_data[1] = kids;
336
	prep->payload[0] = cert->pub;
337 338 339 340 341
	prep->description = desc;
	prep->quotalen = 100;

	/* We've finished with the certificate */
	cert->pub = NULL;
342 343
	cert->id = NULL;
	cert->skid = NULL;
344 345 346
	desc = NULL;
	ret = 0;

347 348
error_free_desc:
	kfree(desc);
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
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);
375 376 377

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