From 2c908c8c58b68795ed3e0e9ccafab515cefccc42 Mon Sep 17 00:00:00 2001 From: Abdel Fane <32418586+thebenignhacker@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:37:39 -0600 Subject: [PATCH 1/4] Handshake failure error names every group the scanner cannot offer for long host names (#23) When a server rejected every handshake, the error ended with one openssl s_client command per key exchange group the scanner does not offer, and each command repeated the address. The CLI prints up to 500 bytes of a scan error, so a long address pushed the last command past that limit, and its group was named nowhere else. Measured with Go 1.26.3 against local servers: run with GODEBUG=fips140=on,tlsmlkem=0, the error for scanner-target-example.localhost on a five-digit port ended in "-groups SecP256r1MLKEM768 and openssl s_client -connect sca..." and did not name SecP384r1MLKEM1024. Without that setting, a 51-character host name on a five-digit port lost it the same way. When the commands do not all fit, the error now names the groups straight after its first sentence and gives only the commands that fit whole. For both host names above that is the command for the first group, and the errors are 453 and 478 bytes. An error whose commands fit is unchanged: against 127.0.0.1 and ::1 on five-digit ports the CLI prints the same bytes as before. A test builds the error for every host name length the scanner accepts, at ports 443 and 65535, and for the longest name after each of the 256 TLS alert values, and finds each group named within the 500 bytes. The FIPS-mode test also scans a 39-character spelling of 127.0.0.1, and that check failed on the earlier code. Fixes #23 --- CHANGELOG.md | 19 ++ internal/scanner/client_hello_written_test.go | 25 ++ .../scanner/handshake_failure_fits_test.go | 242 ++++++++++++++++++ internal/scanner/scanner.go | 67 +++-- 4 files changed, 338 insertions(+), 15 deletions(-) create mode 100644 internal/scanner/handshake_failure_fits_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index f606521..dece038 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -213,6 +213,25 @@ field out. a host name or an IPv4 address is printed as before. The quotes add 4 bytes: against that server the message for a five-digit port is 390 bytes, so an IPv6 address and port of up to 47 characters fit. +- **When the `openssl s_client` commands in that error do not all fit, it still + names each key exchange group this scanner does not offer.** Each command + repeats the address, and the CLI prints up to 500 bytes of a scan error, so a + long address pushed the last command past that limit, and its group was named + nowhere else. Measured with Go 1.26.3 against a local server on `::1`: run + with `GODEBUG=fips140=on,tlsmlkem=0`, where the scanner offers none of the + three hybrid groups, the error for `scanner-target-example.localhost` on a + five-digit port ended in `-groups SecP256r1MLKEM768 and openssl s_client + -connect sca...`, and without that setting the error for a 51-character host + name on a five-digit port lost `SecP384r1MLKEM1024` the same way. Such an + error now names the groups straight after its first sentence and gives only + the commands that fit whole, which for both of those host names is the + command for the first group. An error whose commands fit is unchanged: + against `127.0.0.1` and `::1` on a five-digit port it is byte for byte the + same as before, 398 and 390 bytes, and so is the 467-byte error against + `127.0.0.1` with the setting above. A test builds the error for every host + name length the scanner accepts, at ports 443 and 65535, and for the longest + name after each of the 256 TLS alert values, and finds each group named + within the 500 bytes. - **A port that is not a number from 1 to 65535 is refused without quoting it.** The error used to repeat the text after the colon, which on a `key: value` line is the value. diff --git a/internal/scanner/client_hello_written_test.go b/internal/scanner/client_hello_written_test.go index 8a0108c..d49e058 100644 --- a/internal/scanner/client_hello_written_test.go +++ b/internal/scanner/client_hello_written_test.go @@ -11,6 +11,8 @@ import ( "strings" "testing" "time" + + "github.com/csnp/qramm-tls-analyzer/internal/sanitize" ) // These tests cover a build whose TLS client can offer none of the hybrid @@ -128,6 +130,29 @@ func TestFIPSChildScanNamesTheHybridGroupsItCannotOffer(t *testing.T) { } } + // The same server through a 39-character spelling of 127.0.0.1, read as the + // CLI prints it. The address is written in the headline and in each of the + // three commands, so the CLI's cut fell after the second command and the + // third group went unnamed. A long address takes no name lookup this way. + long := "0000:0000:0000:0000:0000:ffff:127.0.0.1" + addr := net.JoinHostPort(long, strconv.Itoa(port)) + printed := sanitize.WrapError(scanExpectingError(t, long, port)).Error() + t.Logf("error for %s as the CLI prints it, %d bytes: %s", addr, len(printed), printed) + for _, name := range hybridNames { + if !strings.Contains(printed, name) { + t.Errorf("the handshake failure for %s, as the CLI prints it, does not name %s, "+ + "which this build cannot offer: %q", addr, name, printed) + } + } + whole, cut := opensslCommands(printed, sanitize.ShellWord(addr), hybridNames) + if cut != "" { + t.Errorf("the CLI's cut ends the error inside an openssl command: %q", cut) + } + if len(whole) == 0 { + t.Errorf("the error for %s gives no openssl command, though one fits within the %d "+ + "bytes the CLI prints: %q", addr, sanitize.MaxReportDetail, printed) + } + host, port = startTLSServerWithConfig(t, &tls.Config{ Certificates: []tls.Certificate{cert.serving}, MinVersion: tls.VersionTLS13, diff --git a/internal/scanner/handshake_failure_fits_test.go b/internal/scanner/handshake_failure_fits_test.go new file mode 100644 index 0000000..6651e02 --- /dev/null +++ b/internal/scanner/handshake_failure_fits_test.go @@ -0,0 +1,242 @@ +package scanner + +import ( + "crypto/tls" + "errors" + "io" + "net" + "slices" + "strconv" + "strings" + "testing" + + "github.com/csnp/qramm-tls-analyzer/internal/sanitize" +) + +// The error for a scan that completed no handshake ends with one openssl +// s_client command per key exchange group this scanner does not offer, and +// each command repeats the address that the error's headline gives. The CLI +// prints at most sanitize.MaxReportDetail bytes of a scan error and cuts the +// rest, so a long address pushed the last command past the cut, and with it the +// only place its group was named. Run with GODEBUG=fips140=on,tlsmlkem=0, where the scanner +// offers none of the three hybrid groups, a scan of +// scanner-target-example.localhost on a five-digit port ended in +// "-groups SecP256r1MLKEM768 and openssl s_client -connect sca..." and never +// named SecP384r1MLKEM1024. +// +// The mutation each test is written to catch: +// - the groups are named only in the commands, as before this change: +// TestAHandshakeFailureNamesEveryGroupWithinTheCut, and +// TestFIPSChildScanNamesTheHybridGroupsItCannotOffer through a long +// spelling of 127.0.0.1. The second was observed to fail on the earlier +// code, which has no handshakeFailureMessage for the first to call. +// - the groups are named after the sentence saying whether the server is +// reachable rather than before it, so the longest host names push them +// past the cut: TestAHandshakeFailureNamesEveryGroupWithinTheCut. +// - every command is kept, so the cut ends one part-way: +// TestAHandshakeFailureNamesEveryGroupWithinTheCut. +// - a command that fits is left out: after the first command, +// TestAHandshakeFailureNamesEveryGroupWithinTheCut; the first command, +// TestAHandshakeFailureGivesTheCommandsThatFit and +// TestFIPSChildScanNamesTheHybridGroupsItCannotOffer. +// - the groups are named ahead of the commands even when every command fits: +// TestAHandshakeFailureGivesTheCommandsThatFit. + +// TestAHandshakeFailureNamesEveryGroupWithinTheCut builds the error for host +// names of every length the scanner accepts: 1 to 253 bytes at port 443 and +// port 65535, and 253 bytes with a trailing dot at port 65535. It also builds +// it for ::1 at port 443 and for two IPv6 addresses written at their longest, +// with the longest zone, at port 65535. For the 254-byte name and the IPv6 +// addresses the handshake ends with each of the 256 TLS alert values or with +// the server closing the connection; for the other names, with the alert +// crypto/tls reports for a server sharing no key exchange group, the alert +// whose text is longest, or the server closing the connection. Read as the CLI +// prints it, the error opens with its headline, names every group this scanner +// does not offer, gives each openssl command whole and in the groups' order, +// and after the first command leaves one out only when it would not fit. +func TestAHandshakeFailureNamesEveryGroupWithinTheCut(t *testing.T) { + x25519, p256, p384 := tlsGroups[groupX25519MLKEM768].name, + tlsGroups[groupSecP256r1MLKEM768].name, tlsGroups[groupSecP384r1MLKEM1024].name + groupSets := [][]string{ + {x25519, p256, p384}, // GODEBUG=fips140=on,tlsmlkem=0 + {p256, p384}, // a Go 1.25 build + {x25519}, // a single group, named in the singular + } + + alerts := make([]error, 256) + longest := 0 + for a := range alerts { + alerts[a] = &net.OpError{Op: "remote error", Err: tls.AlertError(a)} + if len(alerts[a].Error()) > len(alerts[longest].Error()) { + longest = a + } + } + t.Logf("the alert with the longest text reads %q", alerts[longest]) + closed := []error{io.EOF, io.ErrUnexpectedEOF} + every := append(slices.Clone(alerts), closed...) + some := append([]error{alerts[40], alerts[longest]}, closed...) + + type addressCase struct { + target string + reasons []error + } + cases := []addressCase{ + {hostOfLength(253) + ".:65535", every}, + {"[::1]:443", every}, + {"[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff%abcdefghijklmno]:65535", every}, + {"[0000:0000:0000:0000:0000:ffff:255.255.255.255%abcdefghijklmno]:65535", every}, + } + for n := 1; n <= 253; n++ { + cases = append(cases, + addressCase{hostOfLength(n) + ":443", some}, addressCase{hostOfLength(n) + ":65535", some}) + } + + failures := 0 + fail := func(format string, args ...any) { + t.Helper() + t.Errorf(format, args...) + if failures++; failures == 10 { + t.FailNow() + } + } + for _, c := range cases { + host, port, err := CheckTarget(c.target) + if err != nil { + t.Fatalf("the scanner refuses %q, so this test should not cover it: %v", c.target, err) + } + addr := net.JoinHostPort(host, strconv.Itoa(port)) + connect := sanitize.ShellWord(addr) + for _, groups := range groupSets { + for _, reason := range c.reasons { + msg := handshakeFailureMessage(addr, reason, groups) + printed := sanitize.WrapError(errors.New(msg)).Error() + + headline := "TLS handshake with " + addr + " failed (" + reason.Error() + ")." + if !strings.HasPrefix(printed, headline) { + fail("for %s after %q, the error does not open with %q: %q", + addr, reason, headline, printed) + } + for _, group := range groups { + if !strings.Contains(printed, group) { + fail("for %s after %q, the error as the CLI prints it does not name %s: %q", + addr, reason, group, printed) + } + } + + whole, cut := opensslCommands(printed, connect, groups) + if cut != "" { + fail("for %s after %q, the CLI's cut ends the error inside an openssl "+ + "command: %q", addr, reason, cut) + } + if len(whole) > len(groups) || !slices.Equal(whole, groups[:len(whole)]) { + fail("for %s after %q, the commands check %v, not the groups %v in order: %q", + addr, reason, whole, groups, printed) + continue + } + if n := len(whole); n > 0 && n < len(groups) { + next := "openssl s_client -connect " + connect + " -groups " + groups[n] + if len(msg)+len(" and ")+len(next) <= sanitize.MaxReportDetail { + fail("for %s after %q, the error leaves out %q, which fits: %q", + addr, reason, next, msg) + } + } + } + } + } +} + +// TestAHandshakeFailureGivesTheCommandsThatFit pins the commands for three +// addresses after the alert crypto/tls reports for a server that shares no key +// exchange group with the client, for a build offering none of the three +// hybrid groups. A short address gets every command, with the groups named only +// in them, as before. The host name from the report gets a whole command for +// the first group and the whole error within the CLI's limit. +func TestAHandshakeFailureGivesTheCommandsThatFit(t *testing.T) { + alert := &net.OpError{Op: "remote error", Err: tls.AlertError(40)} + if got, want := alert.Error(), "remote error: tls: handshake failure"; got != want { + t.Fatalf("alert 40 reads %q here, not %q as crypto/tls reports it from a server", got, want) + } + groups := []string{ + tlsGroups[groupX25519MLKEM768].name, + tlsGroups[groupSecP256r1MLKEM768].name, + tlsGroups[groupSecP384r1MLKEM1024].name, + } + + for _, addr := range []string{"127.0.0.1:65535", "[::1]:65535"} { + msg := handshakeFailureMessage(addr, alert, groups) + whole, cut := opensslCommands(msg, sanitize.ShellWord(addr), groups) + if cut != "" || !slices.Equal(whole, groups) || len(msg) > sanitize.MaxReportDetail { + t.Errorf("for %s the error should give a whole command for each of %v within %d "+ + "bytes, got %d bytes: %q", addr, groups, sanitize.MaxReportDetail, len(msg), msg) + } + if strings.Contains(msg, "This scanner does not offer") { + t.Errorf("for %s every command fits, so the groups need no naming ahead of "+ + "them: %q", addr, msg) + } + } + + addr := "scanner-target-example.localhost:65535" + msg := handshakeFailureMessage(addr, alert, groups) + printed := sanitize.WrapError(errors.New(msg)).Error() + t.Logf("error for %s, %d bytes: %s", addr, len(msg), msg) + if printed != msg { + t.Errorf("for %s the CLI cuts the error: %q", addr, printed) + } + for _, group := range groups { + if !strings.Contains(printed, group) { + t.Errorf("for %s the error does not name %s: %q", addr, group, printed) + } + } + whole, _ := opensslCommands(msg, sanitize.ShellWord(addr), groups) + if len(whole) == 0 || whole[0] != groups[0] { + t.Errorf("for %s the error should give a whole command for %s, which fits: %q", + addr, groups[0], msg) + } +} + +// hostOfLength is a host name of exactly n bytes, in labels of at most 50 +// letters, so every label is a legal DNS label and none is empty. +func hostOfLength(n int) string { + var labels []string + for remaining := n; remaining > 0; { + size := min(50, remaining) + if remaining-size == 1 { + size-- // leave room for a dot and a one-letter label + } + labels = append(labels, strings.Repeat("a", size)) + remaining -= size + if remaining > 0 { + remaining-- // the dot + } + } + return strings.Join(labels, ".") +} + +// opensslCommands reads the openssl commands in msg. Each must be a whole +// "openssl s_client -connect -groups " for one of groups, +// followed by " and " or by the end of msg. It returns the groups of the whole +// commands in order, and the text from the first command that is not whole, +// which is empty when every command is. +func opensslCommands(msg, connect string, groups []string) (whole []string, cut string) { + rest := msg + for { + i := strings.Index(rest, "openssl s_client") + if i < 0 { + return whole, "" + } + rest = rest[i:] + matched := "" + for _, group := range groups { + cmd := "openssl s_client -connect " + connect + " -groups " + group + if rest == cmd || strings.HasPrefix(rest, cmd+" and ") { + matched = group + rest = rest[len(cmd):] + break + } + } + if matched == "" { + return whole, rest + } + whole = append(whole, matched) + } +} diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index cd19fff..8d2db49 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -369,42 +369,79 @@ func (s *Scanner) noHandshakeError(ctx context.Context, host string, port int) e "Scan it again", addr) } - // The CLI truncates a scan error to sanitize.MaxReportDetail bytes and the - // address appears once here and once in each openssl command, so the - // wording is kept short to leave room for a host name. + return errors.New(handshakeFailureMessage(addr, hsErr, hybridGroupsNotOffered())) +} + +// handshakeFailureMessage describes a TLS handshake with addr that failed with +// hsErr, made by a client that does not offer the key exchange groups named in +// notOffered. +// +// The CLI prints at most sanitize.MaxReportDetail bytes of a scan error and +// cuts the rest. The address appears in the headline and again in each openssl +// command, so the wording is kept short to leave room for a host name, and a +// command is given whole or left out. +func handshakeFailureMessage(addr string, hsErr error, notOffered []string) string { msg := fmt.Sprintf("TLS handshake with %s failed (%v).", addr, hsErr) var notTLS tls.RecordHeaderError var opErr *net.OpError + var reached string switch { case errors.As(hsErr, ¬TLS): - return fmt.Errorf("%s The host accepted a TCP connection, but its reply was not "+ - "TLS, so the service on this port does not appear to speak TLS", msg) + return msg + " The host accepted a TCP connection, but its reply was not " + + "TLS, so the service on this port does not appear to speak TLS" case errors.As(hsErr, &opErr) && opErr.Op == "remote error": // crypto/tls reports a TLS alert from the peer this way, and only a peer // that speaks TLS sends one. - msg += " The server answered in TLS, so it is reachable, but it rejected the " + + reached = " The server answered in TLS, so it is reachable, but it rejected the " + "handshakes this scanner tried." default: - msg += " The host accepted a TCP connection, so it is reachable, but it may not " + + reached = " The host accepted a TCP connection, so it is reachable, but it may not " + "speak TLS or may accept nothing this scanner offers." } + if len(notOffered) == 0 { + return msg + reached + } // One command per group. s_client negotiates one of the groups named after // -groups, so a command naming two says nothing about the one it did not // pick, which is why docs/how-it-works.md gives each group its own command. // An IPv6 address is quoted, since zsh reads its brackets as a glob and // refuses the command. - if groups := hybridGroupsNotOffered(); len(groups) > 0 { - connect := sanitize.ShellWord(addr) - commands := make([]string, len(groups)) - for i, group := range groups { - commands[i] = fmt.Sprintf("openssl s_client -connect %s -groups %s", connect, group) + connect := sanitize.ShellWord(addr) + commands := make([]string, len(notOffered)) + for i, group := range notOffered { + commands[i] = fmt.Sprintf("openssl s_client -connect %s -groups %s", connect, group) + } + full := msg + reached + " Check the key exchange groups this scanner does not offer, " + + "one command each: " + strings.Join(commands, " and ") + if len(full) <= sanitize.MaxReportDetail { + return full + } + + // Not every command fits. The groups were named only in the commands, so + // the cut took a group's name with its command: under + // GODEBUG=fips140=on,tlsmlkem=0, where this scanner offers none of the three + // hybrid groups, a 38-character host and port lost the third. The groups are + // named straight after the headline instead, where they fit for the longest + // address the scanner accepts, a 254-byte host name and a five-digit port, + // after any TLS alert, and only the commands that fit whole follow. + names := notOffered[len(notOffered)-1] + noun := "group" + if n := len(notOffered); n > 1 { + names = strings.Join(notOffered[:n-1], ", ") + " and " + names + noun = "groups" + } + msg += fmt.Sprintf(" This scanner does not offer the key exchange %s %s.", noun, names) + reached + sep := " Check each group with its own command, for example: " + for _, cmd := range commands { + if len(msg)+len(sep)+len(cmd) > sanitize.MaxReportDetail { + break } - msg += " Check the key exchange groups this scanner does not offer, one command each: " + - strings.Join(commands, " and ") + msg += sep + cmd + sep = " and " } - return errors.New(msg) + return msg } // hybridGroupsNotOffered names the hybrid post-quantum groups this build's TLS From 32711ac371275c03bfa0bdf509d3596a6f8f6fb7 Mon Sep 17 00:00:00 2001 From: Abdel Fane <32418586+thebenignhacker@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:07:31 -0600 Subject: [PATCH 2/4] Report the address the scan reached, not the first one resolved (#24) With no --sni and a host name too long for the quantum.minQuantumScore Verify to name twice, the Verify connects to the result's IP. That field was the first address the host name resolved to, recorded before any connection, while the scan's dials move on to the next address when the first one refuses. A TLS 1.3 server listening on 127.0.0.1 only, scanned under cnsa-2.0-2030 as a 213-character .localhost name that resolves to ::1 and then 127.0.0.1, was measured over 127.0.0.1, reported "ip": "::1", and its Fix ended with -connect '[::1]:52144', an address the server was not listening on. Each probe now records the address of every connection that completed a handshake, and the result's IP is the one reached first; when one scan's connections reached more than one address, a scan coverage note names them. The same scan now reports "ip": "127.0.0.1", the text report's IP line reads the same, and the 498-byte Fix ends with -connect 127.0.0.1:50983 -servername -groups X25519MLKEM768 + -groups X25519MLKEM768 0 { result.ScanWarnings = append(result.ScanWarnings, fmt.Sprintf( @@ -538,7 +603,8 @@ func (w *writeObserver) Write(p []byte) (int, error) { } // probeProtocols checks which TLS versions are supported. -func (s *Scanner) probeProtocols(ctx context.Context, host string, port int) []types.Protocol { +func (s *Scanner) probeProtocols(ctx context.Context, host string, port int, + reached *reachedAddresses) []types.Protocol { versions := []struct { version uint16 name string @@ -570,7 +636,7 @@ func (s *Scanner) probeProtocols(ctx context.Context, host string, port int) []t protocols[idx] = types.Protocol{ Version: name, - Supported: s.tryConnect(ctx, host, port, cfg), + Supported: s.tryConnect(ctx, host, port, cfg, reached), } }(i, v.version, v.name) } @@ -663,8 +729,8 @@ func buildOffersGroup(id tls.CurveID) bool { // Groups this Go build cannot offer are skipped rather than reported // unsupported; skipped groups are returned so callers can be explicit about // coverage instead of implying a negative result. -func (s *Scanner) probeKeyExchangeGroups(ctx context.Context, host string, port int) ( - supported []types.KeyExchange, skipped []string) { +func (s *Scanner) probeKeyExchangeGroups(ctx context.Context, host string, port int, + reached *reachedAddresses) (supported []types.KeyExchange, skipped []string) { candidates := []tls.CurveID{ groupX25519MLKEM768, @@ -712,6 +778,7 @@ func (s *Scanner) probeKeyExchangeGroups(ctx context.Context, host string, port return } defer func() { _ = conn.Close() }() + reached.record(conn.RemoteAddr()) // Confirm the server actually selected the offered group rather // than assuming a successful handshake implies it. @@ -747,8 +814,8 @@ func (s *Scanner) probeKeyExchangeGroups(ctx context.Context, host string, port // 1.3 suite observable from here is the negotiated one. That limit is reported // to the caller rather than hidden, so an absent suite is never mistaken for an // unsupported one. -func (s *Scanner) probeCipherSuites(ctx context.Context, host string, port int) ( - supported []types.CipherSuite, tls13Enumerable bool) { +func (s *Scanner) probeCipherSuites(ctx context.Context, host string, port int, + reached *reachedAddresses) (supported []types.CipherSuite, tls13Enumerable bool) { candidates := tls.CipherSuites() candidates = append(candidates, tls.InsecureCipherSuites()...) @@ -789,6 +856,7 @@ func (s *Scanner) probeCipherSuites(ctx context.Context, host string, port int) return } defer func() { _ = conn.Close() }() + reached.record(conn.RemoteAddr()) state := conn.(*tls.Conn).ConnectionState() if state.CipherSuite != id { @@ -826,7 +894,8 @@ func isTLS13Suite(id uint16) bool { } // probeConnection connects with best available settings and extracts info. -func (s *Scanner) probeConnection(ctx context.Context, host string, port int) ( +func (s *Scanner) probeConnection(ctx context.Context, host string, port int, + reached *reachedAddresses) ( *types.Certificate, []types.Certificate, []types.CipherSuite, []types.KeyExchange) { cfg := &tls.Config{ @@ -842,6 +911,7 @@ func (s *Scanner) probeConnection(ctx context.Context, host string, port int) ( return nil, nil, nil, nil } defer conn.Close() + reached.record(conn.RemoteAddr()) state := conn.ConnectionState() @@ -891,8 +961,10 @@ func (s *Scanner) probeConnection(ctx context.Context, host string, port int) ( return cert, chain, ciphers, keyExchanges } -// tryConnect attempts a TLS connection with the given config. -func (s *Scanner) tryConnect(ctx context.Context, host string, port int, cfg *tls.Config) bool { +// tryConnect attempts a TLS connection with the given config, and records the +// address it reached when the handshake completed. +func (s *Scanner) tryConnect(ctx context.Context, host string, port int, cfg *tls.Config, + reached *reachedAddresses) bool { addr := net.JoinHostPort(host, strconv.Itoa(port)) dialer := &tls.Dialer{ NetDialer: &net.Dialer{Timeout: s.config.ConnectTimeout}, @@ -903,6 +975,7 @@ func (s *Scanner) tryConnect(ctx context.Context, host string, port int, cfg *tl if err != nil { return false } + reached.record(conn.RemoteAddr()) conn.Close() return true } diff --git a/pkg/types/result.go b/pkg/types/result.go index c039af6..72f6e63 100644 --- a/pkg/types/result.go +++ b/pkg/types/result.go @@ -10,9 +10,13 @@ import ( // ScanResult represents the complete result of a TLS scan. type ScanResult struct { // Target information - Target string `json:"target"` - Host string `json:"host"` - Port int `json:"port"` + Target string `json:"target"` + Host string `json:"host"` + Port int `json:"port"` + // IP is the address the scan's connections reached: the remote address of + // the first of them to complete a TLS handshake. A host name can resolve to + // several addresses and a dial moves on when one refuses the connection, so + // this is not always the first address the name resolved to. IP string `json:"ip,omitempty"` Timestamp time.Time `json:"timestamp"` Duration Duration `json:"duration"` From 2467890923c70b75db85810afaf1bca21d1ba335 Mon Sep 17 00:00:00 2001 From: Abdel Fane <32418586+thebenignhacker@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:42:11 -0600 Subject: [PATCH 3/4] CBOM endpoint writes an IPv6 address in brackets (#26) The service endpoint in --format cbom output was written from the bare host and the port with "https://%s:%d", so a scan of '[::1]:8443' listed https://::1:8443. The endpoint is now built with net.JoinHostPort and net/url, and that scan lists https://[::1]:8443. A zone-scoped address is bracketed too, with the % before its zone written %25: fe80::1%lo0 on port 9 is written https://[fe80::1%25lo0]:9. A host name or an IPv4 address is written as before. TestCBOMEndpointWritesAnIPv6AddressInBrackets fails in its three IPv6 cases on the earlier code and passes in all five with this change. Fixes #26 --- CHANGELOG.md | 10 +++ internal/reporter/cbom.go | 10 ++- internal/reporter/cbom_endpoint_test.go | 83 +++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 2 deletions(-) create mode 100644 internal/reporter/cbom_endpoint_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c0df053..6a555e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -265,6 +265,16 @@ field out. and now names `[::1]:1`. A zone-scoped address keeps its brackets the same way: `[fe80::1%lo0]:9` was written `fe80::1%lo0:9`. `127.0.0.1:1` and `localhost:1` are written as before. +- **The service endpoint in `--format cbom` output writes an IPv6 address in + brackets.** Against a local server on `::1`, `tlsanalyzer '[::1]:8443' + --format cbom` listed the endpoint `https://::1:8443`, where the port reads as + part of the address, and now lists `https://[::1]:8443`. A zone-scoped address + is bracketed the same way, and the `%` before its zone is written `%25`, the + form RFC 6874 gives a zone in a URI: `fe80::1%lo0` on port 9 is written + `https://[fe80::1%25lo0]:9`, where it was `https://fe80::1%lo0:9`. Go's + `net/url` refuses the form with a bare `%`, `https://[fe80::1%lo0]:9`, with + `invalid URL escape "%lo"`. A host name or an IPv4 address is written as + before, for example `https://localhost:8443` and `https://127.0.0.1:8443`. ## [0.4.1] - 2026-08-05 diff --git a/internal/reporter/cbom.go b/internal/reporter/cbom.go index ae3d195..bc8af6b 100644 --- a/internal/reporter/cbom.go +++ b/internal/reporter/cbom.go @@ -3,6 +3,8 @@ package reporter import ( "fmt" "io" + "net" + "net/url" "strconv" "strings" "time" @@ -65,12 +67,16 @@ func (r *CBOMReporter) generateCBOM(result *types.ScanResult) types.CryptoBOM { return cbom } - // Add service + // Add service. The endpoint is a URL: net.JoinHostPort puts an IPv6 address + // in brackets, and url.URL writes the % before a zone as %25. Written from + // host and port with "https://%s:%d", ::1 came out as https://::1:8443, + // where the port reads as part of the address. + endpoint := url.URL{Scheme: "https", Host: net.JoinHostPort(result.Host, strconv.Itoa(result.Port))} cbom.Services = []types.CryptoService{ { BOMRef: "service-" + result.Target, Name: result.Target, - Endpoints: []string{fmt.Sprintf("https://%s:%d", result.Host, result.Port)}, + Endpoints: []string{endpoint.String()}, Description: "TLS-enabled service", }, } diff --git a/internal/reporter/cbom_endpoint_test.go b/internal/reporter/cbom_endpoint_test.go new file mode 100644 index 0000000..826adf2 --- /dev/null +++ b/internal/reporter/cbom_endpoint_test.go @@ -0,0 +1,83 @@ +package reporter + +import ( + "net" + "net/url" + "strconv" + "testing" +) + +// cbomEndpoints returns the endpoints of the one service a CBOM lists. +func cbomEndpoints(t *testing.T, out string) []string { + t.Helper() + doc := decodeJSON(t, out) + services, ok := doc["services"].([]any) + if !ok || len(services) != 1 { + t.Fatalf("CBOM lists %v services, want exactly 1", doc["services"]) + } + service, ok := services[0].(map[string]any) + if !ok { + t.Fatal("CBOM service is not an object") + } + raw, _ := service["endpoints"].([]any) + endpoints := make([]string, 0, len(raw)) + for _, e := range raw { + s, ok := e.(string) + if !ok { + t.Fatalf("CBOM endpoint %v is not a string", e) + } + endpoints = append(endpoints, s) + } + return endpoints +} + +// TestCBOMEndpointWritesAnIPv6AddressInBrackets is the reproduction of +// "tlsanalyzer '[::1]:' --format cbom lists the endpoint +// https://::1:". The endpoint was written from the host and the port with +// "https://%s:%d", so an IPv6 address lost its brackets and its port read as +// part of the address. Writing it that way again kills the three IPv6 cases; +// this was observed, all three failed on that code. The IPv4 address and the +// host name are the controls, written as before. +// +// Each endpoint is also read back with net/url, which catches a zone written +// with a bare %: url.Parse refuses "https://[fe80::1%lo0]:9" with "invalid URL +// escape". It does not catch the missing brackets, because it reads +// "https://::1:8443" as host ::1 and port 8443, so the exact string is checked +// too. +func TestCBOMEndpointWritesAnIPv6AddressInBrackets(t *testing.T) { + cases := []struct { + name string + host string + port int + want string + }{ + {"IPv6 loopback", "::1", 8443, "https://[::1]:8443"}, + {"IPv6 documentation address", "2001:db8::1", 443, "https://[2001:db8::1]:443"}, + // A URL writes the % before a zone as %25 (RFC 6874). + {"zone-scoped link-local", "fe80::1%lo0", 9, "https://[fe80::1%25lo0]:9"}, + {"IPv4", "127.0.0.1", 8443, "https://127.0.0.1:8443"}, + {"host name", "example.com", 443, "https://example.com:443"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + result := scannedResult() + result.Target = net.JoinHostPort(tc.host, strconv.Itoa(tc.port)) + result.Host = tc.host + result.Port = tc.port + + endpoints := cbomEndpoints(t, render(t, &CBOMReporter{}, result)) + if len(endpoints) != 1 || endpoints[0] != tc.want { + t.Fatalf("CBOM endpoints = %q, want [%q]", endpoints, tc.want) + } + + u, err := url.Parse(endpoints[0]) + if err != nil { + t.Fatalf("the endpoint is not a URL: %v", err) + } + if u.Scheme != "https" || u.Hostname() != tc.host || u.Port() != strconv.Itoa(tc.port) { + t.Errorf("%q reads back as scheme %q, host %q, port %q; want https, %q, %d", + endpoints[0], u.Scheme, u.Hostname(), u.Port(), tc.host, tc.port) + } + }) + } +} From b05e588ebc4e7baab324376d339cbca918c1875f Mon Sep 17 00:00:00 2001 From: Abdel Fane <32418586+thebenignhacker@users.noreply.github.com> Date: Sat, 17 Oct 2026 13:44:27 -0600 Subject: [PATCH 4/4] Drop the retired Go Report Card badge from the README header (#27) Fixes #27 --- CHANGELOG.md | 3 +++ README.md | 1 - cmd/tlsanalyzer/readme_badges_test.go | 32 +++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 cmd/tlsanalyzer/readme_badges_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a555e5..09ed83f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -275,6 +275,9 @@ field out. `net/url` refuses the form with a bare `%`, `https://[fe80::1%lo0]:9`, with `invalid URL escape "%lo"`. A host name or an IPv4 address is written as before, for example `https://localhost:8443` and `https://127.0.0.1:8443`. +- **The README header no longer shows the Go Report Card badge.** goreportcard.com + has retired its service, and the badge rendered "go report: retired" instead + of a grade. The CI, Go Reference and License badges remain. ## [0.4.1] - 2026-08-05 diff --git a/README.md b/README.md index 7337b27..b3f764d 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,6 @@

CI Status - Go Report Card Go Reference License

diff --git a/cmd/tlsanalyzer/readme_badges_test.go b/cmd/tlsanalyzer/readme_badges_test.go new file mode 100644 index 0000000..8be874f --- /dev/null +++ b/cmd/tlsanalyzer/readme_badges_test.go @@ -0,0 +1,32 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestReadmeBadgesComeFromServicesThatAnswer keeps the README header free of +// badges whose service has shut down. +// +// goreportcard.com retired its service: fetched on 2026-10-17, its badge for +// this module rendered the text "go report: retired" instead of a grade, so the +// README header showed a broken badge to every visitor. +func TestReadmeBadgesComeFromServicesThatAnswer(t *testing.T) { + path := filepath.Join("..", "..", "README.md") + body, err := os.ReadFile(path) + if err != nil { + t.Fatalf("reading %s: %v", path, err) + } + + retired := []string{"goreportcard.com"} + for i, line := range strings.Split(string(body), "\n") { + for _, host := range retired { + if strings.Contains(line, host) { + t.Errorf("README.md:%d links to %s, which has retired its service: %s", + i+1, host, strings.TrimSpace(line)) + } + } + } +}