xref: /freebsd/sbin/decryptcore/decryptcore.c (revision 32cd3ee5901ea33d41ff550e5f40ce743c8d4165)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2016 Konrad Witaszczyk <def@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/types.h>
30 #include <sys/capsicum.h>
31 #include <sys/endian.h>
32 #include <sys/kerneldump.h>
33 #include <sys/wait.h>
34 
35 #include <ctype.h>
36 #include <capsicum_helpers.h>
37 #include <fcntl.h>
38 #include <stdbool.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 
43 #include <openssl/err.h>
44 #include <openssl/evp.h>
45 #include <openssl/pem.h>
46 #include <openssl/rsa.h>
47 #include <openssl/engine.h>
48 
49 #include "pjdlog.h"
50 
51 #define	DECRYPTCORE_CRASHDIR	"/var/crash"
52 
53 static void
54 usage(void)
55 {
56 
57 	pjdlog_exitx(1,
58 	    "usage: decryptcore [-fLv] -p privatekeyfile -k keyfile -e encryptedcore -c core\n"
59 	    "       decryptcore [-fLv] [-d crashdir] -p privatekeyfile -n dumpnr");
60 }
61 
62 static int
63 wait_for_process(pid_t pid)
64 {
65 	int status;
66 
67 	if (waitpid(pid, &status, WUNTRACED | WEXITED) == -1) {
68 		pjdlog_errno(LOG_ERR, "Unable to wait for a child process");
69 		return (1);
70 	}
71 
72 	if (WIFEXITED(status))
73 		return (WEXITSTATUS(status));
74 
75 	return (1);
76 }
77 
78 static struct kerneldumpkey *
79 read_key(int kfd)
80 {
81 	struct kerneldumpkey *kdk;
82 	ssize_t size;
83 	size_t kdksize;
84 
85 	PJDLOG_ASSERT(kfd >= 0);
86 
87 	kdksize = sizeof(*kdk);
88 	kdk = calloc(1, kdksize);
89 	if (kdk == NULL) {
90 		pjdlog_errno(LOG_ERR, "Unable to allocate kernel dump key");
91 		goto failed;
92 	}
93 
94 	size = read(kfd, kdk, kdksize);
95 	if (size == (ssize_t)kdksize) {
96 		kdk->kdk_encryptedkeysize = dtoh32(kdk->kdk_encryptedkeysize);
97 		kdksize += (size_t)kdk->kdk_encryptedkeysize;
98 		kdk = realloc(kdk, kdksize);
99 		if (kdk == NULL) {
100 			pjdlog_errno(LOG_ERR, "Unable to reallocate kernel dump key");
101 			goto failed;
102 		}
103 		size += read(kfd, &kdk->kdk_encryptedkey,
104 		    kdk->kdk_encryptedkeysize);
105 	}
106 	if (size != (ssize_t)kdksize) {
107 		pjdlog_errno(LOG_ERR, "Unable to read key");
108 		goto failed;
109 	}
110 
111 	return (kdk);
112 failed:
113 	free(kdk);
114 	return (NULL);
115 }
116 
117 static bool
118 decrypt(int ofd, const char *privkeyfile, const char *keyfile,
119     const char *input)
120 {
121 	uint8_t buf[KERNELDUMP_BUFFER_SIZE], key[KERNELDUMP_KEY_MAX_SIZE],
122 	    chachaiv[4 * 4];
123 	EVP_CIPHER_CTX *ctx;
124 	const EVP_CIPHER *cipher;
125 	FILE *fp;
126 	struct kerneldumpkey *kdk;
127 	RSA *privkey;
128 	int ifd, kfd, olen, privkeysize;
129 	ssize_t bytes;
130 	pid_t pid;
131 
132 	PJDLOG_ASSERT(ofd >= 0);
133 	PJDLOG_ASSERT(privkeyfile != NULL);
134 	PJDLOG_ASSERT(keyfile != NULL);
135 	PJDLOG_ASSERT(input != NULL);
136 
137 	ctx = NULL;
138 	privkey = NULL;
139 
140 	/*
141 	 * Decrypt a core dump in a child process so we can unlink a partially
142 	 * decrypted core if the child process fails.
143 	 */
144 	pid = fork();
145 	if (pid == -1) {
146 		pjdlog_errno(LOG_ERR, "Unable to create child process");
147 		close(ofd);
148 		return (false);
149 	}
150 
151 	if (pid > 0) {
152 		close(ofd);
153 		return (wait_for_process(pid) == 0);
154 	}
155 
156 	kfd = open(keyfile, O_RDONLY);
157 	if (kfd == -1) {
158 		pjdlog_errno(LOG_ERR, "Unable to open %s", keyfile);
159 		goto failed;
160 	}
161 	ifd = open(input, O_RDONLY);
162 	if (ifd == -1) {
163 		pjdlog_errno(LOG_ERR, "Unable to open %s", input);
164 		goto failed;
165 	}
166 	fp = fopen(privkeyfile, "r");
167 	if (fp == NULL) {
168 		pjdlog_errno(LOG_ERR, "Unable to open %s", privkeyfile);
169 		goto failed;
170 	}
171 
172 	/*
173 	 * Obsolescent OpenSSL only knows about /dev/random, and needs to
174 	 * pre-seed before entering cap mode.  For whatever reason,
175 	 * RSA_pub_encrypt uses the internal PRNG.
176 	 */
177 #if OPENSSL_VERSION_NUMBER < 0x10100000L
178 	{
179 		unsigned char c[1];
180 		RAND_bytes(c, 1);
181 	}
182 	ERR_load_crypto_strings();
183 #else
184 	OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL);
185 #endif
186 
187 	caph_cache_catpages();
188 	if (caph_enter() < 0) {
189 		pjdlog_errno(LOG_ERR, "Unable to enter capability mode");
190 		goto failed;
191 	}
192 
193 	privkey = RSA_new();
194 	if (privkey == NULL) {
195 		pjdlog_error("Unable to allocate an RSA structure: %s",
196 		    ERR_error_string(ERR_get_error(), NULL));
197 		goto failed;
198 	}
199 	ctx = EVP_CIPHER_CTX_new();
200 	if (ctx == NULL)
201 		goto failed;
202 
203 	kdk = read_key(kfd);
204 	close(kfd);
205 	if (kdk == NULL)
206 		goto failed;
207 
208 	privkey = PEM_read_RSAPrivateKey(fp, &privkey, NULL, NULL);
209 	fclose(fp);
210 	if (privkey == NULL) {
211 		pjdlog_error("Unable to read data from %s.", privkeyfile);
212 		goto failed;
213 	}
214 
215 	privkeysize = RSA_size(privkey);
216 	if (privkeysize != (int)kdk->kdk_encryptedkeysize) {
217 		pjdlog_error("RSA modulus size mismatch: equals %db and should be %ub.",
218 		    8 * privkeysize, 8 * kdk->kdk_encryptedkeysize);
219 		goto failed;
220 	}
221 
222 	switch (kdk->kdk_encryption) {
223 	case KERNELDUMP_ENC_AES_256_CBC:
224 		cipher = EVP_aes_256_cbc();
225 		break;
226 	case KERNELDUMP_ENC_CHACHA20:
227 		cipher = EVP_chacha20();
228 		break;
229 	default:
230 		pjdlog_error("Invalid encryption algorithm.");
231 		goto failed;
232 	}
233 
234 	if (RSA_private_decrypt(kdk->kdk_encryptedkeysize,
235 	    kdk->kdk_encryptedkey, key, privkey,
236 	    RSA_PKCS1_OAEP_PADDING) != sizeof(key) &&
237 	    /* Fallback to deprecated, formerly-used PKCS 1.5 padding. */
238 	    RSA_private_decrypt(kdk->kdk_encryptedkeysize,
239 	    kdk->kdk_encryptedkey, key, privkey,
240 	    RSA_PKCS1_PADDING) != sizeof(key)) {
241 		pjdlog_error("Unable to decrypt key: %s",
242 		    ERR_error_string(ERR_get_error(), NULL));
243 		goto failed;
244 	}
245 	RSA_free(privkey);
246 	privkey = NULL;
247 
248 	if (kdk->kdk_encryption == KERNELDUMP_ENC_CHACHA20) {
249 		/*
250 		 * OpenSSL treats the IV as 4 little-endian 32 bit integers.
251 		 *
252 		 * The first two represent a 64-bit counter, where the low half
253 		 * is the first 32-bit word.
254 		 *
255 		 * Start at counter block zero...
256 		 */
257 		memset(chachaiv, 0, 4 * 2);
258 		/*
259 		 * And use the IV specified by the dump.
260 		 */
261 		memcpy(&chachaiv[4 * 2], kdk->kdk_iv, 4 * 2);
262 		EVP_DecryptInit_ex(ctx, cipher, NULL, key, chachaiv);
263 	} else
264 		EVP_DecryptInit_ex(ctx, cipher, NULL, key, kdk->kdk_iv);
265 	EVP_CIPHER_CTX_set_padding(ctx, 0);
266 
267 	explicit_bzero(key, sizeof(key));
268 
269 	do {
270 		bytes = read(ifd, buf, sizeof(buf));
271 		if (bytes < 0) {
272 			pjdlog_errno(LOG_ERR, "Unable to read data from %s",
273 			    input);
274 			goto failed;
275 		}
276 
277 		if (bytes > 0) {
278 			if (EVP_DecryptUpdate(ctx, buf, &olen, buf,
279 			    bytes) == 0) {
280 				pjdlog_error("Unable to decrypt core.");
281 				goto failed;
282 			}
283 		} else {
284 			if (EVP_DecryptFinal_ex(ctx, buf, &olen) == 0) {
285 				pjdlog_error("Unable to decrypt core.");
286 				goto failed;
287 			}
288 		}
289 
290 		if (olen > 0 && write(ofd, buf, olen) != olen) {
291 			pjdlog_errno(LOG_ERR, "Unable to write core");
292 			goto failed;
293 		}
294 	} while (bytes > 0);
295 
296 	explicit_bzero(buf, sizeof(buf));
297 	EVP_CIPHER_CTX_free(ctx);
298 	exit(0);
299 failed:
300 	explicit_bzero(key, sizeof(key));
301 	explicit_bzero(buf, sizeof(buf));
302 	RSA_free(privkey);
303 	if (ctx != NULL)
304 		EVP_CIPHER_CTX_free(ctx);
305 	exit(1);
306 }
307 
308 int
309 main(int argc, char **argv)
310 {
311 	char core[PATH_MAX], encryptedcore[PATH_MAX], keyfile[PATH_MAX];
312 	const char *crashdir, *dumpnr, *privatekey;
313 	int ch, debug, error, ofd;
314 	size_t ii;
315 	bool force, usesyslog;
316 
317 	error = 1;
318 
319 	pjdlog_init(PJDLOG_MODE_STD);
320 	pjdlog_prefix_set("(decryptcore) ");
321 
322 	debug = 0;
323 	*core = '\0';
324 	crashdir = NULL;
325 	dumpnr = NULL;
326 	*encryptedcore = '\0';
327 	force = false;
328 	*keyfile = '\0';
329 	privatekey = NULL;
330 	usesyslog = false;
331 	while ((ch = getopt(argc, argv, "Lc:d:e:fk:n:p:v")) != -1) {
332 		switch (ch) {
333 		case 'L':
334 			usesyslog = true;
335 			break;
336 		case 'c':
337 			if (strlcpy(core, optarg, sizeof(core)) >= sizeof(core))
338 				pjdlog_exitx(1, "Core file path is too long.");
339 			break;
340 		case 'd':
341 			crashdir = optarg;
342 			break;
343 		case 'e':
344 			if (strlcpy(encryptedcore, optarg,
345 			    sizeof(encryptedcore)) >= sizeof(encryptedcore)) {
346 				pjdlog_exitx(1, "Encrypted core file path is too long.");
347 			}
348 			break;
349 		case 'f':
350 			force = true;
351 			break;
352 		case 'k':
353 			if (strlcpy(keyfile, optarg, sizeof(keyfile)) >=
354 			    sizeof(keyfile)) {
355 				pjdlog_exitx(1, "Key file path is too long.");
356 			}
357 			break;
358 		case 'n':
359 			dumpnr = optarg;
360 			break;
361 		case 'p':
362 			privatekey = optarg;
363 			break;
364 		case 'v':
365 			debug++;
366 			break;
367 		default:
368 			usage();
369 		}
370 	}
371 	argc -= optind;
372 	argv += optind;
373 
374 	if (argc != 0)
375 		usage();
376 
377 	/* Verify mutually exclusive options. */
378 	if ((crashdir != NULL || dumpnr != NULL) &&
379 	    (*keyfile != '\0' || *encryptedcore != '\0' || *core != '\0')) {
380 		usage();
381 	}
382 
383 	/*
384 	 * Set key, encryptedcore and core file names using crashdir and dumpnr.
385 	 */
386 	if (dumpnr != NULL) {
387 		for (ii = 0; ii < strnlen(dumpnr, PATH_MAX); ii++) {
388 			if (isdigit((int)dumpnr[ii]) == 0)
389 				usage();
390 		}
391 
392 		if (crashdir == NULL)
393 			crashdir = DECRYPTCORE_CRASHDIR;
394 		PJDLOG_VERIFY(snprintf(keyfile, sizeof(keyfile),
395 		    "%s/key.%s", crashdir, dumpnr) > 0);
396 		PJDLOG_VERIFY(snprintf(core, sizeof(core),
397 		    "%s/vmcore.%s", crashdir, dumpnr) > 0);
398 		PJDLOG_VERIFY(snprintf(encryptedcore, sizeof(encryptedcore),
399 		    "%s/vmcore_encrypted.%s", crashdir, dumpnr) > 0);
400 	}
401 
402 	if (privatekey == NULL || *keyfile == '\0' || *encryptedcore == '\0' ||
403 	    *core == '\0') {
404 		usage();
405 	}
406 
407 	if (usesyslog)
408 		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
409 	pjdlog_debug_set(debug);
410 
411 	if (force && unlink(core) == -1 && errno != ENOENT) {
412 		pjdlog_errno(LOG_ERR, "Unable to remove old core");
413 		goto out;
414 	}
415 	ofd = open(core, O_WRONLY | O_CREAT | O_EXCL, 0600);
416 	if (ofd == -1) {
417 		pjdlog_errno(LOG_ERR, "Unable to open %s", core);
418 		goto out;
419 	}
420 
421 	if (!decrypt(ofd, privatekey, keyfile, encryptedcore)) {
422 		if (unlink(core) == -1 && errno != ENOENT)
423 			pjdlog_errno(LOG_ERR, "Unable to remove core");
424 		goto out;
425 	}
426 
427 	error = 0;
428 out:
429 	pjdlog_fini();
430 	exit(error);
431 }
432