]> git.sesse.net Git - bcachefs-tools-debian/blob - bcache-key.c
53dbe37d011c34b78348cd540c7818e533204163
[bcachefs-tools-debian] / bcache-key.c
1 #include <errno.h>
2 #include <unistd.h>
3 #include <keyutils.h>
4 #include <uuid/uuid.h>
5 #include <nih/command.h>
6 #include <nih/option.h>
7
8 #include "bcache.h"
9 #include "libbcache.h"
10 #include "crypto.h"
11
12 NihOption opts_unlock[] = {
13         NIH_OPTION_LAST
14 };
15
16 int cmd_unlock(NihCommand *command, char * const *args)
17 {
18         struct bcache_disk_key disk_key;
19         struct bcache_key key;
20         struct cache_sb sb;
21         char *passphrase;
22         char uuid[40];
23         char description[60];
24
25         if (!args[0] || args[1])
26                 die("please supply a single device");
27
28         bcache_super_read(args[0], &sb);
29
30         if (!CACHE_SET_ENCRYPTION_KEY(&sb))
31                 die("filesystem is not encrypted");
32
33         memcpy(&disk_key, sb.encryption_key, sizeof(disk_key));
34
35         if (!memcmp(&disk_key, bch_key_header, sizeof(bch_key_header)))
36                 die("filesystem does not have encryption key");
37
38         passphrase = read_passphrase("Enter passphrase: ");
39
40         derive_passphrase(&key, passphrase);
41         disk_key_encrypt(&disk_key, &key);
42
43         if (memcmp(&disk_key, bch_key_header, sizeof(bch_key_header)))
44                 die("incorrect passphrase");
45
46         uuid_unparse_lower(sb.user_uuid.b, uuid);
47         sprintf(description, "bcache:%s", uuid);
48
49         if (add_key("logon", description, &key, sizeof(key),
50                     KEY_SPEC_USER_KEYRING) < 0)
51                 die("add_key error: %s", strerror(errno));
52
53         memzero_explicit(&disk_key, sizeof(disk_key));
54         memzero_explicit(&key, sizeof(key));
55         memzero_explicit(passphrase, strlen(passphrase));
56         free(passphrase);
57         return 0;
58 }