Skip to content

Commit

Permalink
grpc: make the mTLS private keys user-readable only
Browse files Browse the repository at this point in the history
Fixes ElementsProject#6064
Reported-by: denis2342 <@denis2342>

Changelog-Changed: grpc: The mTLS private keys are no longer group-readable
  • Loading branch information
cdecker authored and ddustin committed Apr 11, 2023
1 parent a80fa8c commit 895dda6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
15 changes: 14 additions & 1 deletion plugins/grpc-plugin/src/tls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ fn generate_or_load_identity(
filename: &str,
parent: Option<&Identity>,
) -> Result<Identity> {
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
// Just our naming convention here.
let cert_path = directory.join(format!("{}.pem", filename));
let key_path = directory.join(format!("{}-key.pem", filename));
Expand All @@ -70,7 +72,18 @@ fn generate_or_load_identity(
&key_path
);
let keypair = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
std::fs::write(&key_path, keypair.serialize_pem())?;

// Create the file, but make it user-readable only:
let mut file = std::fs::File::create(&key_path)?;
let mut perms = std::fs::metadata(&key_path)?.permissions();
perms.set_mode(0o600);
std::fs::set_permissions(&key_path, perms)?;

// Only after changing the permissions we can write the
// private key
file.write_all(keypair.serialize_pem().as_bytes())?;
drop(file);

debug!(
"Generating a new certificate for key {:?} at {:?}",
&key_path, &cert_path
Expand Down
5 changes: 5 additions & 0 deletions tests/test_cln_rs.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,11 @@ def test_grpc_generate_certificate(node_factory):
assert contents[-2] != files[-2].open().read()
assert contents[-1] != files[-1].open().read()

keys = [f for f in files if f.name.endswith('-key.pem')]
modes = [f.stat().st_mode for f in keys]
private = [m % 8 == 0 and (m // 8) % 8 == 0 for m in modes]
assert all(private)


def test_grpc_no_auto_start(node_factory):
"""Ensure that we do not start cln-grpc unless a port is configured.
Expand Down

0 comments on commit 895dda6

Please sign in to comment.