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