git » kxd » commit b5069a4

kxd: Quote client-controlled values when logging

author Alberto Bertogli
2026-11-29 00:07:45 UTC
committer Alberto Bertogli
2026-11-29 00:07:45 UTC
parent 018477062c0d53933fd0a41388218021d9475178

kxd: Quote client-controlled values when logging

When logging values coming from clients, such as URL path or client
certificate information, they should be quoted or escaped.

This patch fixes some of the places where they weren't.

kxd/kxd.go +11 -4
kxd/kxd_test.go +40 -0
tests/run_tests +29 -0

diff --git a/kxd/kxd.go b/kxd/kxd.go
index a2f9a7b..e6c3e6d 100644
--- a/kxd/kxd.go
+++ b/kxd/kxd.go
@@ -62,9 +62,13 @@ type Request struct {
 
 // Printf is a wrapper for fmt.Printf+logging.Output, which prefixes a string
 // identifying this request.
+//
+// Values that can come from the client (paths, certificate fields, errors
+// that contain them, etc.) must be logged quoted (e.g. with %q), so they
+// can't inject or forge log lines.
 func (req *Request) Printf(format string, a ...any) {
 	msg := fmt.Sprintf(format, a...)
-	msg = fmt.Sprintf("%s %s %s", req.RemoteAddr, req.URL.Path, msg)
+	msg = fmt.Sprintf("%s %q %s", req.RemoteAddr, req.URL.Path, msg)
 	logging.Output(2, msg)
 }
 
@@ -97,11 +101,13 @@ func (req *Request) KeyPath() (string, error) {
 	return kp, nil
 }
 
+// certToString makes a human-readable string identifying the certificate.
+// The subject is quoted, since it can come from an untrusted client.
 func certToString(cert *x509.Certificate) string {
 	return fmt.Sprintf(
-		"(0x%.8s %s)",
+		"(0x%.8s %q)",
 		fmt.Sprintf("%x", cert.Signature),
-		cert.Subject.ToRDNSequence())
+		cert.Subject.String())
 }
 
 // ChainToString makes a human-readable string out of the given certificate
@@ -138,7 +144,8 @@ func HandlerV1(w http.ResponseWriter, httpreq *http.Request) {
 
 	exists, err := keyConf.Exists()
 	if err != nil {
-		req.Printf("Error checking key path %q: %s", keyPath, err)
+		// The error contains the path, so it needs quoting.
+		req.Printf("Error checking key path %q: %q", keyPath, err)
 		http.Error(w, "Error checking key",
 			http.StatusInternalServerError)
 		return
diff --git a/kxd/kxd_test.go b/kxd/kxd_test.go
index c7d8478..e41e294 100644
--- a/kxd/kxd_test.go
+++ b/kxd/kxd_test.go
@@ -1,12 +1,14 @@
 package main
 
 import (
+	"bytes"
 	"crypto/tls"
 	"errors"
 	"log"
 	"net/http"
 	"net/http/httptest"
 	"net/url"
+	"strings"
 	"testing"
 )
 
@@ -67,3 +69,41 @@ func TestHandlerWithoutCert(t *testing.T) {
 			req, w.Code, http.StatusNotAcceptable)
 	}
 }
+
+func TestRequestPrintf(t *testing.T) {
+	var logBuf bytes.Buffer
+	origLogging := logging
+	t.Cleanup(func() { logging = origLogging })
+	logging = log.New(&logBuf, "", 0)
+
+	cases := []struct {
+		path, msg, want string
+	}{
+		{"/v1/key", "hello", `1.2.3.4:5 "/v1/key" hello` + "\n"},
+		{"/v1/x\nFAKE LOG LINE", "hello",
+			`1.2.3.4:5 "/v1/x\nFAKE LOG LINE" hello` + "\n"},
+	}
+	for _, c := range cases {
+		logBuf.Reset()
+		req := Request{&http.Request{
+			RemoteAddr: "1.2.3.4:5",
+			URL:        &url.URL{Path: c.path},
+		}}
+		req.Printf("%s", c.msg)
+		if got := logBuf.String(); got != c.want {
+			t.Errorf("Printf(%q) on %q logged %q, want %q",
+				c.msg, c.path, got, c.want)
+		}
+	}
+}
+
+func TestCertToString(t *testing.T) {
+	cert, _ := newCert(t, "evil\nINJECTED LOG LINE", false, nil, nil)
+	s := certToString(cert)
+	if strings.ContainsAny(s, "\r\n") {
+		t.Errorf("certToString contains a newline: %q", s)
+	}
+	if !strings.Contains(s, `"O=evil\nINJECTED LOG LINE"`) {
+		t.Errorf("certToString does not contain quoted subject: %q", s)
+	}
+}
diff --git a/tests/run_tests b/tests/run_tests
index 24603ed..8b47eb5 100755
--- a/tests/run_tests
+++ b/tests/run_tests
@@ -629,6 +629,35 @@ class TrickyRequests(TestCase):
         conn.close()
         self.assertEqual(response.status, 406)
 
+    def test_log_injection(self):
+        """Paths with newlines must not inject lines in the log."""
+        self.server.new_key("k1", allowed_clients=[self.client.cert()])
+
+        def get(path):
+            conn = self.https_connection(
+                "localhost",
+                19840,
+                key_file=self.client.key_path(),
+                cert_file=self.client.cert_path(),
+            )
+            conn.request("GET", path)
+            response = conn.getresponse()
+            conn.close()
+            return response.status
+
+        # Unknown key.
+        self.assertEqual(get("/v1/x%0aFAKE%20LOG%20LINE"), 404)
+
+        # Path under the key file, so checking it fails with "not a
+        # directory", and the error (which contains the path) is logged.
+        self.assertEqual(get("/v1/k1/key/x%0aFAKE%20LOG%20LINE"), 500)
+
+        log = read_all(self.server.path + "/log")
+        self.assertIn(r'"/v1/x\nFAKE LOG LINE"', log)
+        self.assertIn(r'"/v1/k1/key/x\nFAKE LOG LINE"', log)
+        for line in log.splitlines():
+            self.assertFalse(line.startswith("FAKE"), line)
+
     def test_extra_cert_in_chain(self):
         """Allowed cert sent after the leaf, without its private key."""
         self.server.new_key(