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