diff --git a/docs/checks/tls.mdx b/docs/checks/tls.mdx index 6b5c0aa..3f2bc23 100644 --- a/docs/checks/tls.mdx +++ b/docs/checks/tls.mdx @@ -5,21 +5,23 @@ description: Protocol version, cipher strength/forward secrecy, certificate chai | Check ID | Title | CVSS 4.0 | CWE | OWASP | | --- | --- | --- | --- | --- | -| `tls.protocol_version` | Weak TLS Protocol Version Accepted | 5.3 | [CWE-326](https://cwe.mitre.org/data/definitions/326.html) | API8:2023 | -| `tls.cipher_strength` | Weak Cipher Suite or Missing Forward Secrecy | 4.8 | [CWE-327](https://cwe.mitre.org/data/definitions/327.html) | API8:2023 | -| `tls.certificate` | Certificate Chain, Expiry, Hostname, or OCSP Stapling Issue | 5.3 | [CWE-295](https://cwe.mitre.org/data/definitions/295.html) | API8:2023 | -| `tls.https_redirect` | Missing HTTP to HTTPS Redirect | 5.3 | [CWE-319](https://cwe.mitre.org/data/definitions/319.html) | API8:2023 | +| `tls.protocol_version` | Weak TLS Protocol Version Accepted | 6.9 | [CWE-326](https://cwe.mitre.org/data/definitions/326.html) | API8:2023 | +| `tls.cipher_strength` | Weak Cipher Suite or Missing Forward Secrecy | 6.9 | [CWE-327](https://cwe.mitre.org/data/definitions/327.html) | API8:2023 | +| `tls.certificate` | Certificate Chain, Expiry, Hostname, or OCSP Stapling Issue | 6.9 | [CWE-295](https://cwe.mitre.org/data/definitions/295.html) | API8:2023 | +| `tls.https_redirect` | Missing HTTP to HTTPS Redirect | 6.9 | [CWE-319](https://cwe.mitre.org/data/definitions/319.html) | API8:2023 | | `tls.hsts` | Missing or Weak Strict-Transport-Security Header | 0 (informational) | [CWE-16](https://cwe.mitre.org/data/definitions/16.html) | API8:2023 | ## `tls.protocol_version` -Tests whether the proxy still accepts deprecated TLS versions (TLS 1.0/1.1) alongside modern ones, by forcing a handshake at each deprecated version. Go's `crypto/tls` no longer implements SSLv3, so that version can't be probed directly — but a server still offering it would also offer TLS 1.0/1.1 in virtually every real deployment. +Tests whether the proxy still accepts deprecated protocol versions alongside modern ones, by forcing a handshake at each deprecated version: TLS 1.0 and 1.1 through `crypto/tls`, and SSL 3.0 through a raw ClientHello since `crypto/tls` no longer implements it. Accepted versions are reported together as one observation, code `protocol.legacy_enabled`. + +Per-CVE findings (Heartbleed, DROWN, ROBOT) are not probed: they need exploit-specific handshakes, and every affected deployment also enables a legacy protocol or suite reported here. **Remediate:** disable TLS 1.0/1.1 (and SSLv3) in the proxy's TLS configuration; require TLS 1.2 or later. ## `tls.cipher_strength` -Inspects the negotiated cipher suite for missing forward secrecy (non-ECDHE/DHE key exchange on TLS ≤ 1.2), and separately forces a handshake offering only known-weak cipher suites (RC4, 3DES, CBC-mode) to test whether the server still accepts them. +Inspects the negotiated cipher suite for missing forward secrecy (non-ECDHE/DHE key exchange on TLS ≤ 1.2), and separately forces handshakes offering only weak cipher suites to test whether the server still accepts them: RC4, 3DES and NULL through a raw ClientHello, the other suites Go marks insecure (CBC mode with SHA-256) through `crypto/tls`. A raw handshake offering only DHE suites reads the Diffie-Hellman group size and flags a group below 2048 bits. **Remediate:** restrict the cipher suite list to modern AEAD suites with ECDHE key exchange (or rely on TLS 1.3, which is always forward-secret). @@ -27,12 +29,28 @@ Inspects the negotiated cipher suite for missing forward secrecy (non-ECDHE/DHE Inspects the leaf certificate presented during the TLS handshake: -- **Chain trust** — independently verifies the presented chain against the system trust store and the request hostname. -- **Expiry** — flags an expired certificate, and separately flags one expiring within 30 days. +- **Chain trust** — independently verifies the presented chain against the system trust store, and tells a self-signed certificate apart from an untrusted chain. +- **Hostname** — flags a certificate not valid for the hostname of the target URL. +- **Expiry** — flags an expired or not yet valid certificate, and separately one expiring within 30 days. - **OCSP stapling** — flags a handshake with no stapled OCSP response. **Remediate:** use a certificate from a trusted CA matching the hostname, automate renewal well before expiry, and enable OCSP stapling. +## Observation codes + +Each kind of finding carries a stable code in `Metadata["code"]`, so an embedder maps it to its own check ID without matching titles: + +| Check | Codes | +| --- | --- | +| `tls.protocol_version` | `protocol.legacy_enabled` | +| `tls.cipher_strength` | `cipher.no_forward_secrecy`, `cipher.rc4`, `cipher.3des`, `cipher.null`, `cipher.weak_suite`, `cipher.weak_dh` | +| `tls.certificate` | `certificate.untrusted_chain`, `certificate.self_signed`, `certificate.hostname_mismatch`, `certificate.expired`, `certificate.not_yet_valid`, `certificate.expires_soon`, `certificate.ocsp_not_stapled` | +| `tls.https_redirect` | `https_redirect.not_redirected`, `https_redirect.not_https` | + +## Skipped targets + +The TLS checks share one handshake, `probe.tls_info`, whose result (`probebase.TLSInfo`) is exported for other scanners. When it fails, they are skipped with the reason given by `TLSInfo.SkipReason`: a plain-HTTP target URL, a port that does not speak TLS, or a closed or unreachable port. + ## `tls.https_redirect` Sends a plain-HTTP request to the target and checks whether it's redirected to HTTPS. diff --git a/proxy/checks/tls/certificate/check.go b/proxy/checks/tls/certificate/check.go index 5fb2c0d..84523dd 100644 --- a/proxy/checks/tls/certificate/check.go +++ b/proxy/checks/tls/certificate/check.go @@ -4,14 +4,18 @@ package certificate import ( + "bytes" "context" + "crypto/x509" _ "embed" "errors" + "net/url" "time" "github.com/cerberauth/harnessx" "github.com/cerberauth/harnessx/checkdef" "github.com/cerberauth/proxyaudit/proxy/probebase" + "github.com/cerberauth/proxyaudit/proxy/scanctx" ) var errNoCertificate = errors.New("no certificate available from probe.tls_info") @@ -25,55 +29,111 @@ var Def = checkdef.MustParseCheckDefYAML("certificate", checkYAML) // soon enough to be an operational risk. const ExpiryWarningWindow = 30 * 24 * time.Hour -var Check = checkdef.NewCheck(Def, func(_ context.Context, _ harnessx.Target, store harnessx.ResultStore) (harnessx.Result, error) { +const ( + CodeUntrustedChain = "certificate.untrusted_chain" + CodeSelfSigned = "certificate.self_signed" + CodeHostnameMismatch = "certificate.hostname_mismatch" + CodeExpired = "certificate.expired" + CodeNotYetValid = "certificate.not_yet_valid" + CodeExpiresSoon = "certificate.expires_soon" + CodeOCSPNotStapled = "certificate.ocsp_not_stapled" +) + +func isSelfSigned(cert *x509.Certificate) bool { + return bytes.Equal(cert.RawIssuer, cert.RawSubject) && cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature) == nil +} + +func chainError(leaf *x509.Certificate, intermediates []*x509.Certificate, roots *x509.CertPool) error { + pool := x509.NewCertPool() + for _, c := range intermediates { + pool.AddCert(c) + } + _, err := leaf.Verify(x509.VerifyOptions{ + Roots: roots, + Intermediates: pool, + CurrentTime: leaf.NotBefore.Add(time.Second), + }) + return err +} + +func observation(code, title, description, evidence string, metadata map[string]string) harnessx.Observation { + if metadata == nil { + metadata = map[string]string{} + } + metadata[probebase.MetadataCode] = code + return harnessx.Observation{Title: title, Description: description, Evidence: evidence, Metadata: metadata} +} + +var Check = checkdef.NewCheck(Def, func(_ context.Context, target harnessx.Target, store harnessx.ResultStore) (harnessx.Result, error) { info, ok := probebase.Info(store) if !ok || info.Err != nil || info.ConnState == nil || len(info.ConnState.PeerCertificates) == 0 { return harnessx.Result{Err: errNoCertificate}, nil } + sctx := scanctx.TargetContext(target) leaf := info.ConnState.PeerCertificates[0] + subject := map[string]string{"subject": leaf.Subject.String()} var observations []harnessx.Observation - if info.VerifyErr != nil { - observations = append(observations, harnessx.Observation{ - Title: "Certificate chain does not verify", - Description: "The certificate presented by the target does not chain to a trusted root, or the hostname does not match.", - Evidence: info.VerifyErr.Error(), - Metadata: map[string]string{"subject": leaf.Subject.String()}, - }) + if err := chainError(leaf, info.ConnState.PeerCertificates[1:], sctx.RootCAs); err != nil { + var unknownAuthority x509.UnknownAuthorityError + if errors.As(err, &unknownAuthority) && isSelfSigned(leaf) { + observations = append(observations, observation(CodeSelfSigned, + "Certificate is self-signed", + "The certificate presented by the target is signed by its own key instead of a trusted certificate authority, so clients cannot authenticate the server.", + err.Error(), subject)) + } else { + observations = append(observations, observation(CodeUntrustedChain, + "Certificate chain does not verify", + "The certificate presented by the target does not chain to a trusted root.", + err.Error(), subject)) + } + } + + if u, err := url.Parse(target.URL); err == nil { + if err := leaf.VerifyHostname(u.Hostname()); err != nil { + observations = append(observations, observation(CodeHostnameMismatch, + "Certificate hostname does not match", + "The certificate presented by the target is not valid for the hostname of the target URL.", + err.Error(), map[string]string{"subject": leaf.Subject.String(), "hostname": u.Hostname()})) + } } now := time.Now() + notAfter := map[string]string{"not_after": leaf.NotAfter.Format(time.RFC3339)} switch { case now.After(leaf.NotAfter): - observations = append(observations, harnessx.Observation{ - Title: "Certificate has expired", - Description: "The certificate presented by the target expired and is no longer valid.", - Evidence: "not_after: " + leaf.NotAfter.Format(time.RFC3339), - Metadata: map[string]string{"not_after": leaf.NotAfter.Format(time.RFC3339)}, - }) + observations = append(observations, observation(CodeExpired, + "Certificate has expired", + "The certificate presented by the target expired and is no longer valid.", + "not_after: "+leaf.NotAfter.Format(time.RFC3339), notAfter)) + case now.Before(leaf.NotBefore): + observations = append(observations, observation(CodeNotYetValid, + "Certificate is not valid yet", + "The certificate presented by the target is not valid before a future date.", + "not_before: "+leaf.NotBefore.Format(time.RFC3339), map[string]string{"not_before": leaf.NotBefore.Format(time.RFC3339)})) case leaf.NotAfter.Before(now.Add(ExpiryWarningWindow)): - observations = append(observations, harnessx.Observation{ - Title: "Certificate expires soon", - Description: "The certificate presented by the target expires within 30 days.", - Evidence: "not_after: " + leaf.NotAfter.Format(time.RFC3339), - Metadata: map[string]string{"not_after": leaf.NotAfter.Format(time.RFC3339)}, - }) + observations = append(observations, observation(CodeExpiresSoon, + "Certificate expires soon", + "The certificate presented by the target expires within 30 days.", + "not_after: "+leaf.NotAfter.Format(time.RFC3339), notAfter)) } if info.ConnState.OCSPResponse == nil { - observations = append(observations, harnessx.Observation{ - Title: "OCSP stapling not enabled", - Description: "The target did not staple an OCSP response during the TLS handshake, so clients must query the CA's OCSP responder separately (or skip revocation checking entirely).", - Evidence: "no OCSP response in TLS handshake", - }) + observations = append(observations, observation(CodeOCSPNotStapled, + "OCSP stapling not enabled", + "The target did not staple an OCSP response during the TLS handshake, so clients must query the CA's OCSP responder separately (or skip revocation checking entirely).", + "no OCSP response in TLS handshake", nil)) } return harnessx.Result{Observations: observations}, nil }, checkdef.WithSkip(harnessx.SkipWhen(func(_ context.Context, _ harnessx.Target, store harnessx.ResultStore) string { - info, ok := probebase.Info(store) - if !ok || info.Err != nil || info.ConnState == nil || len(info.ConnState.PeerCertificates) == 0 { - return "target TLS handshake produced no certificate — see probe.tls_info" + info, _ := probebase.Info(store) + if reason := info.SkipReason(); reason != "" { + return reason + } + if len(info.ConnState.PeerCertificates) == 0 { + return "target TLS handshake produced no certificate" } return "" }))) diff --git a/proxy/checks/tls/certificate/check.yaml b/proxy/checks/tls/certificate/check.yaml index ca088be..04cffd6 100644 --- a/proxy/checks/tls/certificate/check.yaml +++ b/proxy/checks/tls/certificate/check.yaml @@ -9,6 +9,6 @@ tags: depends_on: - "probe.tls_info" cvss_vector: "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N" -cvss_score: 5.3 +cvss_score: 6.9 cwe_id: "CWE-295" owasp: "API8:2023" diff --git a/proxy/checks/tls/cipher_strength/check.go b/proxy/checks/tls/cipher_strength/check.go index 5c358fa..36a9e23 100644 --- a/proxy/checks/tls/cipher_strength/check.go +++ b/proxy/checks/tls/cipher_strength/check.go @@ -1,13 +1,14 @@ // Package cipherstrength checks the negotiated TLS cipher suite for -// forward secrecy and probes whether the target still accepts any -// known-weak cipher suite (RC4, 3DES, CBC-mode) that Go's crypto/tls -// implements but excludes from its default client offer. +// forward secrecy and probes whether the target still accepts RC4, 3DES, +// NULL or other insecure cipher suites, or a weak Diffie-Hellman group. package cipherstrength import ( "context" "crypto/tls" _ "embed" + "fmt" + "strconv" "strings" "github.com/cerberauth/harnessx" @@ -21,6 +22,44 @@ var checkYAML []byte var Def = checkdef.MustParseCheckDefYAML("cipher_strength", checkYAML) +const ( + CodeNoForwardSecrecy = "cipher.no_forward_secrecy" + CodeRC4 = "cipher.rc4" + CodeTripleDES = "cipher.3des" + CodeNULL = "cipher.null" + CodeWeakSuite = "cipher.weak_suite" + CodeWeakDH = "cipher.weak_dh" +) + +const MinDHPrimeBits = 2048 + +const metadataCipherSuite = "cipher_suite" + +var probeLegacyHello = probebase.ProbeLegacyHello + +var legacyFamilies = []struct { + code string + name string + suites []uint16 +}{ + {CodeRC4, "RC4", probebase.RC4Suites}, + {CodeTripleDES, "3DES", probebase.TDESSuites}, + {CodeNULL, "NULL (no encryption)", probebase.NULLSuites}, +} + +func offered(suites []uint16, suite uint16) bool { + for _, s := range suites { + if s == suite { + return true + } + } + return false +} + +func suiteName(id uint16) string { + return fmt.Sprintf("%s (0x%04x)", tls.CipherSuiteName(id), id) +} + var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Target, store harnessx.ResultStore) (harnessx.Result, error) { sctx := scanctx.TargetContext(target) @@ -33,7 +72,7 @@ var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Tar Title: "Negotiated cipher suite lacks forward secrecy", Description: "The default TLS handshake negotiated a cipher suite that does not provide forward secrecy, so a compromised private key could decrypt captured past traffic.", Evidence: "negotiated cipher suite: " + name, - Metadata: map[string]string{"cipher_suite": name}, + Metadata: map[string]string{probebase.MetadataCode: CodeNoForwardSecrecy, metadataCipherSuite: name}, }) } } @@ -43,27 +82,43 @@ var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Tar return harnessx.Result{Observations: observations, Err: err}, nil } - weak := insecureSuiteIDs() - if len(weak) > 0 { + for _, family := range legacyFamilies { + hello, err := probeLegacyHello(ctx, host, probebase.VersionTLS12, family.suites) + if err != nil || !offered(family.suites, hello.CipherSuite) { + continue + } + observations = append(observations, harnessx.Observation{ + Title: "Weak cipher suite accepted: " + family.name, + Description: "The target completed a TLS handshake using a " + family.name + " cipher suite, which does not protect the confidentiality of the traffic.", + Evidence: "negotiated cipher suite: " + suiteName(hello.CipherSuite), + Metadata: map[string]string{probebase.MetadataCode: family.code, metadataCipherSuite: suiteName(hello.CipherSuite)}, + }) + } + + if weak := otherInsecureSuiteIDs(); len(weak) > 0 { state, err := probebase.DialTLS(ctx, host, sctx, tls.VersionTLS10, tls.VersionTLS12, weak...) if err == nil && state != nil { observations = append(observations, harnessx.Observation{ Title: "Weak cipher suite accepted", - Description: "The target completed a TLS handshake using a known-weak cipher suite (RC4, 3DES, or a CBC-mode suite).", + Description: "The target completed a TLS handshake using a cipher suite Go marks as insecure (CBC mode with SHA-256).", Evidence: "negotiated cipher suite: " + tls.CipherSuiteName(state.CipherSuite), - Metadata: map[string]string{"cipher_suite": tls.CipherSuiteName(state.CipherSuite)}, + Metadata: map[string]string{probebase.MetadataCode: CodeWeakSuite, metadataCipherSuite: tls.CipherSuiteName(state.CipherSuite)}, }) } } - return harnessx.Result{Observations: observations}, nil -}, checkdef.WithSkip(harnessx.SkipWhen(func(_ context.Context, target harnessx.Target, store harnessx.ResultStore) string { - info, ok := probebase.Info(store) - if !ok || info.Err != nil { - return "target TLS handshake failed — see probe.tls_info" + if hello, err := probeLegacyHello(ctx, host, probebase.VersionTLS12, probebase.DHESuites); err == nil && probebase.IsDHESuite(hello.CipherSuite) && hello.DHPrimeBits > 0 && hello.DHPrimeBits < MinDHPrimeBits { + bits := strconv.Itoa(hello.DHPrimeBits) + observations = append(observations, harnessx.Observation{ + Title: "Weak Diffie-Hellman group accepted", + Description: "The target negotiated a DHE cipher suite with a Diffie-Hellman group below 2048 bits, which can be broken by a well-resourced attacker (Logjam).", + Evidence: "DH prime: " + bits + " bits, cipher suite: " + suiteName(hello.CipherSuite), + Metadata: map[string]string{probebase.MetadataCode: CodeWeakDH, "dh_bits": bits, metadataCipherSuite: suiteName(hello.CipherSuite)}, + }) } - return "" -}))) + + return harnessx.Result{Observations: observations}, nil +}, checkdef.WithSkip(probebase.SkipUnlessHandshake())) // hasForwardSecrecy reports whether the negotiated cipher suite provides // forward secrecy. TLS 1.3 suites are always forward-secret (fixed ECDHE @@ -76,15 +131,13 @@ func hasForwardSecrecy(cipherSuiteName string, version uint16) bool { return strings.Contains(cipherSuiteName, "ECDHE") || strings.Contains(cipherSuiteName, "DHE") } -// insecureSuiteIDs returns the IDs of cipher suites Go's crypto/tls -// implements but marks insecure (RC4, 3DES, CBC-mode, ...) — excluded from -// the client's default offer, so they must be requested explicitly to test -// whether the server still accepts them. -func insecureSuiteIDs() []uint16 { - suites := tls.InsecureCipherSuites() - ids := make([]uint16, len(suites)) - for i, s := range suites { - ids[i] = s.ID +func otherInsecureSuiteIDs() []uint16 { + var ids []uint16 + for _, s := range tls.InsecureCipherSuites() { + if strings.Contains(s.Name, "RC4") || strings.Contains(s.Name, "3DES") { + continue + } + ids = append(ids, s.ID) } return ids } diff --git a/proxy/checks/tls/cipher_strength/check.yaml b/proxy/checks/tls/cipher_strength/check.yaml index 01fe610..30ccd2d 100644 --- a/proxy/checks/tls/cipher_strength/check.yaml +++ b/proxy/checks/tls/cipher_strength/check.yaml @@ -1,6 +1,6 @@ id: "tls.cipher_strength" name: "Weak Cipher Suite or Missing Forward Secrecy" -description: "Inspects the negotiated cipher suite for known-weak ciphers (RC4, 3DES, CBC-mode) and for support of forward secrecy (ECDHE/DHE key exchange)." +description: "Inspects the negotiated cipher suite for forward secrecy and probes for weak cipher suites (RC4, 3DES, NULL, CBC-mode) and Diffie-Hellman groups below 2048 bits." link: "https://ciphersuite.info/" tags: - tls @@ -8,6 +8,6 @@ tags: depends_on: - "probe.tls_info" cvss_vector: "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N" -cvss_score: 4.8 +cvss_score: 6.9 cwe_id: "CWE-327" owasp: "API8:2023" diff --git a/proxy/checks/tls/cipher_strength/check_internal_test.go b/proxy/checks/tls/cipher_strength/check_internal_test.go new file mode 100644 index 0000000..8047750 --- /dev/null +++ b/proxy/checks/tls/cipher_strength/check_internal_test.go @@ -0,0 +1,40 @@ +package cipherstrength + +import ( + "context" + "crypto/tls" + "errors" + "testing" + + "github.com/cerberauth/harnessx" + "github.com/stretchr/testify/assert" + + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +func TestCheck_LegacySuitesAndWeakDH(t *testing.T) { + t.Cleanup(func() { probeLegacyHello = probebase.ProbeLegacyHello }) + probeLegacyHello = func(_ context.Context, _ string, _ uint16, suites []uint16) (*probebase.LegacyHello, error) { + switch suites[0] { + case probebase.NULLSuites[0]: + return &probebase.LegacyHello{Version: probebase.VersionTLS12, CipherSuite: 0x0002}, nil + case probebase.DHESuites[0]: + return &probebase.LegacyHello{Version: probebase.VersionTLS12, CipherSuite: 0x0033, DHPrimeBits: 1024}, nil + case probebase.RC4Suites[0]: + return &probebase.LegacyHello{Version: probebase.VersionTLS12, CipherSuite: 0x002f}, nil + } + return nil, errors.New("rejected") + } + store := harnessx.NewStaticResultStore(harnessx.ResultData(probebase.TLSInfoCheckID, &probebase.TLSInfo{ + ConnState: &tls.ConnectionState{Version: tls.VersionTLS13, CipherSuite: tls.TLS_AES_128_GCM_SHA256}, + })) + + result, err := Check.Run(context.Background(), harnessx.Target{URL: "https://127.0.0.1:1"}, store) + + assert.NoError(t, err) + var codes []string + for _, o := range result.Observations { + codes = append(codes, o.Metadata["code"]) + } + assert.ElementsMatch(t, []string{CodeNULL, CodeWeakDH}, codes) +} diff --git a/proxy/checks/tls/https_redirect/check.go b/proxy/checks/tls/https_redirect/check.go index 09b3272..2cd89c6 100644 --- a/proxy/checks/tls/https_redirect/check.go +++ b/proxy/checks/tls/https_redirect/check.go @@ -11,6 +11,7 @@ import ( "github.com/cerberauth/harnessx" "github.com/cerberauth/harnessx/checkdef" + "github.com/cerberauth/proxyaudit/proxy/probebase" "github.com/cerberauth/proxyaudit/proxy/scanctx" ) @@ -19,6 +20,11 @@ var checkYAML []byte var Def = checkdef.MustParseCheckDefYAML("https_redirect", checkYAML) +const ( + CodeNotRedirected = "https_redirect.not_redirected" + CodeNotHTTPS = "https_redirect.not_https" +) + var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Target, _ harnessx.ResultStore) (harnessx.Result, error) { sctx := scanctx.TargetContext(target) @@ -54,11 +60,16 @@ var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Tar } defer resp.Body.Close() - if resp.StatusCode < 300 || resp.StatusCode >= 400 { + if resp.StatusCode >= 400 { + return harnessx.Result{}, nil + } + + if resp.StatusCode < 300 { return harnessx.Result{Observations: []harnessx.Observation{{ Title: "Plain HTTP request is not redirected to HTTPS", Description: "A plain-HTTP request to the target received a non-redirect response instead of being redirected to HTTPS, allowing traffic to be sent (and intercepted) unencrypted.", Evidence: fmt.Sprintf("GET %s -> %d", httpURL.String(), resp.StatusCode), + Metadata: map[string]string{probebase.MetadataCode: CodeNotRedirected}, }}}, nil } @@ -69,6 +80,7 @@ var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Tar Title: "HTTP redirect does not point to HTTPS", Description: "A plain-HTTP request to the target was redirected, but not to an https:// URL.", Evidence: "Location: " + location, + Metadata: map[string]string{probebase.MetadataCode: CodeNotHTTPS}, }}}, nil } diff --git a/proxy/checks/tls/https_redirect/check.yaml b/proxy/checks/tls/https_redirect/check.yaml index aebaa6c..c0d946b 100644 --- a/proxy/checks/tls/https_redirect/check.yaml +++ b/proxy/checks/tls/https_redirect/check.yaml @@ -6,6 +6,6 @@ tags: - tls - transport cvss_vector: "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N" -cvss_score: 5.3 +cvss_score: 6.9 cwe_id: "CWE-319" owasp: "API8:2023" diff --git a/proxy/checks/tls/protocol_version/check.go b/proxy/checks/tls/protocol_version/check.go index ea2d8d6..e6e2e15 100644 --- a/proxy/checks/tls/protocol_version/check.go +++ b/proxy/checks/tls/protocol_version/check.go @@ -1,14 +1,13 @@ // Package protocolversion checks whether the target still accepts -// deprecated TLS protocol versions (TLS 1.0/1.1) — Go's crypto/tls no -// longer implements SSLv3, so that version can't be probed directly, but -// a server still offering it would also offer TLS 1.0/1.1 in virtually -// every real deployment, which this check does detect. +// deprecated protocol versions: SSL 3.0 through a raw ClientHello, and +// TLS 1.0/1.1 through crypto/tls. package protocolversion import ( "context" "crypto/tls" _ "embed" + "strings" "github.com/cerberauth/harnessx" "github.com/cerberauth/harnessx/checkdef" @@ -32,6 +31,10 @@ var deprecatedVersions = []struct { {"TLS 1.1", tls.VersionTLS11}, } +const CodeLegacyEnabled = "protocol.legacy_enabled" + +var probeLegacyHello = probebase.ProbeLegacyHello + var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Target, store harnessx.ResultStore) (harnessx.Result, error) { sctx := scanctx.TargetContext(target) @@ -40,42 +43,24 @@ var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Tar return harnessx.Result{Err: err}, nil } - var observations []harnessx.Observation + var accepted []string + if hello, err := probeLegacyHello(ctx, host, probebase.VersionSSL30, probebase.SSL3Suites); err == nil && hello.Version == probebase.VersionSSL30 { + accepted = append(accepted, "SSL 3.0") + } for _, v := range deprecatedVersions { - state, err := probebase.DialTLS(ctx, host, sctx, v.version, v.version) - if err != nil { - // Handshake failure at this forced version means the server - // rejected it — the desired, secure outcome. - continue + if _, err := probebase.DialTLS(ctx, host, sctx, v.version, v.version, probebase.AllCipherSuites()...); err == nil { + accepted = append(accepted, v.name) } - observations = append(observations, harnessx.Observation{ - Title: "Deprecated TLS version accepted: " + v.name, - Description: "The target completed a TLS handshake using " + v.name + ", a deprecated protocol version with known weaknesses.", - Evidence: "negotiated version: " + tlsVersionName(state.Version), - Metadata: map[string]string{"tls_version": v.name}, - }) } - - return harnessx.Result{Observations: observations}, nil -}, checkdef.WithSkip(harnessx.SkipWhen(func(_ context.Context, target harnessx.Target, store harnessx.ResultStore) string { - info, ok := probebase.Info(store) - if !ok || info.Err != nil { - return "target TLS handshake failed — see probe.tls_info" + if len(accepted) == 0 { + return harnessx.Result{}, nil } - return "" -}))) -func tlsVersionName(v uint16) string { - switch v { - case tls.VersionTLS10: - return "TLS 1.0" - case tls.VersionTLS11: - return "TLS 1.1" - case tls.VersionTLS12: - return "TLS 1.2" - case tls.VersionTLS13: - return "TLS 1.3" - default: - return "unknown" - } -} + versions := strings.Join(accepted, ", ") + return harnessx.Result{Observations: []harnessx.Observation{{ + Title: "Deprecated protocol versions accepted: " + versions, + Description: "The target completed a handshake using deprecated protocol versions with known weaknesses (POODLE, BEAST and the downgrade attacks they enable).", + Evidence: "accepted versions: " + versions, + Metadata: map[string]string{probebase.MetadataCode: CodeLegacyEnabled, "versions": versions}, + }}}, nil +}, checkdef.WithSkip(probebase.SkipUnlessHandshake())) diff --git a/proxy/checks/tls/protocol_version/check.yaml b/proxy/checks/tls/protocol_version/check.yaml index 91f40d1..c29aada 100644 --- a/proxy/checks/tls/protocol_version/check.yaml +++ b/proxy/checks/tls/protocol_version/check.yaml @@ -1,6 +1,6 @@ id: "tls.protocol_version" name: "Weak TLS Protocol Version Accepted" -description: "Tests whether the proxy still accepts deprecated TLS versions (TLS 1.0/1.1) alongside modern ones." +description: "Tests whether the proxy still accepts deprecated protocol versions (SSL 3.0, TLS 1.0, TLS 1.1) alongside modern ones." link: "https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security" tags: - tls @@ -8,6 +8,6 @@ tags: depends_on: - "probe.tls_info" cvss_vector: "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N" -cvss_score: 5.3 +cvss_score: 6.9 cwe_id: "CWE-326" owasp: "API8:2023" diff --git a/proxy/checks/tls/protocol_version/check_internal_test.go b/proxy/checks/tls/protocol_version/check_internal_test.go new file mode 100644 index 0000000..ac534ed --- /dev/null +++ b/proxy/checks/tls/protocol_version/check_internal_test.go @@ -0,0 +1,26 @@ +package protocolversion + +import ( + "context" + "testing" + + "github.com/cerberauth/harnessx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +func TestCheck_SSL30Accepted(t *testing.T) { + t.Cleanup(func() { probeLegacyHello = probebase.ProbeLegacyHello }) + probeLegacyHello = func(context.Context, string, uint16, []uint16) (*probebase.LegacyHello, error) { + return &probebase.LegacyHello{Version: probebase.VersionSSL30, CipherSuite: 0x000a}, nil + } + + result, err := Check.Run(context.Background(), harnessx.Target{URL: "https://127.0.0.1:1"}, harnessx.NewStaticResultStore()) + + require.NoError(t, err) + require.Len(t, result.Observations, 1) + assert.Equal(t, CodeLegacyEnabled, result.Observations[0].Metadata["code"]) + assert.Equal(t, "SSL 3.0", result.Observations[0].Metadata["versions"]) +} diff --git a/proxy/checks/tls/tls_test.go b/proxy/checks/tls/tls_test.go index 07ed811..3447810 100644 --- a/proxy/checks/tls/tls_test.go +++ b/proxy/checks/tls/tls_test.go @@ -73,7 +73,7 @@ func TestCertificate_UntrustedChain_Flagged(t *testing.T) { obs := runEngine(t, target, certificate.Check) require.NotEmpty(t, obs) - assert.Contains(t, obs[0].Title, "chain does not verify") + assert.Equal(t, certificate.CodeSelfSigned, obs[0].Metadata["code"]) } func TestCipherStrength_ModernServer_HasForwardSecrecy(t *testing.T) { @@ -118,6 +118,21 @@ func TestHTTPSRedirect_NoRedirect_Flagged(t *testing.T) { assert.Contains(t, summary.Observations[0].Title, "not redirected to HTTPS") } +func TestHTTPSRedirect_PlainHTTPRejected_NoFindings(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "Client sent an HTTP request to an HTTPS server.", http.StatusBadRequest) + })) + defer srv.Close() + + httpsURL := "https" + srv.URL[len("http"):] + target := scanctx.NewTarget(httpsURL, &scanctx.ScanContext{HTTPClient: srv.Client()}) + + engine := harnessx.New(harnessx.WithChecks(httpsredirect.Check)) + summary, err := engine.Run(context.Background(), target) + require.NoError(t, err) + assert.Empty(t, summary.Observations) +} + func TestHTTPSRedirect_RedirectsToHTTPS_NoFindings(t *testing.T) { var httpsHost string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/proxy/checks/tls/variants_test.go b/proxy/checks/tls/variants_test.go new file mode 100644 index 0000000..b56efa5 --- /dev/null +++ b/proxy/checks/tls/variants_test.go @@ -0,0 +1,209 @@ +package tls_test + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/cerberauth/harnessx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cerberauth/proxyaudit/proxy/checks/tls/certificate" + cipherstrength "github.com/cerberauth/proxyaudit/proxy/checks/tls/cipher_strength" + protocolversion "github.com/cerberauth/proxyaudit/proxy/checks/tls/protocol_version" + "github.com/cerberauth/proxyaudit/proxy/probebase" + "github.com/cerberauth/proxyaudit/proxy/scanctx" +) + +const localIP = "127.0.0.1" + +type issuer struct { + cert *x509.Certificate + key *ecdsa.PrivateKey +} + +func newCA(t *testing.T) issuer { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "Test CA"}, + NotBefore: time.Now().Add(-48 * time.Hour), + NotAfter: time.Now().Add(48 * time.Hour), + IsCA: true, + BasicConstraintsValid: true, + KeyUsage: x509.KeyUsageCertSign, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + require.NoError(t, err) + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + return issuer{cert: cert, key: key} +} + +func newLeaf(t *testing.T, ca *issuer, notBefore, notAfter time.Time) tls.Certificate { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + template := &x509.Certificate{ + SerialNumber: big.NewInt(2), + Subject: pkix.Name{CommonName: localIP}, + NotBefore: notBefore, + NotAfter: notAfter, + IPAddresses: []net.IP{net.ParseIP(localIP)}, + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + parent, signer := template, key + if ca != nil { + parent, signer = ca.cert, ca.key + } + der, err := x509.CreateCertificate(rand.Reader, template, parent, &key.PublicKey, signer) + require.NoError(t, err) + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} +} + +func newServer(t *testing.T, config *tls.Config) *httptest.Server { + t.Helper() + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + srv.TLS = config + srv.StartTLS() + t.Cleanup(srv.Close) + return srv +} + +func codes(observations []harnessx.Observation) []string { + var result []string + for _, o := range observations { + result = append(result, o.Metadata["code"]) + } + return result +} + +func TestCertificate_Variants(t *testing.T) { + ca := newCA(t) + other := newCA(t) + now := time.Now() + roots := x509.NewCertPool() + roots.AddCert(ca.cert) + + testCases := []struct { + name string + leaf tls.Certificate + host string + expected []string + absent []string + }{ + {"valid", newLeaf(t, &ca, now.Add(-time.Hour), now.Add(90*24*time.Hour)), localIP, nil, []string{certificate.CodeUntrustedChain, certificate.CodeSelfSigned, certificate.CodeHostnameMismatch, certificate.CodeExpired, certificate.CodeExpiresSoon}}, + {"expired", newLeaf(t, &ca, now.Add(-48*time.Hour), now.Add(-time.Hour)), localIP, []string{certificate.CodeExpired}, []string{certificate.CodeUntrustedChain, certificate.CodeHostnameMismatch}}, + {"expires soon", newLeaf(t, &ca, now.Add(-time.Hour), now.Add(24*time.Hour)), localIP, []string{certificate.CodeExpiresSoon}, []string{certificate.CodeExpired}}, + {"self-signed", newLeaf(t, nil, now.Add(-time.Hour), now.Add(90*24*time.Hour)), localIP, []string{certificate.CodeSelfSigned}, []string{certificate.CodeUntrustedChain}}, + {"untrusted issuer", newLeaf(t, &other, now.Add(-time.Hour), now.Add(90*24*time.Hour)), localIP, []string{certificate.CodeUntrustedChain}, []string{certificate.CodeSelfSigned}}, + {"wrong host", newLeaf(t, &ca, now.Add(-time.Hour), now.Add(90*24*time.Hour)), "localhost", []string{certificate.CodeHostnameMismatch}, []string{certificate.CodeUntrustedChain, certificate.CodeExpired}}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + srv := newServer(t, &tls.Config{Certificates: []tls.Certificate{tc.leaf}}) + url := strings.Replace(srv.URL, localIP, tc.host, 1) + + got := codes(runEngine(t, scanctx.NewTarget(url, &scanctx.ScanContext{RootCAs: roots}), certificate.Check)) + + for _, code := range tc.expected { + assert.Contains(t, got, code) + } + for _, code := range tc.absent { + assert.NotContains(t, got, code) + } + }) + } +} + +func TestProtocolVersion_MinimumVersion(t *testing.T) { + rsaKeyExchangeOnly := []uint16{tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA} + testCases := []struct { + name string + minVersion uint16 + cipherSuites []uint16 + versions string + }{ + {"TLS 1.0 allowed", tls.VersionTLS10, nil, "TLS 1.0, TLS 1.1"}, + {"TLS 1.1 allowed", tls.VersionTLS11, nil, "TLS 1.1"}, + {"TLS 1.2 minimum", tls.VersionTLS12, nil, ""}, + {"TLS 1.0 with RSA key exchange only", tls.VersionTLS10, rsaKeyExchangeOnly, "TLS 1.0, TLS 1.1"}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {})) + srv.TLS = &tls.Config{MinVersion: tc.minVersion, CipherSuites: tc.cipherSuites} + srv.StartTLS() + t.Cleanup(srv.Close) + + obs := runEngine(t, newTLSTarget(t, srv), protocolversion.Check) + + if tc.versions == "" { + assert.Empty(t, obs) + return + } + require.Len(t, obs, 1) + assert.Equal(t, protocolversion.CodeLegacyEnabled, obs[0].Metadata["code"]) + assert.Equal(t, tc.versions, obs[0].Metadata["versions"]) + }) + } +} + +func skipReasons(t *testing.T, target harnessx.Target) map[harnessx.CheckID]string { + t.Helper() + engine := harnessx.New(harnessx.WithChecks(probebase.TLSInfoCheck, certificate.Check, protocolversion.Check, cipherstrength.Check)) + summary, err := engine.Run(context.Background(), target) + require.NoError(t, err) + reasons := map[harnessx.CheckID]string{} + for _, r := range summary.Results { + if r.Skipped { + reasons[r.CheckID] = r.SkipReason + } + } + return reasons +} + +func TestTLSChecks_SkipWithReason(t *testing.T) { + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {})) + t.Cleanup(plain.Close) + closed, err := net.Listen("tcp", localIP+":0") + require.NoError(t, err) + closedAddr := closed.Addr().String() + require.NoError(t, closed.Close()) + + testCases := []struct { + name string + url string + reason string + }{ + {"plain HTTP URL", plain.URL, "target URL uses plain HTTP, no TLS to inspect"}, + {"plain HTTP port", strings.Replace(plain.URL, "http://", "https://", 1), "target port does not speak TLS (plain HTTP)"}, + {"closed port", "https://" + closedAddr, "target port is closed or unreachable"}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + reasons := skipReasons(t, scanctx.NewTarget(tc.url, nil)) + + for _, id := range []harnessx.CheckID{certificate.Check.ID, protocolversion.Check.ID, cipherstrength.Check.ID} { + assert.Equal(t, tc.reason, reasons[id], id) + } + }) + } +} diff --git a/proxy/probebase/legacytls.go b/proxy/probebase/legacytls.go new file mode 100644 index 0000000..d41752b --- /dev/null +++ b/proxy/probebase/legacytls.go @@ -0,0 +1,235 @@ +package probebase + +import ( + "context" + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "time" +) + +const ( + VersionSSL30 uint16 = 0x0300 + VersionTLS12 uint16 = 0x0303 +) + +var ( + RC4Suites = []uint16{0x0004, 0x0005, 0xc007, 0xc011} + TDESSuites = []uint16{0x000a, 0x0016, 0xc012} + NULLSuites = []uint16{0x0001, 0x0002, 0x003b, 0xc010} + DHESuites = []uint16{0x0033, 0x0039, 0x0067, 0x006b, 0x009e, 0x009f, 0xccaa} + SSL3Suites = []uint16{0x0004, 0x0005, 0x000a, 0x0016, 0x002f, 0x0033, 0x0035, 0x0039} +) + +var ErrHandshakeRejected = errors.New("handshake rejected") + +type LegacyHello struct { + Version uint16 + CipherSuite uint16 + DHPrimeBits int +} + +const ( + recordHandshake = 0x16 + recordAlert = 0x15 + + handshakeServerHello = 0x02 + handshakeServerKeyExchange = 0x0c + handshakeServerHelloDone = 0x0e + + maxLegacyResponse = 64 * 1024 +) + +func IsDHESuite(suite uint16) bool { + for _, s := range DHESuites { + if s == suite { + return true + } + } + return suite == 0x0016 +} + +func appendUint16(b []byte, v uint16) []byte { + return binary.BigEndian.AppendUint16(b, v) +} + +func appendUint24(b []byte, v int) []byte { + return append(b, byte(v>>16), byte(v>>8), byte(v)) //nolint:gosec +} + +func appendExtension(b []byte, extType uint16, data []byte) []byte { + b = appendUint16(b, extType) + b = appendUint16(b, uint16(len(data))) //nolint:gosec + return append(b, data...) +} + +func BuildClientHello(version uint16, suites []uint16, serverName string) ([]byte, error) { + random := make([]byte, 32) + if _, err := rand.Read(random); err != nil { + return nil, err + } + + body := appendUint16(nil, version) + body = append(body, random...) + body = append(body, 0) + body = appendUint16(body, uint16(2*len(suites))) //nolint:gosec + for _, s := range suites { + body = appendUint16(body, s) + } + body = append(body, 1, 0) + + if version > VersionSSL30 { + var extensions []byte + if serverName != "" && net.ParseIP(serverName) == nil { + name := appendUint16(nil, uint16(len(serverName)+3)) //nolint:gosec + name = append(name, 0) + name = appendUint16(name, uint16(len(serverName))) //nolint:gosec + name = append(name, serverName...) + extensions = appendExtension(extensions, 0x0000, name) + } + extensions = appendExtension(extensions, 0x000a, []byte{0x00, 0x06, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18}) + extensions = appendExtension(extensions, 0x000b, []byte{0x01, 0x00}) + if version >= VersionTLS12 { + extensions = appendExtension(extensions, 0x000d, []byte{0x00, 0x0a, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x02, 0x01, 0x04, 0x03}) + } + extensions = appendExtension(extensions, 0xff01, []byte{0x00}) + body = appendUint16(body, uint16(len(extensions))) //nolint:gosec + body = append(body, extensions...) + } + + handshake := append([]byte{0x01}, appendUint24(nil, len(body))...) + handshake = append(handshake, body...) + + recordVersion := uint16(0x0301) + if version == VersionSSL30 { + recordVersion = VersionSSL30 + } + record := []byte{recordHandshake} + record = appendUint16(record, recordVersion) + record = appendUint16(record, uint16(len(handshake))) //nolint:gosec + return append(record, handshake...), nil +} + +func ProbeLegacyHello(ctx context.Context, host string, version uint16, suites []uint16) (*LegacyHello, error) { + hostname, _, err := net.SplitHostPort(host) + if err != nil { + hostname = host + } + hello, err := BuildClientHello(version, suites, hostname) + if err != nil { + return nil, err + } + + dialer := &net.Dialer{Timeout: DialTimeout} + conn, err := dialer.DialContext(ctx, "tcp", host) + if err != nil { + return nil, err + } + defer conn.Close() + deadline := time.Now().Add(DialTimeout) + if d, ok := ctx.Deadline(); ok && d.Before(deadline) { + deadline = d + } + _ = conn.SetDeadline(deadline) + + if _, err := conn.Write(hello); err != nil { + return nil, err + } + return ReadLegacyServerHello(conn) +} + +func ReadLegacyServerHello(r io.Reader) (*LegacyHello, error) { + r = io.LimitReader(r, maxLegacyResponse) + var result *LegacyHello + var buffer []byte + header := make([]byte, 5) + for { + if _, err := io.ReadFull(r, header); err != nil { + if result != nil { + return result, nil + } + return nil, fmt.Errorf("%w: %v", ErrHandshakeRejected, err) + } + length := int(binary.BigEndian.Uint16(header[3:5])) + payload := make([]byte, length) + if _, err := io.ReadFull(r, payload); err != nil { + return result, nil + } + switch header[0] { + case recordAlert: + if result != nil { + return result, nil + } + return nil, ErrHandshakeRejected + case recordHandshake: + default: + if result != nil { + return result, nil + } + return nil, fmt.Errorf("%w: unexpected record type %d", ErrHandshakeRejected, header[0]) + } + + buffer = append(buffer, payload...) + for len(buffer) >= 4 { + msgLength := int(buffer[1])<<16 | int(buffer[2])<<8 | int(buffer[3]) + if len(buffer) < 4+msgLength { + break + } + msgType, msg := buffer[0], buffer[4:4+msgLength] + buffer = buffer[4+msgLength:] + switch msgType { + case handshakeServerHello: + hello, err := parseServerHello(msg) + if err != nil { + return nil, err + } + result = hello + if !IsDHESuite(hello.CipherSuite) { + return result, nil + } + case handshakeServerKeyExchange: + if result != nil && len(msg) >= 2 { + result.DHPrimeBits = primeBits(msg[2:], int(binary.BigEndian.Uint16(msg[:2]))) + } + return result, nil + case handshakeServerHelloDone: + return result, nil + } + } + } +} + +func parseServerHello(msg []byte) (*LegacyHello, error) { + if len(msg) < 35 { + return nil, errors.New("short server hello") + } + sessionIDLength := int(msg[34]) + if len(msg) < 35+sessionIDLength+2 { + return nil, errors.New("short server hello") + } + return &LegacyHello{ + Version: binary.BigEndian.Uint16(msg[:2]), + CipherSuite: binary.BigEndian.Uint16(msg[35+sessionIDLength:]), + }, nil +} + +func primeBits(p []byte, length int) int { + if length > len(p) { + length = len(p) + } + p = p[:length] + for len(p) > 0 && p[0] == 0 { + p = p[1:] + } + if len(p) == 0 { + return 0 + } + bits := 8 * len(p) + for b := p[0]; b&0x80 == 0; b <<= 1 { + bits-- + } + return bits +} diff --git a/proxy/probebase/legacytls_test.go b/proxy/probebase/legacytls_test.go new file mode 100644 index 0000000..2184d05 --- /dev/null +++ b/proxy/probebase/legacytls_test.go @@ -0,0 +1,112 @@ +package probebase_test + +import ( + "bytes" + "context" + "encoding/binary" + "io" + "net" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +func record(contentType byte, payload []byte) []byte { + out := []byte{contentType, 0x03, 0x03} + out = binary.BigEndian.AppendUint16(out, uint16(len(payload))) //nolint:gosec + return append(out, payload...) +} + +func handshake(msgType byte, body []byte) []byte { + return append([]byte{msgType, byte(len(body) >> 16), byte(len(body) >> 8), byte(len(body))}, body...) //nolint:gosec +} + +func serverHello(version, suite uint16) []byte { + body := binary.BigEndian.AppendUint16(nil, version) + body = append(body, make([]byte, 32)...) + body = append(body, 0) + body = binary.BigEndian.AppendUint16(body, suite) + body = append(body, 0) + return handshake(0x02, body) +} + +func serverKeyExchange(primeBytes int) []byte { + prime := bytes.Repeat([]byte{0xff}, primeBytes) + body := binary.BigEndian.AppendUint16(nil, uint16(len(prime))) //nolint:gosec + body = append(body, prime...) + body = append(body, 0x00, 0x01, 0x02, 0x00, 0x01, 0x05) + return handshake(0x0c, body) +} + +func TestReadLegacyServerHello(t *testing.T) { + dhe := append(serverHello(probebase.VersionTLS12, 0x0033), handshake(0x0b, []byte{0, 0, 0})...) + dhe = append(dhe, serverKeyExchange(128)...) + + testCases := []struct { + name string + response []byte + expected *probebase.LegacyHello + err error + }{ + {"SSL 3.0 accepted", record(0x16, serverHello(probebase.VersionSSL30, 0x000a)), &probebase.LegacyHello{Version: probebase.VersionSSL30, CipherSuite: 0x000a}, nil}, + {"DHE fragmented across records", append(record(0x16, dhe[:20]), record(0x16, dhe[20:])...), &probebase.LegacyHello{Version: probebase.VersionTLS12, CipherSuite: 0x0033, DHPrimeBits: 1024}, nil}, + {"alert", record(0x15, []byte{0x02, 0x28}), nil, probebase.ErrHandshakeRejected}, + {"connection closed", nil, nil, probebase.ErrHandshakeRejected}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + hello, err := probebase.ReadLegacyServerHello(bytes.NewReader(tc.response)) + + if tc.err != nil { + assert.ErrorIs(t, err, tc.err) + return + } + require.NoError(t, err) + assert.Equal(t, tc.expected, hello) + }) + } +} + +func TestBuildClientHello(t *testing.T) { + hello, err := probebase.BuildClientHello(probebase.VersionSSL30, []uint16{0x000a}, "example.com") + require.NoError(t, err) + + assert.Equal(t, byte(0x16), hello[0]) + assert.Equal(t, probebase.VersionSSL30, binary.BigEndian.Uint16(hello[1:3])) + assert.Equal(t, byte(0x01), hello[5]) + assert.Equal(t, probebase.VersionSSL30, binary.BigEndian.Uint16(hello[9:11])) + assert.NotContains(t, string(hello), "example.com") + + hello, err = probebase.BuildClientHello(probebase.VersionTLS12, probebase.DHESuites, "example.com") + require.NoError(t, err) + assert.Equal(t, uint16(0x0301), binary.BigEndian.Uint16(hello[1:3])) + assert.Contains(t, string(hello), "example.com") +} + +func TestProbeLegacyHello(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = listener.Close() }) + go func() { + conn, err := listener.Accept() + if err != nil { + return + } + defer conn.Close() + header := make([]byte, 5) + if _, err := io.ReadFull(conn, header); err != nil { + return + } + _, _ = io.ReadFull(conn, make([]byte, binary.BigEndian.Uint16(header[3:5]))) + _, _ = conn.Write(record(0x16, serverHello(probebase.VersionSSL30, 0x0005))) + }() + + hello, err := probebase.ProbeLegacyHello(context.Background(), listener.Addr().String(), probebase.VersionSSL30, probebase.SSL3Suites) + + require.NoError(t, err) + assert.Equal(t, probebase.VersionSSL30, hello.Version) + assert.Equal(t, uint16(0x0005), hello.CipherSuite) +} diff --git a/proxy/probebase/tlsinfo.go b/proxy/probebase/tlsinfo.go index 1913b97..c64ccd9 100644 --- a/proxy/probebase/tlsinfo.go +++ b/proxy/probebase/tlsinfo.go @@ -4,6 +4,7 @@ import ( "context" "crypto/tls" "crypto/x509" + "errors" "net" "net/url" "time" @@ -34,6 +35,36 @@ type TLSInfo struct { Err error } +const MetadataCode = "code" + +var ErrPlainHTTPTarget = errors.New("target URL uses plain HTTP") + +// SkipReason explains why the TLS checks cannot inspect the target, or +// returns "" when the handshake succeeded. +func (info *TLSInfo) SkipReason() string { + if info == nil { + return "target TLS handshake did not run — see probe.tls_info" + } + if info.Err == nil { + if info.ConnState == nil { + return "target TLS handshake produced no connection state" + } + return "" + } + var recordErr tls.RecordHeaderError + var opErr *net.OpError + switch { + case errors.Is(info.Err, ErrPlainHTTPTarget): + return "target URL uses plain HTTP, no TLS to inspect" + case errors.As(info.Err, &recordErr): + return "target port does not speak TLS (plain HTTP)" + case errors.As(info.Err, &opErr) && opErr.Op == "dial": + return "target port is closed or unreachable" + default: + return "target TLS handshake failed: " + info.Err.Error() + } +} + // TargetHost extracts host:port (port defaulting to 443) from a target URL. func TargetHost(rawURL string) (string, error) { u, err := url.Parse(rawURL) @@ -56,6 +87,16 @@ func TargetHost(rawURL string) (string, error) { // chain doesn't prevent probing protocol version or cipher suite support. // The connection is closed before returning — proxy only needs handshake // metadata, not a live conn. +// AllCipherSuites lists every cipher suite crypto/tls implements, insecure +// ones included, for probes of deprecated versions. +func AllCipherSuites() []uint16 { + var suites []uint16 + for _, s := range append(tls.CipherSuites(), tls.InsecureCipherSuites()...) { + suites = append(suites, s.ID) + } + return suites +} + func DialTLS(ctx context.Context, host string, sctx *scanctx.ScanContext, minVersion, maxVersion uint16, cipherSuites ...uint16) (*tls.ConnectionState, error) { hostname, _, err := net.SplitHostPort(host) if err != nil { @@ -116,6 +157,10 @@ var TLSInfoCheck = checkdef.NewCheck( func(ctx context.Context, target harnessx.Target, _ harnessx.ResultStore) (harnessx.Result, error) { sctx := scanctx.TargetContext(target) + if u, err := url.Parse(target.URL); err == nil && u.Scheme == "http" { + return harnessx.DataResult(&TLSInfo{Err: ErrPlainHTTPTarget}), nil + } + host, err := TargetHost(target.URL) if err != nil { return harnessx.DataResult(&TLSInfo{Err: err}), nil @@ -140,3 +185,12 @@ var TLSInfoCheck = checkdef.NewCheck( func Info(store harnessx.ResultStore) (*TLSInfo, bool) { return harnessx.GetData[*TLSInfo](store, TLSInfoCheckID) } + +// SkipUnlessHandshake skips a TLS check whose target handshake failed, +// with the reason given by TLSInfo.SkipReason. +func SkipUnlessHandshake() harnessx.SkipDecision { + return harnessx.SkipWhen(func(_ context.Context, _ harnessx.Target, store harnessx.ResultStore) string { + info, _ := Info(store) + return info.SkipReason() + }) +}