xref: /freebsd/sbin/decryptcore/decryptcore.c (revision f9edb08480901b8c7d85837d72f8702008b0a773)
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 [-Lv] -p privatekeyfile -k keyfile -e encryptedcore -c core\n"
59 	    "       decryptcore [-Lv] [-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(const char *privkeyfile, const char *keyfile, const char *input,
119     const char *output)
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, ofd, olen, privkeysize;
128 	ssize_t bytes;
129 	pid_t pid;
130 
131 	PJDLOG_ASSERT(privkeyfile != NULL);
132 	PJDLOG_ASSERT(keyfile != NULL);
133 	PJDLOG_ASSERT(input != NULL);
134 	PJDLOG_ASSERT(output != 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 		return (false);
146 	}
147 
148 	if (pid > 0)
149 		return (wait_for_process(pid) == 0);
150 
151 	kfd = open(keyfile, O_RDONLY);
152 	if (kfd == -1) {
153 		pjdlog_errno(LOG_ERR, "Unable to open %s", keyfile);
154 		goto failed;
155 	}
156 	ifd = open(input, O_RDONLY);
157 	if (ifd == -1) {
158 		pjdlog_errno(LOG_ERR, "Unable to open %s", input);
159 		goto failed;
160 	}
161 	ofd = open(output, O_WRONLY | O_CREAT | O_TRUNC, 0600);
162 	if (ofd == -1) {
163 		pjdlog_errno(LOG_ERR, "Unable to open %s", output);
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 (cap_enter() < 0 && errno != ENOSYS) {
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 	EVP_CIPHER_CTX_init(&ctx);
184 
185 	kdk = read_key(kfd);
186 	close(kfd);
187 	if (kdk == NULL)
188 		goto failed;
189 
190 	privkey = PEM_read_RSAPrivateKey(fp, &privkey, NULL, NULL);
191 	fclose(fp);
192 	if (privkey == NULL) {
193 		pjdlog_error("Unable to read data from %s.", privkeyfile);
194 		goto failed;
195 	}
196 
197 	privkeysize = RSA_size(privkey);
198 	if (privkeysize != (int)kdk->kdk_encryptedkeysize) {
199 		pjdlog_error("RSA modulus size mismatch: equals %db and should be %ub.",
200 		    8 * privkeysize, 8 * kdk->kdk_encryptedkeysize);
201 		goto failed;
202 	}
203 
204 	switch (kdk->kdk_encryption) {
205 	case KERNELDUMP_ENC_AES_256_CBC:
206 		cipher = EVP_aes_256_cbc();
207 		break;
208 	default:
209 		pjdlog_error("Invalid encryption algorithm.");
210 		goto failed;
211 	}
212 
213 	if (RSA_private_decrypt(kdk->kdk_encryptedkeysize,
214 	    kdk->kdk_encryptedkey, key, privkey,
215 	    RSA_PKCS1_PADDING) != sizeof(key)) {
216 		pjdlog_error("Unable to decrypt key: %s",
217 		    ERR_error_string(ERR_get_error(), NULL));
218 		goto failed;
219 	}
220 	RSA_free(privkey);
221 	privkey = NULL;
222 
223 	EVP_DecryptInit_ex(&ctx, cipher, NULL, key, kdk->kdk_iv);
224 	EVP_CIPHER_CTX_set_padding(&ctx, 0);
225 
226 	explicit_bzero(key, sizeof(key));
227 
228 	do {
229 		bytes = read(ifd, buf, sizeof(buf));
230 		if (bytes < 0) {
231 			pjdlog_errno(LOG_ERR, "Unable to read data from %s",
232 			    input);
233 			goto failed;
234 		}
235 
236 		if (bytes > 0) {
237 			if (EVP_DecryptUpdate(&ctx, buf, &olen, buf,
238 			    bytes) == 0) {
239 				pjdlog_error("Unable to decrypt core.");
240 				goto failed;
241 			}
242 		} else {
243 			if (EVP_DecryptFinal_ex(&ctx, buf, &olen) == 0) {
244 				pjdlog_error("Unable to decrypt core.");
245 				goto failed;
246 			}
247 		}
248 
249 		if (olen > 0 && write(ofd, buf, olen) != olen) {
250 			pjdlog_errno(LOG_ERR, "Unable to write data to %s",
251 			    output);
252 			goto failed;
253 		}
254 	} while (bytes > 0);
255 
256 	explicit_bzero(buf, sizeof(buf));
257 	EVP_CIPHER_CTX_cleanup(&ctx);
258 	exit(0);
259 failed:
260 	explicit_bzero(key, sizeof(key));
261 	explicit_bzero(buf, sizeof(buf));
262 	RSA_free(privkey);
263 	EVP_CIPHER_CTX_cleanup(&ctx);
264 	exit(1);
265 }
266 
267 int
268 main(int argc, char **argv)
269 {
270 	char core[PATH_MAX], encryptedcore[PATH_MAX], keyfile[PATH_MAX];
271 	const char *crashdir, *dumpnr, *privatekey;
272 	int ch, debug;
273 	size_t ii;
274 	bool usesyslog;
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 	*keyfile = '\0';
285 	privatekey = NULL;
286 	usesyslog = false;
287 	while ((ch = getopt(argc, argv, "Lc:d:e:k: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 'k':
306 			if (strlcpy(keyfile, optarg, sizeof(keyfile)) >=
307 			    sizeof(keyfile)) {
308 				pjdlog_exitx(1, "Key file path is too long.");
309 			}
310 			break;
311 		case 'n':
312 			dumpnr = optarg;
313 			break;
314 		case 'p':
315 			privatekey = optarg;
316 			break;
317 		case 'v':
318 			debug++;
319 			break;
320 		default:
321 			usage();
322 		}
323 	}
324 	argc -= optind;
325 	argv += optind;
326 
327 	if (argc != 0)
328 		usage();
329 
330 	/* Verify mutually exclusive options. */
331 	if ((crashdir != NULL || dumpnr != NULL) &&
332 	    (*keyfile != '\0' || *encryptedcore != '\0' || *core != '\0')) {
333 		usage();
334 	}
335 
336 	/*
337 	 * Set key, encryptedcore and core file names using crashdir and dumpnr.
338 	 */
339 	if (dumpnr != NULL) {
340 		for (ii = 0; ii < strnlen(dumpnr, PATH_MAX); ii++) {
341 			if (isdigit((int)dumpnr[ii]) == 0)
342 				usage();
343 		}
344 
345 		if (crashdir == NULL)
346 			crashdir = DECRYPTCORE_CRASHDIR;
347 		PJDLOG_VERIFY(snprintf(keyfile, sizeof(keyfile),
348 		    "%s/key.%s", crashdir, dumpnr) > 0);
349 		PJDLOG_VERIFY(snprintf(core, sizeof(core),
350 		    "%s/vmcore.%s", crashdir, dumpnr) > 0);
351 		PJDLOG_VERIFY(snprintf(encryptedcore, sizeof(encryptedcore),
352 		    "%s/vmcore_encrypted.%s", crashdir, dumpnr) > 0);
353 	}
354 
355 	if (privatekey == NULL || *keyfile == '\0' || *encryptedcore == '\0' ||
356 	    *core == '\0') {
357 		usage();
358 	}
359 
360 	if (usesyslog)
361 		pjdlog_mode_set(PJDLOG_MODE_SYSLOG);
362 	pjdlog_debug_set(debug);
363 
364 	if (!decrypt(privatekey, keyfile, encryptedcore, core)) {
365 		if (unlink(core) == -1 && errno != ENOENT)
366 			pjdlog_exit(1, "Unable to remove core");
367 		exit(1);
368 	}
369 
370 	pjdlog_fini();
371 
372 	exit(0);
373 }
374