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