| 168 | } |
| 169 | |
| 170 | static int decrypt_hsm(const char *hsm_secret_path) |
| 171 | { |
| 172 | int fd; |
| 173 | struct secret hsm_secret; |
| 174 | char *passwd, *err; |
| 175 | const char *dir, *backup; |
| 176 | int exit_code = 0; |
| 177 | /* This checks the file existence, too. */ |
| 178 | if (!hsm_secret_is_encrypted(hsm_secret_path)) |
| 179 | errx(ERROR_USAGE, "hsm_secret is not encrypted"); |
| 180 | printf("Enter hsm_secret password:\n"); |
| 181 | fflush(stdout); |
| 182 | passwd = read_stdin_pass_with_exit_code(&err, &exit_code); |
| 183 | if (!passwd) |
| 184 | errx(exit_code, "%s", err); |
| 185 | |
| 186 | if (sodium_init() == -1) |
| 187 | errx(ERROR_LIBSODIUM, |
| 188 | "Could not initialize libsodium. Not enough entropy ?"); |
| 189 | |
| 190 | dir = path_dirname(NULL, hsm_secret_path); |
| 191 | backup = path_join(dir, dir, "hsm_secret.backup"); |
| 192 | |
| 193 | get_encrypted_hsm_secret(&hsm_secret, hsm_secret_path, passwd); |
| 194 | /* Once the encryption key derived, we don't need it anymore. */ |
| 195 | if (passwd) |
| 196 | free(passwd); |
| 197 | |
| 198 | /* Create a backup file, "just in case". */ |
| 199 | rename(hsm_secret_path, backup); |
| 200 | fd = open(hsm_secret_path, O_CREAT|O_EXCL|O_WRONLY, 0400); |
| 201 | if (fd < 0) |
| 202 | errx(EXITCODE_ERROR_HSM_FILE, "Could not open new hsm_secret"); |
| 203 | |
| 204 | if (!write_all(fd, &hsm_secret, sizeof(hsm_secret))) { |
| 205 | unlink_noerr(hsm_secret_path); |
| 206 | close(fd); |
| 207 | rename("hsm_secret.backup", hsm_secret_path); |
| 208 | errx(EXITCODE_ERROR_HSM_FILE, |
| 209 | "Failure writing plaintext seed to hsm_secret."); |
| 210 | } |
| 211 | |
| 212 | /* Be as paranoïd as in hsmd with the file state on disk. */ |
| 213 | if (!ensure_hsm_secret_exists(fd, hsm_secret_path)) { |
| 214 | unlink_noerr(hsm_secret_path); |
| 215 | rename(backup, hsm_secret_path); |
| 216 | errx(EXITCODE_ERROR_HSM_FILE, |
| 217 | "Could not ensure hsm_secret existence."); |
| 218 | } |
| 219 | unlink_noerr(backup); |
| 220 | tal_free(dir); |
| 221 | |
| 222 | printf("Successfully decrypted hsm_secret, be careful now :-).\n"); |
| 223 | return 0; |
| 224 | } |
| 225 | |
| 226 | static int encrypt_hsm(const char *hsm_secret_path) |
| 227 | { |
no test coverage detected