GNU Linux-libre 4.19.286-gnu1
[releases.git] / crypto / asymmetric_keys / verify_pefile.c
1 /* Parse a signed PE binary
2  *
3  * Copyright (C) 2014 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) "PEFILE: "fmt
13 #include <linux/module.h>
14 #include <linux/kernel.h>
15 #include <linux/slab.h>
16 #include <linux/err.h>
17 #include <linux/pe.h>
18 #include <linux/asn1.h>
19 #include <linux/verification.h>
20 #include <crypto/hash.h>
21 #include "verify_pefile.h"
22
23 /*
24  * Parse a PE binary.
25  */
26 static int pefile_parse_binary(const void *pebuf, unsigned int pelen,
27                                struct pefile_context *ctx)
28 {
29         const struct mz_hdr *mz = pebuf;
30         const struct pe_hdr *pe;
31         const struct pe32_opt_hdr *pe32;
32         const struct pe32plus_opt_hdr *pe64;
33         const struct data_directory *ddir;
34         const struct data_dirent *dde;
35         const struct section_header *secs, *sec;
36         size_t cursor, datalen = pelen;
37
38         kenter("");
39
40 #define chkaddr(base, x, s)                                             \
41         do {                                                            \
42                 if ((x) < base || (s) >= datalen || (x) > datalen - (s)) \
43                         return -ELIBBAD;                                \
44         } while (0)
45
46         chkaddr(0, 0, sizeof(*mz));
47         if (mz->magic != MZ_MAGIC)
48                 return -ELIBBAD;
49         cursor = sizeof(*mz);
50
51         chkaddr(cursor, mz->peaddr, sizeof(*pe));
52         pe = pebuf + mz->peaddr;
53         if (pe->magic != PE_MAGIC)
54                 return -ELIBBAD;
55         cursor = mz->peaddr + sizeof(*pe);
56
57         chkaddr(0, cursor, sizeof(pe32->magic));
58         pe32 = pebuf + cursor;
59         pe64 = pebuf + cursor;
60
61         switch (pe32->magic) {
62         case PE_OPT_MAGIC_PE32:
63                 chkaddr(0, cursor, sizeof(*pe32));
64                 ctx->image_checksum_offset =
65                         (unsigned long)&pe32->csum - (unsigned long)pebuf;
66                 ctx->header_size = pe32->header_size;
67                 cursor += sizeof(*pe32);
68                 ctx->n_data_dirents = pe32->data_dirs;
69                 break;
70
71         case PE_OPT_MAGIC_PE32PLUS:
72                 chkaddr(0, cursor, sizeof(*pe64));
73                 ctx->image_checksum_offset =
74                         (unsigned long)&pe64->csum - (unsigned long)pebuf;
75                 ctx->header_size = pe64->header_size;
76                 cursor += sizeof(*pe64);
77                 ctx->n_data_dirents = pe64->data_dirs;
78                 break;
79
80         default:
81                 pr_debug("Unknown PEOPT magic = %04hx\n", pe32->magic);
82                 return -ELIBBAD;
83         }
84
85         pr_debug("checksum @ %x\n", ctx->image_checksum_offset);
86         pr_debug("header size = %x\n", ctx->header_size);
87
88         if (cursor >= ctx->header_size || ctx->header_size >= datalen)
89                 return -ELIBBAD;
90
91         if (ctx->n_data_dirents > (ctx->header_size - cursor) / sizeof(*dde))
92                 return -ELIBBAD;
93
94         ddir = pebuf + cursor;
95         cursor += sizeof(*dde) * ctx->n_data_dirents;
96
97         ctx->cert_dirent_offset =
98                 (unsigned long)&ddir->certs - (unsigned long)pebuf;
99         ctx->certs_size = ddir->certs.size;
100
101         if (!ddir->certs.virtual_address || !ddir->certs.size) {
102                 pr_debug("Unsigned PE binary\n");
103                 return -EKEYREJECTED;
104         }
105
106         chkaddr(ctx->header_size, ddir->certs.virtual_address,
107                 ddir->certs.size);
108         ctx->sig_offset = ddir->certs.virtual_address;
109         ctx->sig_len = ddir->certs.size;
110         pr_debug("cert = %x @%x [%*ph]\n",
111                  ctx->sig_len, ctx->sig_offset,
112                  ctx->sig_len, pebuf + ctx->sig_offset);
113
114         ctx->n_sections = pe->sections;
115         if (ctx->n_sections > (ctx->header_size - cursor) / sizeof(*sec))
116                 return -ELIBBAD;
117         ctx->secs = secs = pebuf + cursor;
118
119         return 0;
120 }
121
122 /*
123  * Check and strip the PE wrapper from around the signature and check that the
124  * remnant looks something like PKCS#7.
125  */
126 static int pefile_strip_sig_wrapper(const void *pebuf,
127                                     struct pefile_context *ctx)
128 {
129         struct win_certificate wrapper;
130         const u8 *pkcs7;
131         unsigned len;
132
133         if (ctx->sig_len < sizeof(wrapper)) {
134                 pr_debug("Signature wrapper too short\n");
135                 return -ELIBBAD;
136         }
137
138         memcpy(&wrapper, pebuf + ctx->sig_offset, sizeof(wrapper));
139         pr_debug("sig wrapper = { %x, %x, %x }\n",
140                  wrapper.length, wrapper.revision, wrapper.cert_type);
141
142         /* sbsign rounds up the length of certificate table (in optional
143          * header data directories) to 8 byte alignment.  However, the PE
144          * specification states that while entries are 8-byte aligned, this is
145          * not included in their length, and as a result, pesign has not
146          * rounded up since 0.110.
147          */
148         if (wrapper.length > ctx->sig_len) {
149                 pr_debug("Signature wrapper bigger than sig len (%x > %x)\n",
150                          ctx->sig_len, wrapper.length);
151                 return -ELIBBAD;
152         }
153         if (wrapper.revision != WIN_CERT_REVISION_2_0) {
154                 pr_debug("Signature is not revision 2.0\n");
155                 return -ENOTSUPP;
156         }
157         if (wrapper.cert_type != WIN_CERT_TYPE_PKCS_SIGNED_DATA) {
158                 pr_debug("Signature certificate type is not PKCS\n");
159                 return -ENOTSUPP;
160         }
161
162         /* It looks like the pkcs signature length in wrapper->length and the
163          * size obtained from the data dir entries, which lists the total size
164          * of certificate table, are both aligned to an octaword boundary, so
165          * we may have to deal with some padding.
166          */
167         ctx->sig_len = wrapper.length;
168         ctx->sig_offset += sizeof(wrapper);
169         ctx->sig_len -= sizeof(wrapper);
170         if (ctx->sig_len < 4) {
171                 pr_debug("Signature data missing\n");
172                 return -EKEYREJECTED;
173         }
174
175         /* What's left should be a PKCS#7 cert */
176         pkcs7 = pebuf + ctx->sig_offset;
177         if (pkcs7[0] != (ASN1_CONS_BIT | ASN1_SEQ))
178                 goto not_pkcs7;
179
180         switch (pkcs7[1]) {
181         case 0 ... 0x7f:
182                 len = pkcs7[1] + 2;
183                 goto check_len;
184         case ASN1_INDEFINITE_LENGTH:
185                 return 0;
186         case 0x81:
187                 len = pkcs7[2] + 3;
188                 goto check_len;
189         case 0x82:
190                 len = ((pkcs7[2] << 8) | pkcs7[3]) + 4;
191                 goto check_len;
192         case 0x83 ... 0xff:
193                 return -EMSGSIZE;
194         default:
195                 goto not_pkcs7;
196         }
197
198 check_len:
199         if (len <= ctx->sig_len) {
200                 /* There may be padding */
201                 ctx->sig_len = len;
202                 return 0;
203         }
204 not_pkcs7:
205         pr_debug("Signature data not PKCS#7\n");
206         return -ELIBBAD;
207 }
208
209 /*
210  * Compare two sections for canonicalisation.
211  */
212 static int pefile_compare_shdrs(const void *a, const void *b)
213 {
214         const struct section_header *shdra = a;
215         const struct section_header *shdrb = b;
216         int rc;
217
218         if (shdra->data_addr > shdrb->data_addr)
219                 return 1;
220         if (shdrb->data_addr > shdra->data_addr)
221                 return -1;
222
223         if (shdra->virtual_address > shdrb->virtual_address)
224                 return 1;
225         if (shdrb->virtual_address > shdra->virtual_address)
226                 return -1;
227
228         rc = strcmp(shdra->name, shdrb->name);
229         if (rc != 0)
230                 return rc;
231
232         if (shdra->virtual_size > shdrb->virtual_size)
233                 return 1;
234         if (shdrb->virtual_size > shdra->virtual_size)
235                 return -1;
236
237         if (shdra->raw_data_size > shdrb->raw_data_size)
238                 return 1;
239         if (shdrb->raw_data_size > shdra->raw_data_size)
240                 return -1;
241
242         return 0;
243 }
244
245 /*
246  * Load the contents of the PE binary into the digest, leaving out the image
247  * checksum and the certificate data block.
248  */
249 static int pefile_digest_pe_contents(const void *pebuf, unsigned int pelen,
250                                      struct pefile_context *ctx,
251                                      struct shash_desc *desc)
252 {
253         unsigned *canon, tmp, loop, i, hashed_bytes;
254         int ret;
255
256         /* Digest the header and data directory, but leave out the image
257          * checksum and the data dirent for the signature.
258          */
259         ret = crypto_shash_update(desc, pebuf, ctx->image_checksum_offset);
260         if (ret < 0)
261                 return ret;
262
263         tmp = ctx->image_checksum_offset + sizeof(uint32_t);
264         ret = crypto_shash_update(desc, pebuf + tmp,
265                                   ctx->cert_dirent_offset - tmp);
266         if (ret < 0)
267                 return ret;
268
269         tmp = ctx->cert_dirent_offset + sizeof(struct data_dirent);
270         ret = crypto_shash_update(desc, pebuf + tmp, ctx->header_size - tmp);
271         if (ret < 0)
272                 return ret;
273
274         canon = kcalloc(ctx->n_sections, sizeof(unsigned), GFP_KERNEL);
275         if (!canon)
276                 return -ENOMEM;
277
278         /* We have to canonicalise the section table, so we perform an
279          * insertion sort.
280          */
281         canon[0] = 0;
282         for (loop = 1; loop < ctx->n_sections; loop++) {
283                 for (i = 0; i < loop; i++) {
284                         if (pefile_compare_shdrs(&ctx->secs[canon[i]],
285                                                  &ctx->secs[loop]) > 0) {
286                                 memmove(&canon[i + 1], &canon[i],
287                                         (loop - i) * sizeof(canon[0]));
288                                 break;
289                         }
290                 }
291                 canon[i] = loop;
292         }
293
294         hashed_bytes = ctx->header_size;
295         for (loop = 0; loop < ctx->n_sections; loop++) {
296                 i = canon[loop];
297                 if (ctx->secs[i].raw_data_size == 0)
298                         continue;
299                 ret = crypto_shash_update(desc,
300                                           pebuf + ctx->secs[i].data_addr,
301                                           ctx->secs[i].raw_data_size);
302                 if (ret < 0) {
303                         kfree(canon);
304                         return ret;
305                 }
306                 hashed_bytes += ctx->secs[i].raw_data_size;
307         }
308         kfree(canon);
309
310         if (pelen > hashed_bytes) {
311                 tmp = hashed_bytes + ctx->certs_size;
312                 ret = crypto_shash_update(desc,
313                                           pebuf + hashed_bytes,
314                                           pelen - tmp);
315                 if (ret < 0)
316                         return ret;
317         }
318
319         return 0;
320 }
321
322 /*
323  * Digest the contents of the PE binary, leaving out the image checksum and the
324  * certificate data block.
325  */
326 static int pefile_digest_pe(const void *pebuf, unsigned int pelen,
327                             struct pefile_context *ctx)
328 {
329         struct crypto_shash *tfm;
330         struct shash_desc *desc;
331         size_t digest_size, desc_size;
332         void *digest;
333         int ret;
334
335         kenter(",%s", ctx->digest_algo);
336
337         /* Allocate the hashing algorithm we're going to need and find out how
338          * big the hash operational data will be.
339          */
340         tfm = crypto_alloc_shash(ctx->digest_algo, 0, 0);
341         if (IS_ERR(tfm))
342                 return (PTR_ERR(tfm) == -ENOENT) ? -ENOPKG : PTR_ERR(tfm);
343
344         desc_size = crypto_shash_descsize(tfm) + sizeof(*desc);
345         digest_size = crypto_shash_digestsize(tfm);
346
347         if (digest_size != ctx->digest_len) {
348                 pr_debug("Digest size mismatch (%zx != %x)\n",
349                          digest_size, ctx->digest_len);
350                 ret = -EBADMSG;
351                 goto error_no_desc;
352         }
353         pr_debug("Digest: desc=%zu size=%zu\n", desc_size, digest_size);
354
355         ret = -ENOMEM;
356         desc = kzalloc(desc_size + digest_size, GFP_KERNEL);
357         if (!desc)
358                 goto error_no_desc;
359
360         desc->tfm   = tfm;
361         desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
362         ret = crypto_shash_init(desc);
363         if (ret < 0)
364                 goto error;
365
366         ret = pefile_digest_pe_contents(pebuf, pelen, ctx, desc);
367         if (ret < 0)
368                 goto error;
369
370         digest = (void *)desc + desc_size;
371         ret = crypto_shash_final(desc, digest);
372         if (ret < 0)
373                 goto error;
374
375         pr_debug("Digest calc = [%*ph]\n", ctx->digest_len, digest);
376
377         /* Check that the PE file digest matches that in the MSCODE part of the
378          * PKCS#7 certificate.
379          */
380         if (memcmp(digest, ctx->digest, ctx->digest_len) != 0) {
381                 pr_debug("Digest mismatch\n");
382                 ret = -EKEYREJECTED;
383         } else {
384                 pr_debug("The digests match!\n");
385         }
386
387 error:
388         kzfree(desc);
389 error_no_desc:
390         crypto_free_shash(tfm);
391         kleave(" = %d", ret);
392         return ret;
393 }
394
395 /**
396  * verify_pefile_signature - Verify the signature on a PE binary image
397  * @pebuf: Buffer containing the PE binary image
398  * @pelen: Length of the binary image
399  * @trust_keys: Signing certificate(s) to use as starting points
400  * @usage: The use to which the key is being put.
401  *
402  * Validate that the certificate chain inside the PKCS#7 message inside the PE
403  * binary image intersects keys we already know and trust.
404  *
405  * Returns, in order of descending priority:
406  *
407  *  (*) -ELIBBAD if the image cannot be parsed, or:
408  *
409  *  (*) -EKEYREJECTED if a signature failed to match for which we have a valid
410  *      key, or:
411  *
412  *  (*) 0 if at least one signature chain intersects with the keys in the trust
413  *      keyring, or:
414  *
415  *  (*) -ENOPKG if a suitable crypto module couldn't be found for a check on a
416  *      chain.
417  *
418  *  (*) -ENOKEY if we couldn't find a match for any of the signature chains in
419  *      the message.
420  *
421  * May also return -ENOMEM.
422  */
423 int verify_pefile_signature(const void *pebuf, unsigned pelen,
424                             struct key *trusted_keys,
425                             enum key_being_used_for usage)
426 {
427         struct pefile_context ctx;
428         int ret;
429
430         kenter("");
431
432         memset(&ctx, 0, sizeof(ctx));
433         ret = pefile_parse_binary(pebuf, pelen, &ctx);
434         if (ret < 0)
435                 return ret;
436
437         ret = pefile_strip_sig_wrapper(pebuf, &ctx);
438         if (ret < 0)
439                 return ret;
440
441         ret = verify_pkcs7_signature(NULL, 0,
442                                      pebuf + ctx.sig_offset, ctx.sig_len,
443                                      trusted_keys, usage,
444                                      mscode_parse, &ctx);
445         if (ret < 0)
446                 goto error;
447
448         pr_debug("Digest: %u [%*ph]\n",
449                  ctx.digest_len, ctx.digest_len, ctx.digest);
450
451         /* Generate the digest and check against the PKCS7 certificate
452          * contents.
453          */
454         ret = pefile_digest_pe(pebuf, pelen, &ctx);
455
456 error:
457         kzfree(ctx.digest);
458         return ret;
459 }