• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * f2fscrypt.c - f2fs encryption management utility
3  *
4  * Authors: Kinglong Mee <kinglongmee@gmail.com>
5  *
6  * Copied from e4crypt that for ext4 filesystem.
7  * Authors: Michael Halcrow <mhalcrow@google.com>,
8  *	    Ildar Muslukhov <ildarm@google.com>
9  */
10 
11 #ifndef _LARGEFILE_SOURCE
12 #define _LARGEFILE_SOURCE
13 #endif
14 
15 #ifndef _LARGEFILE64_SOURCE
16 #define _LARGEFILE64_SOURCE
17 #endif
18 
19 #ifndef _GNU_SOURCE
20 #define _GNU_SOURCE
21 #endif
22 
23 #include "config.h"
24 #include <assert.h>
25 #include <errno.h>
26 #include <getopt.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #ifdef HAVE_MNTENT_H
34 #include <mntent.h>
35 #endif
36 #include <sys/ioctl.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #include <fcntl.h>
40 #include <termios.h>
41 #include <unistd.h>
42 #include <signal.h>
43 #ifdef __KERNEL__
44 #include <linux/fs.h>
45 #endif
46 #include <uuid/uuid.h>
47 
48 #if !defined(HAVE_ADD_KEY) || !defined(HAVE_KEYCTL)
49 #include <sys/syscall.h>
50 #endif
51 #ifdef HAVE_SYS_KEY_H
52 #include <sys/key.h>
53 #endif
54 #include <f2fs_fs.h>
55 
56 #define F2FS_MAX_KEY_SIZE		64
57 #define F2FS_MAX_PASSPHRASE_SIZE	1024
58 #define F2FS_MAX_SALT_SIZE		256
59 
60 /* Encryption algorithms, key size and key reference len */
61 #define F2FS_ENCRYPTION_MODE_INVALID		0
62 #define F2FS_ENCRYPTION_MODE_AES_256_XTS	1
63 #define F2FS_ENCRYPTION_MODE_AES_256_GCM	2
64 #define F2FS_ENCRYPTION_MODE_AES_256_CBC	3
65 #define F2FS_ENCRYPTION_MODE_AES_256_CTS	4
66 
67 #define F2FS_AES_256_XTS_KEY_SIZE		64
68 #define F2FS_AES_256_GCM_KEY_SIZE		32
69 #define F2FS_AES_256_CBC_KEY_SIZE		32
70 #define F2FS_AES_256_CTS_KEY_SIZE		32
71 #define F2FS_MAX_KEY_SIZE			64
72 
73 /* Password derivation constants */
74 #define F2FS_MAX_PASSPHRASE_SIZE		1024
75 #define F2FS_MAX_SALT_SIZE			256
76 #define F2FS_PBKDF2_ITERATIONS			0xFFFF
77 
78 /* special process keyring shortcut IDs */
79 #define KEY_SPEC_THREAD_KEYRING		-1
80 #define KEY_SPEC_PROCESS_KEYRING	-2
81 #define KEY_SPEC_SESSION_KEYRING	-3
82 #define KEY_SPEC_USER_KEYRING		-4
83 #define KEY_SPEC_USER_SESSION_KEYRING	-5
84 #define KEY_SPEC_GROUP_KEYRING		-6
85 
86 #define KEYCTL_GET_KEYRING_ID		0
87 #define KEYCTL_JOIN_SESSION_KEYRING	1
88 #define KEYCTL_DESCRIBE			6
89 #define KEYCTL_SEARCH			10
90 #define KEYCTL_SESSION_TO_PARENT	18
91 
92 /*
93  * File system encryption support
94  */
95 /* Policy provided via an ioctl on the topmost directory */
96 #define F2FS_KEY_DESCRIPTOR_SIZE	8
97 #define F2FS_KEY_REF_STR_BUF_SIZE ((F2FS_KEY_DESCRIPTOR_SIZE * 2) + 1)
98 
99 struct f2fs_fscrypt_policy {
100 	__u8 version;
101 	__u8 contents_encryption_mode;
102 	__u8 filenames_encryption_mode;
103 	__u8 flags;
104 	__u8 master_key_descriptor[F2FS_KEY_DESCRIPTOR_SIZE];
105 } __attribute__((packed));
106 
107 #define F2FS_IOC_SET_ENCRYPTION_POLICY	_IOR('f', 19, struct f2fs_fscrypt_policy)
108 #define F2FS_IOC_GET_ENCRYPTION_PWSALT	_IOW('f', 20, __u8[16])
109 #define F2FS_IOC_GET_ENCRYPTION_POLICY	_IOW('f', 21, struct f2fs_fscrypt_policy)
110 
111 typedef int32_t key_serial_t;
112 
113 
114 
115 #define OPT_VERBOSE	0x0001
116 #define OPT_QUIET	0x0002
117 
118 struct f2fs_encryption_key {
119         __u32 mode;
120         char raw[F2FS_MAX_KEY_SIZE];
121         __u32 size;
122 } __attribute__((__packed__));
123 
124 int options;
125 
126 extern void f2fs_sha512(const unsigned char *in, unsigned long in_size,
127 						unsigned char *out);
128 
129 #if !defined(HAVE_KEYCTL)
keyctl(int cmd,...)130 static long keyctl(int cmd, ...)
131 {
132 	va_list va;
133 	unsigned long arg2, arg3, arg4, arg5;
134 
135 	va_start(va, cmd);
136 	arg2 = va_arg(va, unsigned long);
137 	arg3 = va_arg(va, unsigned long);
138 	arg4 = va_arg(va, unsigned long);
139 	arg5 = va_arg(va, unsigned long);
140 	va_end(va);
141 	return syscall(__NR_keyctl, cmd, arg2, arg3, arg4, arg5);
142 }
143 #endif
144 
145 #if !defined(HAVE_ADD_KEY)
add_key(const char * type,const char * description,const void * payload,size_t plen,key_serial_t keyring)146 static key_serial_t add_key(const char *type, const char *description,
147 			    const void *payload, size_t plen,
148 			    key_serial_t keyring)
149 {
150 	return syscall(__NR_add_key, type, description, payload,
151 		       plen, keyring);
152 }
153 #endif
154 
155 static const unsigned char *hexchars = (const unsigned char *) "0123456789abcdef";
156 static const size_t hexchars_size = 16;
157 
158 #define SHA512_LENGTH 64
159 #define F2FS_KEY_TYPE_LOGON "logon"
160 #define F2FS_KEY_DESC_PREFIX "f2fs:"
161 #define F2FS_KEY_DESC_PREFIX_SIZE 5
162 
int_log2(int arg)163 static int int_log2(int arg)
164 {
165 	int     l = 0;
166 
167 	arg >>= 1;
168 	while (arg) {
169 		l++;
170 		arg >>= 1;
171 	}
172 	return l;
173 }
174 
validate_paths(int argc,char * argv[],int path_start_index)175 static void validate_paths(int argc, char *argv[], int path_start_index)
176 {
177 	int x;
178 	int valid = 1;
179 	struct stat st;
180 
181 	for (x = path_start_index; x < argc; x++) {
182 		int ret = access(argv[x], W_OK);
183 		if (ret) {
184 		invalid:
185 			perror(argv[x]);
186 			valid = 0;
187 			continue;
188 		}
189 		ret = stat(argv[x], &st);
190 		if (ret < 0)
191 			goto invalid;
192 		if (!S_ISDIR(st.st_mode)) {
193 			fprintf(stderr, "%s is not a directory\n", argv[x]);
194 			goto invalid;
195 		}
196 	}
197 	if (!valid)
198 		exit(1);
199 }
200 
hex2byte(const char * hex,size_t hex_size,unsigned char * bytes,size_t bytes_size)201 static int hex2byte(const char *hex, size_t hex_size, unsigned char *bytes,
202 		    size_t bytes_size)
203 {
204 	size_t x;
205 	unsigned char *h, *l;
206 
207 	if (hex_size % 2)
208 		return -EINVAL;
209 	for (x = 0; x < hex_size; x += 2) {
210 		h = memchr(hexchars, hex[x], hexchars_size);
211 		if (!h)
212 			return -EINVAL;
213 		l = memchr(hexchars, hex[x + 1], hexchars_size);
214 		if (!l)
215 			return -EINVAL;
216 		if ((x >> 1) >= bytes_size)
217 			return -EINVAL;
218 		bytes[x >> 1] = (((unsigned char)(h - hexchars) << 4) +
219 				 (unsigned char)(l - hexchars));
220 	}
221 	return 0;
222 }
223 
224 /*
225  * Salt handling
226  */
227 struct salt {
228 	unsigned char *salt;
229 	char key_ref_str[F2FS_KEY_REF_STR_BUF_SIZE];
230 	unsigned char key_desc[F2FS_KEY_DESCRIPTOR_SIZE];
231 	unsigned char key[F2FS_MAX_KEY_SIZE];
232 	size_t salt_len;
233 };
234 struct salt *salt_list;
235 unsigned num_salt;
236 unsigned max_salt;
237 char in_passphrase[F2FS_MAX_PASSPHRASE_SIZE];
238 
find_by_salt(unsigned char * salt,size_t salt_len)239 static struct salt *find_by_salt(unsigned char *salt, size_t salt_len)
240 {
241 	unsigned int i;
242 	struct salt *p;
243 
244 	for (i = 0, p = salt_list; i < num_salt; i++, p++)
245 		if ((p->salt_len == salt_len) &&
246 		    !memcmp(p->salt, salt, salt_len))
247 			return p;
248 	return NULL;
249 }
250 
add_salt(unsigned char * salt,size_t salt_len)251 static void add_salt(unsigned char *salt, size_t salt_len)
252 {
253 	if (find_by_salt(salt, salt_len))
254 		return;
255 	if (num_salt >= max_salt) {
256 		max_salt = num_salt + 10;
257 		salt_list = realloc(salt_list, max_salt * sizeof(struct salt));
258 		if (!salt_list) {
259 			fprintf(stderr, "Couldn't allocate salt list\n");
260 			exit(1);
261 		}
262 	}
263 	salt_list[num_salt].salt = salt;
264 	salt_list[num_salt].salt_len = salt_len;
265 	num_salt++;
266 }
267 
clear_secrets(void)268 static void clear_secrets(void)
269 {
270 	if (salt_list) {
271 		memset(salt_list, 0, sizeof(struct salt) * max_salt);
272 		free(salt_list);
273 		salt_list = NULL;
274 	}
275 	memset(in_passphrase, 0, sizeof(in_passphrase));
276 }
277 
die_signal_handler(int signum,siginfo_t * siginfo,void * context)278 static void die_signal_handler(int signum, siginfo_t *siginfo, void *context)
279 {
280 	clear_secrets();
281 	exit(-1);
282 }
283 
sigcatcher_setup(void)284 static void sigcatcher_setup(void)
285 {
286 	struct sigaction	sa;
287 
288 	memset(&sa, 0, sizeof(struct sigaction));
289 	sa.sa_sigaction = die_signal_handler;
290 	sa.sa_flags = SA_SIGINFO;
291 
292 	sigaction(SIGHUP, &sa, 0);
293 	sigaction(SIGINT, &sa, 0);
294 	sigaction(SIGQUIT, &sa, 0);
295 	sigaction(SIGFPE, &sa, 0);
296 	sigaction(SIGILL, &sa, 0);
297 	sigaction(SIGBUS, &sa, 0);
298 	sigaction(SIGSEGV, &sa, 0);
299 	sigaction(SIGABRT, &sa, 0);
300 	sigaction(SIGPIPE, &sa, 0);
301 	sigaction(SIGALRM, &sa, 0);
302 	sigaction(SIGTERM, &sa, 0);
303 	sigaction(SIGUSR1, &sa, 0);
304 	sigaction(SIGUSR2, &sa, 0);
305 	sigaction(SIGPOLL, &sa, 0);
306 	sigaction(SIGPROF, &sa, 0);
307 	sigaction(SIGSYS, &sa, 0);
308 	sigaction(SIGTRAP, &sa, 0);
309 	sigaction(SIGVTALRM, &sa, 0);
310 	sigaction(SIGXCPU, &sa, 0);
311 	sigaction(SIGXFSZ, &sa, 0);
312 }
313 
314 
315 #define PARSE_FLAGS_NOTSUPP_OK	0x0001
316 #define PARSE_FLAGS_FORCE_FN	0x0002
317 
parse_salt(char * salt_str,int flags)318 static void parse_salt(char *salt_str, int flags)
319 {
320 	unsigned char buf[F2FS_MAX_SALT_SIZE];
321 	char *cp = salt_str;
322 	unsigned char *salt_buf;
323 	int fd, ret, salt_len = 0;
324 
325 	if (flags & PARSE_FLAGS_FORCE_FN)
326 		goto salt_from_filename;
327 	if (strncmp(cp, "s:", 2) == 0) {
328 		cp += 2;
329 		salt_len = strlen(cp);
330 		if (salt_len >= F2FS_MAX_SALT_SIZE)
331 			goto invalid_salt;
332 		strncpy((char *) buf, cp, sizeof(buf));
333 	} else if (cp[0] == '/') {
334 	salt_from_filename:
335 		fd = open(cp, O_RDONLY | O_DIRECTORY);
336 		if (fd == -1 && errno == ENOTDIR)
337 			fd = open(cp, O_RDONLY);
338 		if (fd == -1) {
339 			perror(cp);
340 			exit(1);
341 		}
342 		ret = ioctl(fd, F2FS_IOC_GET_ENCRYPTION_PWSALT, &buf);
343 		close(fd);
344 		if (ret < 0) {
345 			if (flags & PARSE_FLAGS_NOTSUPP_OK)
346 				return;
347 			perror("F2FS_IOC_GET_ENCRYPTION_PWSALT");
348 			exit(1);
349 		}
350 		if (options & OPT_VERBOSE) {
351 			char tmp[80];
352 			uuid_unparse(buf, tmp);
353 			printf("%s has pw salt %s\n", cp, tmp);
354 		}
355 		salt_len = 16;
356 	} else if (strncmp(cp, "f:", 2) == 0) {
357 		cp += 2;
358 		goto salt_from_filename;
359 	} else if (strncmp(cp, "0x", 2) == 0) {
360 		unsigned char *h, *l;
361 
362 		cp += 2;
363 		if (strlen(cp) & 1)
364 			goto invalid_salt;
365 		while (*cp) {
366 			if (salt_len >= F2FS_MAX_SALT_SIZE)
367 				goto invalid_salt;
368 			h = memchr(hexchars, *cp++, hexchars_size);
369 			l = memchr(hexchars, *cp++, hexchars_size);
370 			if (!h || !l)
371 				goto invalid_salt;
372 			buf[salt_len++] =
373 				(((unsigned char)(h - hexchars) << 4) +
374 				 (unsigned char)(l - hexchars));
375 		}
376 	} else if (uuid_parse(cp, buf) == 0) {
377 		salt_len = 16;
378 	} else {
379 	invalid_salt:
380 		fprintf(stderr, "Invalid salt: %s\n", salt_str);
381 		exit(1);
382 	}
383 	salt_buf = malloc(salt_len);
384 	if (!salt_buf) {
385 		fprintf(stderr, "Couldn't allocate salt\n");
386 		exit(1);
387 	}
388 	memcpy(salt_buf, buf, salt_len);
389 	add_salt(salt_buf, salt_len);
390 }
391 
set_policy(struct salt * set_salt,int pad,int argc,char * argv[],int path_start_index)392 static void set_policy(struct salt *set_salt, int pad,
393 		       int argc, char *argv[], int path_start_index)
394 {
395 	struct salt *salt;
396 	struct f2fs_fscrypt_policy policy;
397 	uuid_t	uu;
398 	int fd;
399 	int x;
400 	int rc;
401 
402 	if ((pad != 4) && (pad != 8) &&
403 		 (pad != 16) && (pad != 32)) {
404 		fprintf(stderr, "Invalid padding %d\n", pad);
405 		exit(1);
406 	}
407 
408 	for (x = path_start_index; x < argc; x++) {
409 		fd = open(argv[x], O_DIRECTORY);
410 		if (fd == -1) {
411 			perror(argv[x]);
412 			exit(1);
413 		}
414 		if (set_salt)
415 			salt = set_salt;
416 		else {
417 			if (ioctl(fd, F2FS_IOC_GET_ENCRYPTION_PWSALT,
418 				  &uu) < 0) {
419 				perror("F2FS_IOC_GET_ENCRYPTION_PWSALT");
420 				exit(1);
421 			}
422 			salt = find_by_salt(uu, sizeof(uu));
423 			if (!salt) {
424 				fprintf(stderr, "Couldn't find salt!?!\n");
425 				exit(1);
426 			}
427 		}
428 		policy.version = 0;
429 		policy.contents_encryption_mode =
430 			F2FS_ENCRYPTION_MODE_AES_256_XTS;
431 		policy.filenames_encryption_mode =
432 			F2FS_ENCRYPTION_MODE_AES_256_CTS;
433 		policy.flags = int_log2(pad >> 2);
434 		memcpy(policy.master_key_descriptor, salt->key_desc,
435 		       F2FS_KEY_DESCRIPTOR_SIZE);
436 		rc = ioctl(fd, F2FS_IOC_SET_ENCRYPTION_POLICY, &policy);
437 		close(fd);
438 		if (rc) {
439 			printf("Error [%s] setting policy.\nThe key descriptor "
440 			       "[%s] may not match the existing encryption "
441 			       "context for directory [%s].\n",
442 			       strerror(errno), salt->key_ref_str, argv[x]);
443 			continue;
444 		}
445 		printf("Key with descriptor [%s] applied to %s.\n",
446 		       salt->key_ref_str, argv[x]);
447 	}
448 }
449 
pbkdf2_sha512(const char * passphrase,struct salt * salt,unsigned int count,unsigned char derived_key[F2FS_MAX_KEY_SIZE])450 static void pbkdf2_sha512(const char *passphrase, struct salt *salt,
451 			  unsigned int count,
452 			  unsigned char derived_key[F2FS_MAX_KEY_SIZE])
453 {
454 	size_t passphrase_size = strlen(passphrase);
455 	unsigned char buf[SHA512_LENGTH + F2FS_MAX_PASSPHRASE_SIZE] = {0};
456 	unsigned char tempbuf[SHA512_LENGTH] = {0};
457 	char final[SHA512_LENGTH] = {0};
458 	unsigned char saltbuf[F2FS_MAX_SALT_SIZE + F2FS_MAX_PASSPHRASE_SIZE] = {0};
459 	int actual_buf_len = SHA512_LENGTH + passphrase_size;
460 	int actual_saltbuf_len = F2FS_MAX_SALT_SIZE + passphrase_size;
461 	unsigned int x, y;
462 	__u32 *final_u32 = (__u32 *)final;
463 	__u32 *temp_u32 = (__u32 *)tempbuf;
464 
465 	if (passphrase_size > F2FS_MAX_PASSPHRASE_SIZE) {
466 		printf("Passphrase size is %zd; max is %d.\n", passphrase_size,
467 		       F2FS_MAX_PASSPHRASE_SIZE);
468 		exit(1);
469 	}
470 	if (salt->salt_len > F2FS_MAX_SALT_SIZE) {
471 		printf("Salt size is %zd; max is %d.\n", salt->salt_len,
472 		       F2FS_MAX_SALT_SIZE);
473 		exit(1);
474 	}
475 	assert(F2FS_MAX_KEY_SIZE <= SHA512_LENGTH);
476 
477 	memcpy(saltbuf, salt->salt, salt->salt_len);
478 	memcpy(&saltbuf[F2FS_MAX_SALT_SIZE], passphrase, passphrase_size);
479 
480 	memcpy(&buf[SHA512_LENGTH], passphrase, passphrase_size);
481 
482 	for (x = 0; x < count; ++x) {
483 		if (x == 0) {
484 			f2fs_sha512(saltbuf, actual_saltbuf_len, tempbuf);
485 		} else {
486 			/*
487 			 * buf: [previous hash || passphrase]
488 			 */
489 			memcpy(buf, tempbuf, SHA512_LENGTH);
490 			f2fs_sha512(buf, actual_buf_len, tempbuf);
491 		}
492 		for (y = 0; y < (sizeof(final) / sizeof(*final_u32)); ++y)
493 			final_u32[y] = final_u32[y] ^ temp_u32[y];
494 	}
495 	memcpy(derived_key, final, F2FS_MAX_KEY_SIZE);
496 }
497 
disable_echo(struct termios * saved_settings)498 static int disable_echo(struct termios *saved_settings)
499 {
500 	struct termios current_settings;
501 	int rc = 0;
502 
503 	rc = tcgetattr(0, &current_settings);
504 	if (rc)
505 		return rc;
506 	*saved_settings = current_settings;
507 	current_settings.c_lflag &= ~ECHO;
508 	rc = tcsetattr(0, TCSANOW, &current_settings);
509 
510 	return rc;
511 }
512 
get_passphrase(char * passphrase,int len)513 static void get_passphrase(char *passphrase, int len)
514 {
515 	char *p;
516 	struct termios current_settings;
517 
518 	assert(len > 0);
519 	disable_echo(&current_settings);
520 	p = fgets(passphrase, len, stdin);
521 	tcsetattr(0, TCSANOW, &current_settings);
522 	printf("\n");
523 	if (!p) {
524 		printf("Aborting.\n");
525 		exit(1);
526 	}
527 	p = strrchr(passphrase, '\n');
528 	if (!p)
529 		p = passphrase + len - 1;
530 	*p = '\0';
531 }
532 
533 struct keyring_map {
534 	char name[4];
535 	size_t name_len;
536 	int code;
537 };
538 
539 static const struct keyring_map keyrings[] = {
540 	{"@us", 3, KEY_SPEC_USER_SESSION_KEYRING},
541 	{"@u", 2, KEY_SPEC_USER_KEYRING},
542 	{"@s", 2, KEY_SPEC_SESSION_KEYRING},
543 	{"@g", 2, KEY_SPEC_GROUP_KEYRING},
544 	{"@p", 2, KEY_SPEC_PROCESS_KEYRING},
545 	{"@t", 2, KEY_SPEC_THREAD_KEYRING},
546 };
547 
get_keyring_id(const char * keyring)548 static int get_keyring_id(const char *keyring)
549 {
550 	unsigned int x;
551 	char *end;
552 
553 	/*
554 	 * If no keyring is specified, by default use either the user
555 	 * session key ring or the session keyring.  Fetching the
556 	 * session keyring will return the user session keyring if no
557 	 * session keyring has been set.
558 	 *
559 	 * We need to do this instead of simply adding the key to
560 	 * KEY_SPEC_SESSION_KEYRING since trying to add a key to a
561 	 * session keyring that does not yet exist will cause the
562 	 * kernel to create a session keyring --- which wil then get
563 	 * garbage collected as soon as f2fscrypt exits.
564 	 *
565 	 * The fact that the keyctl system call and the add_key system
566 	 * call treats KEY_SPEC_SESSION_KEYRING differently when a
567 	 * session keyring does not exist is very unfortunate and
568 	 * confusing, but so it goes...
569 	 */
570 	if (keyring == NULL)
571 		return keyctl(KEYCTL_GET_KEYRING_ID,
572 			      KEY_SPEC_SESSION_KEYRING, 0);
573 	for (x = 0; x < (sizeof(keyrings) / sizeof(keyrings[0])); ++x) {
574 		if (strcmp(keyring, keyrings[x].name) == 0) {
575 			return keyrings[x].code;
576 		}
577 	}
578 	x = strtoul(keyring, &end, 10);
579 	if (*end == '\0') {
580 		if (keyctl(KEYCTL_DESCRIBE, x, NULL, 0) < 0)
581 			return 0;
582 		return x;
583 	}
584 	return 0;
585 }
586 
generate_key_ref_str(struct salt * salt)587 static void generate_key_ref_str(struct salt *salt)
588 {
589 	unsigned char key_ref1[SHA512_LENGTH];
590 	unsigned char key_ref2[SHA512_LENGTH];
591 	int x;
592 
593 	f2fs_sha512(salt->key, F2FS_MAX_KEY_SIZE, key_ref1);
594 	f2fs_sha512(key_ref1, SHA512_LENGTH, key_ref2);
595 	memcpy(salt->key_desc, key_ref2, F2FS_KEY_DESCRIPTOR_SIZE);
596 	for (x = 0; x < F2FS_KEY_DESCRIPTOR_SIZE; ++x) {
597 		sprintf(&salt->key_ref_str[x * 2], "%02x",
598 			salt->key_desc[x]);
599 	}
600 	salt->key_ref_str[F2FS_KEY_REF_STR_BUF_SIZE - 1] = '\0';
601 }
602 
insert_key_into_keyring(const char * keyring,struct salt * salt)603 static void insert_key_into_keyring(const char *keyring, struct salt *salt)
604 {
605 	int keyring_id = get_keyring_id(keyring);
606 	struct f2fs_encryption_key key;
607 	char key_ref_full[F2FS_KEY_DESC_PREFIX_SIZE +
608 			  F2FS_KEY_REF_STR_BUF_SIZE];
609 	int rc;
610 
611 	if (keyring_id == 0) {
612 		printf("Invalid keyring [%s].\n", keyring);
613 		exit(1);
614 	}
615 	sprintf(key_ref_full, "%s%s", F2FS_KEY_DESC_PREFIX,
616 		salt->key_ref_str);
617 	rc = keyctl(KEYCTL_SEARCH, keyring_id, F2FS_KEY_TYPE_LOGON,
618 		    key_ref_full, 0);
619 	if (rc != -1) {
620 		if ((options & OPT_QUIET) == 0)
621 			printf("Key with descriptor [%s] already exists\n",
622 			       salt->key_ref_str);
623 		return;
624 	} else if ((rc == -1) && (errno != ENOKEY)) {
625 		printf("keyctl_search failed: %s\n", strerror(errno));
626 		if (errno == -EINVAL)
627 			printf("Keyring [%s] is not available.\n", keyring);
628 		exit(1);
629 	}
630 	key.mode = F2FS_ENCRYPTION_MODE_AES_256_XTS;
631 	memcpy(key.raw, salt->key, F2FS_MAX_KEY_SIZE);
632 	key.size = F2FS_MAX_KEY_SIZE;
633 	rc = add_key(F2FS_KEY_TYPE_LOGON, key_ref_full, (void *)&key,
634 		     sizeof(key), keyring_id);
635 	if (rc == -1) {
636 		if (errno == EDQUOT) {
637 			printf("Error adding key to keyring; quota exceeded\n");
638 		} else {
639 			printf("Error adding key with key descriptor [%s]: "
640 			       "%s\n", salt->key_ref_str, strerror(errno));
641 		}
642 		exit(1);
643 	} else {
644 		if ((options & OPT_QUIET) == 0)
645 			printf("Added key with descriptor [%s]\n",
646 			       salt->key_ref_str);
647 	}
648 }
649 
get_default_salts(void)650 static void get_default_salts(void)
651 {
652 	FILE	*f = setmntent("/etc/mtab", "r");
653 	struct mntent *mnt;
654 
655 	while (f && ((mnt = getmntent(f)) != NULL)) {
656 		if (strcmp(mnt->mnt_type, "f2fs") ||
657 		    access(mnt->mnt_dir, R_OK))
658 			continue;
659 		parse_salt(mnt->mnt_dir, PARSE_FLAGS_NOTSUPP_OK);
660 	}
661 	endmntent(f);
662 }
663 
664 /* Functions which implement user commands */
665 
666 struct cmd_desc {
667 	const char *cmd_name;
668 	void (*cmd_func)(int, char **, const struct cmd_desc *);
669 	const char *cmd_desc;
670 	const char *cmd_help;
671 	int cmd_flags;
672 };
673 
674 #define CMD_HIDDEN 	0x0001
675 
676 static void do_help(int argc, char **argv, const struct cmd_desc *cmd);
677 
678 #define add_key_desc "adds a key to the user's keyring"
679 #define add_key_help \
680 "f2fscrypt add_key -S salt [ -k keyring ] [-v] [-q] [ path ... ]\n\n" \
681 "Prompts the user for a passphrase and inserts it into the specified\n" \
682 "keyring.  If no keyring is specified, f2fscrypt will use the session\n" \
683 "keyring if it exists or the user session keyring if it does not.\n\n" \
684 "If one or more directory paths are specified, f2fscrypt will try to\n" \
685 "set the policy of those directories to use the key just entered by\n" \
686 "the user.\n"
687 
do_add_key(int argc,char ** argv,const struct cmd_desc * cmd)688 static void do_add_key(int argc, char **argv, const struct cmd_desc *cmd)
689 {
690 	struct salt *salt;
691 	char *keyring = NULL;
692 	int i, opt, pad = 4;
693 	unsigned j;
694 
695 	while ((opt = getopt(argc, argv, "k:S:p:vq")) != -1) {
696 		switch (opt) {
697 		case 'k':
698 			/* Specify a keyring. */
699 			keyring = optarg;
700 			break;
701 		case 'p':
702 			pad = atoi(optarg);
703 			break;
704 		case 'S':
705 			/* Salt value for passphrase. */
706 			parse_salt(optarg, 0);
707 			break;
708 		case 'v':
709 			options |= OPT_VERBOSE;
710 			break;
711 		case 'q':
712 			options |= OPT_QUIET;
713 			break;
714 		default:
715 			fprintf(stderr, "Unrecognized option: %c\n", opt);
716 		case '?':
717 			fputs("USAGE:\n  ", stderr);
718 			fputs(cmd->cmd_help, stderr);
719 			exit(1);
720 		}
721 	}
722 	if (num_salt == 0)
723 		get_default_salts();
724 	if (num_salt == 0) {
725 		fprintf(stderr, "No salt values available\n");
726 		exit(1);
727 	}
728 	validate_paths(argc, argv, optind);
729 	for (i = optind; i < argc; i++)
730 		parse_salt(argv[i], PARSE_FLAGS_FORCE_FN);
731 	printf("Enter passphrase (echo disabled): ");
732 	get_passphrase(in_passphrase, sizeof(in_passphrase));
733 	for (j = 0, salt = salt_list; j < num_salt; j++, salt++) {
734 		pbkdf2_sha512(in_passphrase, salt,
735 			      F2FS_PBKDF2_ITERATIONS, salt->key);
736 		generate_key_ref_str(salt);
737 		insert_key_into_keyring(keyring, salt);
738 	}
739 	if (optind != argc)
740 		set_policy(NULL, pad, argc, argv, optind);
741 	clear_secrets();
742 	exit(0);
743 }
744 
745 #define set_policy_desc "sets a policy for directories"
746 #define set_policy_help \
747 "f2fscrypt set_policy policy path ... \n\n" \
748 "Sets the policy for the directories specified on the command line.\n" \
749 "All directories must be empty to set the policy; if the directory\n" \
750 "already has a policy established, f2fscrypt will validate that it the\n" \
751 "policy matches what was specified.  A policy is an encryption key\n" \
752 "identifier consisting of 16 hexadecimal characters.\n"
753 
do_set_policy(int argc,char ** argv,const struct cmd_desc * cmd)754 static void do_set_policy(int argc, char **argv, const struct cmd_desc *cmd)
755 {
756 	struct salt saltbuf;
757 	int c, pad = 4;
758 
759 	while ((c = getopt (argc, argv, "p:")) != EOF) {
760 		switch (c) {
761 		case 'p':
762 			pad = atoi(optarg);
763 			break;
764 		}
765 	}
766 
767 	if (argc < optind + 2) {
768 		fprintf(stderr, "Missing required argument(s).\n\n");
769 		fputs("USAGE:\n  ", stderr);
770 		fputs(cmd->cmd_help, stderr);
771 		exit(1);
772 	}
773 
774 	if ((strlen(argv[optind]) != (F2FS_KEY_DESCRIPTOR_SIZE * 2)) ||
775 	    hex2byte(argv[optind], (F2FS_KEY_DESCRIPTOR_SIZE * 2),
776 		     saltbuf.key_desc, F2FS_KEY_DESCRIPTOR_SIZE)) {
777 		printf("Invalid key descriptor [%s]. Valid characters "
778 		       "are 0-9 and a-f, lower case.  "
779 		       "Length must be %d.\n",
780 		       argv[optind], (F2FS_KEY_DESCRIPTOR_SIZE * 2));
781 			exit(1);
782 	}
783 	validate_paths(argc, argv, optind+1);
784 	strcpy(saltbuf.key_ref_str, argv[optind]);
785 	set_policy(&saltbuf, pad, argc, argv, optind+1);
786 	exit(0);
787 }
788 
789 #define get_policy_desc "get the encryption for directories"
790 #define get_policy_help \
791 "f2fscrypt get_policy path ... \n\n" \
792 "Gets the policy for the directories specified on the command line.\n"
793 
do_get_policy(int argc,char ** argv,const struct cmd_desc * cmd)794 static void do_get_policy(int argc, char **argv, const struct cmd_desc *cmd)
795 {
796 	struct f2fs_fscrypt_policy policy;
797 	struct stat st;
798 	int i, j, fd, rc;
799 
800 	if (argc < 2) {
801 		fprintf(stderr, "Missing required argument(s).\n\n");
802 		fputs("USAGE:\n  ", stderr);
803 		fputs(cmd->cmd_help, stderr);
804 		exit(1);
805 	}
806 
807 	for (i = 1; i < argc; i++) {
808 		if (stat(argv[i], &st) < 0) {
809 			perror(argv[i]);
810 			continue;
811 		}
812 		fd = open(argv[i],
813 			  S_ISDIR(st.st_mode) ? O_DIRECTORY : O_RDONLY);
814 		if (fd == -1) {
815 			perror(argv[i]);
816 			exit(1);
817 		}
818 		rc = ioctl(fd, F2FS_IOC_GET_ENCRYPTION_POLICY, &policy);
819 		close(fd);
820 		if (rc) {
821 			printf("Error getting policy for %s: %s\n",
822 			       argv[i], strerror(errno));
823 			continue;
824 		}
825 		printf("%s: ", argv[i]);
826 		for (j = 0; j < F2FS_KEY_DESCRIPTOR_SIZE; j++) {
827 			printf("%02x", (unsigned char) policy.master_key_descriptor[j]);
828 		}
829 		fputc('\n', stdout);
830 	}
831 	exit(0);
832 }
833 
834 #define new_session_desc "give the invoking process a new session keyring"
835 #define new_session_help \
836 "f2fscrypt new_session\n\n" \
837 "Give the invoking process (typically a shell) a new session keyring,\n" \
838 "discarding its old session keyring.\n"
839 
do_new_session(int argc,char ** argv,const struct cmd_desc * cmd)840 static void do_new_session(int argc, char **argv, const struct cmd_desc *cmd)
841 {
842 	long keyid, ret;
843 
844 	if (argc > 1) {
845 		fputs("Excess arguments\n\n", stderr);
846 		fputs(cmd->cmd_help, stderr);
847 		exit(1);
848 	}
849 	keyid = keyctl(KEYCTL_JOIN_SESSION_KEYRING, NULL);
850 	if (keyid < 0) {
851 		perror("KEYCTL_JOIN_SESSION_KEYRING");
852 		exit(1);
853 	}
854 	ret = keyctl(KEYCTL_SESSION_TO_PARENT, NULL);
855 	if (ret < 0) {
856 		perror("KEYCTL_SESSION_TO_PARENT");
857 		exit(1);
858 	}
859 	printf("Switched invoking process to new session keyring %ld\n", keyid);
860 	exit(0);
861 }
862 
863 #define CMD(name) { #name, do_##name, name##_desc, name##_help, 0 }
864 #define _CMD(name) { #name, do_##name, NULL, NULL, CMD_HIDDEN }
865 
866 const struct cmd_desc cmd_list[] = {
867 	_CMD(help),
868 	CMD(add_key),
869 	CMD(get_policy),
870 	CMD(new_session),
871 	CMD(set_policy),
872 	{ NULL, NULL, NULL, NULL, 0 }
873 };
874 
do_help(int argc,char ** argv,const struct cmd_desc * cmd)875 static void do_help(int argc, char **argv, const struct cmd_desc *cmd)
876 {
877 	const struct cmd_desc *p;
878 
879 	if (argc > 1) {
880 		for (p = cmd_list; p->cmd_name; p++) {
881 			if (p->cmd_flags & CMD_HIDDEN)
882 				continue;
883 			if (strcmp(p->cmd_name, argv[1]) == 0) {
884 				putc('\n', stdout);
885 				fputs("USAGE:\n  ", stdout);
886 				fputs(p->cmd_help, stdout);
887 				exit(0);
888 			}
889 		}
890 		printf("Unknown command: %s\n\n", argv[1]);
891 	}
892 
893 	fputs("Available commands:\n", stdout);
894 	for (p = cmd_list; p->cmd_name; p++) {
895 		if (p->cmd_flags & CMD_HIDDEN)
896 			continue;
897 		printf("  %-20s %s\n", p->cmd_name, p->cmd_desc);
898 	}
899 	printf("\nTo get more information on a command, "
900 	       "type 'f2fscrypt help cmd'\n");
901 	exit(0);
902 }
903 
main(int argc,char * argv[])904 int main(int argc, char *argv[])
905 {
906 	const struct cmd_desc *cmd;
907 
908 	if (argc < 2)
909 		do_help(argc, argv, cmd_list);
910 
911 	sigcatcher_setup();
912 	for (cmd = cmd_list; cmd->cmd_name; cmd++) {
913 		if (strcmp(cmd->cmd_name, argv[1]) == 0) {
914 			cmd->cmd_func(argc-1, argv+1, cmd);
915 			exit(0);
916 		}
917 	}
918 	printf("Unknown command: %s\n\n", argv[1]);
919 	do_help(1, argv, cmd_list);
920 	return 0;
921 }
922