diff --git a/README.md b/README.md index 091b1ca..ad0d4b0 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,8 @@ See the [checks reference](https://www.cerberauth.com/docs/proxyaudit/checks/) for the full list with CWE/OWASP mapping and remediation. - **TLS/Transport**: protocol version, cipher strength/forward secrecy, - certificate chain/expiry/hostname/OCSP stapling, HTTP→HTTPS redirect, HSTS. + certificate chain/expiry/hostname/OCSP stapling, Heartbleed, DROWN, ROBOT, + HTTP→HTTPS redirect, HSTS. - **HTTP Security Headers**: CSP, X-Frame-Options/frame-ancestors, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, Server/ X-Powered-By banner disclosure, cookie flags, CORS misconfiguration diff --git a/docs/checks/tls.mdx b/docs/checks/tls.mdx index 6b5c0aa..f3dcde7 100644 --- a/docs/checks/tls.mdx +++ b/docs/checks/tls.mdx @@ -1,25 +1,30 @@ --- title: TLS / Transport -description: Protocol version, cipher strength/forward secrecy, certificate chain/expiry/hostname, OCSP stapling, HTTPS redirect, and HSTS. +description: Protocol version, cipher strength/forward secrecy, certificate chain/expiry/hostname, OCSP stapling, Heartbleed, DROWN, ROBOT, HTTPS redirect, and HSTS. --- | 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.heartbleed` | Heartbleed (CVE-2014-0160) | 8.7 | [CWE-125](https://cwe.mitre.org/data/definitions/125.html) | API8:2023 | +| `tls.drown` | SSLv2 Enabled (DROWN, CVE-2016-0800) | 8.2 | [CWE-327](https://cwe.mitre.org/data/definitions/327.html) | API8:2023 | +| `tls.robot` | RSA Padding Oracle (ROBOT) | 8.2 | [CWE-203](https://cwe.mitre.org/data/definitions/203.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`. + +Heartbleed, DROWN and ROBOT have their own checks below. **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 +32,49 @@ 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. +## `tls.heartbleed` + +Completes a raw TLS 1.2 handshake up to ServerHelloDone, advertising the heartbeat extension. When the server acknowledges the extension, sends one unencrypted heartbeat request declaring a 16-byte payload with none attached. A patched server discards it; a vulnerable one answers with 16 bytes of its process memory, which the probe discards without reading. + +**Remediate:** upgrade OpenSSL to 1.0.1g or later (or build with `-DOPENSSL_NO_HEARTBEATS`), then revoke and reissue the certificate and rotate session secrets. + +## `tls.drown` + +Sends an SSLv2 ClientHello and reports when the server answers with an SSLv2 ServerHello, with the number of cipher specs offered. Any SSLv2 support is reported, since OpenSSL servers negotiated disabled SSLv2 ciphers (CVE-2015-3197). + +**Remediate:** disable SSLv2 on every server sharing the certificate's RSA key, including mail and other non-HTTP services. + +## `tls.robot` + +Runs five RSA key-exchange handshakes in parallel, each sending a ClientKeyExchange whose premaster secret is encrypted with the server's public key and padded differently: correct PKCS#1 v1.5 padding, wrong prefix, misplaced zero separator, missing separator, and wrong protocol version. Each is followed by ChangeCipherSpec and an invalid Finished, then again without them. The server is reported when its responses (alert, connection close, reset or timeout) differ between variants in two consecutive rounds. Servers that do not negotiate RSA key exchange are not affected. + +**Remediate:** disable RSA key-exchange cipher suites (keep ECDHE only, or use TLS 1.3), or upgrade the TLS library to a version with a constant-time RSA decryption path. + +## 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.heartbleed` | `cve.heartbleed` | +| `tls.drown` | `cve.drown` | +| `tls.robot` | `cve.robot` | +| `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.go b/proxy/checks.go index 284e51e..5a65cb6 100644 --- a/proxy/checks.go +++ b/proxy/checks.go @@ -47,9 +47,12 @@ import ( headerssti "github.com/cerberauth/proxyaudit/proxy/checks/templateinjection/header_ssti" "github.com/cerberauth/proxyaudit/proxy/checks/tls/certificate" cipherstrength "github.com/cerberauth/proxyaudit/proxy/checks/tls/cipher_strength" + "github.com/cerberauth/proxyaudit/proxy/checks/tls/drown" + "github.com/cerberauth/proxyaudit/proxy/checks/tls/heartbleed" "github.com/cerberauth/proxyaudit/proxy/checks/tls/hsts" httpsredirect "github.com/cerberauth/proxyaudit/proxy/checks/tls/https_redirect" protocolversion "github.com/cerberauth/proxyaudit/proxy/checks/tls/protocol_version" + "github.com/cerberauth/proxyaudit/proxy/checks/tls/robot" baselinepayloads "github.com/cerberauth/proxyaudit/proxy/checks/waf/baseline_payloads" contenttypeconsistency "github.com/cerberauth/proxyaudit/proxy/checks/waf/content_type_consistency" encodingbypass "github.com/cerberauth/proxyaudit/proxy/checks/waf/encoding_bypass" @@ -73,6 +76,9 @@ func AllChecks() ([]harnessx.Check, map[harnessx.CheckID]checkdef.CheckDef) { certificate.Check, httpsredirect.Check, hsts.Check, + heartbleed.Check, + drown.Check, + robot.Check, // HTTP Security Headers. csp.Check, @@ -140,6 +146,9 @@ func AllChecks() ([]harnessx.Check, map[harnessx.CheckID]checkdef.CheckDef) { certificate.Check.ID: certificate.Def, httpsredirect.Check.ID: httpsredirect.Def, hsts.Check.ID: hsts.Def, + heartbleed.Check.ID: heartbleed.Def, + drown.Check.ID: drown.Def, + robot.Check.ID: robot.Def, csp.Check.ID: csp.Def, frameoptions.Check.ID: frameoptions.Def, 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/drown/check.go b/proxy/checks/tls/drown/check.go new file mode 100644 index 0000000..61ad91b --- /dev/null +++ b/proxy/checks/tls/drown/check.go @@ -0,0 +1,40 @@ +// Package drown checks whether the target still accepts SSLv2, which +// exposes every TLS session sharing its RSA key to DROWN (CVE-2016-0800). +package drown + +import ( + "context" + _ "embed" + "strconv" + + "github.com/cerberauth/harnessx" + "github.com/cerberauth/harnessx/checkdef" + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +//go:embed check.yaml +var checkYAML []byte + +var Def = checkdef.MustParseCheckDefYAML("drown", checkYAML) + +const CodeDROWN = "cve.drown" + +var probeSSLv2 = probebase.ProbeSSLv2 + +var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Target, _ harnessx.ResultStore) (harnessx.Result, error) { + host, err := probebase.TargetHost(target.URL) + if err != nil { + return harnessx.Result{Err: err}, nil + } + hello, err := probeSSLv2(ctx, host) + if err != nil { + return harnessx.Result{}, nil + } + ciphers := strconv.Itoa(hello.CipherSpecs) + return harnessx.Result{Observations: []harnessx.Observation{{ + Title: "SSLv2 enabled (DROWN, CVE-2016-0800)", + Description: "The target answered an SSLv2 ClientHello with an SSLv2 ServerHello. An attacker can use SSLv2 as a Bleichenbacher oracle to decrypt captured TLS sessions protected by the same RSA key, even on other servers sharing that key.", + Evidence: "SSLv2 ServerHello offering " + ciphers + " cipher specs", + Metadata: map[string]string{probebase.MetadataCode: CodeDROWN, "cve": "CVE-2016-0800", "cipher_specs": ciphers}, + }}}, nil +}, checkdef.WithSkip(probebase.SkipUnlessHandshake())) diff --git a/proxy/checks/tls/drown/check.yaml b/proxy/checks/tls/drown/check.yaml new file mode 100644 index 0000000..da18593 --- /dev/null +++ b/proxy/checks/tls/drown/check.yaml @@ -0,0 +1,14 @@ +id: "tls.drown" +name: "SSLv2 Enabled (DROWN, CVE-2016-0800)" +description: "Sends an SSLv2 ClientHello and reports when the server answers with an SSLv2 ServerHello, which lets an attacker decrypt TLS sessions using the same RSA key." +link: "https://drownattack.com/" +tags: + - tls + - transport + - cve +depends_on: + - "probe.tls_info" +cvss_vector: "CVSS:4.0/AV:N/AC:H/AT:P/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N" +cvss_score: 8.2 +cwe_id: "CWE-327" +owasp: "API8:2023" diff --git a/proxy/checks/tls/drown/check_internal_test.go b/proxy/checks/tls/drown/check_internal_test.go new file mode 100644 index 0000000..c5bfbdd --- /dev/null +++ b/proxy/checks/tls/drown/check_internal_test.go @@ -0,0 +1,28 @@ +package drown + +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_SSLv2Accepted(t *testing.T) { + t.Cleanup(func(previous func(context.Context, string) (*probebase.SSLv2Hello, error)) func() { + return func() { probeSSLv2 = previous } + }(probeSSLv2)) + probeSSLv2 = func(context.Context, string) (*probebase.SSLv2Hello, error) { + return &probebase.SSLv2Hello{CipherSpecs: 7}, 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, CodeDROWN, result.Observations[0].Metadata["code"]) + assert.Equal(t, "7", result.Observations[0].Metadata["cipher_specs"]) +} diff --git a/proxy/checks/tls/heartbleed/check.go b/proxy/checks/tls/heartbleed/check.go new file mode 100644 index 0000000..e404752 --- /dev/null +++ b/proxy/checks/tls/heartbleed/check.go @@ -0,0 +1,37 @@ +// Package heartbleed checks whether the target answers a TLS heartbeat +// request declaring a longer payload than it carries (CVE-2014-0160). +package heartbleed + +import ( + "context" + _ "embed" + + "github.com/cerberauth/harnessx" + "github.com/cerberauth/harnessx/checkdef" + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +//go:embed check.yaml +var checkYAML []byte + +var Def = checkdef.MustParseCheckDefYAML("heartbleed", checkYAML) + +const CodeHeartbleed = "cve.heartbleed" + +var probeHeartbleed = probebase.ProbeHeartbleed + +var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Target, _ harnessx.ResultStore) (harnessx.Result, error) { + host, err := probebase.TargetHost(target.URL) + if err != nil { + return harnessx.Result{Err: err}, nil + } + if vulnerable, err := probeHeartbleed(ctx, host); err != nil || !vulnerable { + return harnessx.Result{}, nil + } + return harnessx.Result{Observations: []harnessx.Observation{{ + Title: "Heartbleed (CVE-2014-0160)", + Description: "The target answered a TLS heartbeat request whose declared payload length exceeds the data sent, returning bytes read past the request from its process memory. An attacker can repeat it to read private keys, session cookies and credentials.", + Evidence: "heartbeat request declaring a 16-byte payload with none sent was answered with a heartbeat response (leaked bytes discarded)", + Metadata: map[string]string{probebase.MetadataCode: CodeHeartbleed, "cve": "CVE-2014-0160"}, + }}}, nil +}, checkdef.WithSkip(probebase.SkipUnlessHandshake())) diff --git a/proxy/checks/tls/heartbleed/check.yaml b/proxy/checks/tls/heartbleed/check.yaml new file mode 100644 index 0000000..98a216b --- /dev/null +++ b/proxy/checks/tls/heartbleed/check.yaml @@ -0,0 +1,14 @@ +id: "tls.heartbleed" +name: "Heartbleed (CVE-2014-0160)" +description: "Sends a TLS heartbeat request declaring a longer payload than it carries and reports when the server answers it, leaking process memory such as private keys and session data." +link: "https://heartbleed.com/" +tags: + - tls + - transport + - cve +depends_on: + - "probe.tls_info" +cvss_vector: "CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N" +cvss_score: 8.7 +cwe_id: "CWE-125" +owasp: "API8:2023" diff --git a/proxy/checks/tls/heartbleed/check_internal_test.go b/proxy/checks/tls/heartbleed/check_internal_test.go new file mode 100644 index 0000000..f65cdc3 --- /dev/null +++ b/proxy/checks/tls/heartbleed/check_internal_test.go @@ -0,0 +1,24 @@ +package heartbleed + +import ( + "context" + "testing" + + "github.com/cerberauth/harnessx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCheck_HeartbeatAnswered(t *testing.T) { + t.Cleanup(func(previous func(context.Context, string) (bool, error)) func() { + return func() { probeHeartbleed = previous } + }(probeHeartbleed)) + probeHeartbleed = func(context.Context, string) (bool, error) { return true, 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, CodeHeartbleed, result.Observations[0].Metadata["code"]) + assert.Equal(t, "CVE-2014-0160", result.Observations[0].Metadata["cve"]) +} diff --git a/proxy/checks/tls/https_redirect/check.go b/proxy/checks/tls/https_redirect/check.go index 09b3272..e813e74 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) @@ -59,6 +65,7 @@ var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Tar 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 +76,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..164258f 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,30 +43,27 @@ 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); 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 "" -}))) + + 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())) func tlsVersionName(v uint16) string { switch v { 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/robot/check.go b/proxy/checks/tls/robot/check.go new file mode 100644 index 0000000..f98042a --- /dev/null +++ b/proxy/checks/tls/robot/check.go @@ -0,0 +1,40 @@ +// Package robot checks whether the target's RSA key exchange answers +// well-formed and malformed PKCS#1 v1.5 padding differently (ROBOT). +package robot + +import ( + "context" + _ "embed" + "strings" + + "github.com/cerberauth/harnessx" + "github.com/cerberauth/harnessx/checkdef" + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +//go:embed check.yaml +var checkYAML []byte + +var Def = checkdef.MustParseCheckDefYAML("robot", checkYAML) + +const CodeROBOT = "cve.robot" + +var probeROBOT = probebase.ProbeROBOT + +var Check = checkdef.NewCheck(Def, func(ctx context.Context, target harnessx.Target, _ harnessx.ResultStore) (harnessx.Result, error) { + host, err := probebase.TargetHost(target.URL) + if err != nil { + return harnessx.Result{Err: err}, nil + } + result, err := probeROBOT(ctx, host) + if err != nil || !result.Vulnerable { + return harnessx.Result{}, nil + } + responses := strings.Join(result.Responses, ", ") + return harnessx.Result{Observations: []harnessx.Observation{{ + Title: "RSA padding oracle (ROBOT)", + Description: "The target answered RSA key-exchange handshakes differently depending on the PKCS#1 v1.5 padding of the encrypted premaster secret, consistently across two rounds. An attacker can use this Bleichenbacher oracle to decrypt captured RSA key-exchange sessions or sign with the server's key.", + Evidence: "responses to correct padding, wrong prefix, misplaced zero, missing zero, wrong version: " + responses, + Metadata: map[string]string{probebase.MetadataCode: CodeROBOT, "cve": "CVE-2017-13099", "responses": responses}, + }}}, nil +}, checkdef.WithSkip(probebase.SkipUnlessHandshake())) diff --git a/proxy/checks/tls/robot/check.yaml b/proxy/checks/tls/robot/check.yaml new file mode 100644 index 0000000..4c5efb2 --- /dev/null +++ b/proxy/checks/tls/robot/check.yaml @@ -0,0 +1,14 @@ +id: "tls.robot" +name: "RSA Padding Oracle (ROBOT)" +description: "Sends RSA key-exchange handshakes with well-formed and malformed PKCS#1 v1.5 padding and reports when the server answers them differently, a Bleichenbacher oracle that lets an attacker decrypt RSA key-exchange sessions." +link: "https://robotattack.org/" +tags: + - tls + - transport + - cve +depends_on: + - "probe.tls_info" +cvss_vector: "CVSS:4.0/AV:N/AC:H/AT:P/PR:N/UI:N/VC:H/VI:N/VA:N/SC:N/SI:N/SA:N" +cvss_score: 8.2 +cwe_id: "CWE-203" +owasp: "API8:2023" diff --git a/proxy/checks/tls/robot/check_internal_test.go b/proxy/checks/tls/robot/check_internal_test.go new file mode 100644 index 0000000..95a0577 --- /dev/null +++ b/proxy/checks/tls/robot/check_internal_test.go @@ -0,0 +1,30 @@ +package robot + +import ( + "context" + "testing" + + "github.com/cerberauth/harnessx" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +const decryptError = "alert 2 51" + +func TestCheck_PaddingOracle(t *testing.T) { + t.Cleanup(func(previous func(context.Context, string) (*probebase.RobotResult, error)) func() { + return func() { probeROBOT = previous } + }(probeROBOT)) + probeROBOT = func(context.Context, string) (*probebase.RobotResult, error) { + return &probebase.RobotResult{Vulnerable: true, Responses: []string{"alert 2 20", decryptError, decryptError, decryptError, "alert 2 20"}}, 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, CodeROBOT, result.Observations[0].Metadata["code"]) + assert.Contains(t, result.Observations[0].Evidence, decryptError) +} diff --git a/proxy/checks/tls/tls_test.go b/proxy/checks/tls/tls_test.go index 07ed811..1afa883 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) { diff --git a/proxy/checks/tls/variants_test.go b/proxy/checks/tls/variants_test.go new file mode 100644 index 0000000..330376b --- /dev/null +++ b/proxy/checks/tls/variants_test.go @@ -0,0 +1,236 @@ +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" + "github.com/cerberauth/proxyaudit/proxy/checks/tls/drown" + "github.com/cerberauth/proxyaudit/proxy/checks/tls/heartbleed" + protocolversion "github.com/cerberauth/proxyaudit/proxy/checks/tls/protocol_version" + "github.com/cerberauth/proxyaudit/proxy/checks/tls/robot" + "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) { + testCases := []struct { + name string + minVersion uint16 + versions string + }{ + {"TLS 1.0 allowed", tls.VersionTLS10, "TLS 1.0, TLS 1.1"}, + {"TLS 1.1 allowed", tls.VersionTLS11, "TLS 1.1"}, + {"TLS 1.2 minimum", tls.VersionTLS12, ""}, + } + 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} + 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, heartbleed.Check, drown.Check, robot.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, heartbleed.Check.ID, drown.Check.ID, robot.Check.ID} { + assert.Equal(t, tc.reason, reasons[id], id) + } + }) + } +} + +func TestKnownCVEs_ModernServer_NoFindings(t *testing.T) { + testCases := []struct { + name string + config *tls.Config + }{ + {"default", nil}, + {"rsa key exchange", &tls.Config{MaxVersion: tls.VersionTLS12, CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_AES_128_CBC_SHA}}}, //nolint:gosec + } + 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 = tc.config + srv.StartTLS() + t.Cleanup(srv.Close) + + engine := harnessx.New(harnessx.WithChecks(probebase.TLSInfoCheck, heartbleed.Check, drown.Check, robot.Check)) + summary, err := engine.Run(context.Background(), newTLSTarget(t, srv)) + + require.NoError(t, err) + assert.Empty(t, summary.Observations) + for _, result := range summary.Results { + assert.False(t, result.Skipped, result.CheckID) + } + }) + } +} diff --git a/proxy/probebase/export_test.go b/proxy/probebase/export_test.go new file mode 100644 index 0000000..5d50ef6 --- /dev/null +++ b/proxy/probebase/export_test.go @@ -0,0 +1,3 @@ +package probebase + +var RobotResponseTimeout = &robotResponseTimeout diff --git a/proxy/probebase/heartbleed.go b/proxy/probebase/heartbleed.go new file mode 100644 index 0000000..0fd9ee0 --- /dev/null +++ b/proxy/probebase/heartbleed.go @@ -0,0 +1,81 @@ +package probebase + +import ( + "context" + "crypto/tls" + "encoding/binary" + "errors" + "io" + "slices" + "time" +) + +const extensionHeartbeat uint16 = 0x000f + +const heartbeatOverread = 16 + +const heartbeatResponseTimeout = 3 * time.Second + +func HeartbeatRequest(version uint16) []byte { + return appendRecord(nil, recordHeartbeat, version, []byte{0x01, 0x00, heartbeatOverread}) +} + +func ProbeHeartbleed(ctx context.Context, host string) (bool, error) { + suites := append(slices.Clone(RSASuites), DHESuites...) + for _, s := range append(tls.CipherSuites(), tls.InsecureCipherSuites()...) { + suites = append(suites, s.ID) + } + slices.Sort(suites) + suites = slices.Compact(suites) + hello, err := buildClientHello(VersionTLS12, suites, hostnameOf(host), appendExtension(nil, extensionHeartbeat, []byte{0x01})) + if err != nil { + return false, err + } + + conn, err := dialRaw(ctx, host) + if err != nil { + return false, err + } + defer conn.Close() + + if _, err := conn.Write(hello); err != nil { + return false, err + } + flight, err := ReadServerFlight(conn) + if err != nil { + if errors.Is(err, ErrHandshakeRejected) { + return false, nil + } + return false, err + } + if _, ok := flight.Extensions[extensionHeartbeat]; !ok { + return false, nil + } + + if _, err := conn.Write(HeartbeatRequest(flight.Version)); err != nil { + return false, err + } + _ = conn.SetReadDeadline(time.Now().Add(heartbeatResponseTimeout)) + return ReadHeartbeatResponse(conn), nil +} + +func ReadHeartbeatResponse(r io.Reader) bool { + r = io.LimitReader(r, maxLegacyResponse) + header := make([]byte, 5) + for { + if _, err := io.ReadFull(r, header); err != nil { + return false + } + length := int64(binary.BigEndian.Uint16(header[3:5])) + switch header[0] { + case recordHeartbeat: + _, _ = io.CopyN(io.Discard, r, length) + return true + case recordAlert: + return false + } + if _, err := io.CopyN(io.Discard, r, length); err != nil { + return false + } + } +} diff --git a/proxy/probebase/knowncves_test.go b/proxy/probebase/knowncves_test.go new file mode 100644 index 0000000..dbb507b --- /dev/null +++ b/proxy/probebase/knowncves_test.go @@ -0,0 +1,295 @@ +package probebase_test + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/rsa" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/binary" + "io" + "math/big" + "net" + "net/http" + "net/http/httptest" + "net/url" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cerberauth/proxyaudit/proxy/probebase" +) + +func serverHelloWithExtensions(version, suite uint16, extensions []byte) []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) + body = binary.BigEndian.AppendUint16(body, uint16(len(extensions))) //nolint:gosec + body = append(body, extensions...) + return handshake(0x02, body) +} + +func certificateMessage(der []byte) []byte { + entry := append([]byte{byte(len(der) >> 16), byte(len(der) >> 8), byte(len(der))}, der...) //nolint:gosec + return handshake(0x0b, append([]byte{byte(len(entry) >> 16), byte(len(entry) >> 8), byte(len(entry))}, entry...)) //nolint:gosec +} + +func readRecord(r io.Reader) (byte, []byte, error) { + header := make([]byte, 5) + if _, err := io.ReadFull(r, header); err != nil { + return 0, nil, err + } + payload := make([]byte, binary.BigEndian.Uint16(header[3:5])) + _, err := io.ReadFull(r, payload) + return header[0], payload, err +} + +func serve(t *testing.T, handler func(net.Conn)) string { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go func() { + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + handler(conn) + }() + } + }() + return listener.Addr().String() +} + +func tlsServerHost(t *testing.T, config *tls.Config) string { + t.Helper() + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + srv.TLS = config + srv.StartTLS() + t.Cleanup(srv.Close) + u, err := url.Parse(srv.URL) + require.NoError(t, err) + return u.Host +} + +func rsaCertificate(t *testing.T) (*rsa.PrivateKey, []byte) { + t.Helper() + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "127.0.0.1"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + require.NoError(t, err) + return key, der +} + +func TestReadServerFlight(t *testing.T) { + extensions := []byte{0x00, 0x0f, 0x00, 0x01, 0x01, 0xff, 0x01, 0x00, 0x01, 0x00} + messages := append(serverHelloWithExtensions(probebase.VersionTLS12, 0x002f, extensions), certificateMessage([]byte{0x30, 0x00})...) + messages = append(messages, handshake(0x0e, nil)...) + + flight, err := probebase.ReadServerFlight(bytes.NewReader(append(record(0x16, messages[:30]), record(0x16, messages[30:])...))) + + require.NoError(t, err) + assert.Equal(t, probebase.VersionTLS12, flight.Version) + assert.Equal(t, uint16(0x002f), flight.CipherSuite) + assert.Equal(t, []byte{0x01}, flight.Extensions[0x000f]) + assert.Equal(t, [][]byte{{0x30, 0x00}}, flight.Certificates) + + _, err = probebase.ReadServerFlight(bytes.NewReader(record(0x15, []byte{0x02, 0x28}))) + assert.ErrorIs(t, err, probebase.ErrHandshakeRejected) +} + +func TestReadHeartbeatResponse(t *testing.T) { + testCases := []struct { + name string + response []byte + expected bool + }{ + {"heartbeat response", append(record(0x16, []byte{0x0e, 0, 0, 0}), record(0x18, make([]byte, 35))...), true}, + {"alert", record(0x15, []byte{0x02, 0x0a}), false}, + {"connection closed", nil, false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.expected, probebase.ReadHeartbeatResponse(bytes.NewReader(tc.response))) + }) + } +} + +func heartbleedServer(vulnerable bool) func(net.Conn) { + return func(conn net.Conn) { + if _, _, err := readRecord(conn); err != nil { + return + } + flight := append(serverHelloWithExtensions(probebase.VersionTLS12, 0x002f, []byte{0x00, 0x0f, 0x00, 0x01, 0x01}), handshake(0x0e, nil)...) + _, _ = conn.Write(record(0x16, flight)) + contentType, payload, err := readRecord(conn) + if err != nil || contentType != 0x18 || !vulnerable { + return + } + length := int(binary.BigEndian.Uint16(payload[1:3])) + _, _ = conn.Write(record(0x18, append([]byte{0x02, payload[1], payload[2]}, make([]byte, length+16)...))) + } +} + +func TestProbeHeartbleed(t *testing.T) { + testCases := []struct { + name string + host string + expected bool + }{ + {"vulnerable", serve(t, heartbleedServer(true)), true}, + {"heartbeat ignored", serve(t, heartbleedServer(false)), false}, + {"crypto/tls", tlsServerHost(t, nil), false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + vulnerable, err := probebase.ProbeHeartbleed(context.Background(), tc.host) + + require.NoError(t, err) + assert.Equal(t, tc.expected, vulnerable) + }) + } +} + +func sslv2ServerHello(cipherSpecs int) []byte { + body := []byte{0x04, 0x00, 0x01, 0x00, 0x02} + body = binary.BigEndian.AppendUint16(body, 0) + body = binary.BigEndian.AppendUint16(body, uint16(3*cipherSpecs)) //nolint:gosec + body = binary.BigEndian.AppendUint16(body, 16) + body = append(body, bytes.Repeat([]byte{0x01, 0x00, 0x80}, cipherSpecs)...) + body = append(body, make([]byte, 16)...) + return append(binary.BigEndian.AppendUint16(nil, 0x8000|uint16(len(body))), body...) //nolint:gosec +} + +func TestBuildSSLv2ClientHello(t *testing.T) { + hello, err := probebase.BuildSSLv2ClientHello() + + require.NoError(t, err) + assert.Equal(t, byte(0x80), hello[0]&0x80) + assert.Equal(t, len(hello)-2, int(binary.BigEndian.Uint16(hello)&0x7fff)) + assert.Equal(t, []byte{0x01, 0x00, 0x02}, hello[2:5]) +} + +func TestReadSSLv2ServerHello(t *testing.T) { + hello, err := probebase.ReadSSLv2ServerHello(bytes.NewReader(sslv2ServerHello(2))) + require.NoError(t, err) + assert.Equal(t, 2, hello.CipherSpecs) + + _, err = probebase.ReadSSLv2ServerHello(bytes.NewReader(record(0x15, []byte{0x02, 0x46}))) + assert.ErrorIs(t, err, probebase.ErrHandshakeRejected) + + _, err = probebase.ReadSSLv2ServerHello(bytes.NewReader(nil)) + assert.ErrorIs(t, err, probebase.ErrHandshakeRejected) +} + +func TestProbeSSLv2(t *testing.T) { + host := serve(t, func(conn net.Conn) { + header := make([]byte, 2) + if _, err := io.ReadFull(conn, header); err != nil { + return + } + _, _ = io.ReadFull(conn, make([]byte, binary.BigEndian.Uint16(header)&0x7fff)) + _, _ = conn.Write(sslv2ServerHello(7)) + }) + + hello, err := probebase.ProbeSSLv2(context.Background(), host) + require.NoError(t, err) + assert.Equal(t, 7, hello.CipherSpecs) + + _, err = probebase.ProbeSSLv2(context.Background(), tlsServerHost(t, nil)) + assert.ErrorIs(t, err, probebase.ErrHandshakeRejected) +} + +func TestRobotPremasterSecrets(t *testing.T) { + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + variants, err := probebase.RobotPremasterSecrets(key.Size()) + require.NoError(t, err) + require.Len(t, variants, 5) + + for i, variant := range variants { + require.Len(t, variant, key.Size()) + ciphertext := new(big.Int).Exp(new(big.Int).SetBytes(variant), big.NewInt(int64(key.E)), key.N).FillBytes(make([]byte, key.Size())) + plaintext, err := rsa.DecryptPKCS1v15(nil, key, ciphertext) //nolint:staticcheck + switch i { + case 0: + require.NoError(t, err) + assert.Len(t, plaintext, 48) + assert.Equal(t, []byte{0x03, 0x03}, plaintext[:2]) + case 1, 3: + assert.Error(t, err) + case 2: + require.NoError(t, err) + assert.Len(t, plaintext, 1) + case 4: + require.NoError(t, err) + assert.Equal(t, []byte{0x02, 0x02}, plaintext[:2]) + } + } +} + +func robotServer(key *rsa.PrivateKey, der []byte, oracle bool) func(net.Conn) { + return func(conn net.Conn) { + if _, _, err := readRecord(conn); err != nil { + return + } + flight := append(serverHelloWithExtensions(probebase.VersionTLS12, 0x002f, nil), certificateMessage(der)...) + flight = append(flight, handshake(0x0e, nil)...) + _, _ = conn.Write(record(0x16, flight)) + _, payload, err := readRecord(conn) + if err != nil || len(payload) < 6 { + return + } + m := new(big.Int).Exp(new(big.Int).SetBytes(payload[6:]), key.D, key.N).FillBytes(make([]byte, key.Size())) + description := byte(20) + if oracle && (m[0] != 0x00 || m[1] != 0x02) { + description = 51 + } + _, _ = conn.Write(record(0x15, []byte{0x02, description})) + } +} + +func TestProbeROBOT(t *testing.T) { + t.Cleanup(func(previous time.Duration) func() { + return func() { *probebase.RobotResponseTimeout = previous } + }(*probebase.RobotResponseTimeout)) + *probebase.RobotResponseTimeout = 200 * time.Millisecond + + key, der := rsaCertificate(t) + testCases := []struct { + name string + host string + expected bool + }{ + {"padding oracle", serve(t, robotServer(key, der, true)), true}, + {"constant response", serve(t, robotServer(key, der, false)), false}, + {"crypto/tls without rsa key exchange", tlsServerHost(t, nil), false}, + {"crypto/tls with rsa key exchange", tlsServerHost(t, &tls.Config{MaxVersion: tls.VersionTLS12, CipherSuites: []uint16{tls.TLS_RSA_WITH_AES_128_CBC_SHA}}), false}, //nolint:gosec + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + result, err := probebase.ProbeROBOT(context.Background(), tc.host) + + require.NoError(t, err) + assert.Equal(t, tc.expected, result.Vulnerable, result.Responses) + }) + } +} diff --git a/proxy/probebase/legacytls.go b/proxy/probebase/legacytls.go new file mode 100644 index 0000000..2b203b9 --- /dev/null +++ b/proxy/probebase/legacytls.go @@ -0,0 +1,252 @@ +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) { + return buildClientHello(version, suites, serverName, nil) +} + +func buildClientHello(version uint16, suites []uint16, serverName string, extraExtensions []byte) ([]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}) + extensions = append(extensions, extraExtensions...) + 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) { + hello, err := BuildClientHello(version, suites, hostnameOf(host)) + if err != nil { + return nil, err + } + + conn, err := dialRaw(ctx, host) + if err != nil { + return nil, err + } + defer conn.Close() + + if _, err := conn.Write(hello); err != nil { + return nil, err + } + return ReadLegacyServerHello(conn) +} + +func hostnameOf(host string) string { + hostname, _, err := net.SplitHostPort(host) + if err != nil { + return host + } + return hostname +} + +func dialRaw(ctx context.Context, host string) (net.Conn, error) { + dialer := &net.Dialer{Timeout: DialTimeout} + conn, err := dialer.DialContext(ctx, "tcp", host) + if err != nil { + return nil, err + } + deadline := time.Now().Add(DialTimeout) + if d, ok := ctx.Deadline(); ok && d.Before(deadline) { + deadline = d + } + _ = conn.SetDeadline(deadline) + return conn, nil +} + +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/robot.go b/proxy/probebase/robot.go new file mode 100644 index 0000000..1ab78ca --- /dev/null +++ b/proxy/probebase/robot.go @@ -0,0 +1,193 @@ +package probebase + +import ( + "bytes" + "context" + "crypto/rsa" + "crypto/x509" + "encoding/binary" + "errors" + "fmt" + "io" + "math/big" + "net" + "os" + "slices" + "sync" + "syscall" + "time" +) + +var RSASuites = []uint16{0x002f, 0x0035, 0x003c, 0x003d, 0x009c, 0x009d, 0x000a} + +var ErrNoRSAKeyExchange = errors.New("server does not negotiate RSA key exchange") + +var robotResponseTimeout = 3 * time.Second + +const ( + robotCorrectPadding = iota + robotWrongPrefix + robotMisplacedZero + robotMissingZero + robotWrongVersion + robotVariants +) + +func RobotPremasterSecrets(size int) ([][]byte, error) { + padLength := size - 3 - 48 + if padLength < 8 { + return nil, errors.New("rsa modulus too small") + } + padding := bytes.Repeat([]byte{0xab, 0xcd}, padLength/2+1)[:padLength] + secret := bytes.Repeat([]byte{0x11, 0x22, 0x33}, 16)[:46] + + build := func(parts ...[]byte) []byte { return bytes.Join(parts, nil) } + variants := make([][]byte, robotVariants) + variants[robotCorrectPadding] = build([]byte{0x00, 0x02}, padding, []byte{0x00, 0x03, 0x03}, secret) + variants[robotWrongPrefix] = build([]byte{0x41, 0x17}, padding, []byte{0x00, 0x03, 0x03}, secret) + variants[robotMisplacedZero] = build([]byte{0x00, 0x02}, padding, []byte{0x11}, secret, []byte{0x00, 0x11}) + variants[robotMissingZero] = build([]byte{0x00, 0x02}, padding, []byte{0x11, 0x11, 0x11}, secret) + variants[robotWrongVersion] = build([]byte{0x00, 0x02}, padding, []byte{0x00, 0x02, 0x02}, secret) + return variants, nil +} + +func encryptRaw(key *rsa.PublicKey, message []byte) []byte { + c := new(big.Int).Exp(new(big.Int).SetBytes(message), big.NewInt(int64(key.E)), key.N) + return c.FillBytes(make([]byte, key.Size())) +} + +func RobotClientFlight(version uint16, key *rsa.PublicKey, premaster []byte, finished bool) []byte { + encrypted := encryptRaw(key, premaster) + body := appendUint16(nil, uint16(len(encrypted))) //nolint:gosec + body = append(body, encrypted...) + message := append([]byte{handshakeClientKeyExchange}, appendUint24(nil, len(body))...) + message = append(message, body...) + + flight := appendRecord(nil, recordHandshake, version, message) + if finished { + flight = appendRecord(flight, recordChangeCipherSpec, version, []byte{0x01}) + flight = appendRecord(flight, recordHandshake, version, bytes.Repeat([]byte{0x07}, 40)) + } + return flight +} + +func rsaKey(flight *ServerFlight) (*rsa.PublicKey, error) { + if !slices.Contains(RSASuites, flight.CipherSuite) || len(flight.Certificates) == 0 { + return nil, ErrNoRSAKeyExchange + } + cert, err := x509.ParseCertificate(flight.Certificates[0]) + if err != nil { + return nil, err + } + key, ok := cert.PublicKey.(*rsa.PublicKey) + if !ok { + return nil, ErrNoRSAKeyExchange + } + return key, nil +} + +func robotOracle(ctx context.Context, host string, variant int, finished bool) (string, error) { + hello, err := BuildClientHello(VersionTLS12, RSASuites, hostnameOf(host)) + if err != nil { + return "", err + } + conn, err := dialRaw(ctx, host) + if err != nil { + return "", err + } + defer conn.Close() + + if _, err := conn.Write(hello); err != nil { + return "", err + } + flight, err := ReadServerFlight(conn) + if err != nil { + if errors.Is(err, ErrHandshakeRejected) { + return "", ErrNoRSAKeyExchange + } + return "", err + } + key, err := rsaKey(flight) + if err != nil { + return "", err + } + premasters, err := RobotPremasterSecrets(key.Size()) + if err != nil { + return "", err + } + if _, err := conn.Write(RobotClientFlight(flight.Version, key, premasters[variant], finished)); err != nil { + return "", err + } + _ = conn.SetReadDeadline(time.Now().Add(robotResponseTimeout)) + return ReadOracleResponse(conn), nil +} + +func ReadOracleResponse(r io.Reader) string { + header := make([]byte, 5) + _, err := io.ReadFull(r, header) + switch { + case err == nil: + case errors.Is(err, os.ErrDeadlineExceeded): + return "timeout" + case errors.Is(err, syscall.ECONNRESET): + return "reset" + case errors.Is(err, io.EOF), errors.Is(err, io.ErrUnexpectedEOF): + return "closed" + default: + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + return "timeout" + } + return "error" + } + if header[0] != recordAlert { + return fmt.Sprintf("record %d", header[0]) + } + alert := make([]byte, 2) + if binary.BigEndian.Uint16(header[3:5]) < 2 { + return "alert" + } + if _, err := io.ReadFull(r, alert); err != nil { + return "alert" + } + return fmt.Sprintf("alert %d %d", alert[0], alert[1]) +} + +func robotRound(ctx context.Context, host string, finished bool) ([]string, error) { + responses := make([]string, robotVariants) + errs := make([]error, robotVariants) + var wg sync.WaitGroup + for variant := range robotVariants { + wg.Go(func() { + responses[variant], errs[variant] = robotOracle(ctx, host, variant, finished) + }) + } + wg.Wait() + return responses, errors.Join(errs...) +} + +type RobotResult struct { + Vulnerable bool + Responses []string +} + +func ProbeROBOT(ctx context.Context, host string) (*RobotResult, error) { + for _, finished := range []bool{true, false} { + first, err := robotRound(ctx, host, finished) + if err != nil { + if errors.Is(err, ErrNoRSAKeyExchange) { + return &RobotResult{}, nil + } + return nil, err + } + if !slices.ContainsFunc(first, func(r string) bool { return r != first[robotCorrectPadding] }) { + continue + } + second, err := robotRound(ctx, host, finished) + if err != nil { + return nil, err + } + return &RobotResult{Vulnerable: slices.Equal(first, second), Responses: first}, nil + } + return &RobotResult{}, nil +} diff --git a/proxy/probebase/serverflight.go b/proxy/probebase/serverflight.go new file mode 100644 index 0000000..616d6fa --- /dev/null +++ b/proxy/probebase/serverflight.go @@ -0,0 +1,125 @@ +package probebase + +import ( + "encoding/binary" + "errors" + "fmt" + "io" +) + +const ( + recordChangeCipherSpec = 0x14 + recordHeartbeat = 0x18 + + handshakeCertificate = 0x0b + handshakeClientKeyExchange = 0x10 +) + +type ServerFlight struct { + Version uint16 + CipherSuite uint16 + Extensions map[uint16][]byte + Certificates [][]byte +} + +func ReadServerFlight(r io.Reader) (*ServerFlight, error) { + r = io.LimitReader(r, maxLegacyResponse) + var flight *ServerFlight + var buffer []byte + header := make([]byte, 5) + for { + if _, err := io.ReadFull(r, header); err != nil { + return nil, fmt.Errorf("%w: %v", ErrHandshakeRejected, err) + } + payload := make([]byte, binary.BigEndian.Uint16(header[3:5])) + if _, err := io.ReadFull(r, payload); err != nil { + return nil, fmt.Errorf("%w: %v", ErrHandshakeRejected, err) + } + if header[0] != recordHandshake { + return nil, fmt.Errorf("%w: 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: + parsed, err := parseServerHelloExtensions(msg) + if err != nil { + return nil, err + } + flight = parsed + case handshakeCertificate: + if flight == nil { + return nil, errors.New("certificate before server hello") + } + certificates, err := parseCertificateList(msg) + if err != nil { + return nil, err + } + flight.Certificates = certificates + case handshakeServerHelloDone: + if flight == nil { + return nil, errors.New("server hello done before server hello") + } + return flight, nil + } + } + } +} + +func parseServerHelloExtensions(msg []byte) (*ServerFlight, error) { + hello, err := parseServerHello(msg) + if err != nil { + return nil, err + } + flight := &ServerFlight{Version: hello.Version, CipherSuite: hello.CipherSuite, Extensions: map[uint16][]byte{}} + offset := 35 + int(msg[34]) + 3 + if len(msg) < offset+2 { + return flight, nil + } + rest := msg[offset:] + extensions := rest[2:] + if length := int(binary.BigEndian.Uint16(rest)); length < len(extensions) { + extensions = extensions[:length] + } + for len(extensions) >= 4 { + extType := binary.BigEndian.Uint16(extensions) + length := int(binary.BigEndian.Uint16(extensions[2:])) + if len(extensions) < 4+length { + break + } + flight.Extensions[extType] = extensions[4 : 4+length] + extensions = extensions[4+length:] + } + return flight, nil +} + +func parseCertificateList(msg []byte) ([][]byte, error) { + if len(msg) < 3 { + return nil, errors.New("short certificate message") + } + list := msg[3:] + var certificates [][]byte + for len(list) >= 3 { + length := int(list[0])<<16 | int(list[1])<<8 | int(list[2]) + if len(list) < 3+length { + return nil, errors.New("short certificate entry") + } + certificates = append(certificates, list[3:3+length]) + list = list[3+length:] + } + return certificates, nil +} + +func appendRecord(b []byte, contentType byte, version uint16, payload []byte) []byte { + b = append(b, contentType) + b = appendUint16(b, version) + b = appendUint16(b, uint16(len(payload))) //nolint:gosec + return append(b, payload...) +} diff --git a/proxy/probebase/sslv2.go b/proxy/probebase/sslv2.go new file mode 100644 index 0000000..76c0150 --- /dev/null +++ b/proxy/probebase/sslv2.go @@ -0,0 +1,85 @@ +package probebase + +import ( + "context" + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "io" +) + +const ( + sslv2ClientHello = 0x01 + sslv2ServerHello = 0x04 + versionSSL20 = 0x0002 +) + +var SSLv2CipherSpecs = [][3]byte{ + {0x01, 0x00, 0x80}, + {0x02, 0x00, 0x80}, + {0x03, 0x00, 0x80}, + {0x04, 0x00, 0x80}, + {0x05, 0x00, 0x80}, + {0x06, 0x00, 0x40}, + {0x07, 0x00, 0xc0}, +} + +type SSLv2Hello struct { + CipherSpecs int +} + +func BuildSSLv2ClientHello() ([]byte, error) { + challenge := make([]byte, 16) + if _, err := rand.Read(challenge); err != nil { + return nil, err + } + body := []byte{sslv2ClientHello} + body = appendUint16(body, versionSSL20) + body = appendUint16(body, uint16(3*len(SSLv2CipherSpecs))) //nolint:gosec + body = appendUint16(body, 0) + body = appendUint16(body, uint16(len(challenge))) //nolint:gosec + for _, spec := range SSLv2CipherSpecs { + body = append(body, spec[:]...) + } + body = append(body, challenge...) + return append(appendUint16(nil, 0x8000|uint16(len(body))), body...), nil //nolint:gosec +} + +func ProbeSSLv2(ctx context.Context, host string) (*SSLv2Hello, error) { + hello, err := BuildSSLv2ClientHello() + if err != nil { + return nil, err + } + conn, err := dialRaw(ctx, host) + if err != nil { + return nil, err + } + defer conn.Close() + + if _, err := conn.Write(hello); err != nil { + return nil, err + } + return ReadSSLv2ServerHello(conn) +} + +func ReadSSLv2ServerHello(r io.Reader) (*SSLv2Hello, error) { + header := make([]byte, 2) + if _, err := io.ReadFull(r, header); err != nil { + return nil, fmt.Errorf("%w: %v", ErrHandshakeRejected, err) + } + if header[0]&0x80 == 0 { + return nil, fmt.Errorf("%w: not an SSLv2 record", ErrHandshakeRejected) + } + body := make([]byte, int(binary.BigEndian.Uint16(header)&0x7fff)) + if _, err := io.ReadFull(r, body); err != nil { + return nil, fmt.Errorf("%w: %v", ErrHandshakeRejected, err) + } + if len(body) < 11 || body[0] != sslv2ServerHello { + return nil, fmt.Errorf("%w: not an SSLv2 server hello", ErrHandshakeRejected) + } + if binary.BigEndian.Uint16(body[3:5]) != versionSSL20 { + return nil, errors.New("unexpected SSLv2 server hello version") + } + return &SSLv2Hello{CipherSpecs: int(binary.BigEndian.Uint16(body[7:9])) / 3}, nil +} diff --git a/proxy/probebase/tlsinfo.go b/proxy/probebase/tlsinfo.go index 1913b97..0eed366 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) @@ -116,6 +147,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 +175,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() + }) +}