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 certificate authority, 32 traps measured against crypto/x509
CarterPerez-dev7c899a7d1f46
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/go.mod b/PROJECTS/intermediate/chaos-engineering-tool/go.modindex 5d1e83cd..cf346997 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/go.mod+++ b/PROJECTS/intermediate/chaos-engineering-tool/go.mod@@ -11,6 +11,7 @@ require (github.com/reeflective/console v0.5.0github.com/spf13/cobra v1.10.2github.com/spf13/pflag v1.0.10+ golang.org/x/crypto v0.57.0golang.org/x/sys v0.48.0golang.org/x/term v0.46.0)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/go.sum b/PROJECTS/intermediate/chaos-engineering-tool/go.sumindex 4eccf5f2..04f4c5d3 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/go.sum+++ b/PROJECTS/intermediate/chaos-engineering-tool/go.sum@@ -111,6 +111,8 @@ go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFgo.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=+golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=+golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=golang.org/x/exp v0.0.0-20260529124908-c761662dc8c9 h1:4d4PbuBNwaxMXkXI8yiIYjydtMU+04RHeuSxJdgKftM=golang.org/x/exp v0.0.0-20260529124908-c761662dc8c9/go.mod h1:d2fgXJLVs4dYDHUk5lwMIfzRzSrWCfGZb0ZqeLa/Vcw=golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.gonew file mode 100644index 00000000..ce9ffd05--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go@@ -0,0 +1,350 @@+// ©AngelaMos | 2026+// authority.go++package pki++import (+ "crypto/x509"+ "errors"+ "fmt"+ "sync"+ "sync/atomic"+ "time"+)++const (+ nameRoot = "khaos chaos root"+ nameInter = "khaos chaos intermediate"+ nameRogueRoot = "khaos rogue root"+ nameRogueInter = "khaos rogue intermediate"+ nameConstrained = "khaos constrained intermediate"+ 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+ // for. Anything else trips Reason 2, which is the fault.+ constrainedDomain = "constrained.khaos.invalid"++ // foreignHost is the name WrongSAN puts in the certificate instead of the+ // one the client asked for.+ foreignHost = "not-the-host-you-asked-for.khaos.invalid"++ caYears = 10++ errNoTrap = "%w: nothing is armed, so there is no chain to serve"+ errArmTrap = "%w: %v"+ errBuildFor = "%w: building a chain for %s: %v"+)++var (+ // ErrNothingArmed is a request for the served chain while the authority is+ // behaving correctly and no trap has been armed.+ ErrNothingArmed = errors.New(+ "khaos's certificate authority has no fault armed",+ )++ // ErrTrapNotObserved is khaos failing to confirm its OWN fault. It is+ // deliberately loud: an unconfirmed fault means the run must not proceed,+ // because a measurement under a fault that may not have landed is not+ // evidence about the target.+ ErrTrapNotObserved = errors.New(+ "khaos could not confirm its own certificate fault landed",+ )+)++// Config is how a caller aims the authority. Every field has a working default,+// because an authority that needs configuring before it can serve an honest+// certificate would make the baseline the hard case.+type Config struct {+ // Host is the name honest certificates are minted for.+ Host string++ // Now overrides the clock, for tests that need a deterministic validity+ // window rather than one relative to a real wall clock.+ Now func() time.Time+}++// Authority is khaos's in-process certificate authority: a CA deliberately+// willing to be wrong, in one named way at a time.+//+// It exists because no correct CA will mint an expired, revoked or+// wrongly-named certificate at any price, and those are precisely the+// certificates this family needs. The same argument that justified the in-+// process identity provider for tokens justifies this for chains.+type Authority struct {+ mu sync.RWMutex++ clock func() time.Time+ host string++ // The hierarchy the target is configured to trust.+ root *pair+ inter *pair++ // A second, complete hierarchy khaos also controls. UntrustedCA serves a+ // leaf under it while the target still trusts the first; CASwap makes this+ // one the root the target trusts, which is the CA-compromise scenario and+ // the one fault nothing in a client can detect.+ rogueRoot *pair+ rogueInter *pair++ // Purpose-built issuers, minted once at construction so that arming a trap+ // is cheap, deterministic, and cannot fail for a reason unrelated to the+ // fault.+ constrained *pair+ ekuLimited *pair+ notACA *pair+ responder *pair+ undelegated *pair++ // deepInter sits under deepCapped, whose MaxPathLen is zero. BOTH have to+ // be presented in the handshake: a client given only deepInter cannot reach+ // the root at all, and the fault then reads as an unknown authority rather+ // than the path-length violation it is. That is measured, not theorised --+ // the first draft presented one and the differential caught it.+ deepInter *pair+ deepCapped *pair++ trap Trap+ armed *Chain++ // inert makes every arming a no-op while still reporting success. It is the+ // NEGATIVE CONTROL for the confirmation oracle: without a way to make the+ // authority refuse to misbehave, a gutted Observe that always says yes+ // leaves the whole suite green. The identity family learned this the+ // expensive way.+ inert atomic.Bool++ // crlFetches and ocspQueries count what the TARGET asked for. khaos's own+ // confirmation probes are counted separately and subtracted, or khaos would+ // be measuring itself.+ crlFetches atomic.Int64+ ocspQueries atomic.Int64+ ownCRL atomic.Int64+ ownOCSP atomic.Int64++ listener listenerState+ closeOnce sync.Once+ closed chan struct{}+}++// New builds the authority and every CA it will ever need. All of the minting+// happens here rather than at arm time, so a trap that cannot be armed is a+// real fault in the trap and never a key generation that happened to fail+// mid-experiment.+func New(cfg Config) (*Authority, error) {+ a := &Authority{+ clock: cfg.Now,+ host: cfg.Host,+ closed: make(chan struct{}),+ }++ if a.clock == nil {+ a.clock = time.Now+ }++ if a.host == "" {+ a.host = DefaultHost+ }++ if err := a.buildHierarchies(); err != nil {+ return nil, err+ }++ if err := a.buildSpecialIssuers(); err != nil {+ return nil, err+ }++ return a, nil+}++func (a *Authority) buildHierarchies() error {+ now := a.clock()+ from := now.Add(-clockSlack)+ until := now.AddDate(caYears, 0, 0)++ var err error++ if a.root, err = a.mintCA(nameRoot, nil, from, until); err != nil {+ return err+ }++ if a.inter, err = a.mintCA(nameInter, a.root, from, until); err != nil {+ return err+ }++ if a.rogueRoot, err = a.mintCA(+ nameRogueRoot,+ nil,+ from,+ until,+ ); err != nil {+ return err+ }++ a.rogueInter, err = a.mintCA(nameRogueInter, a.rogueRoot, from, until)++ return err+}++func (a *Authority) buildSpecialIssuers() error {+ now := a.clock()+ from := now.Add(-clockSlack)+ until := now.AddDate(caYears, 0, 0)++ if err := a.buildConstrained(from, until); err != nil {+ return err+ }++ if err := a.buildEKULimited(from, until); err != nil {+ return err+ }++ if err := a.buildNotACA(from, until); err != nil {+ return err+ }++ if err := a.buildDeepInter(from, until); err != nil {+ return err+ }++ return a.buildResponders(from, until)+}++// mintCA is the one path every CA in this package comes from, so a defect in+// CA construction cannot differ between the honest hierarchy and a trap's.+func (a *Authority) mintCA(+ name string,+ parent *pair,+ from, until time.Time,+) (*pair, error) {+ template, err := caTemplate(name, from, until)+ if err != nil {+ return nil, err+ }++ key, err := newKey(StrongBits)+ if err != nil {+ return nil, err+ }++ return issue(template, parent, key)+}++// Host is the name honest certificates are minted for.+func (a *Authority) Host() string {+ return a.host+}++// TrustedRoot is the anchor the TARGET is configured with. CASwap is the one+// trap that changes what this returns, which is exactly why the trap works.+func (a *Authority) TrustedRoot() *x509.Certificate {+ a.mu.RLock()+ defer a.mu.RUnlock()++ if a.trap.Kind == CASwap {+ return a.rogueRoot.cert+ }++ return a.root.cert+}++// TrustedPool is TrustedRoot as a pool, which is what a client actually needs.+func (a *Authority) TrustedPool() *x509.CertPool {+ pool := x509.NewCertPool()+ pool.AddCert(a.TrustedRoot())++ return pool+}++// Arm applies a trap and mints the chain it will serve. The chain is built HERE+// rather than per handshake so that every handshake in one experiment presents+// the same certificate: a leaf re-minted per connection would get a new serial+// each time, and a revocation answer about a serial the client is no longer+// holding is not a fault, it is khaos racing itself.+func (a *Authority) Arm(trap Trap) error {+ if err := trap.Validate(); err != nil {+ return fmt.Errorf(errArmTrap, ErrInvalidTrap, err)+ }++ if a.inert.Load() {+ return nil+ }++ chain, err := a.build(trap)+ if err != nil {+ return err+ }++ a.mu.Lock()+ defer a.mu.Unlock()++ a.trap = trap+ a.armed = chain++ return nil+}++// Disarm returns the authority to behaving correctly and re-mints an honest+// chain, so the recovery window is measured through a working authority rather+// than through no authority at all.+func (a *Authority) Disarm() error {+ honest, err := a.build(Trap{Kind: PassThrough, Host: a.host})+ if err != nil {+ return err+ }++ a.mu.Lock()+ defer a.mu.Unlock()++ a.trap = Trap{}+ a.armed = honest++ return nil+}++// Inert makes arming a no-op that still reports success, which is the only way+// to give the confirmation oracle an input it MUST reject.+func (a *Authority) Inert(on bool) {+ a.inert.Store(on)+}++// Trap is what is currently armed.+func (a *Authority) Trap() Trap {+ a.mu.RLock()+ defer a.mu.RUnlock()++ return a.trap+}++// Served is the chain the authority is presenting right now.+func (a *Authority) Served() (*Chain, error) {+ a.mu.RLock()+ defer a.mu.RUnlock()++ if a.armed == nil {+ return nil, fmt.Errorf(errNoTrap, ErrNothingArmed)+ }++ return a.armed, nil+}++// CRLFetches and OCSPQueries report what the TARGET did, with khaos's own+// confirmation probes subtracted. A count that included khaos's probes would+// make "the target checked revocation" true for every run.+func (a *Authority) CRLFetches() int64 {+ return a.crlFetches.Load() - a.ownCRL.Load()+}++func (a *Authority) OCSPQueries() int64 {+ return a.ocspQueries.Load() - a.ownOCSP.Load()+}++func (a *Authority) Close() error {+ a.closeOnce.Do(func() { close(a.closed) })++ return a.shutdown()+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.gonew file mode 100644index 00000000..93bdb2fc--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go@@ -0,0 +1,307 @@+// ©AngelaMos | 2026+// catalog.go++package pki++import (+ "fmt"+ "strings"+ "time"+)++const (+ // StrongBits is the modulus khaos mints when it is NOT attacking the key+ // size. 2048 is the floor every current policy agrees on, and x509 path+ // validation enforces none of them.+ StrongBits = 2048++ // LifetimeCapDays is the CA/Browser Forum maximum leaf lifetime. Nothing+ // outside a browser enforces it, which is what ExcessiveLifetime measures.+ LifetimeCapDays = 200++ // DefaultLeafDays is an ordinary, unremarkable lifetime for every honest+ // certificate khaos serves.+ DefaultLeafDays = 90++ // DefaultWindow is how far a time-based trap moves its boundary when the+ // experiment does not say. It is far longer than any plausible clock skew,+ // because a fault inside the skew tolerance is not a fault.+ DefaultWindow = 24 * time.Hour++ // DefaultWeakBits is the modulus WeakKey mints by default. Measured on+ // go1.26.5: a 1024-bit leaf chains and verifies with a nil error.+ DefaultWeakBits = 1024++ // DefaultExcessiveDays is comfortably past the CABF cap and past every+ // shorter policy a target might have adopted instead.+ DefaultExcessiveDays = 2000++ // DefaultHost is the name khaos mints honest certificates for when the+ // caller does not say. It is a .invalid name per RFC 2606, so a chain that+ // escaped into something real can never resolve.+ DefaultHost = "dependency.khaos.invalid"++ // clockSlack backdates every honest certificate slightly. Without it a leaf+ // minted and presented in the same millisecond can land on the wrong side+ // of a NotBefore comparison on a machine whose clock ticks between the two,+ // which would make the CONTROL flaky and leave khaos unable to establish+ // anything.+ clockSlack = time.Minute+)++const (+ // RouteCRL, RouteOCSP and RouteHealth are the authority's HTTP surface.+ //+ // RouteHealth exists to be the CONTROL for the two unreachable traps. Its+ // whole job is to stay up while the CRL or OCSP endpoint refuses, because+ // "khaos broke one endpoint" and "khaos fell over" are different claims and+ // only the first one is a fault.+ RouteCRL = "/crl"+ RouteOCSP = "/ocsp"+ RouteHealth = "/healthz"+)++// Kinds is the whole catalogue, in the order the research groups it: validity,+// identity, authority, algorithm, policy, CRL revocation, OCSP revocation,+// stapling, trust store. Tests census against this, so a new trap without a+// case of its own turns them red.+func Kinds() []string {+ return []string{+ string(LeafExpired),+ string(LeafNotYetValid),+ string(IntermediateExpired),++ string(WrongSAN),+ string(CommonNameOnly),+ string(NoIPSAN),++ string(SelfSigned),+ string(UntrustedCA),+ string(MissingIntermediate),+ string(IssuerNotCA),+ string(NameConstraintViolation),+ string(PathLengthExceeded),++ string(SHA1Signature),+ string(EKUClientAuthOnly),+ string(EKUConstrainedIntermediate),++ string(WeakKey),+ string(ExcessiveLifetime),+ string(KeyUsageWithoutDigitalSignature),++ string(RevokedViaCRL),+ string(StaleCRL),+ string(CRLUnreachable),++ string(OCSPRevoked),+ string(OCSPUnknown),+ string(OCSPTryLater),+ string(OCSPUnreachable),+ string(OCSPStale),+ string(OCSPWrongSerial),+ string(OCSPWrongSigner),+ string(NoOCSPServer),++ string(StapleGarbage),+ string(StapleAbsent),++ string(CASwap),+ }+}++func joinKinds() string {+ return strings.Join(Kinds(), trapSep)+}++// GoAccepts reports whether go1.26.5's own certificate verification returns a+// NIL error for this trap. It is the single most important predicate in the+// package, because it decides what a target's acceptance MEANS.+//+// For a trap Go refuses, an acceptance proves the target weakened or skipped+// verification. For a trap Go accepts, an acceptance proves nothing of the+// kind: there was no check to skip, and the finding is that the target has no+// policy of its own. Reporting the second as the first would be khaos accusing+// a target of a defect that only exists in the operator's expectations.+//+// Every entry here was measured, not assumed; research 04's fault table records+// the run, and the CRL and SHA-1 rows were re-measured on this box before this+// family was built.+func GoAccepts(kind Kind) bool {+ switch kind {+ case WeakKey, ExcessiveLifetime, KeyUsageWithoutDigitalSignature,+ RevokedViaCRL, StaleCRL, CRLUnreachable,+ OCSPRevoked, OCSPUnknown, OCSPTryLater, OCSPUnreachable,+ OCSPStale, OCSPWrongSerial, OCSPWrongSigner, NoOCSPServer,+ StapleGarbage, StapleAbsent, CASwap:+ return true++ case PassThrough, LeafExpired, LeafNotYetValid, IntermediateExpired,+ WrongSAN, CommonNameOnly, NoIPSAN,+ SelfSigned, UntrustedCA, MissingIntermediate, IssuerNotCA,+ NameConstraintViolation, PathLengthExceeded,+ SHA1Signature, EKUClientAuthOnly, EKUConstrainedIntermediate:+ return false++ default:+ // An unknown kind is treated as refused, which is the conservative+ // direction: it makes khaos claim LESS about a target than it could.+ return false+ }+}++// Describe states the trap with its actual magnitude, for the consent prompt+// and the plan output. The identity family established that a description+// naming a parameter without its VALUE is worse than none, because the operator+// approves a sentence and then gets a different fault.+func (t Trap) Describe(target string) string {+ switch t.Kind {+ case LeafExpired, LeafNotYetValid, IntermediateExpired, WrongSAN,+ CommonNameOnly, NoIPSAN:+ return t.describeSubject(target)++ case SelfSigned, UntrustedCA, MissingIntermediate, IssuerNotCA,+ NameConstraintViolation, PathLengthExceeded, SHA1Signature,+ EKUClientAuthOnly, EKUConstrainedIntermediate:+ return t.describeChain(target)++ case WeakKey, ExcessiveLifetime, KeyUsageWithoutDigitalSignature,+ CASwap:+ return t.describePolicy(target)++ case PassThrough:+ return ""++ default:+ return t.describeRevocation(target)+ }+}++// describeSubject covers the faults in WHEN the certificate is valid and WHO it+// is for.+func (t Trap) describeSubject(target string) string {+ switch t.Kind {+ case LeafExpired:+ return fmt.Sprintf(describeLeafExpired, target, t.window())+ case LeafNotYetValid:+ return fmt.Sprintf(describeLeafNotYetValid, target, t.window())+ case IntermediateExpired:+ return fmt.Sprintf(describeIntermediateOld, target, t.window())++ case WrongSAN:+ return fmt.Sprintf(describeWrongSAN, target)+ case CommonNameOnly:+ return fmt.Sprintf(describeCommonNameOnly, target)+ case NoIPSAN:+ return fmt.Sprintf(describeNoIPSAN, target)++ default:+ return ""+ }+}++// describeChain covers the faults in the path from leaf to trusted root, plus+// the two that are structurally the same question about signing and usage.+func (t Trap) describeChain(target string) string {+ switch t.Kind {+ case SelfSigned:+ return fmt.Sprintf(describeSelfSigned, target)+ case UntrustedCA:+ return fmt.Sprintf(describeUntrustedCA, target)+ case MissingIntermediate:+ return fmt.Sprintf(describeMissingInterCA, target)+ case IssuerNotCA:+ return fmt.Sprintf(describeIssuerNotCA, target)+ case NameConstraintViolation:+ return fmt.Sprintf(describeNameConstraint, target)+ case PathLengthExceeded:+ return fmt.Sprintf(describePathLength, target)++ case SHA1Signature:+ return fmt.Sprintf(describeSHA1, target)+ case EKUClientAuthOnly:+ return fmt.Sprintf(describeEKUClientOnly, target)+ case EKUConstrainedIntermediate:+ return fmt.Sprintf(describeEKUConstrained, target)++ default:+ return ""+ }+}++// describePolicy covers the faults crypto/x509 ACCEPTS, where the finding is+// the absence of a policy rather than a skipped check.+func (t Trap) describePolicy(target string) string {+ switch t.Kind {+ case WeakKey:+ return fmt.Sprintf(describeWeakKey, target, t.bits())+ case ExcessiveLifetime:+ return fmt.Sprintf(describeLifetime, target, t.days())+ case KeyUsageWithoutDigitalSignature:+ return fmt.Sprintf(describeKeyUsage, target)+ case CASwap:+ return fmt.Sprintf(describeCASwap, target)++ default:+ return ""+ }+}++// describeRevocation covers everything that acts on revocation rather than on+// the certificate.+func (t Trap) describeRevocation(target string) string {+ switch t.Kind {+ case RevokedViaCRL:+ return fmt.Sprintf(describeRevokedCRL, target)+ case StaleCRL:+ return fmt.Sprintf(describeStaleCRL, target, t.window())+ case CRLUnreachable:+ return fmt.Sprintf(describeCRLUnreachable, target)++ case OCSPRevoked:+ return fmt.Sprintf(describeOCSPRevoked, target)+ case OCSPUnknown:+ return fmt.Sprintf(describeOCSPUnknown, target)+ case OCSPTryLater:+ return fmt.Sprintf(describeOCSPTryLater, target)+ case OCSPUnreachable:+ return fmt.Sprintf(describeOCSPUnreachable, target)+ case OCSPStale:+ return fmt.Sprintf(describeOCSPStale, target, t.window())+ case OCSPWrongSerial:+ return fmt.Sprintf(describeOCSPWrongSerial, target)+ case OCSPWrongSigner:+ return fmt.Sprintf(describeOCSPWrongSigner, target)+ case NoOCSPServer:+ return fmt.Sprintf(describeNoOCSPServer, target)++ case StapleGarbage:+ return fmt.Sprintf(describeStapleGarbage, target)+ case StapleAbsent:+ return fmt.Sprintf(describeStapleAbsent, target)++ default:+ return ""+ }+}++func (t Trap) window() time.Duration {+ if t.Window <= 0 {+ return DefaultWindow+ }+ return t.Window+}++func (t Trap) bits() int {+ if t.Bits <= 0 {+ return DefaultWeakBits+ }+ return t.Bits+}++func (t Trap) days() int {+ if t.Days <= 0 {+ return DefaultExcessiveDays+ }+ return t.Days+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.gonew file mode 100644index 00000000..4f6e1cba--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go@@ -0,0 +1,96 @@+// ©AngelaMos | 2026+// chain.go++package pki++import (+ "crypto"+ "crypto/tls"+ "crypto/x509"+)++// Chain is one assembled certificate chain as it will be PRESENTED in a+// handshake, together with what revocation needs in order to talk about it.+//+// Presented and Issuer are separate fields on purpose, and the distinction is+// the whole of the MissingIntermediate fault: the server can withhold a CA from+// the handshake while that CA is still the one that signed the leaf and still+// the one whose CRL covers it. Collapsing them would make that fault+// inexpressible.+type Chain struct {+ // Leaf is the served certificate.+ Leaf *x509.Certificate+ leafDER []byte+ leafKey crypto.Signer++ // presented is the intermediate DER the handshake carries, leaf-first+ // ordering excluded. It can be empty even when the real chain has an+ // intermediate.+ presented [][]byte++ // Issuer signed the leaf. Revocation answers are always issued by this,+ // even when the handshake withholds it.+ Issuer *x509.Certificate+ issuerKey crypto.Signer++ // Root is the anchor a correct client needs to verify this chain. For+ // CASwap it is a root khaos minted rather than the one the target was+ // originally given.+ Root *x509.Certificate++ // Staple is the DER OCSP response stapled into the handshake, or nil for no+ // staple at all. Go never parses this; it is delivered to the application+ // verbatim, which is what makes both stapling faults reachable.+ Staple []byte+}++// TLS is the chain as crypto/tls wants it: leaf first, then whatever+// intermediates the server is willing to admit to.+func (c *Chain) TLS() tls.Certificate {+ certificate := tls.Certificate{+ Certificate: append([][]byte{c.leafDER}, c.presented...),+ PrivateKey: c.leafKey,+ Leaf: c.Leaf,+ }++ if len(c.Staple) > 0 {+ certificate.OCSPStaple = c.Staple+ }++ return certificate+}++// RootPool is the trust anchor set a correct client needs for this chain. It is+// what the range hands its reference client, and what CASwap quietly changes.+func (c *Chain) RootPool() *x509.CertPool {+ pool := x509.NewCertPool()+ if c.Root != nil {+ pool.AddCert(c.Root)+ }+ return pool+}++// Presented is how many intermediates the handshake actually carries, which is+// the observable MissingIntermediate is confirmed by.+func (c *Chain) Presented() int {+ return len(c.presented)+}++// PresentedPool is the intermediate set a client receives in the handshake, and+// therefore the only one it may use to build a path. Supplying khaos's real+// intermediate here instead would quietly repair MissingIntermediate, which is+// the mistake that makes that fault untestable.+func (c *Chain) PresentedPool() (*x509.CertPool, error) {+ pool := x509.NewCertPool()++ for _, der := range c.presented {+ cert, err := x509.ParseCertificate(der)+ if err != nil {+ return nil, err+ }++ pool.AddCert(cert)+ }++ return pool, nil+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.gonew file mode 100644index 00000000..1db18f25--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go@@ -0,0 +1,475 @@+// ©AngelaMos | 2026+// defect.go++package pki++import (+ "crypto/x509"+ "crypto/x509/pkix"+ "time"+)++// build assembles the chain for one trap. Every trap starts from the HONEST+// leaf template and corrupts exactly one property of it, which is the same+// discipline the token family uses and for the same reason: a certificate that+// is wrong twice trips two checks and isolates neither.+//+// The groups are the ones research 04 uses, and each is confirmed differently.+func (a *Authority) build(trap Trap) (*Chain, error) {+ now := a.clock()++ host := trap.Host+ if host == "" {+ host = a.host+ }++ chain, err := a.chainFor(trap, host, now)+ if err != nil {+ return nil, err+ }++ // EVERY chain staples, not just the stapling traps. A well-configured+ // server staples, so the honest chain has to as well: if only the stapling+ // faults produced one, then StapleAbsent would serve exactly what the+ // baseline serves and the fault would be inert. The control test for this+ // file is what caught that.+ return a.staple(trap, chain, now)+}++func (a *Authority) chainFor(+ trap Trap,+ host string,+ now time.Time,+) (*Chain, error) {+ switch trap.Kind {+ case LeafExpired, LeafNotYetValid, IntermediateExpired:+ return a.buildValidity(trap, host, now)++ case WrongSAN, CommonNameOnly, NoIPSAN:+ return a.buildIdentity(trap, host, now)++ case SelfSigned, UntrustedCA, MissingIntermediate, IssuerNotCA,+ NameConstraintViolation, PathLengthExceeded:+ return a.buildChainFault(trap, host, now)++ case SHA1Signature, EKUClientAuthOnly, EKUConstrainedIntermediate:+ return a.buildAlgorithm(trap, host, now)++ case WeakKey, ExcessiveLifetime, KeyUsageWithoutDigitalSignature:+ return a.buildPolicy(trap, host, now)++ case RevokedViaCRL, StaleCRL, CRLUnreachable, OCSPRevoked, OCSPUnknown,+ OCSPTryLater, OCSPUnreachable, OCSPStale, OCSPWrongSerial,+ OCSPWrongSigner, NoOCSPServer, StapleGarbage, StapleAbsent:+ return a.buildRevocation(trap, host, now)++ case CASwap:+ return a.buildCASwap(host, now)++ case PassThrough:+ return a.honest(host, now)++ default:+ return a.honest(host, now)+ }+}++// honest is the control every other chain is compared against: a correctly+// signed, in-date leaf under the trusted intermediate, naming both revocation+// endpoints so that a target which WANTS to check revocation can.+//+// Carrying the pointers on the honest chain matters. If only the revocation+// traps named a responder, then "the target queried OCSP" would be true only+// when khaos was already attacking it, and the baseline could never establish+// that the target checks revocation at all.+func (a *Authority) honest(host string, now time.Time) (*Chain, error) {+ template, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ return a.assemble(template, a.inter, a.root.cert, StrongBits, true)+}++// leaf is the honest template plus the revocation pointers, which depend on the+// configured base URL rather than on wherever khaos happens to be listening.+func (a *Authority) leaf(+ host string,+ now time.Time,+ days int,+) (*x509.Certificate, error) {+ template, err := leafTemplate(host, now, days)+ if err != nil {+ return nil, err+ }++ if base := a.Base(); base != "" {+ template.OCSPServer = []string{base + RouteOCSP}+ template.CRLDistributionPoints = []string{base + RouteCRL}+ }++ return template, nil+}++// assemble mints the leaf and wraps it with what the handshake and revocation+// both need. presentChain says whether the intermediate is admitted to the+// handshake, which is the entire MissingIntermediate fault.+func (a *Authority) assemble(+ template *x509.Certificate,+ issuer *pair,+ root *x509.Certificate,+ bits int,+ presentChain bool,+) (*Chain, error) {+ key, err := newKey(bits)+ if err != nil {+ return nil, err+ }++ leaf, err := issue(template, issuer, key)+ if err != nil {+ return nil, err+ }++ chain := &Chain{+ Leaf: leaf.cert,+ leafDER: leaf.der,+ leafKey: key,+ Issuer: issuer.cert,+ issuerKey: issuer.key,+ Root: root,+ }++ if presentChain && issuer != a.root && issuer.cert != root {+ chain.presented = [][]byte{issuer.der}+ }++ return chain, nil+}++// buildValidity moves a NotBefore or NotAfter. Both leaf faults come back as+// InvalidReason 1 with no separate not-yet-valid reason, so the only thing+// distinguishing them is the Detail wording, and the experiments assert on that+// rather than on the reason alone.+func (a *Authority) buildValidity(+ trap Trap,+ host string,+ now time.Time,+) (*Chain, error) {+ window := trap.window()++ if trap.Kind == IntermediateExpired {+ return a.underExpiredCA(host, now, window)+ }++ template, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ switch trap.Kind {+ case LeafExpired:+ // Internally consistent: the certificate is expired and nothing else.+ // Its NotBefore moves with its NotAfter so it was never also+ // not-yet-valid, which would trip the same reason for the other cause.+ template.NotBefore = now.Add(-window - DefaultWindow)+ template.NotAfter = now.Add(-window)++ case LeafNotYetValid:+ template.NotBefore = now.Add(window)+ template.NotAfter = now.Add(window).AddDate(0, 0, DefaultLeafDays)++ default:+ // Unreachable: build routes only the validity group here.+ }++ return a.assemble(template, a.inter, a.root.cert, StrongBits, true)+}++// underExpiredCA mints an in-date leaf under an intermediate that has expired.+// The leaf is deliberately blameless: monitoring that watches leaf expiry only+// sees nothing wrong, which is the fail-open this catches.+func (a *Authority) underExpiredCA(+ host string,+ now time.Time,+ window time.Duration,+) (*Chain, error) {+ template, err := caTemplate(+ nameInter,+ now.Add(-window-DefaultWindow),+ now.Add(-window),+ )+ if err != nil {+ return nil, err+ }++ key, err := newKey(StrongBits)+ if err != nil {+ return nil, err+ }++ expired, err := issue(template, a.root, key)+ if err != nil {+ return nil, err+ }++ leaf, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ return a.assemble(leaf, expired, a.root.cert, StrongBits, true)+}++// buildIdentity corrupts who the certificate is FOR. All three are+// HostnameError, which carries no reason code, so the experiments assert on the+// error type and on which name the certificate actually carries.+func (a *Authority) buildIdentity(+ trap Trap,+ host string,+ now time.Time,+) (*Chain, error) {+ template, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ switch trap.Kind {+ case WrongSAN:+ template.DNSNames = []string{foreignHost}+ template.Subject = pkix.Name{CommonName: foreignHost}++ case CommonNameOnly:+ // No SAN extension at all, with the host named only in the legacy+ // CommonName. Go removed the CommonName fallback outright, so this+ // produces a DIFFERENT message from a plain mismatch: it names the+ // legacy field, which is the teaching point.+ template.DNSNames = nil+ template.Subject = pkix.Name{CommonName: host}++ case NoIPSAN:+ // Named by DNS but carrying no IP SAN, so a client that dials by+ // address has nothing to match against. The fail-open is a service+ // dialled by pod IP with verification disabled because it is internal.+ template.DNSNames = []string{host}+ template.IPAddresses = nil++ default:+ // Unreachable: build routes only the identity group here.+ }++ return a.assemble(template, a.inter, a.root.cert, StrongBits, true)+}++// buildChainFault breaks the path from leaf to trusted root. Three of these+// produce a BYTE-IDENTICAL client error and the experiments exist to tell them+// apart by what khaos knows it served, never by the string.+func (a *Authority) buildChainFault(+ trap Trap,+ host string,+ now time.Time,+) (*Chain, error) {+ template, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ switch trap.Kind {+ case SelfSigned:+ return a.selfSigned(template)++ case UntrustedCA:+ // Signed by khaos's OTHER complete hierarchy. The chain is internally+ // valid and simply anchors somewhere the target does not trust.+ return a.assemble(+ template,+ a.rogueInter,+ a.rogueRoot.cert,+ StrongBits,+ true,+ )++ case MissingIntermediate:+ // A perfectly good chain with the intermediate withheld from the+ // handshake. Works in a browser that chases AIA, fails in Go.+ return a.assemble(template, a.inter, a.root.cert, StrongBits, false)++ case IssuerNotCA:+ return a.assemble(template, a.notACA, a.root.cert, StrongBits, true)++ case NameConstraintViolation:+ return a.assemble(+ template,+ a.constrained,+ a.root.cert,+ StrongBits,+ true,+ )++ case PathLengthExceeded:+ return a.overDeep(template)++ default:+ // Unreachable: build routes only the chain group here.+ return a.honest(host, now)+ }+}++// overDeep serves a leaf two intermediates below the root, under a CA whose+// MaxPathLen is zero.+//+// BOTH intermediates are presented. A handshake carrying only the lower one+// leaves the client unable to reach the root at all, and Go then reports an+// unknown authority rather than the path-length violation: the fault would+// still fail the connection, for a reason khaos did not inject and could not+// attribute. The differential caught exactly that in the first draft.+func (a *Authority) overDeep(+ template *x509.Certificate,+) (*Chain, error) {+ chain, err := a.assemble(+ template,+ a.deepInter,+ a.root.cert,+ StrongBits,+ true,+ )+ if err != nil {+ return nil, err+ }++ chain.presented = append(chain.presented, a.deepCapped.der)++ return chain, nil+}++// selfSigned signs the leaf with its own key, which needs the CA bits on the+// template because Go refuses to let a non-CA certificate sign anything,+// including itself.+func (a *Authority) selfSigned(+ template *x509.Certificate,+) (*Chain, error) {+ template.IsCA = true+ template.BasicConstraintsValid = true+ template.KeyUsage |= x509.KeyUsageCertSign++ key, err := newKey(StrongBits)+ if err != nil {+ return nil, err+ }++ leaf, err := issue(template, nil, key)+ if err != nil {+ return nil, err+ }++ return &Chain{+ Leaf: leaf.cert,+ leafDER: leaf.der,+ leafKey: key,+ Issuer: leaf.cert,+ issuerKey: key,+ Root: a.root.cert,+ }, nil+}++// buildAlgorithm corrupts how the certificate is signed or what it is permitted+// to be used for. Two of the three surface as an authority failure unless the+// caller unwraps the error, which is itself the finding.+func (a *Authority) buildAlgorithm(+ trap Trap,+ host string,+ now time.Time,+) (*Chain, error) {+ template, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ switch trap.Kind {+ case SHA1Signature:+ // Measured on go1.26.5: CreateCertificate emits this without+ // complaint and Verify refuses it, wrapping InsecureAlgorithmError+ // inside UnknownAuthorityError.+ template.SignatureAlgorithm = x509.SHA1WithRSA++ case EKUClientAuthOnly:+ template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}++ case EKUConstrainedIntermediate:+ // The LEAF is blameless here. The constraint is on the CA above it,+ // which is what separates this from the leaf-level EKU fault.+ return a.assemble(+ template,+ a.ekuLimited,+ a.root.cert,+ StrongBits,+ true,+ )++ default:+ // Unreachable: build routes only the algorithm group here.+ }++ return a.assemble(template, a.inter, a.root.cert, StrongBits, true)+}++// buildPolicy mints the certificates Go ACCEPTS. Verify returns nil for all+// three, so they do not test x509 at all -- they test whether the target+// imposed a floor of its own, and an acceptance here is not proof of a skipped+// check because there was no check to skip.+func (a *Authority) buildPolicy(+ trap Trap,+ host string,+ now time.Time,+) (*Chain, error) {+ days := DefaultLeafDays+ bits := StrongBits++ if trap.Kind == ExcessiveLifetime {+ days = trap.days()+ }++ if trap.Kind == WeakKey {+ bits = trap.bits()+ }++ template, err := a.leaf(host, now, days)+ if err != nil {+ return nil, err+ }++ if trap.Kind == KeyUsageWithoutDigitalSignature {+ // Verify enforces EXTENDED key usage, nested down the chain, and does+ // not look at the basic KeyUsage bits on a leaf at all. A leaf without+ // digitalSignature is unusable for TLS per RFC 5280 and Go will not say+ // a word about it.+ template.KeyUsage = x509.KeyUsageCRLSign+ }++ // bits, not StrongBits. Passing the constant here is what the first draft+ // did, and it made WeakKey mint a 2048-bit key: the trap armed, reported+ // success, and served a certificate with nothing wrong with it.+ return a.assemble(template, a.inter, a.root.cert, bits, true)+}++// buildCASwap serves a chain that is VALID under a root khaos controls, having+// made that root the one the target trusts. Nothing in the client can detect+// it, which is the point: the only defences are pinning and certificate+// transparency, and neither is in crypto/x509.+func (a *Authority) buildCASwap(+ host string,+ now time.Time,+) (*Chain, error) {+ template, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ return a.assemble(+ template,+ a.rogueInter,+ a.rogueRoot.cert,+ StrongBits,+ true,+ )+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.gonew file mode 100644index 00000000..820d4d8d--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/issuers.go@@ -0,0 +1,179 @@+// ©AngelaMos | 2026+// issuers.go++package pki++import (+ "crypto/x509"+ "crypto/x509/pkix"+ "time"+)++// The purpose-built issuers. Each one is a CA that is wrong in exactly one+// structural way, minted once at construction.+//+// They are separate certificates rather than mutations of the honest+// intermediate because the fault is IN THE ISSUER for all four: a leaf cannot+// express "my CA is constrained against my name" or "my CA is not a CA" by+// anything it carries itself.++// buildConstrained is a CA carrying PermittedDNSDomains. A leaf it signs for+// any other name trips InvalidReason 2, CANotAuthorizedForThisName. The+// fail-open this catches is a constrained corporate sub-CA that a verifier lets+// issue for anything.+func (a *Authority) buildConstrained(from, until time.Time) error {+ template, err := caTemplate(nameConstrained, from, until)+ if err != nil {+ return err+ }++ template.PermittedDNSDomains = []string{constrainedDomain}+ template.PermittedDNSDomainsCritical = true++ key, err := newKey(StrongBits)+ if err != nil {+ return err+ }++ a.constrained, err = issue(template, a.root, key)++ return err+}++// buildEKULimited is a CA authorised for client authentication only. Go checks+// extended key usage NESTED DOWN THE CHAIN, so a perfectly ordinary serverAuth+// leaf under this CA trips InvalidReason 9,+// CANotAuthorizedForExtKeyUsage. The leaf itself is blameless, which is what+// makes this distinct from the leaf-level EKU fault.+func (a *Authority) buildEKULimited(from, until time.Time) error {+ template, err := caTemplate(nameEKULimited, from, until)+ if err != nil {+ return err+ }++ template.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}++ key, err := newKey(StrongBits)+ if err != nil {+ return err+ }++ a.ekuLimited, err = issue(template, a.root, key)++ return err+}++// buildNotACA is a certificate with basic constraints saying it is NOT a CA,+// which khaos then signs a leaf with anyway. Go reports this as+// UnknownAuthorityError wrapping ConstraintViolationError, so a caller that+// only reads the outer error sees "unknown authority" and learns nothing about+// the real defect.+func (a *Authority) buildNotACA(from, until time.Time) error {+ number, err := serial()+ if err != nil {+ return err+ }++ template := &x509.Certificate{+ SerialNumber: number,+ Subject: pkix.Name{CommonName: nameNotACA},+ NotBefore: from,+ NotAfter: until,+ IsCA: false,+ BasicConstraintsValid: true,+ KeyUsage: x509.KeyUsageDigitalSignature,+ }++ key, err := newKey(StrongBits)+ if err != nil {+ return err+ }++ a.notACA, err = issue(template, a.root, key)++ return err+}++// buildDeepInter sits one level below an intermediate whose MaxPathLen is zero,+// so a leaf under it exceeds the path length the CA above permits and trips+// InvalidReason 3, TooManyIntermediates.+//+// The pathLen-0 CA is minted here too rather than reusing the honest+// intermediate, because setting MaxPathLen on the honest one would constrain+// every other trap in the family.+func (a *Authority) buildDeepInter(from, until time.Time) error {+ capped, err := caTemplate(nameInter, from, until)+ if err != nil {+ return err+ }++ capped.MaxPathLen = 0+ capped.MaxPathLenZero = true++ cappedKey, err := newKey(StrongBits)+ if err != nil {+ return err+ }++ if a.deepCapped, err = issue(capped, a.root, cappedKey); err != nil {+ return err+ }++ template, err := caTemplate(nameDeepInter, from, until)+ if err != nil {+ return err+ }++ key, err := newKey(StrongBits)+ if err != nil {+ return err+ }++ a.deepInter, err = issue(template, a.deepCapped, key)++ 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.+//+// 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.+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+ }++ rogueKey, err := newKey(StrongBits)+ if err != nil {+ return err+ }++ a.undelegated, err = issue(rogue, nil, rogueKey)++ return err+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.gonew file mode 100644index 00000000..39b7b36c--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go@@ -0,0 +1,159 @@+// ©AngelaMos | 2026+// mint.go++package pki++import (+ "crypto"+ "crypto/rand"+ "crypto/rsa"+ "crypto/x509"+ "crypto/x509/pkix"+ "errors"+ "fmt"+ "math/big"+ "time"+)++const (+ serialBits = 128++ errKeyGen = "%w: generating a %d-bit key: %v"+ errSign = "%w: signing %q: %v"+ errReparse = "%w: re-parsing %q: %v"+ errSerial = "%w: drawing a serial: %v"+)++// ErrMint is any failure to produce the certificate material a trap needs. It+// is deliberately distinct from a trap that armed and then behaved wrongly:+// this one means khaos could not express the fault at all.+var ErrMint = errors.New("khaos could not mint the certificate material")++// pair is a certificate with the key that goes with it, always re-parsed from+// its own DER.+//+// The re-parse is not defensive tidiness. x509.CreateRevocationList requires+// the issuer to have SubjectKeyId set and reads it from the PARSED certificate,+// ignoring whatever the template said, and Go only computes a SubjectKeyId+// while creating a CA certificate. Holding the template would produce a CA that+// cannot issue a CRL, which is most of this family.+type pair struct {+ cert *x509.Certificate+ der []byte+ key crypto.Signer+}++func newKey(bits int) (*rsa.PrivateKey, error) {+ key, err := rsa.GenerateKey(rand.Reader, bits)+ if err != nil {+ return nil, fmt.Errorf(errKeyGen, ErrMint, bits, err)+ }+ return key, nil+}++func serial() (*big.Int, error) {+ limit := new(big.Int).Lsh(big.NewInt(1), serialBits)++ n, err := rand.Int(rand.Reader, limit)+ if err != nil {+ return nil, fmt.Errorf(errSerial, ErrMint, err)+ }++ return n, nil+}++// issue signs template with parent, or self-signs it when parent is nil, and+// returns the result re-parsed. The signing key is the PARENT's, which is what+// makes a self-signed leaf and a CA-signed leaf one code path with one+// difference.+func issue(+ template *x509.Certificate,+ parent *pair,+ subject crypto.Signer,+) (*pair, error) {+ issuerCert := template+ issuerKey := subject++ if parent != nil {+ issuerCert = parent.cert+ issuerKey = parent.key+ }++ der, err := x509.CreateCertificate(+ rand.Reader,+ template,+ issuerCert,+ subject.Public(),+ issuerKey,+ )+ if err != nil {+ return nil, fmt.Errorf(+ errSign,+ ErrMint,+ template.Subject.CommonName,+ err,+ )+ }++ cert, err := x509.ParseCertificate(der)+ if err != nil {+ return nil, fmt.Errorf(+ errReparse,+ ErrMint,+ template.Subject.CommonName,+ err,+ )+ }++ return &pair{cert: cert, der: der, key: subject}, nil+}++// caTemplate is every CA khaos mints. crlSign is set on all of them because+// CreateRevocationList refuses an issuer without it, and a CA that cannot+// revoke could not host most of this catalogue.+func caTemplate(name string, from, until time.Time) (+ *x509.Certificate,+ error,+) {+ number, err := serial()+ if err != nil {+ return nil, err+ }++ return &x509.Certificate{+ SerialNumber: number,+ Subject: pkix.Name{CommonName: name},+ NotBefore: from,+ NotAfter: until,+ IsCA: true,+ BasicConstraintsValid: true,+ KeyUsage: x509.KeyUsageCertSign |+ x509.KeyUsageCRLSign |+ x509.KeyUsageDigitalSignature,+ }, nil+}++// leafTemplate is an HONEST leaf. Every defect in this family is expressed by+// mutating what this returns, so anything wrong with it is wrong with the+// control too, and a control that is already broken cannot establish anything.+func leafTemplate(host string, now time.Time, days int) (+ *x509.Certificate,+ error,+) {+ number, err := serial()+ if err != nil {+ return nil, err+ }++ return &x509.Certificate{+ SerialNumber: number,+ Subject: pkix.Name{CommonName: host},+ DNSNames: []string{host},+ NotBefore: now.Add(-clockSlack),+ NotAfter: now.AddDate(0, 0, days),+ KeyUsage: x509.KeyUsageDigitalSignature |+ x509.KeyUsageKeyEncipherment,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},+ BasicConstraintsValid: true,+ }, nil+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.gonew file mode 100644index 00000000..8285cafb--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation.go@@ -0,0 +1,261 @@+// ©AngelaMos | 2026+// revocation.go++package pki++import (+ "crypto/rand"+ "crypto/x509"+ "fmt"+ "math/big"+ "time"++ "golang.org/x/crypto/ocsp"+)++const (+ // reasonKeyCompromise is RFC 5280 section 5.3.1. Reason code 0 is NOT used+ // anywhere in khaos: when creating a CRL, 0 means the reasonCode extension+ // is omitted entirely, and when parsing, 0 is ambiguous between "extension+ // absent" and "extension present, value zero". An ambiguous signal cannot+ // carry a finding.+ reasonKeyCompromise = 1++ // crlNumber is the cRLNumber extension. khaos issues one CRL per arming, so+ // it does not need to increment.+ crlNumber = 1++ // wrongSerialOffset is added to the leaf's serial to mint an OCSP response+ // that is about a DIFFERENT certificate. Any value works; a fixed offset+ // makes the resulting serial reproducible in a failure message.+ wrongSerialOffset = 1++ // garbageStaple is bytes that are definitively not an OCSP response. Go+ // never parses a staple, so these reach the application verbatim and only+ // its own handling decides.+ garbageStaple = "khaos: this is not an OCSP response"++ errCRL = "%w: minting a CRL: %v"+ errOCSPGen = "%w: minting an OCSP response: %v"+)++// buildRevocation mints the chain for every fault that acts on revocation+// rather than on the certificate itself.+//+// Go performs NO revocation checking of any kind, so every chain in this group+// verifies with a nil error. That is not a weakness of the faults, it IS the+// finding: the certificate is impeccable and the only thing wrong with it is+// something the standard library will never look at.+func (a *Authority) buildRevocation(+ trap Trap,+ host string,+ now time.Time,+) (*Chain, error) {+ template, err := a.leaf(host, now, DefaultLeafDays)+ if err != nil {+ return nil, err+ }++ if trap.Kind == NoOCSPServer {+ // Models Let's Encrypt after it ended OCSP in 2025. The CRL pointer+ // stays, so the honest answer for a target is to fall back to it; the+ // question is whether it does, or treats "nothing to ask" as "fine".+ template.OCSPServer = nil+ }++ return a.assemble(template, a.inter, a.root.cert, StrongBits, true)+}++// staple attaches whatever stapled response the trap calls for. A nil staple is+// not an error: it is the StapleAbsent fault, and it is also what every+// non-stapling trap serves.+func (a *Authority) staple(+ trap Trap,+ chain *Chain,+ now time.Time,+) (*Chain, error) {+ switch trap.Kind {+ case StapleGarbage:+ chain.Staple = []byte(garbageStaple)++ case StapleAbsent:+ chain.Staple = nil++ case OCSPRevoked, OCSPStale, OCSPWrongSerial, OCSPWrongSigner,+ OCSPUnknown:+ // The responder faults also staple what they would have answered, so a+ // target that reads the staple instead of querying sees the same fault.+ // Without this, an app that trusts staples would be measured against a+ // responder it never contacts and would read as fail-closed.+ der, err := a.ocspFor(trap, chain, now)+ if err != nil {+ return nil, err+ }++ chain.Staple = der++ default:+ // Every other trap staples an honest Good, which is what a correct+ // authority serving a good certificate would do.+ der, err := a.ocspGood(chain, now, now.Add(DefaultWindow))+ if err != nil {+ return nil, err+ }++ chain.Staple = der+ }++ return chain, nil+}++// CRLFor mints the revocation list the authority serves for this chain. The+// trap decides whether the leaf is listed and whether the list is fresh, and+// those are INDEPENDENT: a stale CRL that revokes nothing finds nothing, and a+// fresh CRL that revokes the leaf is the baseline every correct client passes.+func (a *Authority) CRLFor(+ trap Trap,+ chain *Chain,+ now time.Time,+) ([]byte, error) {+ template := &x509.RevocationList{+ Number: big.NewInt(crlNumber),+ ThisUpdate: now.Add(-clockSlack),+ NextUpdate: now.Add(DefaultWindow),+ }++ if trap.Kind == StaleCRL {+ // ThisUpdate has to move with NextUpdate, or the list is both stale and+ // not yet issued and a client rejecting it cannot say which it rejected.+ window := trap.window()+ template.ThisUpdate = now.Add(-window - DefaultWindow)+ template.NextUpdate = now.Add(-window)+ }++ if trap.Kind == RevokedViaCRL || trap.Kind == StaleCRL {+ template.RevokedCertificateEntries = []x509.RevocationListEntry{{+ SerialNumber: chain.Leaf.SerialNumber,+ RevocationTime: now.Add(-clockSlack),+ ReasonCode: reasonKeyCompromise,+ }}+ }++ der, err := x509.CreateRevocationList(+ rand.Reader,+ template,+ chain.Issuer,+ chain.issuerKey,+ )+ if err != nil {+ return nil, fmt.Errorf(errCRL, ErrMint, err)+ }++ return der, nil+}++// ocspFor mints the response the trap calls for. Each branch corrupts exactly+// one property of an otherwise correct Good response, so a client that refuses+// one of them has refused for the reason khaos intended.+func (a *Authority) ocspFor(+ trap Trap,+ 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`.+ //+ // That failure mode is indistinguishable from the OCSPWrongSigner fault+ // landing, so omitting this made four traps look like they were working.+ template := ocsp.Response{+ Status: ocsp.Good,+ SerialNumber: chain.Leaf.SerialNumber,+ ThisUpdate: now.Add(-clockSlack),+ NextUpdate: now.Add(DefaultWindow),+ }++ switch trap.Kind {+ case OCSPRevoked:+ template.Status = ocsp.Revoked+ template.RevokedAt = now.Add(-clockSlack)+ template.RevocationReason = reasonKeyCompromise++ case OCSPUnknown:+ // Unknown from the AUTHORITATIVE responder is not good. Collapsing the+ // two is its own fail-open and a common one.+ template.Status = ocsp.Unknown++ case OCSPStale:+ window := trap.window()+ template.ThisUpdate = now.Add(-window - DefaultWindow)+ template.NextUpdate = now.Add(-window)++ case OCSPWrongSerial:+ // The highest-value trap in the group: the bypass is one word of caller+ // code. ParseResponseForCert rejects this; ParseResponse does not bind+ // the response to the certificate at all and returns a nil error, so a+ // caller reading Status accepts a Good minted for another certificate.+ template.SerialNumber = new(big.Int).Add(+ chain.Leaf.SerialNumber,+ big.NewInt(wrongSerialOffset),+ )++ case OCSPWrongSigner:+ signer = a.undelegated++ default:+ // 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++ der, err := ocsp.CreateResponse(+ chain.Issuer,+ signer.cert,+ template,+ signer.key,+ )+ if err != nil {+ return nil, fmt.Errorf(errOCSPGen, ErrMint, err)+ }++ return der, nil+}++// ocspGood is the honest response, and the control for every responder fault.+func (a *Authority) ocspGood(+ chain *Chain,+ now, until time.Time,+) ([]byte, error) {+ der, err := ocsp.CreateResponse(+ chain.Issuer,+ a.responder.cert,+ ocsp.Response{+ Status: ocsp.Good,+ SerialNumber: chain.Leaf.SerialNumber,+ ThisUpdate: now.Add(-clockSlack),+ NextUpdate: until,+ Certificate: a.responder.cert,+ },+ a.responder.key,+ )+ if err != nil {+ return nil, fmt.Errorf(errOCSPGen, ErrMint, err)+ }++ 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.gonew file mode 100644index 00000000..1551aaac--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/revocation_test.go@@ -0,0 +1,476 @@+// ©AngelaMos | 2026+// revocation_test.go++package pki++import (+ "crypto/x509"+ "errors"+ "testing"+ "time"++ "golang.org/x/crypto/ocsp"+)++// Every trap in the revocation group is ACCEPTED by crypto/x509, because Go+// performs no revocation checking of any kind. That makes the fault-table+// differential blind here: it cannot tell RevokedViaCRL from PassThrough,+// because both verify with a nil error and both complete a handshake.+//+// So this file is the group's only liveness evidence. Each case asserts the+// specific corruption in the bytes khaos actually serves, against the honest+// answer as its control. Without it, nine of these traps could be gutted to a+// no-op and the whole package would stay green.++// revocationCase is one trap and what has to be true of what khaos serves.+type revocationCase struct {+ kind Kind++ // assert reads the served artefacts and fails if the corruption is absent.+ assert func(t *testing.T, a *Authority, chain *Chain)+}++func revocationCases() []revocationCase {+ return []revocationCase{+ {RevokedViaCRL, assertCRLRevokesAndIsFresh},+ {StaleCRL, assertCRLRevokesAndIsStale},+ {CRLUnreachable, assertCRLRefuses},++ {OCSPRevoked, assertOCSPStatus(ocsp.Revoked)},+ {OCSPUnknown, assertOCSPStatus(ocsp.Unknown)},+ {OCSPTryLater, assertOCSPTryLater},+ {OCSPUnreachable, assertOCSPRefuses},+ {OCSPStale, assertOCSPStale},+ {OCSPWrongSerial, assertOCSPWrongSerial},+ {OCSPWrongSigner, assertOCSPWrongSigner},+ {NoOCSPServer, assertNoOCSPPointer},++ {StapleGarbage, assertStapleIsNotAnOCSPResponse},+ {StapleAbsent, assertNoStaple},+ }+}++// The census. A revocation trap without a case here is one khaos would arm,+// report as armed, and serve nothing different for.+func TestEveryRevocationTrapCorruptsWhatItServes(t *testing.T) {+ cases := revocationCases()++ if len(cases) != countRevocationKinds() {+ t.Fatalf(+ "this file covers %d revocation traps and the catalogue has %d; a new one needs a case here or it can be inert and stay green",+ len(cases),+ countRevocationKinds(),+ )+ }++ for _, each := range cases {+ t.Run(string(each.kind), func(t *testing.T) {+ a := listening(t)++ if err := a.Arm(Trap{+ Kind: each.kind,+ Host: a.Host(),+ Window: DefaultWindow,+ }); err != nil {+ t.Fatalf("arm %s: %v", each.kind, err)+ }++ chain, err := a.Served()+ if err != nil {+ t.Fatalf("served chain: %v", err)+ }++ each.assert(t, a, chain)+ })+ }+}++// countRevocationKinds is derived from GoAccepts rather than hand-counted, so+// the census cannot drift from the catalogue. The policy and trust-store traps+// are also accepted by Go but corrupt the certificate rather than its+// revocation, so they are excluded by name.+func countRevocationKinds() int {+ notRevocation := map[Kind]bool{+ WeakKey: true,+ ExcessiveLifetime: true,+ KeyUsageWithoutDigitalSignature: true,+ CASwap: true,+ }++ count := 0++ for _, name := range Kinds() {+ kind := Kind(name)+ if GoAccepts(kind) && !notRevocation[kind] {+ count+++ }+ }++ return count+}++func servedCRL(t *testing.T, a *Authority) *x509.RevocationList {+ t.Helper()++ base, err := a.Addr()+ if err != nil {+ t.Fatalf("revocation address: %v", err)+ }++ der, err := fetch(schemeHTTP + base + RouteCRL)+ if err != nil {+ t.Fatalf("fetch the CRL: %v", err)+ }++ list, err := x509.ParseRevocationList(der)+ if err != nil {+ t.Fatalf("parse the CRL: %v", err)+ }++ return list+}++func assertCRLRevokesAndIsFresh(+ t *testing.T,+ a *Authority,+ chain *Chain,+) {+ t.Helper()++ list := servedCRL(t, a)++ if !revokes(list, chain.Leaf.SerialNumber.String()) {+ t.Fatal("the served CRL does not revoke the served leaf")+ }++ if !list.NextUpdate.After(a.Now()) {+ t.Fatal(+ "the CRL is stale, which is a DIFFERENT fault; these two have to stay distinguishable or one alibis the other",+ )+ }+}++func assertCRLRevokesAndIsStale(+ t *testing.T,+ a *Authority,+ chain *Chain,+) {+ t.Helper()++ 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()) {+ t.Fatal(+ "the stale CRL does not revoke the leaf, so a target checking freshness has nothing to be wrong about",+ )+ }++ if !list.NextUpdate.Before(a.Now()) {+ t.Fatalf(+ "the CRL's NextUpdate is %s, which is not in the past; this is then just RevokedViaCRL",+ list.NextUpdate,+ )+ }++ if !list.ThisUpdate.Before(list.NextUpdate) {+ t.Fatal(+ "ThisUpdate is not before NextUpdate, so the list is both stale and not yet issued and a client rejecting it cannot say which",+ )+ }+}++func assertCRLRefuses(t *testing.T, a *Authority, _ *Chain) {+ t.Helper()++ base, err := a.Addr()+ if err != nil {+ t.Fatalf("revocation address: %v", err)+ }++ if _, err := get(schemeHTTP + base + RouteCRL); err == nil {+ t.Fatal("the CRL endpoint still answered")+ }+}++func servedOCSP(t *testing.T, a *Authority) []byte {+ t.Helper()++ base, err := a.Addr()+ if err != nil {+ t.Fatalf("revocation address: %v", err)+ }++ der, err := fetch(schemeHTTP + base + RouteOCSP)+ if err != nil {+ t.Fatalf("fetch the OCSP response: %v", err)+ }++ return der+}++func assertOCSPStatus(want int) func(*testing.T, *Authority, *Chain) {+ return func(t *testing.T, a *Authority, chain *Chain) {+ t.Helper()++ response, err := ocsp.ParseResponseForCert(+ servedOCSP(t, a),+ chain.Leaf,+ chain.Issuer,+ )+ if err != nil {+ t.Fatalf("parse the response: %v", err)+ }++ if response.Status != want {+ t.Fatalf(+ "the responder answered status %d, want %d",+ response.Status,+ want,+ )+ }+ }+}++func assertOCSPTryLater(t *testing.T, a *Authority, chain *Chain) {+ t.Helper()++ _, err := ocsp.ParseResponseForCert(+ servedOCSP(t, a),+ chain.Leaf,+ chain.Issuer,+ )++ // TryLater is a RESPONSE STATUS, not a certificate status, so parsing is+ // supposed to fail. A nil error here would mean khaos served a real answer+ // and a soft-failing client was never given the chance to proceed on+ // nothing, which is the entire fault.+ if err == nil {+ t.Fatal(+ "the TryLater response parsed as a real answer, so the soft-fail trap is inert",+ )+ }++ var responseErr ocsp.ResponseError+ if !asResponseError(err, &responseErr) {+ t.Fatalf("expected an ocsp.ResponseError, got %v", err)+ }++ if responseErr.Status != ocsp.TryLater {+ t.Fatalf(+ "the responder answered response status %v, want TryLater",+ responseErr.Status,+ )+ }+}++func assertOCSPRefuses(t *testing.T, a *Authority, _ *Chain) {+ t.Helper()++ base, err := a.Addr()+ if err != nil {+ t.Fatalf("revocation address: %v", err)+ }++ if _, err := get(schemeHTTP + base + RouteOCSP); err == nil {+ t.Fatal("the OCSP endpoint still answered")+ }+}++func assertOCSPStale(t *testing.T, a *Authority, chain *Chain) {+ t.Helper()++ response, err := ocsp.ParseResponseForCert(+ servedOCSP(t, a),+ chain.Leaf,+ chain.Issuer,+ )+ // Measured: x/crypto/ocsp does NOT check freshness, so a stale response+ // parses with a nil error. That is the fault, so a parse failure here would+ // mean khaos had corrupted something else as well.+ if err != nil {+ t.Fatalf(+ "the stale response failed to parse (%v); x/crypto/ocsp does not check freshness, so this means something else is wrong with it too",+ err,+ )+ }++ if response.Status != ocsp.Good {+ t.Fatalf(+ "the stale response says status %d; it has to be Good, or a client refusing it is refusing the status and not the staleness",+ response.Status,+ )+ }++ if !response.NextUpdate.Before(a.Now()) {+ t.Fatalf(+ "NextUpdate is %s, which is not in the past, so the response is simply correct",+ response.NextUpdate,+ )+ }+}++func assertOCSPWrongSerial(t *testing.T, a *Authority, chain *Chain) {+ t.Helper()++ der := servedOCSP(t, a)++ // The whole fault in one pair of assertions, and it is why this trap is the+ // most valuable in the group: the bypass is one word of caller code.+ if _, err := ocsp.ParseResponseForCert(+ der,+ chain.Leaf,+ chain.Issuer,+ ); err == nil {+ t.Fatal(+ "ParseResponseForCert accepted a response minted for another serial, so the trap is inert",+ )+ }++ loose, err := ocsp.ParseResponse(der, chain.Issuer)+ if err != nil {+ t.Fatalf(+ "ParseResponse rejected it too (%v); the fault only exists because that call does NOT bind the response to the certificate",+ err,+ )+ }++ if loose.Status != ocsp.Good {+ t.Fatalf(+ "the loose parse reports status %d, want Good; a caller reading Status has to be handed an apparently fine answer",+ loose.Status,+ )+ }++ if loose.SerialNumber.Cmp(chain.Leaf.SerialNumber) == 0 {+ t.Fatal(+ "the response is for the served leaf's own serial, so nothing is being substituted",+ )+ }+}++func assertOCSPWrongSigner(t *testing.T, a *Authority, chain *Chain) {+ t.Helper()++ if _, err := ocsp.ParseResponseForCert(+ servedOCSP(t, a),+ chain.Leaf,+ chain.Issuer,+ ); err == nil {+ t.Fatal(+ "a response signed by an undelegated key was accepted, so the trap is inert",+ )+ }+}++func assertNoOCSPPointer(t *testing.T, _ *Authority, chain *Chain) {+ t.Helper()++ if len(chain.Leaf.OCSPServer) != 0 {+ t.Fatalf(+ "the leaf still names %v as a responder, so there is something to ask and the fault is inert",+ chain.Leaf.OCSPServer,+ )+ }++ // The CRL pointer has to SURVIVE. The fault asks what a target does when+ // OCSP is gone, and the honest answer is to fall back to the CRL; removing+ // both would make it an outage instead.+ if len(chain.Leaf.CRLDistributionPoints) == 0 {+ t.Fatal(+ "the leaf names no CRL distribution point either, so this is a total revocation outage rather than the end of OCSP",+ )+ }+}++func assertStapleIsNotAnOCSPResponse(+ t *testing.T,+ _ *Authority,+ chain *Chain,+) {+ t.Helper()++ if len(chain.Staple) == 0 {+ t.Fatal(+ "no staple was attached, which is the StapleAbsent fault and not this one",+ )+ }++ if _, err := ocsp.ParseResponse(chain.Staple, chain.Issuer); err == nil {+ t.Fatal(+ "the garbage staple parsed as a real OCSP response, so it is not garbage",+ )+ }+}++func assertNoStaple(t *testing.T, _ *Authority, chain *Chain) {+ t.Helper()++ if len(chain.Staple) != 0 {+ t.Fatalf(+ "a %d-byte staple was attached, so the fault is inert",+ len(chain.Staple),+ )+ }+}++// The control for the whole file. An unarmed authority has to serve a fresh CRL+// that revokes nothing and a Good, in-date, correctly signed OCSP response. If+// it did not, every assertion above would be comparing one broken answer with+// another.+func TestAnUnarmedAuthoritySaysTheCertificateIsFine(t *testing.T) {+ a := listening(t)++ chain, err := a.Served()+ if err != nil {+ t.Fatalf("served chain: %v", err)+ }++ list := servedCRL(t, a)++ if revokes(list, chain.Leaf.SerialNumber.String()) {+ t.Fatal("the honest CRL revokes the honest leaf")+ }++ if !list.NextUpdate.After(a.Now()) {+ t.Fatal("the honest CRL is already stale")+ }++ response, err := ocsp.ParseResponseForCert(+ servedOCSP(t, a),+ chain.Leaf,+ chain.Issuer,+ )+ if err != nil {+ t.Fatalf("the honest OCSP response does not parse: %v", err)+ }++ if response.Status != ocsp.Good {+ t.Fatalf("the honest responder says status %d", response.Status)+ }++ if !response.NextUpdate.After(a.Now()) {+ t.Fatal("the honest OCSP response is already stale")+ }++ if len(chain.Staple) == 0 {+ t.Fatal(+ "the honest chain carries no staple, so StapleAbsent has nothing to remove and that fault is inert",+ )+ }++ if time.Since(response.ProducedAt) > time.Hour {+ t.Fatalf(+ "the honest response was produced at %s, which is not now",+ response.ProducedAt,+ )+ }+}++// asResponseError unwraps an ocsp.ResponseError. x/crypto returns it by value,+// but errors.As handles that and survives a future wrap, which a bare type+// assertion would not.+func asResponseError(err error, into *ocsp.ResponseError) bool {+ return errors.As(err, into)+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.gonew file mode 100644index 00000000..06a4b53c--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go@@ -0,0 +1,182 @@+// ©AngelaMos | 2026+// routes.go++package pki++import (+ "io"+ "net/http"+ "time"++ "golang.org/x/crypto/ocsp"+)++const (+ routeDependency = "/"+ dependencyBody = "khaos range dependency"++ // headerProbe marks a request as khaos's OWN confirmation probe, so the+ // counters can subtract it. Without this, "the target fetched the CRL"+ // would be true for every run in which khaos confirmed its own fault.+ headerProbe = "X-Khaos-Probe"+ probeValue = "confirmation"+)++// routes is the revocation surface. RouteHealth is not decoration: it is the+// CONTROL for the two unreachable traps, and its entire job is to keep+// answering while the CRL or OCSP endpoint refuses. Without it, "khaos broke+// one endpoint" and "khaos fell over" are the same observation.+func (a *Authority) routes() http.Handler {+ mux := http.NewServeMux()++ mux.HandleFunc(RouteCRL, a.serveCRL)+ mux.HandleFunc(RouteOCSP, a.serveOCSP)+ mux.HandleFunc(RouteHealth, a.serveHealth)++ return mux+}++// dependencyRoutes is what khaos answers once a client has got through the+// handshake. The body is deliberately trivial: this endpoint exists so that a+// client which ACCEPTED a bad certificate has something to succeed at, and the+// finding is the acceptance, not anything in the response.+func (a *Authority) dependencyRoutes() http.Handler {+ mux := http.NewServeMux()++ mux.HandleFunc(+ routeDependency,+ func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = io.WriteString(w, dependencyBody)+ },+ )++ return mux+}++func (a *Authority) serveHealth(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ _, _ = io.WriteString(w, healthBody)+}++func (a *Authority) serveCRL(w http.ResponseWriter, r *http.Request) {+ a.countCRL(r)++ trap := a.Trap()++ if trap.Kind == CRLUnreachable {+ refuse(w)++ return+ }++ chain, err := a.Served()+ if err != nil {+ w.WriteHeader(http.StatusServiceUnavailable)++ return+ }++ der, err := a.CRLFor(trap, chain, a.clock())+ if err != nil {+ w.WriteHeader(http.StatusInternalServerError)++ return+ }++ w.Header().Set(headerType, mimePKIX)+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(der)+}++func (a *Authority) serveOCSP(w http.ResponseWriter, r *http.Request) {+ a.countOCSP(r)++ trap := a.Trap()++ switch trap.Kind {+ case OCSPUnreachable:+ refuse(w)++ return++ case OCSPTryLater:+ // A protocol-level refusal, not a transport one. The responder IS+ // reachable and IS answering; it is declining to say. Research 04 calls+ // soft-fail the reason revocation is near-useless in practice, and this+ // is the exact shape that exploits it.+ w.Header().Set(headerType, mimeOCSP)+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(ocsp.TryLaterErrorResponse)++ return++ default:+ // Every other trap answers with a real, signed response.+ }++ chain, err := a.Served()+ if err != nil {+ w.WriteHeader(http.StatusServiceUnavailable)++ return+ }++ der, err := a.ocspFor(trap, chain, a.clock())+ if err != nil {+ w.WriteHeader(http.StatusInternalServerError)++ return+ }++ w.Header().Set(headerType, mimeOCSP)+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write(der)+}++// refuse drops the connection without answering, which is what makes one route+// unreachable while its neighbour on the same listener keeps serving.+//+// Dropping the whole listener would be the more literal reading of "the+// responder is down", and it is the wrong choice: it would take RouteHealth+// with it, and then khaos could not show that it had broken one endpoint rather+// than fallen over. A hijacked connection is a transport failure the client+// cannot tell from a dead port, scoped to the route that is supposed to be+// dead.+func refuse(w http.ResponseWriter) {+ hijacker, ok := w.(http.Hijacker)+ if !ok {+ w.WriteHeader(http.StatusServiceUnavailable)++ return+ }++ conn, _, err := hijacker.Hijack()+ if err != nil {+ return+ }++ _ = conn.Close()+}++func (a *Authority) countCRL(r *http.Request) {+ a.crlFetches.Add(1)++ if r.Header.Get(headerProbe) == probeValue {+ a.ownCRL.Add(1)+ }+}++func (a *Authority) countOCSP(r *http.Request) {+ a.ocspQueries.Add(1)++ if r.Header.Get(headerProbe) == probeValue {+ a.ownOCSP.Add(1)+ }+}++// Now is the authority's clock, which the experiments need in order to assert+// about a validity window without racing a real one.+func (a *Authority) Now() time.Time {+ return a.clock()+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.gonew file mode 100644index 00000000..987c29d6--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go@@ -0,0 +1,243 @@+// ©AngelaMos | 2026+// server.go++package pki++import (+ "crypto/tls"+ "errors"+ "fmt"+ "net"+ "net/http"+ "sync"+ "time"+)++const (+ network = "tcp"+ schemeHTTP = "http://"+ mimePKIX = "application/pkix-crl"+ mimeOCSP = "application/ocsp-response"+ headerType = "Content-Type"+ healthBody = "ok"+ maxOCSPBody = 64 << 10++ errNoListener = "%w: the authority is not listening, so %s cannot be reached"+ errBindFailed = "%w: binding %q: %v"+ errAlreadyUp = "%w: the authority is already listening on %s"+)++// ErrListener is any failure to stand up or reach the authority's own+// endpoints. It is separate from a trap failing, because khaos being+// unreachable is khaos's bug and a trap landing is the product working.+var ErrListener = errors.New("khaos's certificate authority listener")++// listenerState holds both of the authority's listeners. There are two because+// they serve different protocols to the same target: a TLS endpoint where khaos+// IS the dependency whose certificate is under test, and a plain HTTP endpoint+// for the revocation data that certificate points at.+//+// They cannot be one listener. The revocation endpoints have to stay reachable+// while the TLS certificate is broken, or every revocation fault would also be+// an outage and khaos could not attribute what it measured.+type listenerState struct {+ mu sync.Mutex++ revocation net.Listener+ revSrv *http.Server++ dependency net.Listener+ depSrv *http.Server++ base string+ wg sync.WaitGroup+}++// Base is the URL the TARGET uses to reach the CRL and OCSP endpoints.+//+// It is configured rather than derived from the listener, and that distinction+// cost a full debugging session in the identity family. khaos binds the Docker+// bridge gateway's numeric address while the target addresses+// `host.docker.internal`, so a URL built from khaos's own listener address is+// unreachable from inside the target's network namespace. Every revocation+// fetch would then fail for a reason that has nothing to do with the trap, and+// the run would report the target as fail-closed when khaos had simply pointed+// it at nowhere.+func (a *Authority) Base() string {+ a.listener.mu.Lock()+ defer a.listener.mu.Unlock()++ return a.listener.base+}++// SetBase pins the externally-reachable base URL. It refuses to overwrite one+// that is already set, because Listen used to do exactly that in the identity+// provider and silently invalidated every credential it minted.+func (a *Authority) SetBase(base string) {+ a.listener.mu.Lock()+ defer a.listener.mu.Unlock()++ if a.listener.base == "" {+ a.listener.base = base+ }+}++// Listen binds the revocation endpoints. If no base URL has been pinned, the+// listener's own address becomes it, which is right for a test on loopback and+// wrong for a container, hence SetBase.+func (a *Authority) Listen(addr string) error {+ a.listener.mu.Lock()+ defer a.listener.mu.Unlock()++ if a.listener.revocation != nil {+ return fmt.Errorf(+ errAlreadyUp,+ ErrListener,+ a.listener.revocation.Addr(),+ )+ }++ listener, err := net.Listen(network, addr)+ if err != nil {+ return fmt.Errorf(errBindFailed, ErrListener, addr, err)+ }++ a.listener.revocation = listener+ a.listener.revSrv = &http.Server{+ Handler: a.routes(),+ ReadHeaderTimeout: readHeaderTimeout,+ }++ if a.listener.base == "" {+ a.listener.base = schemeHTTP + listener.Addr().String()+ }++ a.listener.wg.Add(1)++ go func() {+ defer a.listener.wg.Done()+ _ = a.listener.revSrv.Serve(listener)+ }()++ return nil+}++// ListenTLS binds the endpoint where khaos plays the dependency, presenting+// whatever chain is armed. The certificate is resolved per handshake through+// GetCertificate rather than fixed at bind time, so arming a trap takes effect+// on the next connection without the listener moving.+func (a *Authority) ListenTLS(addr string) error {+ a.listener.mu.Lock()+ defer a.listener.mu.Unlock()++ if a.listener.dependency != nil {+ return fmt.Errorf(+ errAlreadyUp,+ ErrListener,+ a.listener.dependency.Addr(),+ )+ }++ listener, err := net.Listen(network, addr)+ if err != nil {+ return fmt.Errorf(errBindFailed, ErrListener, addr, err)+ }++ a.listener.dependency = listener+ a.listener.depSrv = &http.Server{+ Handler: a.dependencyRoutes(),+ ReadHeaderTimeout: readHeaderTimeout,+ TLSConfig: &tls.Config{+ MinVersion: tls.VersionTLS12,+ GetCertificate: a.getCertificate,+ },+ }++ a.listener.wg.Add(1)++ go func() {+ defer a.listener.wg.Done()+ _ = a.listener.depSrv.ServeTLS(listener, "", "")+ }()++ return nil+}++// getCertificate resolves the armed chain per handshake.+//+// A handshake that arrives with nothing armed is served the honest chain rather+// than refused, because the baseline is measured through this listener and a+// baseline that cannot connect establishes nothing.+func (a *Authority) getCertificate(+ *tls.ClientHelloInfo,+) (*tls.Certificate, error) {+ chain, err := a.Served()+ if err != nil {+ honest, buildErr := a.build(Trap{Kind: PassThrough, Host: a.host})+ if buildErr != nil {+ return nil, buildErr+ }++ certificate := honest.TLS()++ return &certificate, nil+ }++ certificate := chain.TLS()++ return &certificate, nil+}++// Addr is where the revocation endpoints are bound.+func (a *Authority) Addr() (string, error) {+ a.listener.mu.Lock()+ defer a.listener.mu.Unlock()++ if a.listener.revocation == nil {+ return "", fmt.Errorf(errNoListener, ErrListener, "revocation")+ }++ return a.listener.revocation.Addr().String(), nil+}++// TLSAddr is where khaos is playing the dependency.+func (a *Authority) TLSAddr() (string, error) {+ a.listener.mu.Lock()+ defer a.listener.mu.Unlock()++ if a.listener.dependency == nil {+ return "", fmt.Errorf(errNoListener, ErrListener, "the dependency")+ }++ return a.listener.dependency.Addr().String(), nil+}++func (a *Authority) shutdown() error {+ a.listener.mu.Lock()++ servers := []*http.Server{a.listener.revSrv, a.listener.depSrv}+ a.listener.revSrv = nil+ a.listener.depSrv = nil+ a.listener.revocation = nil+ a.listener.dependency = nil++ a.listener.mu.Unlock()++ var failures []error++ for _, server := range servers {+ if server == nil {+ continue+ }++ if err := server.Close(); err != nil {+ failures = append(failures, err)+ }+ }++ a.listener.wg.Wait()++ return errors.Join(failures...)+}++const readHeaderTimeout = 10 * time.Seconddiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server_test.gonew file mode 100644index 00000000..bd9e65af--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server_test.go@@ -0,0 +1,365 @@+// ©AngelaMos | 2026+// server_test.go++package pki++import (+ "crypto/tls"+ "crypto/x509"+ "errors"+ "io"+ "net"+ "net/http"+ "strings"+ "testing"+ "time"+)++const (+ loopbackAny = "127.0.0.1:0"+ probeTimeout = 5 * time.Second+)++// listening stands the authority up on both of its listeners, which is how+// every experiment uses it: a TLS endpoint where khaos plays the dependency,+// and an HTTP endpoint for the revocation data its certificate points at.+func listening(t *testing.T) *Authority {+ t.Helper()++ a := authority_t(t)++ if err := a.Listen(loopbackAny); err != nil {+ t.Fatalf("bind the revocation endpoints: %v", err)+ }++ if err := a.ListenTLS(loopbackAny); err != nil {+ t.Fatalf("bind the dependency: %v", err)+ }++ if err := a.Disarm(); err != nil {+ t.Fatalf("mint the honest chain: %v", err)+ }++ return a+}++// dial does what the target does: connect over TLS, verifying against the root+// the target was configured to trust, and asking for the name it expects.+func dial(t *testing.T, a *Authority) error {+ t.Helper()++ addr, err := a.TLSAddr()+ if err != nil {+ t.Fatalf("dependency address: %v", err)+ }++ conn, dialErr := tls.DialWithDialer(+ &net.Dialer{Timeout: probeTimeout},+ network,+ addr,+ &tls.Config{+ RootCAs: a.TrustedPool(),+ ServerName: a.Host(),+ MinVersion: tls.VersionTLS12,+ },+ )+ if dialErr != nil {+ return dialErr+ }++ defer func() { _ = conn.Close() }()++ return nil+}++// The control for the whole file. A target that cannot complete a handshake+// against an unarmed authority would make every fault below unattributable.+func TestAHandshakeSucceedsAgainstAnUnarmedAuthority(t *testing.T) {+ a := listening(t)++ if err := dial(t, a); err != nil {+ t.Fatalf(+ "the honest chain was refused over a real handshake (%v); every TLS fault is measured against this",+ err,+ )+ }+}++// The fault table verifies chains in isolation. This asserts the same verdict+// survives a real handshake, because a chain that is wrong on paper and fine+// over the wire would make every experiment in the family report HELD.+func TestTheServedChainFailsAHandshakeWhenGoRefusesIt(t *testing.T) {+ for _, row := range faultTable() {+ if row.want == accepted {+ // Go accepts these, so a handshake MUST succeed. Asserting the+ // opposite would be asserting khaos's own wrong expectation.+ continue+ }++ if row.dialAs != "" {+ // Dialled by address, which this helper does not do.+ continue+ }++ t.Run(string(row.kind), func(t *testing.T) {+ a := listening(t)++ if err := a.Arm(Trap{+ Kind: row.kind,+ Host: a.Host(),+ Window: DefaultWindow,+ Bits: DefaultWeakBits,+ Days: DefaultExcessiveDays,+ }); err != nil {+ t.Fatalf("arm %s: %v", row.kind, err)+ }++ if err := dial(t, a); err == nil {+ t.Fatalf(+ "%s completed a handshake, but crypto/x509 refuses this chain; the fault is inert over the wire",+ row.kind,+ )+ }+ })+ }+}++// The seventeen traps Go ACCEPTS have to complete a handshake, or the+// experiments built on them would be measuring a connection failure khaos+// caused rather than a policy the target lacks.+func TestTheServedChainCompletesAHandshakeWhenGoAcceptsIt(t *testing.T) {+ for _, row := range faultTable() {+ if row.want != accepted {+ continue+ }++ t.Run(string(row.kind), func(t *testing.T) {+ a := listening(t)++ if err := a.Arm(Trap{+ Kind: row.kind,+ Host: a.Host(),+ Window: DefaultWindow,+ Bits: DefaultWeakBits,+ Days: DefaultExcessiveDays,+ }); err != nil {+ t.Fatalf("arm %s: %v", row.kind, err)+ }++ if err := dial(t, a); err != nil {+ t.Fatalf(+ "%s failed a handshake (%v), but crypto/x509 accepts this chain; the experiment would report a refusal khaos caused",+ row.kind,+ err,+ )+ }+ })+ }+}++// The control for both unreachable traps. Their whole design rests on the+// health route staying up while one endpoint dies: if the whole listener went+// down, khaos could not tell "I broke the responder" from "I fell over", and+// the experiment would be unattributable.+func TestAnUnreachableEndpointLeavesHealthServing(t *testing.T) {+ cases := []struct {+ kind Kind+ route string+ }{+ {CRLUnreachable, RouteCRL},+ {OCSPUnreachable, RouteOCSP},+ }++ for _, each := range cases {+ t.Run(string(each.kind), func(t *testing.T) {+ a := listening(t)++ base, err := a.Addr()+ if err != nil {+ t.Fatalf("revocation address: %v", err)+ }++ root := schemeHTTP + base++ if status, err := get(root + each.route); err != nil ||+ status != http.StatusOK {+ t.Fatalf(+ "%s is not reachable before the trap is armed (status %d, err %v), so its refusal afterwards would prove nothing",+ each.route,+ status,+ err,+ )+ }++ if err := a.Arm(Trap{+ Kind: each.kind,+ Host: a.Host(),+ }); err != nil {+ t.Fatalf("arm %s: %v", each.kind, err)+ }++ if _, err := get(root + each.route); err == nil {+ t.Fatalf(+ "%s still answered after %s was armed; the fault is inert",+ each.route,+ each.kind,+ )+ }++ status, err := get(root + RouteHealth)+ if err != nil || status != http.StatusOK {+ t.Fatalf(+ "the health route died with %s (status %d, err %v); khaos cannot then show it broke ONE endpoint rather than falling over",+ each.kind,+ status,+ err,+ )+ }+ })+ }+}++// A revoked certificate is only a finding if the CRL khaos serves actually says+// so. This checks the served bytes rather than the intent.+func TestTheServedCRLRevokesTheServedLeaf(t *testing.T) {+ a := listening(t)++ if err := a.Arm(Trap{+ Kind: RevokedViaCRL,+ Host: a.Host(),+ }); err != nil {+ t.Fatalf("arm: %v", err)+ }++ chain, err := a.Served()+ if err != nil {+ t.Fatalf("served chain: %v", err)+ }++ base, err := a.Addr()+ if err != nil {+ t.Fatalf("revocation address: %v", err)+ }++ der, err := fetch(schemeHTTP + base + RouteCRL)+ if err != nil {+ t.Fatalf("fetch the CRL: %v", err)+ }++ list, err := x509.ParseRevocationList(der)+ if err != nil {+ t.Fatalf("parse the CRL: %v", err)+ }++ if err := list.CheckSignatureFrom(chain.Issuer); err != nil {+ t.Fatalf(+ "the served CRL is not signed by the leaf's own issuer (%v); a client that checks the signature would discard it and read as fail-closed for the wrong reason",+ err,+ )+ }++ if !revokes(list, chain.Leaf.SerialNumber.String()) {+ t.Fatalf(+ "the served CRL does not list serial %s; khaos would be claiming a revocation it never published",+ chain.Leaf.SerialNumber,+ )+ }++ // Freshness, because a stale CRL is a DIFFERENT fault and this one must not+ // accidentally be it.+ if !list.NextUpdate.After(a.Now()) {+ t.Fatalf(+ "the CRL for %s is already stale (NextUpdate %s); that is the StaleCRL fault, and these two have to stay distinguishable",+ RevokedViaCRL,+ list.NextUpdate,+ )+ }+}++func revokes(list *x509.RevocationList, serial string) bool {+ for _, entry := range list.RevokedCertificateEntries {+ if entry.SerialNumber.String() == serial {+ return true+ }+ }++ return false+}++func get(url string) (int, error) {+ client := &http.Client{Timeout: probeTimeout}++ response, err := client.Get(url)+ if err != nil {+ return 0, err+ }++ defer func() { _ = response.Body.Close() }()++ _, _ = io.Copy(io.Discard, response.Body)++ return response.StatusCode, nil+}++func fetch(url string) ([]byte, error) {+ client := &http.Client{Timeout: probeTimeout}++ response, err := client.Get(url)+ if err != nil {+ return nil, err+ }++ defer func() { _ = response.Body.Close() }()++ if response.StatusCode != http.StatusOK {+ return nil, errors.New(+ "revocation endpoint answered " + response.Status,+ )+ }++ return io.ReadAll(response.Body)+}++// SetBase must not be overwritten by Listen. This is the identity provider's+// most expensive bug restated as a test: there, Listen replaced the pinned+// issuer with its own listener address, every credential was refused on `iss`,+// and the run blamed the target. No unit test could see it because the value+// was only wrong once a container was involved.+func TestListenDoesNotOverwriteAPinnedBase(t *testing.T) {+ const pinned = "http://host.docker.internal:48123"++ a := authority_t(t)++ a.SetBase(pinned)++ if err := a.Listen(loopbackAny); err != nil {+ t.Fatalf("listen: %v", err)+ }++ if got := a.Base(); got != pinned {+ t.Fatalf(+ "Listen replaced the pinned base with %q; the target addresses khaos by a name khaos cannot see from its own listener, so every revocation fetch would fail for a reason unrelated to the trap",+ got,+ )+ }++ if err := a.Disarm(); err != nil {+ t.Fatalf("disarm: %v", err)+ }++ chain, err := a.Served()+ if err != nil {+ t.Fatalf("served chain: %v", err)+ }++ if len(chain.Leaf.CRLDistributionPoints) == 0 {+ t.Fatal("the honest leaf names no CRL distribution point")+ }++ if !strings.HasPrefix(chain.Leaf.CRLDistributionPoints[0], pinned) {+ t.Fatalf(+ "the leaf points at %q, not the pinned base; a target following it would reach nowhere",+ chain.Leaf.CRLDistributionPoints[0],+ )+ }+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.gonew file mode 100644index 00000000..c1f26c01--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go@@ -0,0 +1,301 @@+// ©AngelaMos | 2026+// trap.go++package pki++import (+ "errors"+ "fmt"+ "slices"+ "time"+)++// Kind names one way khaos makes its own certificate authority wrong. Every+// kind maps to a row of the fault table in research 04, which recorded the+// client-side error type, the x509 InvalidReason integer and the fail-open+// behaviour the fault is for, all measured on go1.26.5.+//+// The groups below are the ones the research itself uses, and they are not+// cosmetic: a fault that corrupts the validity window is confirmed differently+// from one that corrupts the chain, and three of the chain faults produce a+// BYTE-IDENTICAL client error, which is the problem this family exists to make+// tractable.+type Kind string++const (+ // PassThrough is the zero value: the authority behaves correctly. An+ // authority with nothing armed has to be indistinguishable from a real one,+ // because every experiment's baseline is measured through it.+ PassThrough Kind = ""++ // LeafExpired and LeafNotYetValid both come back as+ // CertificateInvalidError with Reason 1. There is NO separate+ // NotYetValid reason, so the only thing that tells them apart is whether+ // the Detail says "is after" or "is before". Rows F01 and F02.+ LeafExpired Kind = "leaf-expired"+ LeafNotYetValid Kind = "leaf-not-yet-valid"++ // IntermediateExpired leaves the leaf in date and expires the CA above it.+ // Row F03, and the fail-open it catches is monitoring that watches leaf+ // expiry only.+ IntermediateExpired Kind = "intermediate-expired"++ // WrongSAN, CommonNameOnly and NoIPSAN are the hostname faults, all+ // HostnameError. CommonNameOnly is worth its own kind because Go removed the+ // CommonName fallback outright: the error names the legacy field, which is a+ // different message from a plain mismatch. Rows F04, F05 and F07.+ WrongSAN Kind = "wrong-san"+ CommonNameOnly Kind = "common-name-only"+ NoIPSAN Kind = "no-ip-san"++ // SelfSigned, UntrustedCA and MissingIntermediate are THE THREE that matter+ // most in this family. All three produce exactly+ // `x509: certificate signed by unknown authority`, with no reason code and+ // nothing in the string to separate them, so a target's logs cannot tell an+ // operator which one happened. Disambiguating them is M7's exit gate. Rows+ // F09, F10 and F11.+ SelfSigned Kind = "self-signed"+ UntrustedCA Kind = "untrusted-ca"+ MissingIntermediate Kind = "missing-intermediate"++ // IssuerNotCA signs the leaf with a certificate whose IsCA is false, which+ // surfaces as UnknownAuthorityError wrapping ConstraintViolationError. Row+ // F16.+ IssuerNotCA Kind = "issuer-not-ca"++ // NameConstraintViolation and PathLengthExceeded are the two constraint+ // faults, Reason 2 and Reason 3. Rows F17 and F18.+ NameConstraintViolation Kind = "name-constraint-violation"+ PathLengthExceeded Kind = "path-length-exceeded"++ // SHA1Signature signs the leaf with SHA1WithRSA. Go CREATES it without+ // complaint and refuses it at verification, wrapping InsecureAlgorithmError+ // inside UnknownAuthorityError, so this reads as an authority failure unless+ // the caller unwraps. Row F12, measured again on this box before the family+ // was built.+ SHA1Signature Kind = "sha1-signature"++ // WeakKey through KeyUsageWithoutDigitalSignature are the faults Go+ // ACCEPTS. They return nil from Verify, so they do not test the x509+ // library at all -- they test whether the TARGET imposed a policy of its+ // own. Rows F13, F20 and F19.+ //+ // These are the most valuable experiments in the family for exactly that+ // reason, and also the ones whose polarity is easiest to get wrong: a target+ // that accepts them is not being caught out by Go, it simply has no floor.+ WeakKey Kind = "weak-key"+ ExcessiveLifetime Kind = "excessive-lifetime"+ KeyUsageWithoutDigitalSignature Kind = "key-usage-no-digital-signature"++ // EKUClientAuthOnly and EKUConstrainedIntermediate are the extended key+ // usage faults, Reason 4 and Reason 9. Go checks EKU nested down the chain+ // but does not check the basic KeyUsage bits on a leaf, which is why the+ // kind above exists beside these two. Rows F14 and F15.+ EKUClientAuthOnly Kind = "eku-client-auth-only"+ EKUConstrainedIntermediate Kind = "eku-constrained-intermediate"++ // RevokedViaCRL is the headline of the whole family. The leaf is revoked in+ // a valid, in-date, correctly signed CRL from its own issuer, and+ // `Certificate.Verify` returns nil, because Go performs no revocation+ // checking of any kind and has no option to turn it on. Row F21.+ //+ // khaos must therefore report `unsupported` rather than `pass` against a Go+ // target that does nothing: there is no revocation check to have failed.+ // That distinction is the other half of M7's exit gate.+ RevokedViaCRL Kind = "revoked-via-crl"++ // StaleCRL revokes the leaf in a CRL whose NextUpdate is in the past. It is+ // a DIFFERENT fault from RevokedViaCRL and strictly harder to pass: the+ // target does fetch and parse a CRL, and still accepts the certificate,+ // because nothing in the standard library checks freshness and step 5 of the+ // six-step check is the one people skip. Row F33.+ StaleCRL Kind = "stale-crl"++ // CRLUnreachable serves the leaf with a CRL distribution point that refuses+ // the connection, while every other endpoint stays up. A target that treats+ // "could not fetch" as "not revoked" fails open here and nowhere else.+ CRLUnreachable Kind = "crl-unreachable"++ // OCSPRevoked and OCSPUnknown are the two answers a responder gives that a+ // correct client must reject. "Unknown" from the authoritative responder is+ // not "good", and collapsing the two is its own fail-open.+ OCSPRevoked Kind = "ocsp-revoked"+ OCSPUnknown Kind = "ocsp-unknown"++ // OCSPTryLater and OCSPUnreachable are the soft-fail traps, and research 04+ // calls soft-fail the reason revocation is near-useless in practice. A+ // client that proceeds because it could not get an answer has a seat belt+ // that unbuckles under load.+ OCSPTryLater Kind = "ocsp-try-later"+ OCSPUnreachable Kind = "ocsp-unreachable"++ // OCSPStale returns a correctly signed Good response whose NextUpdate is in+ // the past. Measured: x/crypto/ocsp does not check freshness, so this parses+ // with a nil error and a replayed Good is trusted forever. Row F30.+ OCSPStale Kind = "ocsp-stale"++ // OCSPWrongSerial is the single highest-value trap in the OCSP group,+ // because the bypass is one word of caller code. A Good response minted for+ // a DIFFERENT serial is rejected by ocsp.ParseResponseForCert and accepted+ // by ocsp.ParseResponse, which does not bind the response to the+ // certificate at all. Row F31.+ OCSPWrongSerial Kind = "ocsp-wrong-serial"++ // OCSPWrongSigner signs the response with a key the CA never delegated.+ // CheckSignatureFrom catches it, but only if the caller calls it.+ OCSPWrongSigner Kind = "ocsp-wrong-signer"++ // NoOCSPServer mints a leaf with no OCSPServer at all, which models Let's+ // Encrypt after it ended OCSP in 2025. The question it asks is what the+ // target does when there is nothing to ask: fail open, or fall back to the+ // CRL it also published. Row F34.+ NoOCSPServer Kind = "no-ocsp-server"++ // StapleGarbage and StapleAbsent act on the stapled response rather than on+ // the responder. Go never parses a staple, so both reach the application+ // untouched: one as bytes that are not an OCSP response, the other as an+ // empty field a soft-failing app reads as good. Rows F28 and F29.+ StapleGarbage Kind = "staple-garbage"+ StapleAbsent Kind = "staple-absent"++ // CASwap replaces the root the target trusts with one khaos controls, and+ // then serves a chain that is VALID under it. Nothing in the client can+ // detect this, which is the point: it is the CA-compromise scenario, and the+ // only defences are pinning or certificate transparency. Row F24.+ CASwap Kind = "ca-swap"+)++const (+ describeLeafExpired = "serve %s a certificate that expired %s ago"+ describeLeafNotYetValid = "serve %s a certificate that is not valid for another %s"+ describeIntermediateOld = "serve %s a valid leaf under an intermediate that expired %s ago"++ describeWrongSAN = "serve %s a certificate whose SANs name a different host"+ describeCommonNameOnly = "serve %s a certificate with no SAN extension at all, naming the host only in the legacy CommonName field"+ describeNoIPSAN = "serve %s a certificate with no IP SANs, reached by address"++ describeSelfSigned = "serve %s a self-signed leaf where a CA-signed one is expected"+ describeUntrustedCA = "serve %s a leaf signed by a CA it does not trust"+ describeMissingInterCA = "serve %s a valid leaf while withholding the intermediate that chains it"+ describeIssuerNotCA = "serve %s a leaf signed by a certificate whose basic constraints say it is not a CA"+ describeNameConstraint = "serve %s a leaf for a name its issuing CA is constrained against"+ describePathLength = "serve %s a chain one intermediate deeper than its CA's path length allows"++ describeSHA1 = "serve %s a leaf signed with SHA-1 RSA"+ describeWeakKey = "serve %s a leaf carrying a %d-bit RSA key, which x509 path validation has no floor against"+ describeLifetime = "serve %s a leaf valid for %d days, which nothing outside a browser enforces"+ describeKeyUsage = "serve %s a leaf whose KeyUsage omits digitalSignature, which Verify does not check"+ describeEKUClientOnly = "serve %s a leaf whose extended key usage permits client authentication only"+ describeEKUConstrained = "serve %s a leaf under an intermediate not authorised for server authentication"++ describeRevokedCRL = "revoke %s's certificate in a valid, in-date CRL from its own issuer"+ describeStaleCRL = "revoke %s's certificate in a correctly signed CRL whose freshness window closed %s ago"+ describeCRLUnreachable = "refuse %s's connections to the CRL distribution point while every other endpoint stays up"++ describeOCSPRevoked = "answer %s's revocation queries with a signed Revoked response"+ describeOCSPUnknown = "answer %s's revocation queries with a signed Unknown response"+ describeOCSPTryLater = "answer %s's revocation queries with TryLater, the soft-fail trap"+ describeOCSPUnreachable = "refuse %s's connections to the OCSP responder while every other endpoint stays up"+ describeOCSPStale = "answer %s with a correctly signed Good response whose freshness window closed %s ago"+ describeOCSPWrongSerial = "answer %s with a signed Good response minted for a different certificate's serial"+ describeOCSPWrongSigner = "answer %s with a Good response signed by a key its CA never delegated"+ describeNoOCSPServer = "serve %s a leaf that names no OCSP responder at all"++ describeStapleGarbage = "staple bytes that are not an OCSP response to %s's handshake"+ describeStapleAbsent = "omit the stapled revocation response from %s's handshake entirely"++ describeCASwap = "replace the root %s trusts with one khaos controls, and serve a chain that is valid under it"+)++const (+ errNeedsDelay = "%w: %s has no magnitude, and a window of zero is indistinguishable from no fault at all"+ errNeedsHost = "%w: %s has to name the host its certificate is served for"+ errBadBits = "%w: %s needs an RSA size below %d bits to be a weak key at all, got %d"+ errBadDays = "%w: %s needs a lifetime longer than %d days to exceed anything, got %d"+ errUnknown = "%w: %q (known traps: %s)"+ trapSep = ", "+)++var (+ // ErrInvalidTrap is a trap khaos understands, specified in a way that cannot+ // express the fault.+ ErrInvalidTrap = errors.New("that trap cannot be armed as specified")++ // ErrUnknownTrap is a name khaos's authority has no fault for.+ ErrUnknownTrap = errors.New(+ "khaos's certificate authority has no such trap",+ )+)++// Trap is one armed misbehaviour and its magnitude. It is a value rather than a+// closure so it can be journaled: the authority dies with the process, so the+// journal record is the only durable account of what a run actually did.+type Trap struct {+ Kind Kind `json:"kind"`++ // Window is how far a time-based fault moves the boundary it corrupts: how+ // long ago the leaf expired, how far in the future it starts, how stale the+ // CRL or OCSP response is.+ Window time.Duration `json:"window,omitempty"`++ // Host is the name the served certificate is minted for, and the name the+ // hostname faults deliberately get wrong.+ Host string `json:"host,omitempty"`++ // Bits is the RSA modulus size WeakKey mints. It is a parameter because the+ // interesting question is where the target's floor sits, and a single fixed+ // size can only ever answer it for one floor.+ Bits int `json:"bits,omitempty"`++ // Days is the leaf lifetime ExcessiveLifetime mints, for the same reason.+ Days int `json:"days,omitempty"`+}++func (t Trap) Validate() error {+ switch t.Kind {+ case LeafExpired, LeafNotYetValid, IntermediateExpired, StaleCRL,+ OCSPStale:+ if t.Window <= 0 {+ return fmt.Errorf(errNeedsDelay, ErrInvalidTrap, t.Kind)+ }++ case WeakKey:+ if t.Bits <= 0 || t.Bits >= StrongBits {+ return fmt.Errorf(+ errBadBits,+ ErrInvalidTrap,+ t.Kind,+ StrongBits,+ t.Bits,+ )+ }++ case ExcessiveLifetime:+ if t.Days <= LifetimeCapDays {+ return fmt.Errorf(+ errBadDays,+ ErrInvalidTrap,+ t.Kind,+ LifetimeCapDays,+ t.Days,+ )+ }++ default:+ // The remaining traps carry no magnitude to validate.+ }++ // EVERY trap mints and serves a leaf, including the ones that act on the+ // responder, because a revocation answer about no certificate is not a fault+ // anyone can observe. So the host is required unconditionally rather than+ // through a per-kind predicate that would have no false case.+ if t.Kind != PassThrough && t.Host == "" {+ return fmt.Errorf(errNeedsHost, ErrInvalidTrap, t.Kind)+ }++ if t.Kind != PassThrough && !slices.Contains(Kinds(), string(t.Kind)) {+ return fmt.Errorf(errUnknown, ErrUnknownTrap, t.Kind, joinKinds())+ }++ return nil+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/verify_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/verify_test.gonew file mode 100644index 00000000..c93b82d8--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/verify_test.go@@ -0,0 +1,361 @@+// ©AngelaMos | 2026+// verify_test.go++package pki++import (+ "crypto/x509"+ "errors"+ "strings"+ "testing"+ "time"+)++// outcome is what a correct client's verification does with a chain. It is the+// error TYPE plus the InvalidReason integer, never the error string: research+// 04 is explicit that the strings embed timestamps and name lists, so matching+// on them would make these assertions drift with the clock.+type outcome int++const (+ // accepted is a nil error from Verify. For seventeen of these traps that is+ // the CORRECT result and the whole point of the fault.+ accepted outcome = iota+ invalid+ hostname+ authority+)++func (o outcome) String() string {+ switch o {+ case accepted:+ return "accepted"+ case invalid:+ return "x509.CertificateInvalidError"+ case hostname:+ return "x509.HostnameError"+ case authority:+ return "x509.UnknownAuthorityError"+ default:+ return "unknown"+ }+}++// classify maps whatever Verify returned onto the taxonomy, so a trap that+// fails for an unexpected REASON is distinguishable from one that fails as+// designed.+func classify(err error) (outcome, x509.InvalidReason) {+ if err == nil {+ return accepted, 0+ }++ var bad x509.CertificateInvalidError+ if errors.As(err, &bad) {+ return invalid, bad.Reason+ }++ var wrongName x509.HostnameError+ if errors.As(err, &wrongName) {+ return hostname, 0+ }++ var unknown x509.UnknownAuthorityError+ if errors.As(err, &unknown) {+ return authority, 0+ }++ return -1, 0+}++// expectation is one row of research 04's fault table, restated as something+// executable. detail is a substring of CertificateInvalidError.Detail, needed+// only where two traps share a reason code and nothing else separates them.+type expectation struct {+ kind Kind+ want outcome+ reason x509.InvalidReason+ detail string++ // dialAs is the name the client asks for, and it is not always the host the+ // certificate was minted for. NoIPSAN is the reason this field exists: a+ // certificate with no IP SANs is perfectly correct for a client dialling by+ // NAME, and is only a fault for one dialling by address. Asserting it+ // through a DNS name would record it as accepted and the experiment built on+ // that row would measure nothing.+ dialAs string+}++// The table. Every row came from the research's measured fault table, and this+// test is the differential that keeps khaos's minting honest about it: if Go+// changes what it enforces, or if a defect builder stops expressing its fault,+// the row goes red rather than the experiment silently measuring nothing.+func faultTable() []expectation {+ return []expectation{+ // Validity. Both leaf faults share Reason 1 because there is no+ // separate not-yet-valid reason, so the Detail wording is the only+ // thing telling them apart. That trap is the reason detail exists here.+ {LeafExpired, invalid, x509.Expired, "is after", ""},+ {LeafNotYetValid, invalid, x509.Expired, "is before", ""},+ {IntermediateExpired, invalid, x509.Expired, "is after", ""},++ // Identity. NoIPSAN is dialled by address on purpose; see dialAs.+ {WrongSAN, hostname, 0, "", ""},+ {CommonNameOnly, hostname, 0, "", ""},+ {NoIPSAN, hostname, 0, "", loopbackIP},++ // Authority. These three are the family's reason for existing: all of+ // them are UnknownAuthorityError with no reason code and an identical+ // string, so nothing a target logs can tell an operator which happened.+ {SelfSigned, authority, 0, "", ""},+ {UntrustedCA, authority, 0, "", ""},+ {MissingIntermediate, authority, 0, "", ""},+ {IssuerNotCA, authority, 0, "", ""},+ {+ NameConstraintViolation,+ invalid,+ x509.CANotAuthorizedForThisName,+ "",+ "",+ },+ {PathLengthExceeded, invalid, x509.TooManyIntermediates, "", ""},++ // Algorithm. SHA-1 arrives wrapped inside an authority error, which is+ // itself the finding: a caller that does not unwrap blames the CA.+ {SHA1Signature, authority, 0, "", ""},++ // BOTH EKU faults are Reason 4, and research 04's F15 row saying the+ // CA-level one is Reason 9 is wrong for go1.26.5. Measured four ways+ // (CA clientAuth or codeSigning, leaf serverAuth or empty) and all four+ // returned 4. Traced to the source: CANotAuthorizedForExtKeyUsage+ // appears in crypto/x509 ONLY in its own declaration and in the Error()+ // string switch, and is never constructed anywhere, so Go cannot return+ // it. The constant is formattable dead code.+ //+ // This makes the two EKU faults a SECOND pair of byte-identical+ // outcomes, alongside the three authority ones, and the family treats+ // them the same way: distinguished by what khaos knows it served.+ {EKUClientAuthOnly, invalid, x509.IncompatibleUsage, "", ""},+ {EKUConstrainedIntermediate, invalid, x509.IncompatibleUsage, "", ""},++ // Policy. Go returns nil for all three. These do not test x509 at all;+ // they test whether the target has a floor of its own.+ {WeakKey, accepted, 0, "", ""},+ {ExcessiveLifetime, accepted, 0, "", ""},+ {KeyUsageWithoutDigitalSignature, accepted, 0, "", ""},++ // Revocation. Every one of these is accepted, because Go performs no+ // revocation checking of any kind and there is no option to turn it on.+ // That is the single most important fact in this family.+ {RevokedViaCRL, accepted, 0, "", ""},+ {StaleCRL, accepted, 0, "", ""},+ {CRLUnreachable, accepted, 0, "", ""},+ {OCSPRevoked, accepted, 0, "", ""},+ {OCSPUnknown, accepted, 0, "", ""},+ {OCSPTryLater, accepted, 0, "", ""},+ {OCSPUnreachable, accepted, 0, "", ""},+ {OCSPStale, accepted, 0, "", ""},+ {OCSPWrongSerial, accepted, 0, "", ""},+ {OCSPWrongSigner, accepted, 0, "", ""},+ {NoOCSPServer, accepted, 0, "", ""},+ {StapleGarbage, accepted, 0, "", ""},+ {StapleAbsent, accepted, 0, "", ""},++ // Trust store. Accepted BY CONSTRUCTION: khaos moved the anchor, so the+ // chain is genuinely valid under what the target now trusts. Nothing in+ // a client can detect this.+ {CASwap, accepted, 0, "", ""},+ }+}++const (+ testHost = "dependency.khaos.invalid"++ // loopbackIP is what the NoIPSAN row dials. Verifying by address is the+ // only way that fault exists at all.+ loopbackIP = "127.0.0.1"+)++func authority_t(t *testing.T) *Authority {+ t.Helper()++ a, err := New(Config{Host: testHost})+ if err != nil {+ t.Fatalf("build an authority: %v", err)+ }++ t.Cleanup(func() { _ = a.Close() })++ return a+}++// verifyAsClient does exactly what a correct client does and nothing more: it+// anchors on the root the TARGET trusts, supplies only the intermediates the+// handshake actually presented, and checks the name it asked for.+//+// Supplying khaos's real intermediate here regardless of what was presented+// would quietly repair MissingIntermediate, and that row would then pass for+// the wrong reason.+func verifyAsClient(+ t *testing.T,+ a *Authority,+ chain *Chain,+ host string,+) error {+ t.Helper()++ intermediates, err := chain.PresentedPool()+ if err != nil {+ t.Fatalf("parse the presented chain: %v", err)+ }++ _, verifyErr := chain.Leaf.Verify(x509.VerifyOptions{+ Roots: a.TrustedPool(),+ Intermediates: intermediates,+ DNSName: host,+ CurrentTime: a.Now(),+ })++ return verifyErr+}++func TestEveryTrapProducesTheMeasuredClientOutcome(t *testing.T) {+ table := faultTable()++ // The census. A trap without a row here is a fault khaos would arm and then+ // never check the meaning of, which is how a family ends up with an+ // experiment that measures nothing.+ if len(table) != len(Kinds()) {+ t.Fatalf(+ "the fault table has %d rows and khaos advertises %d traps; a new trap needs a row",+ len(table),+ len(Kinds()),+ )+ }++ for _, row := range table {+ t.Run(string(row.kind), func(t *testing.T) {+ a := authority_t(t)++ trap := Trap{+ Kind: row.kind,+ Host: testHost,+ Window: DefaultWindow,+ Bits: DefaultWeakBits,+ Days: DefaultExcessiveDays,+ }++ if err := a.Arm(trap); err != nil {+ t.Fatalf("arm %s: %v", row.kind, err)+ }++ chain, err := a.Served()+ if err != nil {+ t.Fatalf("served chain: %v", err)+ }++ host := testHost+ if row.dialAs != "" {+ host = row.dialAs+ }++ got, reason := classify(verifyAsClient(t, a, chain, host))++ if got != row.want {+ t.Fatalf(+ "%s verified as %s, want %s (err: %v)",+ row.kind,+ got,+ row.want,+ verifyAsClient(t, a, chain, host),+ )+ }++ if row.want == invalid && reason != row.reason {+ t.Fatalf(+ "%s gave InvalidReason %d, want %d; two traps sharing a reason are only distinguishable by it",+ row.kind,+ reason,+ row.reason,+ )+ }++ if row.detail != "" {+ assertDetail(t, verifyAsClient(t, a, chain, host), row)+ }+ })+ }+}++func assertDetail(t *testing.T, err error, row expectation) {+ t.Helper()++ var bad x509.CertificateInvalidError+ if !errors.As(err, &bad) {+ t.Fatalf(+ "%s: expected a CertificateInvalidError, got %v",+ row.kind,+ err,+ )+ }++ if !strings.Contains(bad.Detail, row.detail) {+ t.Fatalf(+ "%s detail is %q, which does not contain %q; expired and not-yet-valid share a reason code and this substring is the only thing separating them",+ row.kind,+ bad.Detail,+ row.detail,+ )+ }+}++// GoAccepts is the predicate that decides what an acceptance MEANS, so it must+// agree with what Go actually did rather than with what the catalogue claims.+// This is the differential: the table above is measured against crypto/x509,+// and this asserts the predicate matches the table row for row.+func TestGoAcceptsAgreesWithMeasuredVerification(t *testing.T) {+ for _, row := range faultTable() {+ t.Run(string(row.kind), func(t *testing.T) {+ claimed := GoAccepts(row.kind)+ measured := row.want == accepted++ if claimed != measured {+ t.Fatalf(+ "GoAccepts(%s) says %v but verification measured %v; the predicate decides whether an acceptance is a defect or merely the absence of a policy, so a wrong answer here makes khaos accuse a target of something that did not happen",+ row.kind,+ claimed,+ measured,+ )+ }+ })+ }+}++// The control for the whole file. If an unarmed authority served anything a+// correct client refused, every row above would be measuring khaos's own broken+// baseline rather than the trap.+func TestAnUnarmedAuthorityServesAChainAClientAccepts(t *testing.T) {+ a := authority_t(t)++ if err := a.Disarm(); err != nil {+ t.Fatalf("disarm: %v", err)+ }++ chain, err := a.Served()+ if err != nil {+ t.Fatalf("served chain: %v", err)+ }++ if err := verifyAsClient(t, a, chain, testHost); err != nil {+ t.Fatalf(+ "the honest chain was refused (%v); every fault in this family is measured against it, so a broken control establishes nothing",+ err,+ )+ }++ if chain.Leaf.NotAfter.Sub(chain.Leaf.NotBefore) >+ time.Duration(LifetimeCapDays)*24*time.Hour {+ t.Fatal(+ "the honest leaf is already over the lifetime cap, so the excessive-lifetime trap has nothing to exceed",+ )+ }+}