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