xref: /freebsd/sbin/decryptcore/decryptcore.c (revision 63d1fd5970ec814904aa0f4580b10a0d302d08b2)
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/stat.h>
35 #include <sys/sysctl.h>
36 #include <sys/wait.h>
37 
38 #include <ctype.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 [-Lv] -p privatekeyfile -k keyfile -e encryptedcore -c core\n"
60 	    "       decryptcore [-Lv] [-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(const char *privkeyfile, const char *keyfile, const char *input,
120     const char *output)
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, ofd, olen, privkeysize;
129 	ssize_t bytes;
130 	pid_t pid;
131 
132 	PJDLOG_ASSERT(privkeyfile != NULL);
133 	PJDLOG_ASSERT(keyfile != NULL);
134 	PJDLOG_ASSERT(input != NULL);
135 	PJDLOG_ASSERT(output != 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 		return (false);
147 	}
148 
149 	if (pid > 0)
150 		return (wait_for_process(pid) == 0);
151 
152 	kfd = open(keyfile, O_RDONLY);
153 	if (kfd == -1) {
154 		pjdlog_errno(LOG_ERR, "Unable to open %s", keyfile);
155 		goto failed;
156 	}
157 	ifd = open(input, O_RDONLY);
158 	if (ifd == -1) {
159 		pjdlog_errno(LOG_ERR, "Unable to open %s", input);
160 		goto failed;
161 	}
162 	ofd = open(output, O_WRONLY | O_CREAT | O_TRUNC, 0600);
163 	if (ofd == -1) {
164 		pjdlog_errno(LOG_ERR, "Unable to open %s", output);
165 		goto failed;
166 	}
167 	fp = fopen(privkeyfile, "r");
168 	if (fp == NULL) {
169 		pjdlog_errno(LOG_ERR, "Unable to open %s", privkeyfile);
170 		goto failed;
171 	}
172 
173 	if (cap_enter() < 0 && errno != ENOSYS) {
174 		pjdlog_errno(LOG_ERR, "Unable to enter capability mode");
175 		goto failed;
176 	}
177 
178 	privkey = RSA_new();
179 	if (privkey == NULL) {
180 		pjdlog_error("Unable to allocate an RSA structure: %s",
181 		    ERR_error_string(ERR_get_error(), NULL));
182 		goto failed;
183 	}
184 	EVP_CIPHER_CTX_init(&ctx);
185 
186 	kdk = read_key(kfd);
187 	close(kfd);
188 	if (kdk == NULL)
189 		goto failed;
190 
191 	privkey = PEM_read_RSAPrivateKey(fp, &privkey, NULL, NULL);
192 	fclose(fp);
193 	if (privkey == NULL) {
194 		pjdlog_error("Unable to read data from %s.", privkeyfile);
195 		goto failed;
196 	}
197 
198 	privkeysize = RSA_size(privkey);
199 	if (privkeysize != (int)kdk->kdk_encryptedkeysize) {
200 		pjdlog_error("RSA modulus size mismatch: equals %db and should be %ub.",
201 		    8 * privkeysize, 8 * kdk->kdk_encryptedkeysize);
202 		goto failed;
203 	}
204 
205 	switch (kdk->kdk_encryption) {
206 	case KERNELDUMP_ENC_AES_256_CBC:
207 		cipher = EVP_aes_256_cbc();
208 		break;
209 	default:
210 		pjdlog_error("Invalid encryption algorithm.");
211 		goto failed;
212 	}
213 
214 	if (RSA_private_decrypt(kdk->kdk_encryptedkeysize,
215 	    kdk->kdk_encryptedkey, key, privkey,
216 	    RSA_PKCS1_PADDING) != sizeof(key)) {
217 		pjdlog_error("Unable to decrypt key: %s",
218 		    ERR_error_string(ERR_get_error(), NULL));
219 		goto failed;
220 	}
221 	RSA_free(privkey);
222 	privkey = NULL;
223 
224 	EVP_DecryptInit_ex(&ctx, cipher, NULL, key, kdk->kdk_iv);
225 	EVP_CIPHER_CTX_set_padding(&ctx, 0);
226 
227 	explicit_bzero(key, sizeof(key));
228 
229 	do {
230 		bytes = read(ifd, buf, sizeof(buf));
231 		if (bytes < 0) {
232 			pjdlog_errno(LOG_ERR, "Unable to read data from %s",
233 			    input);
234 			goto failed;
235 		} else if (bytes == 0) {
236 			break;
237 		}
238 
239 		if (bytes > 0) {
240 			if (EVP_DecryptUpdate(&ctx, buf, &olen, buf,
241 			    bytes) == 0) {
242 				pjdlog_error("Unable to decrypt core.");
243 				goto failed;
244 			}
245 		} else {
246 			if (EVP_DecryptFinal_ex(&ctx, buf, &olen) == 0) {
247 				pjdlog_error("Unable to decrypt core.");
248 				goto failed;
249 			}
250 		}
251 
252 		if (olen == 0)
253 			continue;
254 
255 		if (write(ofd, buf, olen) != olen) {
256 			pjdlog_errno(LOG_ERR, "Unable to write data to %s",
257 			    output);
258 			goto failed;
259 		}
260 	} while (bytes > 0);
261 
262 	explicit_bzero(buf, sizeof(buf));
263 	EVP_CIPHER_CTX_cleanup(&ctx);
264 	exit(0);
265 failed:
266 	explicit_bzero(key, sizeof(key));
267 	explicit_bzero(buf, sizeof(buf));
268 	RSA_free(privkey);
269 	EVP_CIPHER_CTX_cleanup(&ctx);
270 	exit(1);
271 }
272 
273 int
274 main(int argc, char **argv)
275 {
276 	char core[PATH_MAX], encryptedcore[PATH_MAX], keyfile[PATH_MAX];
277 	struct stat sb;
278 	const char *crashdir, *dumpnr, *privatekey;
279 	int ch, debug;
280 	size_t ii;
281 	bool usesyslog;
282 
283 	pjdlog_init(PJDLOG_MODE_STD);
284 	pjdlog_prefix_set("(decryptcore) ");
285 
286 	debug = 0;
287 	*core = '\0';
288 	crashdir = NULL;
289 	dumpnr = NULL;
290 	*encryptedcore = '\0';
291 	*keyfile = '\0';
292 	privatekey = NULL;
293 	usesyslog = false;
294 	while ((ch = getopt(argc, argv, "Lc:d:e:k:n:p:v")) != -1) {
295 		switch (ch) {
296 		case 'L':
297 			usesyslog = true;
298 			break;
299 		case 'c':
300 			strncpy(core, optarg, sizeof(core));
301 			break;
302 		case 'd':
303 			crashdir = optarg;
304 			break;
305 		case 'e':
306 			strncpy(encryptedcore, optarg, sizeof(encryptedcore));
307 			break;
308 		case 'k':
309 			strncpy(keyfile, optarg, sizeof(keyfile));
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 (stat(core, &sb) == 0 && unlink(core) != 0)
366 			pjdlog_exit(1, "Unable to remove core");
367 		exit(1);
368 	}
369 
370 	pjdlog_fini();
371 
372 	exit(0);
373 }
374