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