xref: /freebsd/sbin/decryptcore/decryptcore.c (revision d3d381b2b194b4d24853e92eecef55f262688d1a)
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/sysctl.h>
35 #include <sys/wait.h>
36 
37 #include <ctype.h>
38 #include <capsicum_helpers.h>
39 #include <fcntl.h>
40 #include <stdbool.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 
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 	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 	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 	if (caph_enter() < 0) {
172 		pjdlog_errno(LOG_ERR, "Unable to enter capability mode");
173 		goto failed;
174 	}
175 
176 	privkey = RSA_new();
177 	if (privkey == NULL) {
178 		pjdlog_error("Unable to allocate an RSA structure: %s",
179 		    ERR_error_string(ERR_get_error(), NULL));
180 		goto failed;
181 	}
182 	EVP_CIPHER_CTX_init(&ctx);
183 
184 	kdk = read_key(kfd);
185 	close(kfd);
186 	if (kdk == NULL)
187 		goto failed;
188 
189 	privkey = PEM_read_RSAPrivateKey(fp, &privkey, NULL, NULL);
190 	fclose(fp);
191 	if (privkey == NULL) {
192 		pjdlog_error("Unable to read data from %s.", privkeyfile);
193 		goto failed;
194 	}
195 
196 	privkeysize = RSA_size(privkey);
197 	if (privkeysize != (int)kdk->kdk_encryptedkeysize) {
198 		pjdlog_error("RSA modulus size mismatch: equals %db and should be %ub.",
199 		    8 * privkeysize, 8 * kdk->kdk_encryptedkeysize);
200 		goto failed;
201 	}
202 
203 	switch (kdk->kdk_encryption) {
204 	case KERNELDUMP_ENC_AES_256_CBC:
205 		cipher = EVP_aes_256_cbc();
206 		break;
207 	default:
208 		pjdlog_error("Invalid encryption algorithm.");
209 		goto failed;
210 	}
211 
212 	if (RSA_private_decrypt(kdk->kdk_encryptedkeysize,
213 	    kdk->kdk_encryptedkey, key, privkey,
214 	    RSA_PKCS1_PADDING) != sizeof(key)) {
215 		pjdlog_error("Unable to decrypt key: %s",
216 		    ERR_error_string(ERR_get_error(), NULL));
217 		goto failed;
218 	}
219 	RSA_free(privkey);
220 	privkey = NULL;
221 
222 	EVP_DecryptInit_ex(&ctx, cipher, NULL, key, kdk->kdk_iv);
223 	EVP_CIPHER_CTX_set_padding(&ctx, 0);
224 
225 	explicit_bzero(key, sizeof(key));
226 
227 	do {
228 		bytes = read(ifd, buf, sizeof(buf));
229 		if (bytes < 0) {
230 			pjdlog_errno(LOG_ERR, "Unable to read data from %s",
231 			    input);
232 			goto failed;
233 		}
234 
235 		if (bytes > 0) {
236 			if (EVP_DecryptUpdate(&ctx, buf, &olen, buf,
237 			    bytes) == 0) {
238 				pjdlog_error("Unable to decrypt core.");
239 				goto failed;
240 			}
241 		} else {
242 			if (EVP_DecryptFinal_ex(&ctx, buf, &olen) == 0) {
243 				pjdlog_error("Unable to decrypt core.");
244 				goto failed;
245 			}
246 		}
247 
248 		if (olen > 0 && write(ofd, buf, olen) != olen) {
249 			pjdlog_errno(LOG_ERR, "Unable to write core");
250 			goto failed;
251 		}
252 	} while (bytes > 0);
253 
254 	explicit_bzero(buf, sizeof(buf));
255 	EVP_CIPHER_CTX_cleanup(&ctx);
256 	exit(0);
257 failed:
258 	explicit_bzero(key, sizeof(key));
259 	explicit_bzero(buf, sizeof(buf));
260 	RSA_free(privkey);
261 	EVP_CIPHER_CTX_cleanup(&ctx);
262 	exit(1);
263 }
264 
265 int
266 main(int argc, char **argv)
267 {
268 	char core[PATH_MAX], encryptedcore[PATH_MAX], keyfile[PATH_MAX];
269 	const char *crashdir, *dumpnr, *privatekey;
270 	int ch, debug, error, ofd;
271 	size_t ii;
272 	bool force, usesyslog;
273 
274 	error = 1;
275 
276 	pjdlog_init(PJDLOG_MODE_STD);
277 	pjdlog_prefix_set("(decryptcore) ");
278 
279 	debug = 0;
280 	*core = '\0';
281 	crashdir = NULL;
282 	dumpnr = NULL;
283 	*encryptedcore = '\0';
284 	force = false;
285 	*keyfile = '\0';
286 	privatekey = NULL;
287 	usesyslog = false;
288 	while ((ch = getopt(argc, argv, "Lc:d:e:fk:n:p:v")) != -1) {
289 		switch (ch) {
290 		case 'L':
291 			usesyslog = true;
292 			break;
293 		case 'c':
294 			if (strlcpy(core, optarg, sizeof(core)) >= sizeof(core))
295 				pjdlog_exitx(1, "Core file path is too long.");
296 			break;
297 		case 'd':
298 			crashdir = optarg;
299 			break;
300 		case 'e':
301 			if (strlcpy(encryptedcore, optarg,
302 			    sizeof(encryptedcore)) >= sizeof(encryptedcore)) {
303 				pjdlog_exitx(1, "Encrypted core file path is too long.");
304 			}
305 			break;
306 		case 'f':
307 			force = true;
308 			break;
309 		case 'k':
310 			if (strlcpy(keyfile, optarg, sizeof(keyfile)) >=
311 			    sizeof(keyfile)) {
312 				pjdlog_exitx(1, "Key file path is too long.");
313 			}
314 			break;
315 		case 'n':
316 			dumpnr = optarg;
317 			break;
318 		case 'p':
319 			privatekey = optarg;
320 			break;
321 		case 'v':
322 			debug++;
323 			break;
324 		default:
325 			usage();
326 		}
327 	}
328 	argc -= optind;
329 	argv += optind;
330 
331 	if (argc != 0)
332 		usage();
333 
334 	/* Verify mutually exclusive options. */
335 	if ((crashdir != NULL || dumpnr != NULL) &&
336 	    (*keyfile != '\0' || *encryptedcore != '\0' || *core != '\0')) {
337 		usage();
338 	}
339 
340 	/*
341 	 * Set key, encryptedcore and core file names using crashdir and dumpnr.
342 	 */
343 	if (dumpnr != NULL) {
344 		for (ii = 0; ii < strnlen(dumpnr, PATH_MAX); ii++) {
345 			if (isdigit((int)dumpnr[ii]) == 0)
346 				usage();
347 		}
348 
349 		if (crashdir == NULL)
350 			crashdir = DECRYPTCORE_CRASHDIR;
351 		PJDLOG_VERIFY(snprintf(keyfile, sizeof(keyfile),
352 		    "%s/key.%s", crashdir, dumpnr) > 0);
353 		PJDLOG_VERIFY(snprintf(core, sizeof(core),
354 		    "%s/vmcore.%s", crashdir, dumpnr) > 0);
355 		PJDLOG_VERIFY(snprintf(encryptedcore, sizeof(encryptedcore),
356 		    "%s/vmcore_encrypted.%s", crashdir, dumpnr) > 0);
357 	}
358 
359 	if (privatekey == NULL || *keyfile == '\0' || *encryptedcore == '\0' ||
360 	    *core == '\0') {
361 		usage();
362 	}
363 
364 	if (usesyslog)
365 		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
366 	pjdlog_debug_set(debug);
367 
368 	if (force && unlink(core) == -1 && errno != ENOENT) {
369 		pjdlog_errno(LOG_ERR, "Unable to remove old core");
370 		goto out;
371 	}
372 	ofd = open(core, O_WRONLY | O_CREAT | O_EXCL, 0600);
373 	if (ofd == -1) {
374 		pjdlog_errno(LOG_ERR, "Unable to open %s", core);
375 		goto out;
376 	}
377 
378 	if (!decrypt(ofd, privatekey, keyfile, encryptedcore)) {
379 		if (unlink(core) == -1 && errno != ENOENT)
380 			pjdlog_errno(LOG_ERR, "Unable to remove core");
381 		goto out;
382 	}
383 
384 	error = 0;
385 out:
386 	pjdlog_fini();
387 	exit(error);
388 }
389