xref: /linux/scripts/sign-file.c (revision 23b0f90ba871f096474e1c27c3d14f455189d2d9)
1 /* Sign a module file using the given key.
2  *
3  * Copyright © 2014-2016 Red Hat, Inc. All Rights Reserved.
4  * Copyright © 2015      Intel Corporation.
5  * Copyright © 2016      Hewlett Packard Enterprise Development LP
6  *
7  * Authors: David Howells <dhowells@redhat.com>
8  *          David Woodhouse <dwmw2@infradead.org>
9  *          Juerg Haefliger <juerg.haefliger@hpe.com>
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the licence, or (at your option) any later version.
15  */
16 #define _GNU_SOURCE
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <stdint.h>
20 #include <stdbool.h>
21 #include <string.h>
22 #include <getopt.h>
23 #include <err.h>
24 #include <arpa/inet.h>
25 #include <openssl/opensslv.h>
26 #include <openssl/bio.h>
27 #include <openssl/cms.h>
28 #include <openssl/evp.h>
29 #include <openssl/pem.h>
30 #include <openssl/err.h>
31 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
32 # define USE_PKCS11_PROVIDER
33 # include <openssl/provider.h>
34 # include <openssl/store.h>
35 #else
36 # if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DEPRECATED_3_0)
37 #  define USE_PKCS11_ENGINE
38 #  include <openssl/engine.h>
39 # endif
40 #endif
41 #include "ssl-common.h"
42 
43 struct module_signature {
44 	uint8_t		algo;		/* Public-key crypto algorithm [0] */
45 	uint8_t		hash;		/* Digest algorithm [0] */
46 	uint8_t		id_type;	/* Key identifier type [PKEY_ID_PKCS7] */
47 	uint8_t		signer_len;	/* Length of signer's name [0] */
48 	uint8_t		key_id_len;	/* Length of key identifier [0] */
49 	uint8_t		__pad[3];
50 	uint32_t	sig_len;	/* Length of signature data */
51 };
52 
53 #define PKEY_ID_PKCS7 2
54 
55 static char magic_number[] = "~Module signature appended~\n";
56 
57 static __attribute__((noreturn))
58 void format(void)
59 {
60 	fprintf(stderr,
61 		"Usage: scripts/sign-file [-dp] <hash algo> <key> <x509> <module> [<dest>]\n");
62 	fprintf(stderr,
63 		"       scripts/sign-file -s <raw sig> <hash algo> <x509> <module> [<dest>]\n");
64 	exit(2);
65 }
66 
67 static const char *key_pass;
68 
69 static int pem_pw_cb(char *buf, int len, int w, void *v)
70 {
71 	int pwlen;
72 
73 	if (!key_pass)
74 		return -1;
75 
76 	pwlen = strlen(key_pass);
77 	if (pwlen >= len)
78 		return -1;
79 
80 	strcpy(buf, key_pass);
81 
82 	/* If it's wrong, don't keep trying it. */
83 	key_pass = NULL;
84 
85 	return pwlen;
86 }
87 
88 static EVP_PKEY *read_private_key_pkcs11(const char *private_key_name)
89 {
90 	EVP_PKEY *private_key = NULL;
91 #ifdef USE_PKCS11_PROVIDER
92 	OSSL_STORE_CTX *store;
93 
94 	if (!OSSL_PROVIDER_try_load(NULL, "pkcs11", true))
95 		ERR(1, "OSSL_PROVIDER_try_load(pkcs11)");
96 	if (!OSSL_PROVIDER_try_load(NULL, "default", true))
97 		ERR(1, "OSSL_PROVIDER_try_load(default)");
98 
99 	store = OSSL_STORE_open(private_key_name, NULL, NULL, NULL, NULL);
100 	ERR(!store, "OSSL_STORE_open");
101 
102 	while (!OSSL_STORE_eof(store)) {
103 		OSSL_STORE_INFO *info = OSSL_STORE_load(store);
104 
105 		if (!info) {
106 			drain_openssl_errors(__LINE__, 0);
107 			continue;
108 		}
109 		if (OSSL_STORE_INFO_get_type(info) == OSSL_STORE_INFO_PKEY) {
110 			private_key = OSSL_STORE_INFO_get1_PKEY(info);
111 			ERR(!private_key, "OSSL_STORE_INFO_get1_PKEY");
112 		}
113 		OSSL_STORE_INFO_free(info);
114 		if (private_key)
115 			break;
116 	}
117 	OSSL_STORE_close(store);
118 #elif defined(USE_PKCS11_ENGINE)
119 	ENGINE *e;
120 
121 	ENGINE_load_builtin_engines();
122 	drain_openssl_errors(__LINE__, 1);
123 	e = ENGINE_by_id("pkcs11");
124 	ERR(!e, "Load PKCS#11 ENGINE");
125 	if (ENGINE_init(e))
126 		drain_openssl_errors(__LINE__, 1);
127 	else
128 		ERR(1, "ENGINE_init");
129 	if (key_pass)
130 		ERR(!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0), "Set PKCS#11 PIN");
131 	private_key = ENGINE_load_private_key(e, private_key_name, NULL, NULL);
132 	ERR(!private_key, "%s", private_key_name);
133 #else
134 	fprintf(stderr, "no pkcs11 engine/provider available\n");
135 	exit(1);
136 #endif
137 	return private_key;
138 }
139 
140 static EVP_PKEY *read_private_key(const char *private_key_name)
141 {
142 	if (!strncmp(private_key_name, "pkcs11:", 7)) {
143 		return read_private_key_pkcs11(private_key_name);
144 	} else {
145 		EVP_PKEY *private_key;
146 		BIO *b;
147 
148 		b = BIO_new_file(private_key_name, "rb");
149 		ERR(!b, "%s", private_key_name);
150 		private_key = PEM_read_bio_PrivateKey(b, NULL, pem_pw_cb,
151 						      NULL);
152 		ERR(!private_key, "%s", private_key_name);
153 		BIO_free(b);
154 
155 		return private_key;
156 	}
157 }
158 
159 static X509 *read_x509(const char *x509_name)
160 {
161 	unsigned char buf[2];
162 	X509 *x509;
163 	BIO *b;
164 	int n;
165 
166 	b = BIO_new_file(x509_name, "rb");
167 	ERR(!b, "%s", x509_name);
168 
169 	/* Look at the first two bytes of the file to determine the encoding */
170 	n = BIO_read(b, buf, 2);
171 	if (n != 2) {
172 		if (BIO_should_retry(b)) {
173 			fprintf(stderr, "%s: Read wanted retry\n", x509_name);
174 			exit(1);
175 		}
176 		if (n >= 0) {
177 			fprintf(stderr, "%s: Short read\n", x509_name);
178 			exit(1);
179 		}
180 		ERR(1, "%s", x509_name);
181 	}
182 
183 	ERR(BIO_reset(b) != 0, "%s", x509_name);
184 
185 	if (buf[0] == 0x30 && buf[1] >= 0x81 && buf[1] <= 0x84)
186 		/* Assume raw DER encoded X.509 */
187 		x509 = d2i_X509_bio(b, NULL);
188 	else
189 		/* Assume PEM encoded X.509 */
190 		x509 = PEM_read_bio_X509(b, NULL, NULL, NULL);
191 
192 	BIO_free(b);
193 	ERR(!x509, "%s", x509_name);
194 
195 	return x509;
196 }
197 
198 int main(int argc, char **argv)
199 {
200 	struct module_signature sig_info = { .id_type = PKEY_ID_PKCS7 };
201 	char *hash_algo = NULL;
202 	char *private_key_name = NULL, *raw_sig_name = NULL;
203 	char *x509_name, *module_name, *dest_name;
204 	bool save_sig = false, replace_orig;
205 	bool sign_only = false;
206 	bool raw_sig = false;
207 	unsigned char buf[4096];
208 	unsigned long module_size, sig_size;
209 	const EVP_MD *digest_algo;
210 	EVP_PKEY *private_key;
211 	CMS_ContentInfo *cms = NULL;
212 	unsigned int use_keyid = 0;
213 	X509 *x509;
214 	BIO *bd, *bm;
215 	int opt, n;
216 	OpenSSL_add_all_algorithms();
217 	ERR_load_crypto_strings();
218 	ERR_clear_error();
219 
220 	key_pass = getenv("KBUILD_SIGN_PIN");
221 
222 	do {
223 		opt = getopt(argc, argv, "sdpk");
224 		switch (opt) {
225 		case 's': raw_sig = true; break;
226 		case 'p': save_sig = true; break;
227 		case 'd': sign_only = true; save_sig = true; break;
228 		case 'k': use_keyid = CMS_USE_KEYID; break;
229 		case -1: break;
230 		default: format();
231 		}
232 	} while (opt != -1);
233 
234 	argc -= optind;
235 	argv += optind;
236 	if (argc < 4 || argc > 5)
237 		format();
238 
239 	if (raw_sig) {
240 		raw_sig_name = argv[0];
241 		hash_algo = argv[1];
242 	} else {
243 		hash_algo = argv[0];
244 		private_key_name = argv[1];
245 	}
246 	x509_name = argv[2];
247 	module_name = argv[3];
248 	if (argc == 5 && strcmp(argv[3], argv[4]) != 0) {
249 		dest_name = argv[4];
250 		replace_orig = false;
251 	} else {
252 		ERR(asprintf(&dest_name, "%s.~signed~", module_name) < 0,
253 		    "asprintf");
254 		replace_orig = true;
255 	}
256 
257 	/* Open the module file */
258 	bm = BIO_new_file(module_name, "rb");
259 	ERR(!bm, "%s", module_name);
260 
261 	if (!raw_sig) {
262 		/* Read the private key and the X.509 cert the PKCS#7 message
263 		 * will point to.
264 		 */
265 		private_key = read_private_key(private_key_name);
266 		x509 = read_x509(x509_name);
267 
268 		/* Digest the module data. */
269 		OpenSSL_add_all_digests();
270 		drain_openssl_errors(__LINE__, 0);
271 		digest_algo = EVP_get_digestbyname(hash_algo);
272 		ERR(!digest_algo, "EVP_get_digestbyname");
273 
274 		unsigned int flags =
275 			CMS_NOCERTS |
276 			CMS_NOATTR |
277 			CMS_PARTIAL |
278 			CMS_BINARY |
279 			CMS_DETACHED |
280 			CMS_STREAM  |
281 			CMS_NOSMIMECAP |
282 #ifdef CMS_NO_SIGNING_TIME
283 			CMS_NO_SIGNING_TIME |
284 #endif
285 			use_keyid;
286 
287 #if OPENSSL_VERSION_NUMBER >= 0x30000000L && OPENSSL_VERSION_NUMBER < 0x40000000L
288 		if (EVP_PKEY_is_a(private_key, "ML-DSA-44") ||
289 		    EVP_PKEY_is_a(private_key, "ML-DSA-65") ||
290 		    EVP_PKEY_is_a(private_key, "ML-DSA-87")) {
291 			 /* ML-DSA + CMS_NOATTR is not supported in openssl-3.5
292 			  * and before.
293 			  */
294 			flags &= ~CMS_NOATTR;
295 		}
296 #endif
297 
298 		/* Load the signature message from the digest buffer. */
299 		cms = CMS_sign(NULL, NULL, NULL, NULL, flags);
300 		ERR(!cms, "CMS_sign");
301 
302 		ERR(!CMS_add1_signer(cms, x509, private_key, digest_algo, flags),
303 		    "CMS_add1_signer");
304 		ERR(CMS_final(cms, bm, NULL, flags) != 1,
305 		    "CMS_final");
306 
307 		if (save_sig) {
308 			char *sig_file_name;
309 			BIO *b;
310 
311 			ERR(asprintf(&sig_file_name, "%s.p7s", module_name) < 0,
312 			    "asprintf");
313 			b = BIO_new_file(sig_file_name, "wb");
314 			ERR(!b, "%s", sig_file_name);
315 			ERR(i2d_CMS_bio_stream(b, cms, NULL, 0) != 1,
316 			    "%s", sig_file_name);
317 			BIO_free(b);
318 		}
319 
320 		if (sign_only) {
321 			BIO_free(bm);
322 			return 0;
323 		}
324 	}
325 
326 	/* Open the destination file now so that we can shovel the module data
327 	 * across as we read it.
328 	 */
329 	bd = BIO_new_file(dest_name, "wb");
330 	ERR(!bd, "%s", dest_name);
331 
332 	/* Append the marker and the PKCS#7 message to the destination file */
333 	ERR(BIO_reset(bm) < 0, "%s", module_name);
334 	while ((n = BIO_read(bm, buf, sizeof(buf))),
335 	       n > 0) {
336 		ERR(BIO_write(bd, buf, n) < 0, "%s", dest_name);
337 	}
338 	BIO_free(bm);
339 	ERR(n < 0, "%s", module_name);
340 	module_size = BIO_number_written(bd);
341 
342 	if (!raw_sig) {
343 		ERR(i2d_CMS_bio_stream(bd, cms, NULL, 0) != 1, "%s", dest_name);
344 	} else {
345 		BIO *b;
346 
347 		/* Read the raw signature file and write the data to the
348 		 * destination file
349 		 */
350 		b = BIO_new_file(raw_sig_name, "rb");
351 		ERR(!b, "%s", raw_sig_name);
352 		while ((n = BIO_read(b, buf, sizeof(buf))), n > 0)
353 			ERR(BIO_write(bd, buf, n) < 0, "%s", dest_name);
354 		BIO_free(b);
355 	}
356 
357 	sig_size = BIO_number_written(bd) - module_size;
358 	sig_info.sig_len = htonl(sig_size);
359 	ERR(BIO_write(bd, &sig_info, sizeof(sig_info)) < 0, "%s", dest_name);
360 	ERR(BIO_write(bd, magic_number, sizeof(magic_number) - 1) < 0, "%s", dest_name);
361 
362 	ERR(BIO_free(bd) != 1, "%s", dest_name);
363 
364 	/* Finally, if we're signing in place, replace the original. */
365 	if (replace_orig)
366 		ERR(rename(dest_name, module_name) < 0, "%s", dest_name);
367 
368 	return 0;
369 }
370