git » kxd » commit e22818f

Restrict file permissions when creating keys

author Alberto Bertogli
2026-11-29 00:45:13 UTC
committer Alberto Bertogli
2026-11-29 00:49:38 UTC
parent cfbfe7f6020d68dccbd289a45e0df6f2db93a745

Restrict file permissions when creating keys

kxd-add-client-key generated the keys with the default umask; on some
systems, the files could have ended up being world-readable on the
server. Similarly, kxgencert created private keys using the default
permissions and the scripts chmod them afterwards, which is a bit
brittle.

This patch makes kxd-add-client-key use a restrictive umask, and
kxgencert create the private key file with 0600 permissions. kxgencert
also refuses to overwrite an existing key file now, and writes the key
before the certificate, so that if it fails, it doesn't leave a
certificate that doesn't match the key.

Note existing keys are not affected.

kxgencert/kxgencert.go +20 -16
scripts/kxd-add-client-key +4 -0
tests/run_tests +50 -0

diff --git a/kxgencert/kxgencert.go b/kxgencert/kxgencert.go
index 72ee06e..7af7aa7 100644
--- a/kxgencert/kxgencert.go
+++ b/kxgencert/kxgencert.go
@@ -73,25 +73,19 @@ func main() {
 		fatalf("Error generating key: %v\n", err)
 	}
 
-	// Write the certificate.
-	{
-		derBytes, err := x509.CreateCertificate(
-			crand.Reader, &tmpl, &tmpl, &privK.PublicKey, privK)
-		if err != nil {
-			fatalf("Failed to create certificate: %v\n", err)
-		}
-
-		fullchain, err := os.Create(*certPath)
-		if err != nil {
-			fatalf("Failed to open %q: %v\n", *certPath, err)
-		}
-		pem.Encode(fullchain, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
-		fullchain.Close()
+	derBytes, err := x509.CreateCertificate(
+		crand.Reader, &tmpl, &tmpl, &privK.PublicKey, privK)
+	if err != nil {
+		fatalf("Failed to create certificate: %v\n", err)
 	}
 
-	// Write the private key.
+	// Write the private key. Do it before the certificate, so if the key
+	// already exists, we fail without overwriting the certificate.
+	// Only the owner can read it, and we refuse to overwrite an existing
+	// file (which could be an existing key, or a symlink).
 	{
-		privkey, err := os.Create(*keyPath)
+		privkey, err := os.OpenFile(*keyPath,
+			os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
 		if err != nil {
 			fatalf("failed to open %q: %v\n", *keyPath, err)
 		}
@@ -100,4 +94,14 @@ func main() {
 		pem.Encode(privkey, block)
 		privkey.Close()
 	}
+
+	// Write the certificate.
+	{
+		fullchain, err := os.Create(*certPath)
+		if err != nil {
+			fatalf("Failed to open %q: %v\n", *certPath, err)
+		}
+		pem.Encode(fullchain, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
+		fullchain.Close()
+	}
 }
diff --git a/scripts/kxd-add-client-key b/scripts/kxd-add-client-key
index dbeb958..d02838a 100755
--- a/scripts/kxd-add-client-key
+++ b/scripts/kxd-add-client-key
@@ -2,6 +2,10 @@
 
 set -e
 
+# Everything we create here (in particular the key) must only be readable by
+# kxd.
+umask 077
+
 CLIENT="$1"
 KEYNAME="$2"
 
diff --git a/tests/run_tests b/tests/run_tests
index cdd59e6..c77a4a7 100755
--- a/tests/run_tests
+++ b/tests/run_tests
@@ -602,6 +602,56 @@ class Multiples(TestCase):
         self.assertEqual(key, server2.keys["k1"])
 
 
+class Kxgencert(unittest.TestCase):
+    """Tests for kxgencert."""
+
+    def setUp(self):
+        self.path = tempfile.mkdtemp(prefix="kxgencert-", dir=TEMPDIR)
+        self.key = self.path + "/key.pem"
+        self.cert = self.path + "/cert.pem"
+
+    def kxgencert(self):
+        cmd = [BINS + "/kxgencert", "-key=" + self.key, "-cert=" + self.cert]
+        return subprocess.run(
+            cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False
+        )
+
+    def test_key_permissions(self):
+        """The private key is only readable by the owner."""
+        # Use a permissive umask, to make sure it's not what protects it.
+        old_umask = os.umask(0o022)
+        try:
+            result = self.kxgencert()
+        finally:
+            os.umask(old_umask)
+        self.assertEqual(result.returncode, 0, result.stdout)
+
+        self.assertEqual(os.stat(self.key).st_mode & 0o777, 0o600)
+        self.assertEqual(os.stat(self.cert).st_mode & 0o777, 0o644)
+
+    def test_existing_key(self):
+        """Existing keys (and their certs) are not overwritten."""
+        self.assertEqual(self.kxgencert().returncode, 0)
+        key, cert = read_all(self.key), read_all(self.cert)
+
+        result = self.kxgencert()
+        self.assertNotEqual(result.returncode, 0)
+        self.assertIn(b"file exists", result.stdout)
+        self.assertEqual(read_all(self.key), key)
+        self.assertEqual(read_all(self.cert), cert)
+
+    def test_key_is_symlink(self):
+        """Don't write the key through a symlink."""
+        target = self.path + "/target"
+        os.symlink(target, self.key)
+
+        result = self.kxgencert()
+        self.assertNotEqual(result.returncode, 0)
+        self.assertIn(b"file exists", result.stdout)
+        self.assertFalse(os.path.exists(target))
+        self.assertFalse(os.path.exists(self.cert))
+
+
 class TrickyRequests(TestCase):
     """Tests for tricky requests."""