1// SPDX-License-Identifier: GPL-2.0-or-later
2/* Verify the signature on a PKCS#7 message.
3 *
4 * Copyright (C) 2012 Red Hat, Inc. All Rights Reserved.
5 * Written by David Howells (dhowells@redhat.com)
6 */
7
8#define pr_fmt(fmt) "PKCS7: "fmt
9#include <linux/kernel.h>
10#include <linux/export.h>
11#include <linux/slab.h>
12#include <linux/err.h>
13#include <linux/asn1.h>
14#include <crypto/hash.h>
15#include <crypto/hash_info.h>
16#include <crypto/public_key.h>
17#include "pkcs7_parser.h"
18
19/*
20 * Digest the relevant parts of the PKCS#7 data
21 */
22static int pkcs7_digest(struct pkcs7_message *pkcs7,
23			struct pkcs7_signed_info *sinfo)
24{
25	struct public_key_signature *sig = sinfo->sig;
26	struct crypto_shash *tfm;
27	struct shash_desc *desc;
28	size_t desc_size;
29	int ret;
30
31	kenter(",%u,%s", sinfo->index, sinfo->sig->hash_algo);
32
33	/* The digest was calculated already. */
34	if (sig->digest)
35		return 0;
36
37	if (!sinfo->sig->hash_algo)
38		return -ENOPKG;
39
40	/* Allocate the hashing algorithm we're going to need and find out how
41	 * big the hash operational data will be.
42	 */
43	tfm = crypto_alloc_shash(sinfo->sig->hash_algo, 0, 0);
44	if (IS_ERR(tfm))
45		return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm);
46
47	desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
48	sig->digest_size = crypto_shash_digestsize(tfm);
49
50	ret = -ENOMEM;
51	sig->digest = kmalloc(sig->digest_size, GFP_KERNEL);
52	if (!sig->digest)
53		goto error_no_desc;
54
55	desc = kzalloc(desc_size, GFP_KERNEL);
56	if (!desc)
57		goto error_no_desc;
58
59	desc->tfm   = tfm;
60
61	/* Digest the message [RFC2315 9.3] */
62	ret = crypto_shash_digest(desc, pkcs7->data, pkcs7->data_len,
63				  sig->digest);
64	if (ret < 0)
65		goto error;
66	pr_devel("MsgDigest = [%*ph]\n", 8, sig->digest);
67
68	/* However, if there are authenticated attributes, there must be a
69	 * message digest attribute amongst them which corresponds to the
70	 * digest we just calculated.
71	 */
72	if (sinfo->authattrs) {
73		u8 tag;
74
75		if (!sinfo->msgdigest) {
76			pr_warn("Sig %u: No messageDigest\n", sinfo->index);
77			ret = -EKEYREJECTED;
78			goto error;
79		}
80
81		if (sinfo->msgdigest_len != sig->digest_size) {
82			pr_warn("Sig %u: Invalid digest size (%u)\n",
83				sinfo->index, sinfo->msgdigest_len);
84			ret = -EBADMSG;
85			goto error;
86		}
87
88		if (memcmp(sig->digest, sinfo->msgdigest,
89			   sinfo->msgdigest_len) != 0) {
90			pr_warn("Sig %u: Message digest doesn't match\n",
91				sinfo->index);
92			ret = -EKEYREJECTED;
93			goto error;
94		}
95
96		/* We then calculate anew, using the authenticated attributes
97		 * as the contents of the digest instead.  Note that we need to
98		 * convert the attributes from a CONT.0 into a SET before we
99		 * hash it.
100		 */
101		memset(sig->digest, 0, sig->digest_size);
102
103		ret = crypto_shash_init(desc);
104		if (ret < 0)
105			goto error;
106		tag = ASN1_CONS_BIT | ASN1_SET;
107		ret = crypto_shash_update(desc, &tag, 1);
108		if (ret < 0)
109			goto error;
110		ret = crypto_shash_finup(desc, sinfo->authattrs,
111					 sinfo->authattrs_len, sig->digest);
112		if (ret < 0)
113			goto error;
114		pr_devel("AADigest = [%*ph]\n", 8, sig->digest);
115	}
116
117error:
118	kfree(desc);
119error_no_desc:
120	crypto_free_shash(tfm);
121	kleave(" = %d", ret);
122	return ret;
123}
124
125int pkcs7_get_digest(struct pkcs7_message *pkcs7, const u8 **buf, u32 *len,
126		     enum hash_algo *hash_algo)
127{
128	struct pkcs7_signed_info *sinfo = pkcs7->signed_infos;
129	int i, ret;
130
131	/*
132	 * This function doesn't support messages with more than one signature.
133	 */
134	if (sinfo == NULL || sinfo->next != NULL)
135		return -EBADMSG;
136
137	ret = pkcs7_digest(pkcs7, sinfo);
138	if (ret)
139		return ret;
140
141	*buf = sinfo->sig->digest;
142	*len = sinfo->sig->digest_size;
143
144	for (i = 0; i < HASH_ALGO__LAST; i++)
145		if (!strcmp(hash_algo_name[i], sinfo->sig->hash_algo)) {
146			*hash_algo = i;
147			break;
148		}
149
150	return 0;
151}
152
153/*
154 * Find the key (X.509 certificate) to use to verify a PKCS#7 message.  PKCS#7
155 * uses the issuer's name and the issuing certificate serial number for
156 * matching purposes.  These must match the certificate issuer's name (not
157 * subject's name) and the certificate serial number [RFC 2315 6.7].
158 */
159static int pkcs7_find_key(struct pkcs7_message *pkcs7,
160			  struct pkcs7_signed_info *sinfo)
161{
162	struct x509_certificate *x509;
163	unsigned certix = 1;
164
165	kenter("%u", sinfo->index);
166
167	for (x509 = pkcs7->certs; x509; x509 = x509->next, certix++) {
168		/* I'm _assuming_ that the generator of the PKCS#7 message will
169		 * encode the fields from the X.509 cert in the same way in the
170		 * PKCS#7 message - but I can't be 100% sure of that.  It's
171		 * possible this will need element-by-element comparison.
172		 */
173		if (!asymmetric_key_id_same(x509->id, sinfo->sig->auth_ids[0]))
174			continue;
175		pr_devel("Sig %u: Found cert serial match X.509[%u]\n",
176			 sinfo->index, certix);
177
178		sinfo->signer = x509;
179		return 0;
180	}
181
182	/* The relevant X.509 cert isn't found here, but it might be found in
183	 * the trust keyring.
184	 */
185	pr_debug("Sig %u: Issuing X.509 cert not found (#%*phN)\n",
186		 sinfo->index,
187		 sinfo->sig->auth_ids[0]->len, sinfo->sig->auth_ids[0]->data);
188	return 0;
189}
190
191/*
192 * Verify the internal certificate chain as best we can.
193 */
194static int pkcs7_verify_sig_chain(struct pkcs7_message *pkcs7,
195				  struct pkcs7_signed_info *sinfo)
196{
197	struct public_key_signature *sig;
198	struct x509_certificate *x509 = sinfo->signer, *p;
199	struct asymmetric_key_id *auth;
200	int ret;
201
202	kenter("");
203
204	for (p = pkcs7->certs; p; p = p->next)
205		p->seen = false;
206
207	for (;;) {
208		pr_debug("verify %s: %*phN\n",
209			 x509->subject,
210			 x509->raw_serial_size, x509->raw_serial);
211		x509->seen = true;
212
213		if (x509->blacklisted) {
214			/* If this cert is blacklisted, then mark everything
215			 * that depends on this as blacklisted too.
216			 */
217			sinfo->blacklisted = true;
218			for (p = sinfo->signer; p != x509; p = p->signer)
219				p->blacklisted = true;
220			pr_debug("- blacklisted\n");
221			return 0;
222		}
223
224		if (x509->unsupported_key)
225			goto unsupported_crypto_in_x509;
226
227		pr_debug("- issuer %s\n", x509->issuer);
228		sig = x509->sig;
229		if (sig->auth_ids[0])
230			pr_debug("- authkeyid.id %*phN\n",
231				 sig->auth_ids[0]->len, sig->auth_ids[0]->data);
232		if (sig->auth_ids[1])
233			pr_debug("- authkeyid.skid %*phN\n",
234				 sig->auth_ids[1]->len, sig->auth_ids[1]->data);
235
236		if (x509->self_signed) {
237			/* If there's no authority certificate specified, then
238			 * the certificate must be self-signed and is the root
239			 * of the chain.  Likewise if the cert is its own
240			 * authority.
241			 */
242			if (x509->unsupported_sig)
243				goto unsupported_crypto_in_x509;
244			x509->signer = x509;
245			pr_debug("- self-signed\n");
246			return 0;
247		}
248
249		/* Look through the X.509 certificates in the PKCS#7 message's
250		 * list to see if the next one is there.
251		 */
252		auth = sig->auth_ids[0];
253		if (auth) {
254			pr_debug("- want %*phN\n", auth->len, auth->data);
255			for (p = pkcs7->certs; p; p = p->next) {
256				pr_debug("- cmp [%u] %*phN\n",
257					 p->index, p->id->len, p->id->data);
258				if (asymmetric_key_id_same(p->id, auth))
259					goto found_issuer_check_skid;
260			}
261		} else if (sig->auth_ids[1]) {
262			auth = sig->auth_ids[1];
263			pr_debug("- want %*phN\n", auth->len, auth->data);
264			for (p = pkcs7->certs; p; p = p->next) {
265				if (!p->skid)
266					continue;
267				pr_debug("- cmp [%u] %*phN\n",
268					 p->index, p->skid->len, p->skid->data);
269				if (asymmetric_key_id_same(p->skid, auth))
270					goto found_issuer;
271			}
272		}
273
274		/* We didn't find the root of this chain */
275		pr_debug("- top\n");
276		return 0;
277
278	found_issuer_check_skid:
279		/* We matched issuer + serialNumber, but if there's an
280		 * authKeyId.keyId, that must match the CA subjKeyId also.
281		 */
282		if (sig->auth_ids[1] &&
283		    !asymmetric_key_id_same(p->skid, sig->auth_ids[1])) {
284			pr_warn("Sig %u: X.509 chain contains auth-skid nonmatch (%u->%u)\n",
285				sinfo->index, x509->index, p->index);
286			return -EKEYREJECTED;
287		}
288	found_issuer:
289		pr_debug("- subject %s\n", p->subject);
290		if (p->seen) {
291			pr_warn("Sig %u: X.509 chain contains loop\n",
292				sinfo->index);
293			return 0;
294		}
295		ret = public_key_verify_signature(p->pub, x509->sig);
296		if (ret < 0)
297			return ret;
298		x509->signer = p;
299		if (x509 == p) {
300			pr_debug("- self-signed\n");
301			return 0;
302		}
303		x509 = p;
304		might_sleep();
305	}
306
307unsupported_crypto_in_x509:
308	/* Just prune the certificate chain at this point if we lack some
309	 * crypto module to go further.  Note, however, we don't want to set
310	 * sinfo->unsupported_crypto as the signed info block may still be
311	 * validatable against an X.509 cert lower in the chain that we have a
312	 * trusted copy of.
313	 */
314	return 0;
315}
316
317/*
318 * Verify one signed information block from a PKCS#7 message.
319 */
320static int pkcs7_verify_one(struct pkcs7_message *pkcs7,
321			    struct pkcs7_signed_info *sinfo)
322{
323	int ret;
324
325	kenter(",%u", sinfo->index);
326
327	/* First of all, digest the data in the PKCS#7 message and the
328	 * signed information block
329	 */
330	ret = pkcs7_digest(pkcs7, sinfo);
331	if (ret < 0)
332		return ret;
333
334	/* Find the key for the signature if there is one */
335	ret = pkcs7_find_key(pkcs7, sinfo);
336	if (ret < 0)
337		return ret;
338
339	if (!sinfo->signer)
340		return 0;
341
342	pr_devel("Using X.509[%u] for sig %u\n",
343		 sinfo->signer->index, sinfo->index);
344
345	/* Check that the PKCS#7 signing time is valid according to the X.509
346	 * certificate.  We can't, however, check against the system clock
347	 * since that may not have been set yet and may be wrong.
348	 */
349	if (test_bit(sinfo_has_signing_time, &sinfo->aa_set)) {
350		if (sinfo->signing_time < sinfo->signer->valid_from ||
351		    sinfo->signing_time > sinfo->signer->valid_to) {
352			pr_warn("Message signed outside of X.509 validity window\n");
353			return -EKEYREJECTED;
354		}
355	}
356
357	/* Verify the PKCS#7 binary against the key */
358	ret = public_key_verify_signature(sinfo->signer->pub, sinfo->sig);
359	if (ret < 0)
360		return ret;
361
362	pr_devel("Verified signature %u\n", sinfo->index);
363
364	/* Verify the internal certificate chain */
365	return pkcs7_verify_sig_chain(pkcs7, sinfo);
366}
367
368/**
369 * pkcs7_verify - Verify a PKCS#7 message
370 * @pkcs7: The PKCS#7 message to be verified
371 * @usage: The use to which the key is being put
372 *
373 * Verify a PKCS#7 message is internally consistent - that is, the data digest
374 * matches the digest in the AuthAttrs and any signature in the message or one
375 * of the X.509 certificates it carries that matches another X.509 cert in the
376 * message can be verified.
377 *
378 * This does not look to match the contents of the PKCS#7 message against any
379 * external public keys.
380 *
381 * Returns, in order of descending priority:
382 *
383 *  (*) -EKEYREJECTED if a key was selected that had a usage restriction at
384 *      odds with the specified usage, or:
385 *
386 *  (*) -EKEYREJECTED if a signature failed to match for which we found an
387 *	appropriate X.509 certificate, or:
388 *
389 *  (*) -EBADMSG if some part of the message was invalid, or:
390 *
391 *  (*) 0 if a signature chain passed verification, or:
392 *
393 *  (*) -EKEYREJECTED if a blacklisted key was encountered, or:
394 *
395 *  (*) -ENOPKG if none of the signature chains are verifiable because suitable
396 *	crypto modules couldn't be found.
397 */
398int pkcs7_verify(struct pkcs7_message *pkcs7,
399		 enum key_being_used_for usage)
400{
401	struct pkcs7_signed_info *sinfo;
402	int actual_ret = -ENOPKG;
403	int ret;
404
405	kenter("");
406
407	switch (usage) {
408	case VERIFYING_MODULE_SIGNATURE:
409		if (pkcs7->data_type != OID_data) {
410			pr_warn("Invalid module sig (not pkcs7-data)\n");
411			return -EKEYREJECTED;
412		}
413		if (pkcs7->have_authattrs) {
414			pr_warn("Invalid module sig (has authattrs)\n");
415			return -EKEYREJECTED;
416		}
417		break;
418	case VERIFYING_FIRMWARE_SIGNATURE:
419		if (pkcs7->data_type != OID_data) {
420			pr_warn("Invalid firmware sig (not pkcs7-data)\n");
421			return -EKEYREJECTED;
422		}
423		if (!pkcs7->have_authattrs) {
424			pr_warn("Invalid firmware sig (missing authattrs)\n");
425			return -EKEYREJECTED;
426		}
427		break;
428	case VERIFYING_KEXEC_PE_SIGNATURE:
429		if (pkcs7->data_type != OID_msIndirectData) {
430			pr_warn("Invalid kexec sig (not Authenticode)\n");
431			return -EKEYREJECTED;
432		}
433		/* Authattr presence checked in parser */
434		break;
435	case VERIFYING_UNSPECIFIED_SIGNATURE:
436		if (pkcs7->data_type != OID_data) {
437			pr_warn("Invalid unspecified sig (not pkcs7-data)\n");
438			return -EKEYREJECTED;
439		}
440		break;
441	default:
442		return -EINVAL;
443	}
444
445	for (sinfo = pkcs7->signed_infos; sinfo; sinfo = sinfo->next) {
446		ret = pkcs7_verify_one(pkcs7, sinfo);
447		if (sinfo->blacklisted) {
448			if (actual_ret == -ENOPKG)
449				actual_ret = -EKEYREJECTED;
450			continue;
451		}
452		if (ret < 0) {
453			if (ret == -ENOPKG) {
454				sinfo->unsupported_crypto = true;
455				continue;
456			}
457			kleave(" = %d", ret);
458			return ret;
459		}
460		actual_ret = 0;
461	}
462
463	kleave(" = %d", actual_ret);
464	return actual_ret;
465}
466EXPORT_SYMBOL_GPL(pkcs7_verify);
467
468/**
469 * pkcs7_supply_detached_data - Supply the data needed to verify a PKCS#7 message
470 * @pkcs7: The PKCS#7 message
471 * @data: The data to be verified
472 * @datalen: The amount of data
473 *
474 * Supply the detached data needed to verify a PKCS#7 message.  Note that no
475 * attempt to retain/pin the data is made.  That is left to the caller.  The
476 * data will not be modified by pkcs7_verify() and will not be freed when the
477 * PKCS#7 message is freed.
478 *
479 * Returns -EINVAL if data is already supplied in the message, 0 otherwise.
480 */
481int pkcs7_supply_detached_data(struct pkcs7_message *pkcs7,
482			       const void *data, size_t datalen)
483{
484	if (pkcs7->data) {
485		pr_warn("Data already supplied\n");
486		return -EINVAL;
487	}
488	pkcs7->data = data;
489	pkcs7->data_len = datalen;
490	return 0;
491}
492