MCPcopy Create free account
hub / github.com/ElementsProject/lightning / load_hsm

Function load_hsm

hsmd/hsmd.c:376–432  ·  view source on GitHub ↗

~ We always load the HSM file, even if we just created it above. This * both unifies the code paths, and provides a nice sanity check that the * file contents are as they will be for future invocations. */

Source from the content-addressed store, hash-verified

374 * both unifies the code paths, and provides a nice sanity check that the
375 * file contents are as they will be for future invocations. */
376static void load_hsm(const struct secret *encryption_key)
377{
378 struct stat st;
379 int fd = open("hsm_secret", O_RDONLY);
380 if (fd < 0)
381 status_failed(STATUS_FAIL_INTERNAL_ERROR,
382 "opening: %s", strerror(errno));
383 if (stat("hsm_secret", &st) != 0)
384 status_failed(STATUS_FAIL_INTERNAL_ERROR,
385 "stating: %s", strerror(errno));
386
387 /* If the seed is stored in clear. */
388 if (st.st_size == 32) {
389 if (!read_all(fd, &hsm_secret, sizeof(hsm_secret)))
390 status_failed(STATUS_FAIL_INTERNAL_ERROR,
391 "reading: %s", strerror(errno));
392 /* If an encryption key was passed with a not yet encrypted hsm_secret,
393 * remove the old one and create an encrypted one. */
394 if (encryption_key) {
395 if (close(fd) != 0)
396 status_failed(STATUS_FAIL_INTERNAL_ERROR,
397 "closing: %s", strerror(errno));
398 if (remove("hsm_secret") != 0)
399 status_failed(STATUS_FAIL_INTERNAL_ERROR,
400 "removing clear hsm_secret: %s", strerror(errno));
401 maybe_create_new_hsm(encryption_key, false);
402 fd = open("hsm_secret", O_RDONLY);
403 if (fd < 0)
404 status_failed(STATUS_FAIL_INTERNAL_ERROR,
405 "opening: %s", strerror(errno));
406 }
407 }
408 /* If an encryption key was passed and the `hsm_secret` is stored
409 * encrypted, recover the seed from the cipher. */
410 else if (st.st_size == ENCRYPTED_HSM_SECRET_LEN) {
411 struct encrypted_hsm_secret encrypted_secret;
412
413 /* hsm_control must have checked it! */
414 assert(encryption_key);
415
416 if (!read_all(fd, encrypted_secret.data, ENCRYPTED_HSM_SECRET_LEN))
417 status_failed(STATUS_FAIL_INTERNAL_ERROR,
418 "Reading encrypted hsm_secret: %s", strerror(errno));
419 if (!decrypt_hsm_secret(encryption_key, &encrypted_secret,
420 &hsm_secret)) {
421 /* Exit but don't throw a backtrace when the user made a mistake in typing
422 * its password. Instead exit and `lightningd` will be able to give
423 * an error message. */
424 exit(1);
425 }
426 }
427 else
428 status_failed(STATUS_FAIL_INTERNAL_ERROR, "Invalid hsm_secret, "
429 "no plaintext nor encrypted"
430 " seed.");
431 close(fd);
432}
433

Callers 1

init_hsmFunction · 0.85

Calls 5

read_allFunction · 0.85
maybe_create_new_hsmFunction · 0.85
decrypt_hsm_secretFunction · 0.85
statClass · 0.70
status_failedFunction · 0.50

Tested by

no test coverage detected