6 #include "libbcachefs/checksum.h"
8 #include "libbcachefs.h"
10 static void unlock_usage(void)
12 puts("bcachefs unlock - unlock an encrypted filesystem so it can be mounted\n"
13 "Usage: bcachefs unlock [OPTION] device\n"
16 " -c Check if a device is encrypted\n"
17 " -k (session|user|user_session)\n"
18 " Keyring to add to (default: user)\n"
19 " -h Display this help and exit\n"
20 "Report bugs to <linux-bcachefs@vger.kernel.org>");
23 int cmd_unlock(int argc, char *argv[])
25 const char *keyring = "user";
29 while ((opt = getopt(argc, argv, "ck:h")) != -1)
35 keyring = strdup(optarg);
43 char *dev = arg_pop();
45 die("Please supply a device");
48 die("Too many arguments");
50 struct bch_opts opts = bch2_opts_empty();
52 opt_set(opts, noexcl, true);
53 opt_set(opts, nochanges, true);
55 struct bch_sb_handle sb;
56 int ret = bch2_read_super(dev, &opts, &sb);
58 die("Error opening %s: %s", dev, bch2_err_str(ret));
60 if (!bch2_sb_is_encrypted(sb.sb))
61 die("%s is not encrypted", dev);
66 char *passphrase = read_passphrase("Enter passphrase: ");
68 bch2_add_key(sb.sb, "user", keyring, passphrase);
71 memzero_explicit(passphrase, strlen(passphrase));
76 int cmd_set_passphrase(int argc, char *argv[])
78 struct bch_opts opts = bch2_opts_empty();
82 die("Please supply one or more devices");
84 opt_set(opts, nostart, true);
87 * we use bch2_fs_open() here, instead of just reading the superblock,
88 * to make sure we're opening and updating every component device:
91 c = bch2_fs_open(argv + 1, argc - 1, opts);
93 die("Error opening %s: %s", argv[1], bch2_err_str(PTR_ERR(c)));
95 struct bch_sb_field_crypt *crypt = bch2_sb_get_crypt(c->disk_sb.sb);
97 die("Filesystem does not have encryption enabled");
99 struct bch_encrypted_key new_key;
100 new_key.magic = BCH_KEY_MAGIC;
102 int ret = bch2_decrypt_sb_key(c, crypt, &new_key.key);
104 die("Error getting current key");
106 char *new_passphrase = read_passphrase_twice("Enter new passphrase: ");
107 struct bch_key passphrase_key = derive_passphrase(crypt, new_passphrase);
109 if (bch2_chacha_encrypt_key(&passphrase_key, __bch2_sb_key_nonce(c->disk_sb.sb),
110 &new_key, sizeof(new_key)))
111 die("error encrypting key");
112 crypt->key = new_key;
119 int cmd_remove_passphrase(int argc, char *argv[])
121 struct bch_opts opts = bch2_opts_empty();
125 die("Please supply one or more devices");
127 opt_set(opts, nostart, true);
128 c = bch2_fs_open(argv + 1, argc - 1, opts);
130 die("Error opening %s: %s", argv[1], bch2_err_str(PTR_ERR(c)));
132 struct bch_sb_field_crypt *crypt = bch2_sb_get_crypt(c->disk_sb.sb);
134 die("Filesystem does not have encryption enabled");
136 struct bch_encrypted_key new_key;
137 new_key.magic = BCH_KEY_MAGIC;
139 int ret = bch2_decrypt_sb_key(c, crypt, &new_key.key);
141 die("Error getting current key");
143 crypt->key = new_key;