Test that we can encrypt and decrypt hsm_secret using hsmtool
(node_factory)
| 1310 | |
| 1311 | @unittest.skipIf(VALGRIND, "It does not play well with prompt and key derivation.") |
| 1312 | def test_hsmtool_secret_decryption(node_factory): |
| 1313 | """Test that we can encrypt and decrypt hsm_secret using hsmtool""" |
| 1314 | l1 = node_factory.get_node(start=False) # Don't start the node |
| 1315 | password = "test_password\n" |
| 1316 | hsm_path = os.path.join(l1.daemon.lightning_dir, TEST_NETWORK, "hsm_secret") |
| 1317 | |
| 1318 | # Write a known 32-byte key to hsm_secret |
| 1319 | known_secret = b'\x01' * 32 # 32 bytes of 0x01 |
| 1320 | with open(hsm_path, 'wb') as f: |
| 1321 | f.write(known_secret) |
| 1322 | |
| 1323 | # Read the hsm_secret to verify it's what we expect |
| 1324 | with open(hsm_path, 'rb') as f: |
| 1325 | content = f.read() |
| 1326 | assert content == known_secret, f"Expected {known_secret}, got {content}" |
| 1327 | assert len(content) == 32, f"Expected 32 bytes, got {len(content)}" |
| 1328 | |
| 1329 | # Encrypt it using hsmtool |
| 1330 | master_fd, slave_fd = os.openpty() |
| 1331 | hsmtool = HsmTool(node_factory.directory, "encrypt", hsm_path) |
| 1332 | hsmtool.start(stdin=slave_fd) |
| 1333 | hsmtool.wait_for_log(r"Enter hsm_secret password:") |
| 1334 | write_all(master_fd, password.encode("utf-8")) |
| 1335 | hsmtool.wait_for_log(r"Confirm hsm_secret password:") |
| 1336 | write_all(master_fd, password.encode("utf-8")) |
| 1337 | assert hsmtool.proc.wait(WAIT_TIMEOUT) == 0 |
| 1338 | hsmtool.is_in_log(r"Successfully encrypted") |
| 1339 | |
| 1340 | # Read the hsm_secret again - it should now be encrypted (73 bytes) |
| 1341 | with open(hsm_path, 'rb') as f: |
| 1342 | encrypted_content = f.read() |
| 1343 | assert len(encrypted_content) == 73, f"Expected 73 bytes after encryption, got {len(encrypted_content)}" |
| 1344 | assert encrypted_content != known_secret, "File should be encrypted and different from original" |
| 1345 | |
| 1346 | # Decrypt it using hsmtool |
| 1347 | master_fd, slave_fd = os.openpty() |
| 1348 | hsmtool = HsmTool(node_factory.directory, "decrypt", hsm_path) |
| 1349 | hsmtool.start(stdin=slave_fd) |
| 1350 | hsmtool.wait_for_log(r"Enter hsm_secret password:") |
| 1351 | write_all(master_fd, password.encode("utf-8")) |
| 1352 | assert hsmtool.proc.wait(WAIT_TIMEOUT) == 0 |
| 1353 | hsmtool.is_in_log(r"Successfully decrypted") |
| 1354 | |
| 1355 | # Read the hsm_secret again - it should now be back to the original 32 bytes |
| 1356 | with open(hsm_path, 'rb') as f: |
| 1357 | decrypted_content = f.read() |
| 1358 | assert decrypted_content == known_secret, f"Expected {known_secret}, got {decrypted_content}" |
| 1359 | assert len(decrypted_content) == 32, f"Expected 32 bytes after decryption, got {len(decrypted_content)}" |
| 1360 | |
| 1361 | |
| 1362 | @unittest.skipIf(TEST_NETWORK == 'liquid-regtest', '') |