| author | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-11-28 18:56:25 UTC |
| committer | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-11-28 21:03:38 UTC |
| parent | dfb48c334b2336ad2af6f7d235682f5e9862f98d |
| .github/workflows/tests.yaml | +1 | -1 |
| README.md | +1 | -1 |
| doc/man/kxd.1 | +1 | -1 |
| doc/man/kxd.1.pod | +1 | -1 |
| go.mod | +1 | -1 |
| kxc/kxc.go | +8 | -6 |
| kxd/email.go | +1 | -1 |
| kxd/hook.go | +6 | -5 |
| kxd/key_config.go | +18 | -18 |
| kxd/kxd.go | +8 | -3 |
| kxgencert/kxgencert.go | +2 | -3 |
| tests/run_tests | +3 | -3 |
diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 8a5a152..64f00fa 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -16,7 +16,7 @@ jobs: strategy: matrix: # Test against stable, and the oldest supported version. - go: [ 'stable', '1.21.x' ] + go: [ 'stable', '1.26.x' ] steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 diff --git a/README.md b/README.md index 7226e03..ff549cd 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ assumption that the server's host is secure and trusted. There are no runtime dependencies for the kxd and kxc binaries. -Building requires Go 1.21. +Building requires Go 1.26. The configuration helper scripts (`create-kxd-config`, `kxc-add-key`, etc.) depend on: `bash` and core utilities (`mkdir`, `dd`, etc.). diff --git a/doc/man/kxd.1 b/doc/man/kxd.1 index dcde8f2..78e73f9 100644 --- a/doc/man/kxd.1 +++ b/doc/man/kxd.1 @@ -187,7 +187,7 @@ Data directory, where the key and configuration live (see the \s-1SETUP\s0 secti above). Defaults to \fI/etc/kxd/data\fR. .IP "\fB\-\-ip_addr\fR=\fIip-address\fR" 8 .IX Item "--ip_addr=ip-address" -\&\s-1IP\s0 address to listen on. Defaults to all. +\&\s-1IP\s0 address to listen on (\s-1IP\s0v4 or \s-1IP\s0v6). Defaults to all. .IP "\fB\-\-logfile\fR=\fIfile\fR" 8 .IX Item "--logfile=file" File to write logs to, use \*(L"\-\*(R" for stdout. By default, the daemon will log to diff --git a/doc/man/kxd.1.pod b/doc/man/kxd.1.pod index 07eda6e..e7523bf 100644 --- a/doc/man/kxd.1.pod +++ b/doc/man/kxd.1.pod @@ -67,7 +67,7 @@ above). Defaults to F</etc/kxd/data>. =item B<--ip_addr>=I<ip-address> -IP address to listen on. Defaults to all. +IP address to listen on (IPv4 or IPv6). Defaults to all. =item B<--logfile>=I<file> diff --git a/go.mod b/go.mod index 2492972..3213bbd 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ module blitiri.com.ar/go/kxd -go 1.20 +go 1.26 diff --git a/kxc/kxc.go b/kxc/kxc.go index fca6532..32969da 100644 --- a/kxc/kxc.go +++ b/kxc/kxc.go @@ -10,12 +10,14 @@ import ( "crypto/tls" "crypto/x509" "encoding/pem" + "errors" "flag" "fmt" - "io/ioutil" + "io" "log" "net/http" "net/url" + "os" "slices" "strings" ) @@ -30,7 +32,7 @@ var clientKey = flag.String( "client_key", "", "File containing the client private key") func loadServerCerts() (*x509.CertPool, bool, error) { - pemData, err := ioutil.ReadFile(*serverCert) + pemData, err := os.ReadFile(*serverCert) if err != nil { return nil, false, err } @@ -40,7 +42,7 @@ func loadServerCerts() (*x509.CertPool, bool, error) { // we need to identify them at parsing time. hasWildcard := false { - data := pemData[:] + data := pemData for { var block *pem.Block block, data = pem.Decode(data) @@ -67,7 +69,7 @@ func loadServerCerts() (*x509.CertPool, bool, error) { pool := x509.NewCertPool() if !pool.AppendCertsFromPEM(pemData) { - return nil, false, fmt.Errorf("error appending certificates") + return nil, false, errors.New("error appending certificates") } return pool, hasWildcard, nil @@ -93,7 +95,7 @@ func extractURL(rawurl string) (*url.URL, error) { case "http", "kxd": serverURL.Scheme = "https" default: - return nil, fmt.Errorf("unsupported URL schema (try kxd://)") + return nil, errors.New("unsupported URL schema (try kxd://)") } // The path must begin with /v1/, although we hide that from the user @@ -187,7 +189,7 @@ func main() { log.Fatalf("Failed to get key: %s", err) } - content, err := ioutil.ReadAll(resp.Body) + content, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { log.Fatalf("Error reading key body: %s", err) diff --git a/kxd/email.go b/kxd/email.go index 529cdba..6eea8d0 100644 --- a/kxd/email.go +++ b/kxd/email.go @@ -43,7 +43,7 @@ Authorizing chains: var emailTmpl = template.New("email") func init() { - emailTmpl.Funcs(map[string]interface{}{ + emailTmpl.Funcs(map[string]any{ "ChainToString": ChainToString, }) diff --git a/kxd/hook.go b/kxd/hook.go index 94e36bc..6b072bf 100644 --- a/kxd/hook.go +++ b/kxd/hook.go @@ -3,7 +3,9 @@ package main import ( "context" "crypto/x509" + "errors" "fmt" + "io/fs" "os" "os/exec" "strings" @@ -20,13 +22,12 @@ func RunHook(kc *KeyConfig, req *Request, chains [][]*x509.Certificate) error { return nil } - if _, err := os.Stat(*hookPath); os.IsNotExist(err) { + if _, err := os.Stat(*hookPath); errors.Is(err, fs.ErrNotExist) { req.Printf("Hook not present, skipping") return nil } - ctx, cancel := context.WithDeadline(context.Background(), - time.Now().Add(1*time.Minute)) + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) defer cancel() cmd := exec.CommandContext(ctx, *hookPath) @@ -35,7 +36,7 @@ func RunHook(kc *KeyConfig, req *Request, chains [][]*x509.Certificate) error { // Prepare the environment, copying some common variables so the hook has // something reasonable, and then setting the specific ones for this case. - for _, v := range strings.Fields("USER PWD SHELL PATH") { + for v := range strings.FieldsSeq("USER PWD SHELL PATH") { cmd.Env = append(cmd.Env, v+"="+os.Getenv(v)) } @@ -64,7 +65,7 @@ func RunHook(kc *KeyConfig, req *Request, chains [][]*x509.Certificate) error { _, err = cmd.Output() if err != nil { - if ee, ok := err.(*exec.ExitError); ok { + if ee, ok := errors.AsType[*exec.ExitError](err); ok { err = fmt.Errorf("exited with error: %v -- stderr: %q", ee.String(), ee.Stderr) } diff --git a/kxd/key_config.go b/kxd/key_config.go index f086eaf..7dd9d3b 100644 --- a/kxd/key_config.go +++ b/kxd/key_config.go @@ -2,10 +2,12 @@ package main import ( "crypto/x509" + "errors" "fmt" - "io/ioutil" + "io/fs" "net" "os" + "slices" "strings" ) @@ -61,7 +63,7 @@ func NewKeyConfig(configPath string) *KeyConfig { // Exists checks if this key exists. func (kc *KeyConfig) Exists() (bool, error) { isDir, err := isDir(kc.ConfigPath) - if os.IsNotExist(err) { + if errors.Is(err, fs.ErrNotExist) { return false, nil } else if err != nil { return false, err @@ -71,7 +73,7 @@ func (kc *KeyConfig) Exists() (bool, error) { } isRegular, err := isRegular(kc.keyPath) - if os.IsNotExist(err) { + if errors.Is(err, fs.ErrNotExist) { return false, nil } else if err != nil { return false, err @@ -82,15 +84,15 @@ func (kc *KeyConfig) Exists() (bool, error) { // LoadClientCerts loads the client certificates allowed for this key. func (kc *KeyConfig) LoadClientCerts() error { - rawContents, err := ioutil.ReadFile(kc.allowedClientsPath) - if os.IsNotExist(err) { + rawContents, err := os.ReadFile(kc.allowedClientsPath) + if errors.Is(err, fs.ErrNotExist) { return nil } else if err != nil { return err } if !kc.allowedClientCerts.AppendCertsFromPEM(rawContents) { - return fmt.Errorf("error parsing client certificate file") + return errors.New("error parsing client certificate file") } return nil @@ -98,8 +100,8 @@ func (kc *KeyConfig) LoadClientCerts() error { // LoadAllowedHosts loads the hosts allowed for this key. func (kc *KeyConfig) LoadAllowedHosts() error { - contents, err := ioutil.ReadFile(kc.allowedHostsPath) - if os.IsNotExist(err) { + contents, err := os.ReadFile(kc.allowedHostsPath) + if errors.Is(err, fs.ErrNotExist) { return nil } else if err != nil { return err @@ -108,8 +110,8 @@ func (kc *KeyConfig) LoadAllowedHosts() error { // If the file is there, we want our array to exist, even if it's // empty, to avoid authorizing everyone on an empty file (which means // authorize no one). - kc.allowedHosts = make([]string, 1) - for _, line := range strings.Split(string(contents), "\n") { + kc.allowedHosts = []string{} + for line := range strings.SplitSeq(string(contents), "\n") { line = strings.TrimSpace(line) if line == "" { continue @@ -163,10 +165,8 @@ func (kc *KeyConfig) IsHostAllowed(addr string) error { return err } - for _, allowedHost := range kc.allowedHosts { - if allowedHost == host { - return nil - } + if slices.Contains(kc.allowedHosts, host) { + return nil } return fmt.Errorf("host %q not allowed", host) @@ -174,13 +174,13 @@ func (kc *KeyConfig) IsHostAllowed(addr string) error { // Key returns the private key. func (kc *KeyConfig) Key() (key []byte, err error) { - return ioutil.ReadFile(kc.keyPath) + return os.ReadFile(kc.keyPath) } // EmailTo returns the list of addresses to email when this key is accessed. func (kc *KeyConfig) EmailTo() ([]string, error) { - contents, err := ioutil.ReadFile(kc.emailToPath) - if os.IsNotExist(err) { + contents, err := os.ReadFile(kc.emailToPath) + if errors.Is(err, fs.ErrNotExist) { return nil, nil } if err != nil { @@ -188,7 +188,7 @@ func (kc *KeyConfig) EmailTo() ([]string, error) { } var emails []string - for _, line := range strings.Split(string(contents), "\n") { + for line := range strings.SplitSeq(string(contents), "\n") { email := strings.TrimSpace(line) if !strings.Contains(email, "@") { continue diff --git a/kxd/kxd.go b/kxd/kxd.go index 264963c..e234355 100644 --- a/kxd/kxd.go +++ b/kxd/kxd.go @@ -17,11 +17,13 @@ import ( "io" "log" "log/syslog" + "net" "net/http" "os" "os/signal" "path" "runtime/debug" + "strconv" "strings" "syscall" "time" @@ -60,7 +62,7 @@ type Request struct { // Printf is a wrapper for fmt.Printf+logging.Output, which prefixes a string // identifying this request. -func (req *Request) Printf(format string, a ...interface{}) { +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) logging.Output(2, msg) @@ -117,7 +119,7 @@ func ChainToString(chain []*x509.Certificate) (s string) { // HandlerV1 handles /v1/ key requests. func HandlerV1(w http.ResponseWriter, httpreq *http.Request) { req := Request{httpreq} - if len(req.TLS.PeerCertificates) <= 0 { + if len(req.TLS.PeerCertificates) == 0 { req.Printf("Rejecting request without certificate") http.Error(w, "Client certificate not provided", http.StatusNotAcceptable) @@ -288,7 +290,10 @@ func main() { strings.Split(*smtpAddr, ":")[0]) } - listenAddr := fmt.Sprintf("%s:%d", *ipAddr, *port) + // Strip brackets in case the user passed an IPv6 address like "[::1]", + // since JoinHostPort adds them as needed. + listenAddr := net.JoinHostPort( + strings.Trim(*ipAddr, "[]"), strconv.Itoa(*port)) tlsConfig := tls.Config{ ClientAuth: tls.RequireAnyClientCert, diff --git a/kxgencert/kxgencert.go b/kxgencert/kxgencert.go index b69f6c1..72ee06e 100644 --- a/kxgencert/kxgencert.go +++ b/kxgencert/kxgencert.go @@ -31,7 +31,7 @@ var ( "Where to write the generated key") ) -func fatalf(f string, a ...interface{}) { +func fatalf(f string, a ...any) { fmt.Printf(f, a...) os.Exit(1) } @@ -59,8 +59,7 @@ func main() { BasicConstraintsValid: true, } - hosts := strings.Split(*host, ",") - for _, h := range hosts { + for h := range strings.SplitSeq(*host, ",") { if ip := net.ParseIP(h); ip != nil { tmpl.IPAddresses = append(tmpl.IPAddresses, ip) } else { diff --git a/tests/run_tests b/tests/run_tests index 5b05e81..b9ed18a 100755 --- a/tests/run_tests +++ b/tests/run_tests @@ -613,9 +613,9 @@ class TrickyRequests(TestCase): response = conn.getresponse() conn.close() - # Go's http server intercepts these and gives us a 301 Moved - # Permanently. - self.assertEqual(response.status, 301) + # Go's http server intercepts these and gives us a 307 Temporary + # Redirect. + self.assertEqual(response.status, 307) def test_invalid_path(self): conn = self.https_connection(