Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company đŸ‘‡
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
feat(khaos): M7 reference TLS client, and the 416-cell differential it failed
CarterPerez-dev7914adc98ae4
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.goindex ce9ffd05..378f561a 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go@@ -21,7 +21,6 @@ const (nameEKULimited = "khaos client-auth-only intermediate"nameNotACA = "khaos issuer that is not a CA"nameDeepInter = "khaos over-deep intermediate"- nameResponder = "khaos ocsp responder"nameUndelegated = "khaos undelegated responder"// constrainedDomain is what the name-constrained CA is permitted to issue@@ -97,7 +96,6 @@ type Authority struct {constrained *pairekuLimited *pairnotACA *pair- responder *pairundelegated *pair// deepInter sits under deepCapped, whose MaxPathLen is zero. BOTH have todiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.goindex 1db18f25..f5cec40b 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go@@ -348,9 +348,17 @@ func (a *Authority) overDeep(func (a *Authority) selfSigned(template *x509.Certificate,) (*Chain, error) {+ // CertSign because Go refuses to let a non-CA certificate sign anything,+ // including itself. CRLSign because this leaf is its OWN issuer, so it is+ // also the thing that has to sign the CRL covering it, and+ // CreateRevocationList refuses an issuer without that bit.+ //+ // Omitting CRLSign made the CRL endpoint answer 500 for this trap, which+ // reached the client as "no usable revocation answer was obtained" -- a+ // refusal caused by khaos rather than by the fault. The matrix caught it.template.IsCA = truetemplate.BasicConstraintsValid = true- template.KeyUsage |= x509.KeyUsageCertSign+ template.KeyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSignkey, err := newKey(StrongBits)if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.goindex 820d4d8d..9da87ef3 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go@@ -81,7 +81,22 @@ func (a *Authority) buildNotACA(from, until time.Time) error {NotAfter: until,IsCA: false,BasicConstraintsValid: true,- KeyUsage: x509.KeyUsageDigitalSignature,++ // CRLSign despite IsCA being false, because this certificate is still+ // the issuer of the leaf it signs and therefore still the thing that+ // signs the CRL covering it. CreateRevocationList refuses an issuer+ // without the bit, and without it the CRL endpoint answered 500 and the+ // client refused for khaos's reason instead of the fault's.+ //+ // The fault is unaffected: IsCA is still false, which is the defect.+ KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCRLSign,++ // Set BY HAND, because Go computes a SubjectKeyId automatically only+ // while creating a CA certificate and this one is deliberately not a+ // CA. CreateRevocationList reads the identifier from the parsed issuer+ // and refuses an issuer without one, so a CRL for this chain could not+ // be minted at all and the endpoint answered 500.+ SubjectKeyId: []byte(nameNotACA),}key, err := newKey(StrongBits)@@ -134,40 +149,30 @@ func (a *Authority) buildDeepInter(from, until time.Time) error {return err}-// buildResponders mints the two OCSP signers: one the CA delegated by giving it-// the OCSPSigning extended key usage, and one it never signed at all.+// buildResponders mints the ONE OCSP signer khaos needs to hold: a certificate+// the CA never issued.//-// The undelegated signer is what OCSPWrongSigner answers with. It is a-// self-signed certificate rather than one under the rogue CA, so that a client-// which happens to trust the rogue root (because CASwap ran earlier in the same-// session) still cannot be fooled by it.+// There is no delegated responder here any more. Every honest response is+// signed by the chain's own issuer, acting as its own responder, which RFC 6960+// section 2.6 permits and which is the only arrangement that is consistent with+// EVERY chain this authority serves. A single delegated responder cannot be,+// because seven traps serve a chain under a different CA entirely, and the+// matrix caught six of them being refused for khaos's own mismatch.+//+// The undelegated signer stays, because OCSPWrongSigner is the fault that+// exercises delegation from the other side. It is self-signed rather than+// issued by the rogue hierarchy, so a client that happens to trust the rogue+// root -- because CASwap ran earlier in the same session -- still cannot be+// fooled by it.func (a *Authority) buildResponders(from, until time.Time) error {- delegated, err := caTemplate(nameResponder, from, until)- if err != nil {- return err- }-- delegated.IsCA = false- delegated.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageOCSPSigning}-- delegatedKey, err := newKey(StrongBits)- if err != nil {- return err- }-- if a.responder, err = issue(- delegated,- a.inter,- delegatedKey,- ); err != nil {- return err- }-rogue, err := caTemplate(nameUndelegated, from, until)if err != nil {return err}+ rogue.IsCA = false+ rogue.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageOCSPSigning}+rogueKey, err := newKey(StrongBits)if err != nil {return errdiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.goindex 8285cafb..bb3fec0d 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go@@ -81,6 +81,17 @@ func (a *Authority) staple(case StapleAbsent:chain.Staple = nil+ case OCSPTryLater, OCSPUnreachable, CRLUnreachable:+ // NOTHING is stapled. These three faults are about an answer the client+ // cannot OBTAIN, and a stapled Good is an answer obtained for free: the+ // client would read it, be satisfied, and never contact the endpoint+ // khaos broke. The fault would be completely unreachable.+ //+ // The matrix caught exactly this. Nine modes, including the correct+ // one, accepted ocsp-try-later and ocsp-unreachable because the staple+ // answered first.+ chain.Staple = nil+case OCSPRevoked, OCSPStale, OCSPWrongSerial, OCSPWrongSigner,OCSPUnknown:// The responder faults also staple what they would have answered, so a@@ -131,7 +142,19 @@ func (a *Authority) CRLFor(template.NextUpdate = now.Add(-window)}- if trap.Kind == RevokedViaCRL || trap.Kind == StaleCRL {+ // Only RevokedViaCRL lists the serial. StaleCRL deliberately does NOT, and+ // that is the difference between the two faults.+ //+ // The first draft had the stale list also revoke the leaf, which made the+ // fault catch nothing: a client that ignores freshness still reaches the+ // serial scan, still finds the entry, and still refuses, so the broken+ // client behaved exactly like the correct one. The matrix caught it.+ //+ // The real scenario is a three-week-old list that PREDATES the revocation.+ // A correct client refuses because a list it cannot trust is not an answer;+ // a client that skips step five reads "not listed" as "not revoked" and+ // accepts. That differential is the whole fault.+ if trap.Kind == RevokedViaCRL {template.RevokedCertificateEntries = []x509.RevocationListEntry{{SerialNumber: chain.Leaf.SerialNumber,RevocationTime: now.Add(-clockSlack),@@ -160,17 +183,22 @@ func (a *Authority) ocspFor(chain *Chain,now time.Time,) ([]byte, error) {- signer := a.responder-- // The responder certificate has to be EMBEDDED in the response, and- // x/crypto only embeds it when template.Certificate is non-nil- // (ocsp.go:783). Without it, ParseResponse falls through to verifying the- // response signature directly against the ISSUER key, which khaos did not- // sign with, and every delegated answer comes back- // `bad OCSP signature: crypto/rsa: verification error`.+ // The chain's OWN issuer signs, acting as its own responder, which RFC 6960+ // section 2.6 permits alongside a delegated one.+ //+ // A single delegated responder cannot work here, and the matrix proved it.+ // Seven of these traps serve a chain under a DIFFERENT CA -- the rogue+ // hierarchy, a non-CA issuer, an over-deep intermediate, or the leaf+ // itself -- and a response signed by a responder delegated by the honest+ // intermediate does not verify against any of them. Six traps were being+ // refused for `the stapled response is not a usable OCSP response`, which+ // is khaos's own mismatch wearing the wrong-signer fault's clothes.//- // That failure mode is indistinguishable from the OCSPWrongSigner fault- // landing, so omitting this made four traps look like they were working.+ // Signing with the chain's issuer is always consistent with the chain by+ // construction. The delegation path is still exercised, from the other+ // side, by OCSPWrongSigner.+ signer := &pair{cert: chain.Issuer, key: chain.issuerKey}+template := ocsp.Response{Status: ocsp.Good,SerialNumber: chain.Leaf.SerialNumber,@@ -211,11 +239,19 @@ func (a *Authority) ocspFor(// Good, fresh, correctly signed, for this serial.}- // AFTER the switch, because OCSPWrongSigner changes who signs. Embedding- // the delegated certificate alongside a signature made by the undelegated- // key would be rejected for a mismatch between the two rather than for the- // delegation that is the actual fault, and those are different findings.- template.Certificate = signer.cert+ // Embedded ONLY for the wrong-signer fault, and only after the switch has+ // decided who signs.+ //+ // x/crypto embeds the responder certificate just when template.Certificate+ // is non-nil (ocsp.go:783), and ParseResponse branches on whether one is+ // present: with a certificate it checks the response against that and that+ // against the issuer, and without one it checks the response against the+ // issuer directly. The issuer signs its own responses here, so leaving this+ // nil is what makes them verify. Setting it for the undelegated signer is+ // what makes that response fail at the SECOND check, which is the fault.+ if signer != nil && signer.cert != chain.Issuer {+ template.Certificate = signer.cert+ }der, err := ocsp.CreateResponse(chain.Issuer,@@ -231,21 +267,21 @@ func (a *Authority) ocspFor(}// ocspGood is the honest response, and the control for every responder fault.+// Signed by the chain's own issuer for the same reason ocspFor is.func (a *Authority) ocspGood(chain *Chain,now, until time.Time,) ([]byte, error) {der, err := ocsp.CreateResponse(chain.Issuer,- a.responder.cert,+ chain.Issuer,ocsp.Response{Status: ocsp.Good,SerialNumber: chain.Leaf.SerialNumber,ThisUpdate: now.Add(-clockSlack),NextUpdate: until,- Certificate: a.responder.cert,},- a.responder.key,+ chain.issuerKey,)if err != nil {return nil, fmt.Errorf(errOCSPGen, ErrMint, err)@@ -253,9 +289,3 @@ func (a *Authority) ocspGood(return der, nil}--// Responder is the certificate khaos signs OCSP responses with, which a client-// needs in order to check the signature at all.-func (a *Authority) Responder() *x509.Certificate {- return a.responder.cert-}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation_test.goindex 1551aaac..4ca2cda9 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation_test.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation_test.go@@ -159,11 +159,17 @@ func assertCRLRevokesAndIsStale(list := servedCRL(t, a)- // Both halves. A stale CRL that revokes nothing finds nothing, because the- // target has no reason to refuse and the freshness hole is never reached.- if !revokes(list, chain.Leaf.SerialNumber.String()) {+ // The list must NOT revoke the leaf. This assertion was inverted in the+ // first draft and the matrix proved it wrong: a stale list that also+ // revokes the serial is caught by a client that ignores freshness, because+ // it still reaches the serial scan, so the broken client and the correct+ // one behave identically and the fault measures nothing.+ //+ // The fault is a three-week-old list that predates the revocation. The+ // staleness is the whole finding.+ if revokes(list, chain.Leaf.SerialNumber.String()) {t.Fatal(- "the stale CRL does not revoke the leaf, so a target checking freshness has nothing to be wrong about",+ "the stale CRL also revokes the leaf, which makes a freshness-ignoring client refuse for the right answer by accident and the fault inert",)}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/client.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/client.gonew file mode 100644index 00000000..f3940617--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/client.go@@ -0,0 +1,365 @@+// ©AngelaMos | 2026+// client.go++package tlsclient++import (+ "context"+ "crypto/tls"+ "crypto/x509"+ "errors"+ "net"+ "net/http"+ "time"+)++const (+ network = "tcp"++ // MinimumModulusBits is khaos's reference key floor. x509 path validation+ // has NO minimum of its own -- crypto/tls has a maximum of 8192 as the fix+ // for CVE-2023-29409, and neither package has a floor -- so this is a policy+ // the application imposes or nobody does.+ MinimumModulusBits = 2048++ // MaximumLifetimeDays is the CA/Browser Forum leaf cap. Nothing outside a+ // browser enforces it.+ MaximumLifetimeDays = 200++ // DefaultTimeout bounds both the handshake and every revocation fetch. A+ // client with no timeout cannot distinguish a slow responder from a dead+ // one, and that distinction is a fault in its own right.+ DefaultTimeout = 5 * time.Second+)++const (+ reasonAccepted = ""+ reasonHandshake = "the handshake failed: "+ reasonNoChain = "the server presented no certificate"+ reasonWeakKey = "the leaf's key is below the configured floor"+ reasonLongLife = "the leaf's lifetime exceeds the configured maximum"+ reasonRevoked = "the certificate is revoked"+ reasonNoAnswer = "no usable revocation answer was obtained"+ reasonStaleCRL = "the CRL's freshness window has closed"+ reasonStaleOCSP = "the OCSP response's freshness window has closed"+ reasonBadCRLSig = "the CRL is not signed by the certificate's issuer"+ reasonOCSPStatus = "the responder did not say the certificate is good"+ reasonBadStaple = "the stapled response is not a usable OCSP response"++ reasonNoSigningUse = "the leaf's KeyUsage does not permit digital signatures"+)++// Config aims a reference client at one dependency.+type Config struct {+ // Mode decides which checks this client performs. Correct performs all of+ // them.+ Mode Mode++ // Host is the name the client asks for and expects to be in the+ // certificate.+ Host string++ // Roots is what the client trusts. For the trust-store faults this is the+ // thing khaos changed.+ Roots *x509.CertPool++ // Timeout bounds the handshake and every revocation fetch.+ Timeout time.Duration++ // Now overrides the clock, so a freshness assertion does not race a real+ // one.+ Now func() time.Time+}++// Client is khaos's reference TLS client: what a correct consumer of a+// dependency's certificate does, and eleven named ways of doing it wrong.+//+// It is a teaching artifact as much as a test fixture. The Correct path is the+// code a reader should copy, which is why it performs the whole six-step CRL+// check rather than the two steps that are usually written.+type Client struct {+ mode Mode+ host string+ roots *x509.CertPool+ timeout time.Duration+ clock func() time.Time++ http *http.Client+}++// New builds a client. Every field has a working default except the mode and+// the host, because a client with no trust anchors and no name is not a client+// that can decide anything.+func New(cfg Config) *Client {+ c := &Client{+ mode: cfg.Mode,+ host: cfg.Host,+ roots: cfg.Roots,+ timeout: cfg.Timeout,+ clock: cfg.Now,+ }++ if c.mode == "" {+ c.mode = Correct+ }++ if c.timeout <= 0 {+ c.timeout = DefaultTimeout+ }++ if c.clock == nil {+ c.clock = time.Now+ }++ c.http = &http.Client{Timeout: c.timeout}++ return c+}++// Mode is which client this is.+func (c *Client) Mode() Mode {+ return c.mode+}++// Decision is one client's answer about one dependency.+type Decision struct {+ // Accepted is whether the client was willing to use the dependency.+ Accepted bool++ // Reason is why it refused, empty when it accepted. It is for a human+ // reading a khaos run, and tests assert on Accepted rather than on this.+ Reason string++ // AskedCRL and AskedOCSP record whether the client actually went and+ // looked. A client that accepted WITHOUT asking is a different finding from+ // one that asked and was satisfied, and only these fields separate them.+ AskedCRL bool+ AskedOCSP bool+}++// Decide connects to addr and reports whether this client was willing to use+// what it found there.+//+// The handshake and the policy are deliberately separate. crypto/tls is left to+// do the chain, the hostname and the validity window, because khaos+// re-implementing those would mean khaos's own bugs showing up as findings+// about the target. What this adds afterwards is only the layer Go does not+// have.+func (c *Client) Decide(+ ctx context.Context,+ addr string,+) Decision {+ state, err := c.handshake(ctx, addr)+ if err != nil {+ return Decision{Reason: reasonHandshake + err.Error()}+ }++ if len(state.PeerCertificates) == 0 {+ return Decision{Reason: reasonNoChain}+ }++ leaf := state.PeerCertificates[0]+ issuer := c.issuerOf(state)++ if reason, ok := c.policy(leaf); !ok {+ return Decision{Reason: reason}+ }++ return c.revocation(ctx, leaf, issuer, state)+}++// handshake performs the TLS exchange under this mode's verification settings.+func (c *Client) handshake(+ ctx context.Context,+ addr string,+) (tls.ConnectionState, error) {+ dialer := &tls.Dialer{+ NetDialer: &net.Dialer{Timeout: c.timeout},+ Config: c.tlsConfig(),+ }++ conn, err := dialer.DialContext(ctx, network, addr)+ if err != nil {+ return tls.ConnectionState{}, err+ }++ defer func() { _ = conn.Close() }()++ tlsConn, ok := conn.(*tls.Conn)+ if !ok {+ return tls.ConnectionState{}, errors.New("not a TLS connection")+ }++ // The handshake has already completed by the time DialContext returns, but+ // under TLS 1.3 a server's rejection of a CLIENT certificate surfaces only+ // on the first read. khaos does not use client certificates here, so this+ // state is final; research 04 section 7.2 covers the case where it is not.+ return tlsConn.ConnectionState(), nil+}++func (c *Client) tlsConfig() *tls.Config {+ cfg := &tls.Config{+ ServerName: c.host,+ RootCAs: c.roots,+ MinVersion: tls.VersionTLS12,+ }++ if !c.mode.checksChain() {+ // InsecureSkipVerify in one assignment turns off the chain, the name+ // and the validity window together. That breadth is the reason it is+ // the most common fail-open in real code.+ cfg.InsecureSkipVerify = true++ return cfg+ }++ if !c.mode.checksHostname() {+ // The chain is still checked, by hand, with the name left out. Go has+ // no setting for this, which is why a client that wants it has to+ // reimplement verification and usually gets something else wrong too.+ cfg.InsecureSkipVerify = true+ cfg.VerifyPeerCertificate = c.verifyWithoutName++ return cfg+ }++ if c.mode == TrustPresentedCA {+ // Anchoring on whatever arrived accepts any self-consistent chain,+ // including one minted by anybody at all.+ cfg.InsecureSkipVerify = true+ cfg.VerifyPeerCertificate = c.verifyAgainstPresented++ return cfg+ }++ return cfg+}++// verifyWithoutName does the full path check and omits the hostname, which is+// the SkipHostname fault.+func (c *Client) verifyWithoutName(+ raw [][]byte,+ _ [][]*x509.Certificate,+) error {+ leaf, pool, err := parseChain(raw)+ if err != nil {+ return err+ }++ _, err = leaf.Verify(x509.VerifyOptions{+ Roots: c.roots,+ Intermediates: pool,+ CurrentTime: c.clock(),+ })++ return err+}++// verifyAgainstPresented anchors on the chain the server sent, which is the+// TrustPresentedCA fault.+func (c *Client) verifyAgainstPresented(+ raw [][]byte,+ _ [][]*x509.Certificate,+) error {+ leaf, pool, err := parseChain(raw)+ if err != nil {+ return err+ }++ roots := x509.NewCertPool()++ for _, der := range raw {+ cert, parseErr := x509.ParseCertificate(der)+ if parseErr != nil {+ return parseErr+ }++ roots.AddCert(cert)+ }++ _, err = leaf.Verify(x509.VerifyOptions{+ Roots: roots,+ Intermediates: pool,+ DNSName: c.host,+ CurrentTime: c.clock(),+ })++ return err+}++func parseChain(raw [][]byte) (+ *x509.Certificate,+ *x509.CertPool,+ error,+) {+ if len(raw) == 0 {+ return nil, nil, errors.New(reasonNoChain)+ }++ leaf, err := x509.ParseCertificate(raw[0])+ if err != nil {+ return nil, nil, err+ }++ pool := x509.NewCertPool()++ for _, der := range raw[1:] {+ cert, parseErr := x509.ParseCertificate(der)+ if parseErr != nil {+ return nil, nil, parseErr+ }++ pool.AddCert(cert)+ }++ return leaf, pool, nil+}++// issuerOf is whichever certificate signed the leaf, taken from the verified+// chain where there is one and from the presented chain otherwise. Revocation+// needs it to check a CRL signature or an OCSP response.+func (c *Client) issuerOf(state tls.ConnectionState) *x509.Certificate {+ for _, chain := range state.VerifiedChains {+ if len(chain) > 1 {+ return chain[1]+ }+ }++ if len(state.PeerCertificates) > 1 {+ return state.PeerCertificates[1]+ }++ // A self-signed leaf is its own issuer, which is the honest answer rather+ // than nil: a revocation question about it is still answerable.+ return state.PeerCertificates[0]+}++// policy is the pair of checks crypto/x509 does not have. A mode without them+// is not breaking any rule Go enforces, which is exactly why the traps they+// catch are the ones that reveal whether a target has a policy of its own.+func (c *Client) policy(leaf *x509.Certificate) (string, bool) {+ if c.mode.checksKeyFloor() {+ if bits, ok := modulusBits(leaf); ok &&+ bits < MinimumModulusBits {+ return reasonWeakKey, false+ }+ }++ if c.mode.checksLifetime() {+ lifetime := leaf.NotAfter.Sub(leaf.NotBefore)+ if lifetime > time.Duration(MaximumLifetimeDays)*24*time.Hour {+ return reasonLongLife, false+ }+ }++ if c.mode.checksKeyUsage() &&+ leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 {+ // RFC 5280 section 4.2.1.3: a leaf without digitalSignature cannot be+ // used for a TLS handshake. Verify enforces EXTENDED key usage and+ // never reads these bits, so this check exists in the application or+ // nowhere.+ return reasonNoSigningUse, false+ }++ return reasonAccepted, true+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/matrix_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/matrix_test.gonew file mode 100644index 00000000..ec40aa26--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/matrix_test.go@@ -0,0 +1,494 @@+// ©AngelaMos | 2026+// matrix_test.go++package tlsclient_test++import (+ "context"+ "testing"+ "time"++ "github.com/CarterPerez-dev/khaos/internal/pki"+ "github.com/CarterPerez-dev/khaos/internal/tlsclient"+)++// The matrix. Every trap khaos's authority can arm, judged by every reference+// client, in both directions.+//+// The expectation is DERIVED rather than recorded. Each trap names the one+// check that catches it, each mode names the checks it still performs, and the+// cell is the conjunction. A table of observed results would pass no matter+// what the client did; this one disagrees with the client whenever either the+// reasoning or the implementation is wrong, and both have been.++// guard is the check a trap can only be caught by.+type guard int++const (+ // byAnchor is a fault in WHO signed the certificate: the signature itself,+ // or the path up to a trusted root. It is separate from byValidity because+ // TrustPresentedCA defeats this one and not the other. Putting the served+ // leaf into the root pool makes it a trusted anchor, and crypto/x509 does+ // not check the signature on a certificate it already trusts, so a SHA-1+ // leaf sails through while an expired one still does not.+ //+ // The matrix found that: sha1-signature was the only chain fault+ // TrustPresentedCA accepted, which is what forced this split.+ byAnchor guard = iota++ // byLeaf is a defect in the LEAF itself, which no amount of trusting the+ // presented chain can hide, because the leaf is the certificate being+ // judged either way.+ byLeaf++ // byAnyVerification is defeated only by InsecureSkipVerify. It exists for+ // one trap: withholding the intermediate breaks the chain AND the+ // revocation path, because a client that cannot see the issuer cannot check+ // a CRL signature or an OCSP response from it either. So even the mode that+ // trusts whatever arrived refuses it, through the second route rather than+ // the first.+ byAnyVerification++ byHostname+ byKeyFloor+ byLifetime+ byKeyUsage++ // A list or responder that SAYS the certificate is bad. Which CHANNEL+ // carries the answer decides who can see it, so these are three guards+ // rather than one.+ //+ // byCRLStatus is carried by the revocation list, which even a+ // staple-trusting client goes on to consult. byStapledStatus is carried by+ // the stapled response, which that client accepts without reading.+ // byStapledAmbiguity is a stapled "unknown", invisible to the same client+ // and also waved through by a soft-failing one.+ byCRLStatus+ byStapledStatus+ byStapledAmbiguity++ // The remaining revocation guards are one per CHECK, not one per channel,+ // because the modes break different checks on different channels and a+ // single quality guard got four cells wrong. LooseOCSPParse breaks OCSP+ // binding and leaves CRL freshness intact; NoCRLFreshness is the mirror+ // image. Lumping them together predicted that each would accept both+ // faults, and the matrix refused each prediction.+ byCRLFreshness+ byOCSPFreshness+ byOCSPBinding+ byOCSPSignature+ byStapleValidity++ // byAvailability is an answer that could not be obtained at all, which only+ // a hard-failing client treats as a refusal.+ byAvailability++ // byNothing is a trap no client-side check can catch. CASwap is the only+ // one, and that is the finding rather than a gap: once the anchor is+ // replaced the chain is genuinely valid, and only pinning or certificate+ // transparency helps.+ byNothing+)++// catches is the semantic predicate: does this mode still perform the check+// that this guard represents.+func catches(mode tlsclient.Mode, by guard) bool {+ switch by {+ case byAnchor:+ // TrustPresentedCA defeats every defect ABOVE the leaf, not just the+ // signature. Adding the served certificates to the root pool lets the+ // leaf anchor ITSELF, and crypto/x509 then never consults the chain+ // above it, so an expired intermediate and a CA-level key-usage+ // constraint go unexamined along with the signature. Measured: those+ // two were the cells that refused this prediction.+ return mode != tlsclient.SkipVerify &&+ mode != tlsclient.TrustPresentedCA++ case byLeaf, byAnyVerification:+ return mode != tlsclient.SkipVerify++ case byHostname:+ return mode != tlsclient.SkipVerify &&+ mode != tlsclient.SkipHostname++ case byKeyFloor:+ return mode != tlsclient.SkipVerify &&+ mode != tlsclient.NoKeyFloor++ case byLifetime:+ return mode != tlsclient.SkipVerify &&+ mode != tlsclient.NoLifetimePolicy++ case byKeyUsage:+ return mode != tlsclient.SkipVerify &&+ mode != tlsclient.NoKeyUsagePolicy++ case byCRLStatus:+ return asks(mode)++ case byStapledStatus:+ return asks(mode) && mode != tlsclient.TrustStaple++ case byStapledAmbiguity:+ return asks(mode) &&+ mode != tlsclient.TrustStaple &&+ mode != tlsclient.SoftFailOCSP++ case byCRLFreshness:+ // Caught by anyone who asks and compares the list's window against the+ // clock. TrustStaple still gets here, because a staple answers about+ // OCSP and the CRL is consulted afterwards.+ return asks(mode) &&+ mode != tlsclient.StaleAccepted &&+ mode != tlsclient.NoCRLFreshness++ case byOCSPFreshness:+ // NOT excluded for SoftFailOCSP: a stale response is an answer that was+ // obtained, so there is nothing to soft-fail over, and the client+ // refuses it on freshness like any other.+ return asks(mode) &&+ mode != tlsclient.StaleAccepted &&+ mode != tlsclient.TrustStaple++ case byOCSPBinding:+ // SoftFailOCSP is excluded here and not above, because an unbound+ // response fails to PARSE, which is indistinguishable from not having+ // got one, and that is exactly what a soft-failing client proceeds on.+ return asks(mode) &&+ mode != tlsclient.LooseOCSPParse &&+ mode != tlsclient.TrustStaple &&+ mode != tlsclient.SoftFailOCSP++ case byOCSPSignature, byStapleValidity:+ return asks(mode) &&+ mode != tlsclient.TrustStaple &&+ mode != tlsclient.SoftFailOCSP++ case byAvailability:+ return mode != tlsclient.SkipVerify &&+ mode != tlsclient.NoRevocationCheck &&+ mode != tlsclient.SoftFailOCSP++ case byNothing:+ return false++ default:+ return false+ }+}++// asks is the precondition every revocation guard shares: a client that never+// consults revocation cannot catch anything about it, however correct the rest+// of its verification is. Go's own default is in this group.+func asks(mode tlsclient.Mode) bool {+ return mode != tlsclient.SkipVerify &&+ mode != tlsclient.NoRevocationCheck+}++// guardFor maps each trap to the single check that catches it. A trap mapped to+// the wrong guard makes a whole row of the matrix wrong, so these are grouped+// to read against research 04's fault table.+func guardFor(kind pki.Kind) guard {+ switch kind {+ // In the leaf, so nothing hides them.+ case pki.LeafExpired, pki.LeafNotYetValid, pki.EKUClientAuthOnly:+ return byLeaf++ // Above the leaf, so trusting the presented chain hides them all.+ case pki.SelfSigned, pki.UntrustedCA,+ pki.NameConstraintViolation, pki.PathLengthExceeded,+ pki.SHA1Signature, pki.IntermediateExpired,+ pki.EKUConstrainedIntermediate:+ return byAnchor++ // These two break the chain AND the revocation path, so even the mode that+ // trusts whatever arrived refuses them, through the second route.+ //+ // MissingIntermediate withholds the issuer, and a client that cannot see+ // the issuer cannot check a CRL signature or an OCSP response from it.+ //+ // IssuerNotCA is the same shape for a different reason, traced to+ // crypto/x509: RevocationList.CheckSignatureFrom returns+ // ConstraintViolationError whenever the parent has BasicConstraintsValid+ // and IsCA false (x509.go:2569), BEFORE it looks at KeyUsage or the+ // signature. A CRL from a non-CA issuer is unusable by construction, so+ // this fault cannot be hidden by trusting the chain either.+ case pki.MissingIntermediate, pki.IssuerNotCA:+ return byAnyVerification++ case pki.WrongSAN, pki.CommonNameOnly, pki.NoIPSAN:+ return byHostname++ case pki.WeakKey:+ return byKeyFloor++ case pki.ExcessiveLifetime:+ return byLifetime++ case pki.KeyUsageWithoutDigitalSignature:+ return byKeyUsage++ case pki.RevokedViaCRL:+ return byCRLStatus++ case pki.OCSPRevoked:+ return byStapledStatus++ case pki.StaleCRL:+ return byCRLFreshness++ case pki.OCSPStale:+ return byOCSPFreshness++ case pki.OCSPWrongSerial:+ return byOCSPBinding++ case pki.OCSPWrongSigner:+ return byOCSPSignature++ case pki.StapleGarbage:+ return byStapleValidity++ // Unknown is soft-failable, because SoftFailOCSP is defined as proceeding+ // whenever it cannot get a USABLE answer and "I don't know about this+ // certificate" is not one. It is NOT grouped with the unreachable faults,+ // though, because khaos staples it: those three staple nothing at all, so a+ // staple-trusting client is forced to go and ask and then refuses, while+ // this one it reads and waves through.+ case pki.OCSPUnknown:+ return byStapledAmbiguity++ case pki.CRLUnreachable, pki.OCSPUnreachable, pki.OCSPTryLater:+ return byAvailability++ case pki.CASwap, pki.NoOCSPServer, pki.StapleAbsent:+ // NoOCSPServer and StapleAbsent are not caught by a refusal at all. A+ // correct client falls back to the other revocation channel and+ // rightly accepts, because the certificate is not revoked. What they+ // measure is whether the target ASKED, which the asked-census below+ // covers and an accept/refuse assertion cannot.+ return byNothing++ default:+ return byNothing+ }+}++const (+ host = "dependency.khaos.invalid"+ timeout = 20 * time.Second++ // loopback is the name the NoIPSAN row asks for. A certificate with no IP+ // SANs is perfectly correct for a client dialling by NAME, so asking for+ // the host would record that trap as accepted by every mode and the+ // experiment built on it would measure nothing.+ loopback = "127.0.0.1"+)++// dialName is the server name a client asks for when judging this trap, which+// is not always the host the certificate was minted for.+func dialName(kind pki.Kind) string {+ if kind == pki.NoIPSAN {+ return loopback+ }++ return host+}++// armed stands up an authority with one trap and returns the address a client+// should dial. One authority is reused across every mode for the same trap,+// which is both faster and more honest: every mode judges the SAME served+// chain, which is what makes the row a differential.+func armed(t *testing.T, kind pki.Kind) (*pki.Authority, string) {+ t.Helper()++ a, err := pki.New(pki.Config{Host: host})+ if err != nil {+ t.Fatalf("build an authority: %v", err)+ }++ t.Cleanup(func() { _ = a.Close() })++ if err := a.Listen("127.0.0.1:0"); err != nil {+ t.Fatalf("bind revocation: %v", err)+ }++ if err := a.ListenTLS("127.0.0.1:0"); err != nil {+ t.Fatalf("bind the dependency: %v", err)+ }++ trap := pki.Trap{+ Kind: kind,+ Host: host,+ Window: pki.DefaultWindow,+ Bits: pki.DefaultWeakBits,+ Days: pki.DefaultExcessiveDays,+ }++ if kind == pki.PassThrough {+ if err := a.Disarm(); err != nil {+ t.Fatalf("disarm: %v", err)+ }+ } else if err := a.Arm(trap); err != nil {+ t.Fatalf("arm %s: %v", kind, err)+ }++ addr, err := a.TLSAddr()+ if err != nil {+ t.Fatalf("dependency address: %v", err)+ }++ return a, addr+}++func decide(+ t *testing.T,+ a *pki.Authority,+ addr string,+ mode tlsclient.Mode,+ asking string,+) tlsclient.Decision {+ t.Helper()++ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()++ client := tlsclient.New(tlsclient.Config{+ Mode: mode,+ Host: asking,+ Roots: a.TrustedPool(),+ Now: a.Now,+ })++ return client.Decide(ctx, addr)+}++func TestEveryTrapAgainstEveryReferenceClient(t *testing.T) {+ kinds := pki.Kinds()+ modes := tlsclient.Modes()++ if len(kinds) == 0 || len(modes) == 0 {+ t.Fatal("the matrix is empty, so it asserts nothing")+ }++ for _, name := range kinds {+ kind := pki.Kind(name)++ t.Run(name, func(t *testing.T) {+ a, addr := armed(t, kind)+ by := guardFor(kind)++ for _, modeName := range modes {+ mode := tlsclient.Mode(modeName)++ t.Run(modeName, func(t *testing.T) {+ decision := decide(+ t,+ a,+ addr,+ mode,+ dialName(kind),+ )+ wantRefusal := catches(mode, by)++ if wantRefusal && decision.Accepted {+ t.Fatalf(+ "%s accepted %s, but this mode still performs the check that catches it",+ mode,+ kind,+ )+ }++ if !wantRefusal && !decision.Accepted {+ t.Fatalf(+ "%s refused %s (%s), but this mode does not perform the check that catches it, so the refusal came from somewhere khaos did not intend",+ mode,+ kind,+ decision.Reason,+ )+ }+ })+ }+ })+ }+}++// The control for the whole matrix. The correct client has to accept an unarmed+// authority, or every refusal above could be khaos's own broken baseline.+func TestTheCorrectClientAcceptsAnUnarmedAuthority(t *testing.T) {+ a, addr := armed(t, pki.PassThrough)++ decision := decide(t, a, addr, tlsclient.Correct, host)++ if !decision.Accepted {+ t.Fatalf(+ "the correct client refused an honest dependency (%s); every cell in the matrix is measured against this",+ decision.Reason,+ )+ }++ // And it has to have LOOKED. A client that accepted without asking would+ // pass the line above while being exactly the fail-open this family exists+ // to find.+ if !decision.AskedOCSP && !decision.AskedCRL {+ t.Fatal(+ "the correct client accepted without consulting revocation at all, which is the NoRevocationCheck mode wearing the correct client's name",+ )+ }+}++// The two traps that no refusal can catch still have to be measurable, and the+// only thing that separates a target which fell back from one which shrugged is+// whether it asked. This is that assertion.+func TestFallbackTrapsAreMeasuredByWhatTheClientAsked(t *testing.T) {+ cases := []struct {+ kind pki.Kind+ want func(tlsclient.Decision) bool+ why string+ }{+ {+ kind: pki.NoOCSPServer,+ want: func(d tlsclient.Decision) bool { return d.AskedCRL },+ why: "fall back to the CRL when the certificate names no responder",+ },+ {+ kind: pki.StapleAbsent,+ want: func(d tlsclient.Decision) bool { return d.AskedOCSP },+ why: "query the responder directly when no staple arrives",+ },+ }++ for _, each := range cases {+ t.Run(string(each.kind), func(t *testing.T) {+ a, addr := armed(t, each.kind)++ correct := decide(t, a, addr, tlsclient.Correct, host)+ if !correct.Accepted {+ t.Fatalf(+ "the correct client refused %s; the certificate is not revoked, so accepting is right and the finding is whether it asked",+ each.kind,+ )+ }++ if !each.want(correct) {+ t.Fatalf(+ "the correct client did not %s, so this trap cannot tell a target that falls back from one that shrugs",+ each.why,+ )+ }++ blind := decide(+ t,+ a,+ addr,+ tlsclient.NoRevocationCheck,+ host,+ )+ if blind.AskedCRL || blind.AskedOCSP {+ t.Fatalf(+ "the no-revocation-check client consulted revocation anyway, so the asked-census cannot distinguish the two",+ )+ }+ })+ }+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/mode.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/mode.gonew file mode 100644index 00000000..1830ddd3--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/mode.go@@ -0,0 +1,201 @@+// ©AngelaMos | 2026+// mode.go++package tlsclient++import (+ "errors"+ "fmt"+ "slices"+ "strings"+)++// Mode is one way a TLS client can be wrong, drawn from the fail-open taxonomy+// in research 04 and 07.+//+// Correct is a REFERENCE IMPLEMENTATION, not a wrapper around crypto/tls.+// Go verifies the chain, the hostname and the validity window and then stops,+// because `crypto/x509` performs no revocation checking of any kind. So the+// correct client here is Go's verification PLUS the layer Go does not have:+// the six-step CRL check, OCSP with freshness and certificate binding, a key+// floor and a lifetime policy. Every broken mode below removes exactly one+// piece of that layer, which is what makes a differential meaningful.+type Mode string++const (+ // Correct refuses everything a correct client should refuse. It is the+ // control for every other mode and the only one khaos ships as an example+ // worth copying.+ Correct Mode = "closed"++ // SkipVerify is InsecureSkipVerify. It is first because it is the single+ // most common fail-open in real code: it turns off the chain, the hostname+ // and the validity window in one assignment, and it is what people reach+ // for when a certificate error blocks a deploy.+ SkipVerify Mode = "skip-verify"++ // SkipHostname verifies the chain and skips only the name. It is a real and+ // subtler shape than SkipVerify: the connection is to a provably valid+ // certificate for somebody else.+ SkipHostname Mode = "skip-hostname"++ // TrustPresentedCA builds its trust anchors out of whatever the server+ // sent, which accepts any self-consistent chain. This is the shape a+ // developer writes when "add the CA to the pool" is the error they are+ // trying to silence.+ TrustPresentedCA Mode = "trust-presented-ca"++ // NoRevocationCheck is Go's own default behaviour, stated as a mode. It+ // verifies the chain properly and never asks whether the certificate was+ // revoked, which is correct Go and an incorrect client.+ NoRevocationCheck Mode = "no-revocation-check"++ // SoftFailOCSP asks and then proceeds whenever it does not get a usable+ // answer: a transport failure, a TryLater, an Unknown. Research 04 calls+ // soft-fail the reason revocation is near-useless in practice.+ SoftFailOCSP Mode = "soft-fail-ocsp"++ // StaleAccepted checks the status and never the freshness window, so a+ // replayed or cached Good is trusted forever.+ StaleAccepted Mode = "stale-accepted"++ // LooseOCSPParse calls ParseResponse instead of ParseResponseForCert. That+ // one word stops the response being bound to the certificate, so a Good+ // minted for a different serial is accepted. It is the cheapest total+ // bypass of revocation checking in the whole taxonomy.+ LooseOCSPParse Mode = "loose-ocsp-parse"++ // NoCRLFreshness performs the whole CRL check except step five. It fetches,+ // verifies the signature and scans the serials, and never looks at+ // NextUpdate, so a three-week-old list is authoritative.+ NoCRLFreshness Mode = "no-crl-freshness"++ // TrustStaple reads the stapled response and believes it without checking+ // that it is a response at all. Go never parses a staple, so whatever the+ // server attached arrives verbatim.+ TrustStaple Mode = "trust-staple"++ // NoKeyFloor, NoLifetimePolicy and NoKeyUsagePolicy drop the three policy+ // checks x509 does not have. They exist so that each trap Go accepts has+ // both a mode that catches it and a mode that does not, which is the only+ // way those experiments can distinguish a target with a policy of its own+ // from one with none.+ //+ // NoKeyUsagePolicy is the subtlest of the three. Verify enforces EXTENDED+ // key usage, nested down the chain, and never looks at the basic KeyUsage+ // bits on a leaf. A leaf whose KeyUsage omits digitalSignature is unusable+ // for TLS under RFC 5280 section 4.2.1.3 and Go will not say a word about+ // it, so a correct client has to check it here or not at all.+ NoKeyFloor Mode = "no-key-floor"+ NoLifetimePolicy Mode = "no-lifetime-policy"+ NoKeyUsagePolicy Mode = "no-key-usage-policy"+)++const (+ errUnknownMode = "%w: %q (known modes: %s)"+ modeSep = ", "+)++// ErrUnknownMode is a name this package has no client for.+var ErrUnknownMode = errors.New("no such reference client mode")++// Modes is every mode, Correct first. Tests census against this.+func Modes() []string {+ return []string{+ string(Correct),+ string(SkipVerify),+ string(SkipHostname),+ string(TrustPresentedCA),+ string(NoRevocationCheck),+ string(SoftFailOCSP),+ string(StaleAccepted),+ string(LooseOCSPParse),+ string(NoCRLFreshness),+ string(TrustStaple),+ string(NoKeyFloor),+ string(NoLifetimePolicy),+ string(NoKeyUsagePolicy),+ }+}++// ParseMode resolves a mode name, refusing anything it does not implement+// rather than silently falling back to Correct. A range fixture that quietly+// became correct would report every experiment as fail-closed.+func ParseMode(name string) (Mode, error) {+ if !slices.Contains(Modes(), name) {+ return "", fmt.Errorf(+ errUnknownMode,+ ErrUnknownMode,+ name,+ strings.Join(Modes(), modeSep),+ )+ }++ return Mode(name), nil+}++// checksChain reports whether the mode lets crypto/x509 build and check the+// path at all.+func (m Mode) checksChain() bool {+ return m != SkipVerify+}++// checksHostname reports whether the mode matches the name it asked for.+func (m Mode) checksHostname() bool {+ return m != SkipVerify && m != SkipHostname+}++// checksRevocation reports whether the mode asks about revocation in any way.+// Go's default is false, which is the whole reason this family exists.+func (m Mode) checksRevocation() bool {+ switch m {+ case SkipVerify, NoRevocationCheck:+ return false+ default:+ return true+ }+}++// hardFails reports whether a revocation answer the mode could not obtain is+// treated as a refusal. A soft-failing client proceeds, which is Langley's+// seat belt that unbuckles in a crash.+func (m Mode) hardFails() bool {+ return m != SoftFailOCSP+}++// checksCRLFreshness and checksOCSPFreshness are SEPARATE, because the modes+// break them separately. Nothing in the standard library checks either one.+//+// A single predicate covering both was wrong and the matrix caught it:+// NoCRLFreshness is named for the CRL and was silently disabling the OCSP+// freshness check as well, so a stale OCSP response was accepted by a client+// whose only declared defect was about certificate revocation lists.+func (m Mode) checksCRLFreshness() bool {+ return m != StaleAccepted && m != NoCRLFreshness+}++func (m Mode) checksOCSPFreshness() bool {+ return m != StaleAccepted+}++// bindsResponse reports whether the mode checks that an OCSP response is about+// the certificate in hand.+func (m Mode) bindsResponse() bool {+ return m != LooseOCSPParse+}++// checksKeyFloor and checksLifetime are the two policies x509 does not have, so+// a mode without them is not breaking any rule Go enforces.+func (m Mode) checksKeyFloor() bool {+ return m != SkipVerify && m != NoKeyFloor+}++func (m Mode) checksLifetime() bool {+ return m != SkipVerify && m != NoLifetimePolicy+}++// checksKeyUsage reports whether the mode enforces the basic KeyUsage bits,+// which crypto/x509 never does on a leaf.+func (m Mode) checksKeyUsage() bool {+ return m != SkipVerify && m != NoKeyUsagePolicy+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/revocation.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/revocation.gonew file mode 100644index 00000000..e7b58960--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/tlsclient/revocation.go@@ -0,0 +1,314 @@+// ©AngelaMos | 2026+// revocation.go++package tlsclient++import (+ "bytes"+ "context"+ "crypto/rsa"+ "crypto/tls"+ "crypto/x509"+ "io"+ "net/http"++ "golang.org/x/crypto/ocsp"+)++const maxRevocationBody = 1 << 20++// revocation is the layer crypto/x509 does not have.+//+// The order matters and is not arbitrary. A STAPLED response is preferred+// because it costs no round trip and is what a real client sees first; then+// OCSP, because it answers about one certificate rather than about every+// certificate the CA ever revoked; then the CRL as a fallback, because that is+// what remains once a CA ends OCSP, which Let's Encrypt did in 2025.+//+// A mode that checks nothing returns accepted here without asking anything, and+// the Asked fields record that, because "accepted without looking" and+// "accepted after looking" are different findings about a target.+func (c *Client) revocation(+ ctx context.Context,+ leaf, issuer *x509.Certificate,+ state tls.ConnectionState,+) Decision {+ if !c.mode.checksRevocation() {+ return Decision{Accepted: true}+ }++ decision := Decision{Accepted: true}++ if reason, ok := c.fromStaple(state, leaf, issuer, &decision); !ok {+ return Decision{Reason: reason, AskedOCSP: decision.AskedOCSP}+ }++ if reason, ok := c.fromOCSP(ctx, leaf, issuer, &decision); !ok {+ return Decision{+ Reason: reason,+ AskedOCSP: decision.AskedOCSP,+ AskedCRL: decision.AskedCRL,+ }+ }++ if reason, ok := c.fromCRL(ctx, leaf, issuer, &decision); !ok {+ return Decision{+ Reason: reason,+ AskedOCSP: decision.AskedOCSP,+ AskedCRL: decision.AskedCRL,+ }+ }++ return decision+}++// fromStaple reads the response the handshake carried. Go never parses a+// staple, so whatever the server attached arrives verbatim and only this code+// decides anything about it.+func (c *Client) fromStaple(+ state tls.ConnectionState,+ leaf, issuer *x509.Certificate,+ decision *Decision,+) (string, bool) {+ if len(state.OCSPResponse) == 0 {+ // No staple at all. A soft-failing client reads this as "fine", which+ // is the StapleAbsent fault, and a correct one falls through to asking+ // the responder directly rather than refusing outright.+ return reasonAccepted, true+ }++ if c.mode == TrustStaple {+ // Believed without being parsed. Garbage bytes are accepted here, which+ // is the whole of the StapleGarbage fault.+ //+ // The question is marked ANSWERED. A client that trusts the staple does+ // not then go and ask the responder as well, and the first version fell+ // through to doing exactly that: it accepted the staple, queried the+ // endpoint anyway, and refused on the real answer. Three traps looked+ // caught by a mode that by construction cannot catch them.+ decision.AskedOCSP = true++ return reasonAccepted, true+ }++ response, err := c.parseOCSP(state.OCSPResponse, leaf, issuer)+ if err != nil {+ if c.mode.hardFails() {+ return reasonBadStaple, false+ }++ return reasonAccepted, true+ }++ decision.AskedOCSP = true++ return c.judgeOCSP(response)+}++// fromOCSP asks the responder named in the certificate. A certificate naming no+// responder is not an error: it is what Let's Encrypt now issues, and the+// honest answer is to fall through to the CRL.+func (c *Client) fromOCSP(+ ctx context.Context,+ leaf, issuer *x509.Certificate,+ decision *Decision,+) (string, bool) {+ if len(leaf.OCSPServer) == 0 {+ return reasonAccepted, true+ }++ if decision.AskedOCSP {+ // Already answered by the staple.+ return reasonAccepted, true+ }++ request, err := ocsp.CreateRequest(leaf, issuer, nil)+ if err != nil {+ return c.cannotTell()+ }++ body, err := c.post(ctx, leaf.OCSPServer[0], request)+ if err != nil {+ // Could not reach the responder, or it answered TryLater. A+ // soft-failing client proceeds here, which is the trap.+ return c.cannotTell()+ }++ response, err := c.parseOCSP(body, leaf, issuer)+ if err != nil {+ return c.cannotTell()+ }++ decision.AskedOCSP = true++ return c.judgeOCSP(response)+}++// parseOCSP is the one-word difference that is a total bypass. ParseResponse+// does NOT bind the response to the certificate, so a Good minted for another+// serial is accepted; ParseResponseForCert refuses it. Both verify the+// signature.+func (c *Client) parseOCSP(+ der []byte,+ leaf, issuer *x509.Certificate,+) (*ocsp.Response, error) {+ if c.mode.bindsResponse() {+ return ocsp.ParseResponseForCert(der, leaf, issuer)+ }++ return ocsp.ParseResponse(der, issuer)+}++// judgeOCSP decides on a response that already verified. Good is the only+// acceptable status: Unknown from the authoritative responder is not good, and+// collapsing the two is its own fail-open.+func (c *Client) judgeOCSP(response *ocsp.Response) (string, bool) {+ if response.Status == ocsp.Revoked {+ return reasonRevoked, false+ }++ if response.Status != ocsp.Good {+ if c.mode.hardFails() {+ return reasonOCSPStatus, false+ }++ return reasonAccepted, true+ }++ if c.mode.checksOCSPFreshness() && !response.NextUpdate.IsZero() &&+ response.NextUpdate.Before(c.clock()) {+ // x/crypto/ocsp does not check this, measured: a response with+ // NextUpdate a day in the past parses with a nil error. A client that+ // skips it trusts a replayed Good forever.+ return reasonStaleOCSP, false+ }++ return reasonAccepted, true+}++// fromCRL is the six-step check from research 04 section 4.3, in full, because+// steps five and six are the ones people skip and skipping either is a+// fail-open on its own.+func (c *Client) fromCRL(+ ctx context.Context,+ leaf, issuer *x509.Certificate,+ decision *Decision,+) (string, bool) {+ if len(leaf.CRLDistributionPoints) == 0 {+ return reasonAccepted, true+ }++ // Step 2: fetch. Go parses the distribution point and never follows it.+ der, err := c.fetch(ctx, leaf.CRLDistributionPoints[0])+ if err != nil {+ return c.cannotTell()+ }++ // Step 3: parse.+ list, err := x509.ParseRevocationList(der)+ if err != nil {+ return c.cannotTell()+ }++ decision.AskedCRL = true++ // Step 4: the signature, or anyone can hand you a list.+ if err := list.CheckSignatureFrom(issuer); err != nil {+ return reasonBadCRLSig, false+ }++ // Step 5: freshness. Nothing in the standard library does this, and a+ // three-week-old list is otherwise authoritative.+ if c.mode.checksCRLFreshness() && !list.NextUpdate.IsZero() &&+ list.NextUpdate.Before(c.clock()) {+ return reasonStaleCRL, false+ }++ // Step 6: the linear scan.+ for _, entry := range list.RevokedCertificateEntries {+ if entry.SerialNumber.Cmp(leaf.SerialNumber) == 0 {+ return reasonRevoked, false+ }+ }++ return reasonAccepted, true+}++// cannotTell is the soft-fail decision point, and the single most consequential+// branch in this file. A client that proceeds because it could not get an+// answer has a seat belt that unbuckles in a crash.+func (c *Client) cannotTell() (string, bool) {+ if c.mode.hardFails() {+ return reasonNoAnswer, false+ }++ return reasonAccepted, true+}++func (c *Client) fetch(ctx context.Context, url string) ([]byte, error) {+ request, err := http.NewRequestWithContext(+ ctx,+ http.MethodGet,+ url,+ nil,+ )+ if err != nil {+ return nil, err+ }++ return c.send(request)+}++func (c *Client) post(+ ctx context.Context,+ url string,+ body []byte,+) ([]byte, error) {+ request, err := http.NewRequestWithContext(+ ctx,+ http.MethodPost,+ url,+ bytes.NewReader(body),+ )+ if err != nil {+ return nil, err+ }++ request.Header.Set("Content-Type", "application/ocsp-request")++ return c.send(request)+}++func (c *Client) send(request *http.Request) ([]byte, error) {+ response, err := c.http.Do(request)+ if err != nil {+ return nil, err+ }++ defer func() { _ = response.Body.Close() }()++ if response.StatusCode != http.StatusOK {+ return nil, &httpStatusError{status: response.Status}+ }++ return io.ReadAll(io.LimitReader(response.Body, maxRevocationBody))+}++type httpStatusError struct {+ status string+}++func (e *httpStatusError) Error() string {+ return "revocation endpoint answered " + e.status+}++// modulusBits is the leaf's RSA size, and false for any other key type. An+// ECDSA key has no modulus and the floor does not apply to it.+func modulusBits(leaf *x509.Certificate) (int, bool) {+ key, ok := leaf.PublicKey.(*rsa.PublicKey)+ if !ok {+ return 0, false+ }++ return key.N.BitLen(), true+}