Skip to content

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 đŸ‘‡

feat(khaos): the authority's confirmation oracle, and what its control found

CarterPerez-dev5985166c9f82
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go
index 378f561a..a6f3f8f6 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go
@@ -109,6 +109,17 @@ type Authority struct {
trap Trap
armed *Chain
+ // swapped is BUILT state, not derived from the trap, and the distinction is
+ // what makes the confirmation oracle honest.
+ //
+ // UntrustedCA and CASwap build the IDENTICAL chain under the rogue
+ // hierarchy; the only difference between them is what the target trusts. So
+ // the trusted root cannot come from the chain, and reading it off trap.Kind
+ // instead meant an INERT authority -- one that records a trap and builds
+ // nothing -- would report the swap as confirmed. The oracle's negative
+ // control would have been passing against a fault that never happened.
+ swapped bool
+
// 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
@@ -243,7 +254,7 @@ func (a *Authority) TrustedRoot() *x509.Certificate {
a.mu.RLock()
defer a.mu.RUnlock()
- if a.trap.Kind == CASwap {
+ if a.swapped {
return a.rogueRoot.cert
}
@@ -268,7 +279,16 @@ func (a *Authority) Arm(trap Trap) error {
return fmt.Errorf(errArmTrap, ErrInvalidTrap, err)
}
+ // An inert authority RECORDS the trap and builds nothing. Recording it is
+ // deliberate: it makes the confirmation oracle run its real observable
+ // against honest material, rather than short-circuiting on the
+ // wrong-trap-armed guard and never reaching the branch under test.
if a.inert.Load() {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ a.trap = trap
+
return nil
}
@@ -282,6 +302,7 @@ func (a *Authority) Arm(trap Trap) error {
a.trap = trap
a.armed = chain
+ a.swapped = trap.Kind == CASwap
return nil
}
@@ -300,6 +321,7 @@ func (a *Authority) Disarm() error {
a.trap = Trap{}
a.armed = honest
+ a.swapped = false
return nil
}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go
index 93bdb2fc..f07db38c 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go
@@ -41,6 +41,12 @@ const (
// escaped into something real can never resolve.
DefaultHost = "dependency.khaos.invalid"
+ // loopbackSAN is the IP the honest leaf carries so that NoIPSAN has
+ // something to take away. khaos binds loopback in tests and a bridge
+ // address in a container, and this SAN only has to exist for the trap to be
+ // expressible -- the hostname faults are what judge the names.
+ loopbackSAN = "127.0.0.1"
+
// 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,
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go
index 4f6e1cba..c7be36c9 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/chain.go
@@ -42,6 +42,34 @@ type Chain struct {
// staple at all. Go never parses this; it is delivered to the application
// verbatim, which is what makes both stapling faults reachable.
Staple []byte
+
+ // crl and ocsp are the bytes the endpoints serve, minted at ARM time and
+ // served verbatim.
+ //
+ // They live here rather than being minted per request for two reasons. A
+ // real CA publishes a revocation list and does not regenerate it for each
+ // fetch, so a freshness window that slid forward on every request was
+ // wrong on its own terms. And minting from the trap at request time meant
+ // an INERT authority -- one that records a trap and builds nothing -- still
+ // served a revoked list, so thirteen traps confirmed against a fault that
+ // never happened. The oracle's negative control caught it.
+ crl []byte
+ ocsp []byte
+
+ // crlOut and ocspOut say whether each endpoint answers at all. Built state
+ // for the same reason, since an unreachable endpoint cannot be expressed in
+ // pre-minted bytes.
+ crlOut bool
+ ocspOut bool
+}
+
+// CRL and OCSP are what the endpoints serve for this chain.
+func (c *Chain) CRL() ([]byte, bool) {
+ return c.crl, !c.crlOut
+}
+
+func (c *Chain) OCSP() ([]byte, bool) {
+ return c.ocsp, !c.ocspOut
}
// TLS is the chain as crypto/tls wants it: leaf first, then whatever
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go
index f5cec40b..2757812f 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go
@@ -7,6 +7,8 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"time"
+
+ "golang.org/x/crypto/ocsp"
)
// build assembles the chain for one trap. Every trap starts from the HONEST
@@ -33,7 +35,48 @@ func (a *Authority) build(trap Trap) (*Chain, error) {
// 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)
+ if chain, err = a.staple(trap, chain, now); err != nil {
+ return nil, err
+ }
+
+ return a.publish(trap, chain, now)
+}
+
+// publish mints the revocation artefacts this chain's endpoints will serve, at
+// ARM time, so that everything the authority does under a trap is decided here
+// and nothing is derived from the trap record at request time.
+func (a *Authority) publish(
+ trap Trap,
+ chain *Chain,
+ now time.Time,
+) (*Chain, error) {
+ chain.crlOut = trap.Kind == CRLUnreachable
+ chain.ocspOut = trap.Kind == OCSPUnreachable
+
+ list, err := a.CRLFor(trap, chain, now)
+ if err != nil {
+ return nil, err
+ }
+
+ chain.crl = list
+
+ if trap.Kind == OCSPTryLater {
+ // A protocol-level refusal rather than a transport one. The responder
+ // IS reachable and IS answering; it is declining to say, which is the
+ // exact shape that exploits a soft-failing client.
+ chain.ocsp = ocsp.TryLaterErrorResponse
+
+ return chain, nil
+ }
+
+ answer, err := a.ocspFor(trap, chain, now)
+ if err != nil {
+ return nil, err
+ }
+
+ chain.ocsp = answer
+
+ return chain, nil
}
func (a *Authority) chainFor(
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go
index 39b7b36c..28c8bc6e 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mint.go
@@ -12,6 +12,7 @@ import (
"errors"
"fmt"
"math/big"
+ "net"
"time"
)
@@ -149,8 +150,15 @@ func leafTemplate(host string, now time.Time, days int) (
SerialNumber: number,
Subject: pkix.Name{CommonName: host},
DNSNames: []string{host},
- NotBefore: now.Add(-clockSlack),
- NotAfter: now.AddDate(0, 0, days),
+
+ // The honest leaf carries a loopback IP SAN so that NoIPSAN has
+ // something to REMOVE. Without it the honest certificate has no IP SANs
+ // either, that trap serves material identical to the control, and its
+ // observable confirmed against an authority that armed nothing.
+ IPAddresses: []net.IP{net.ParseIP(loopbackSAN)},
+
+ NotBefore: now.Add(-clockSlack),
+ NotAfter: now.AddDate(0, 0, days),
KeyUsage: x509.KeyUsageDigitalSignature |
x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go
new file mode 100644
index 00000000..79c9cd98
--- /dev/null
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go
@@ -0,0 +1,481 @@
+// ©AngelaMos | 2026
+// observe.go
+
+package pki
+
+import (
+ "context"
+ "crypto/rsa"
+ "crypto/x509"
+ "fmt"
+ "net/http"
+ "time"
+
+ "golang.org/x/crypto/ocsp"
+)
+
+const (
+ observeTimeout = 5 * time.Second
+
+ errWrongArmed = "%w: this authority has %q armed, not %q"
+ errNoChain = "%w: nothing is armed, so there is no chain to read back"
+ errNoControl = "%w: khaos could not mint an honest chain to compare against (%v)"
+ errAuthDown = "%w: khaos's own authority did not answer its health route (%v)"
+
+ observedExpired = "the served leaf expired %s ago, where an honest one from the same authority is valid until %s"
+ observedNotYet = "the served leaf is not valid for another %s"
+ observedInterOld = "the served leaf is in date and the intermediate above it expired %s ago"
+ observedWrongSAN = "the served leaf names %v, not %q"
+ observedNoSAN = "the served leaf carries no SAN extension at all, naming %q only in the legacy CommonName"
+ observedNoIPSAN = "the served leaf carries no IP SANs"
+ observedSelfSigned = "the served leaf is its own issuer"
+ observedForeignCA = "the served chain anchors on %q, which is not the root the target trusts"
+ observedNoInter = "the handshake carries %d intermediates where an honest one carries %d"
+ observedNotACA = "the leaf's issuer %q has basic constraints saying it is not a CA"
+ observedConstrained = "the leaf's issuer is constrained to %v and the leaf names %q"
+ observedDeep = "the handshake carries %d intermediates under a CA whose path length permits %d"
+ observedSHA1 = "the served leaf is signed with %v"
+ observedEKULeaf = "the served leaf permits %v, not server authentication"
+ observedEKUAbove = "the leaf's issuer permits %v, which does not include server authentication"
+ observedWeakKey = "the served leaf carries a %d-bit key where an honest one carries %d"
+ observedLifetime = "the served leaf is valid for %d days, where the cap is %d"
+ observedKeyUsage = "the served leaf's KeyUsage omits digitalSignature"
+ observedCASwap = "the root the target trusts is now %q, which khaos controls"
+
+ observedRevoked = "khaos's CRL lists the served leaf's serial %s as revoked"
+ observedStale = "khaos's %s closed its freshness window %s ago"
+ observedUnreached = "khaos's %s refuses connections while its health route still answers %d"
+ observedOCSPSays = "khaos's responder answers status %d for the served leaf"
+ observedOCSPOther = "khaos's responder answers about serial %s, not the served leaf's %s"
+ observedBadSigner = "khaos's responder signs with a certificate its CA never issued"
+ observedNoOCSP = "the served leaf names no OCSP responder, and still names a CRL at %s"
+ observedStapleBad = "the handshake staples %d bytes that are not an OCSP response"
+ observedNoStaple = "the handshake carries no stapled response, where an honest one carries %d bytes"
+)
+
+// Observe confirms khaos's own fault landed, by reading back what the authority
+// actually serves and comparing it against an HONEST chain from the same
+// authority.
+//
+// Every branch asserts two things, not one: that the served material carries
+// the defect AND that the control does not. An authority that was never armed
+// must not be able to confirm a trap, which is what the inert flag exists to
+// prove, and a one-sided assertion would let it.
+//
+// It reads the SERVED artefacts rather than the flag that was set. A flag
+// records which branch khaos chose; it says nothing about what a target would
+// receive, and an authority whose minting broke would happily confirm a fault
+// it is not producing.
+func (a *Authority) Observe(
+ ctx context.Context,
+ expected Kind,
+) (string, bool, error) {
+ armed := a.Trap()
+
+ if armed.Kind != expected {
+ return "", false, fmt.Errorf(
+ errWrongArmed,
+ ErrTrapNotObserved,
+ armed.Kind,
+ expected,
+ )
+ }
+
+ chain, err := a.Served()
+ if err != nil {
+ return "", false, fmt.Errorf(errNoChain, ErrTrapNotObserved)
+ }
+
+ honest, err := a.build(Trap{Kind: PassThrough, Host: a.host})
+ if err != nil {
+ return "", false, fmt.Errorf(errNoControl, ErrTrapNotObserved, err)
+ }
+
+ switch expected {
+ case LeafExpired, LeafNotYetValid, IntermediateExpired, WrongSAN,
+ CommonNameOnly, NoIPSAN:
+ return a.observeSubject(armed, chain, honest)
+
+ case SelfSigned, UntrustedCA, MissingIntermediate, IssuerNotCA,
+ NameConstraintViolation, PathLengthExceeded, SHA1Signature,
+ EKUClientAuthOnly, EKUConstrainedIntermediate:
+ return a.observeChainFault(armed, chain, honest)
+
+ case WeakKey, ExcessiveLifetime, KeyUsageWithoutDigitalSignature,
+ CASwap:
+ return a.observePolicy(armed, chain, honest)
+
+ case StapleGarbage, StapleAbsent, NoOCSPServer:
+ return a.observeStaple(armed, chain, honest)
+
+ case RevokedViaCRL, StaleCRL, CRLUnreachable, OCSPRevoked, OCSPUnknown,
+ OCSPTryLater, OCSPUnreachable, OCSPStale, OCSPWrongSerial,
+ OCSPWrongSigner:
+ return a.observeRevocation(ctx, armed, chain)
+
+ case PassThrough:
+ return "", false, nil
+
+ default:
+ return "", false, nil
+ }
+}
+
+// observeSubject confirms the faults in when the certificate is valid and who
+// it is for, all of which are visible in the served leaf itself.
+func (a *Authority) observeSubject(
+ trap Trap,
+ chain, honest *Chain,
+) (string, bool, error) {
+ now := a.clock()
+
+ switch trap.Kind {
+ case LeafExpired:
+ if chain.Leaf.NotAfter.Before(now) &&
+ honest.Leaf.NotAfter.After(now) {
+ return sprintf(
+ observedExpired,
+ now.Sub(chain.Leaf.NotAfter).Round(time.Second),
+ honest.Leaf.NotAfter.Format(time.RFC3339),
+ ), true, nil
+ }
+
+ case LeafNotYetValid:
+ if chain.Leaf.NotBefore.After(now) &&
+ !honest.Leaf.NotBefore.After(now) {
+ return sprintf(
+ observedNotYet,
+ chain.Leaf.NotBefore.Sub(now).Round(time.Second),
+ ), true, nil
+ }
+
+ case IntermediateExpired:
+ // The leaf has to be BLAMELESS, or this is just LeafExpired wearing a
+ // different name and monitoring that watches leaf expiry would catch it.
+ if chain.Issuer.NotAfter.Before(now) &&
+ chain.Leaf.NotAfter.After(now) {
+ return sprintf(
+ observedInterOld,
+ now.Sub(chain.Issuer.NotAfter).Round(time.Second),
+ ), true, nil
+ }
+
+ case WrongSAN:
+ if len(chain.Leaf.DNSNames) > 0 &&
+ !names(chain.Leaf).has(a.host) &&
+ names(honest.Leaf).has(a.host) {
+ return sprintf(
+ observedWrongSAN,
+ chain.Leaf.DNSNames,
+ a.host,
+ ), true, nil
+ }
+
+ case CommonNameOnly:
+ if len(chain.Leaf.DNSNames) == 0 &&
+ len(honest.Leaf.DNSNames) > 0 &&
+ chain.Leaf.Subject.CommonName == a.host {
+ return sprintf(observedNoSAN, a.host), true, nil
+ }
+
+ case NoIPSAN:
+ if len(chain.Leaf.IPAddresses) == 0 &&
+ len(chain.Leaf.DNSNames) > 0 {
+ return observedNoIPSAN, true, nil
+ }
+
+ default:
+ // Unreachable: Observe routes only the subject group here.
+ }
+
+ return "", false, nil
+}
+
+// observeChainFault confirms the faults in the path from leaf to trusted root.
+// Five of these produce byte-identical client errors in two groups, so what
+// khaos knows it SERVED is the only thing that can tell them apart, and that is
+// precisely what these branches record.
+func (a *Authority) observeChainFault(
+ trap Trap,
+ chain, honest *Chain,
+) (string, bool, error) {
+ switch trap.Kind {
+ case SelfSigned:
+ if chain.Issuer.Equal(chain.Leaf) && !honest.Issuer.Equal(honest.Leaf) {
+ return observedSelfSigned, true, nil
+ }
+
+ case UntrustedCA:
+ if !chain.Root.Equal(a.root.cert) {
+ return sprintf(
+ observedForeignCA,
+ chain.Root.Subject.CommonName,
+ ), true, nil
+ }
+
+ case MissingIntermediate:
+ if chain.Presented() < honest.Presented() {
+ return sprintf(
+ observedNoInter,
+ chain.Presented(),
+ honest.Presented(),
+ ), true, nil
+ }
+
+ case IssuerNotCA:
+ if chain.Issuer.BasicConstraintsValid && !chain.Issuer.IsCA {
+ return sprintf(
+ observedNotACA,
+ chain.Issuer.Subject.CommonName,
+ ), true, nil
+ }
+
+ case NameConstraintViolation:
+ if len(chain.Issuer.PermittedDNSDomains) > 0 &&
+ !permits(chain.Issuer, a.host) {
+ return sprintf(
+ observedConstrained,
+ chain.Issuer.PermittedDNSDomains,
+ a.host,
+ ), true, nil
+ }
+
+ case PathLengthExceeded:
+ if chain.Presented() > honest.Presented() {
+ return sprintf(
+ observedDeep,
+ chain.Presented(),
+ a.deepCapped.cert.MaxPathLen,
+ ), true, nil
+ }
+
+ case SHA1Signature, EKUClientAuthOnly, EKUConstrainedIntermediate:
+ return a.observeSigning(trap, chain, honest)
+
+ default:
+ // Unreachable: Observe routes only the chain group here.
+ }
+
+ return "", false, nil
+}
+
+// observeSigning confirms the three faults in HOW the certificate is signed or
+// what it may be used for. They sit apart from the path faults because none of
+// them breaks the chain: the path is intact and the signature or the usage is
+// what a correct client rejects.
+func (a *Authority) observeSigning(
+ trap Trap,
+ chain, honest *Chain,
+) (string, bool, error) {
+ switch trap.Kind {
+ case SHA1Signature:
+ if chain.Leaf.SignatureAlgorithm == x509.SHA1WithRSA &&
+ honest.Leaf.SignatureAlgorithm != x509.SHA1WithRSA {
+ return sprintf(
+ observedSHA1,
+ chain.Leaf.SignatureAlgorithm,
+ ), true, nil
+ }
+
+ case EKUClientAuthOnly:
+ if !serverAuth(chain.Leaf.ExtKeyUsage) &&
+ serverAuth(honest.Leaf.ExtKeyUsage) {
+ return sprintf(
+ observedEKULeaf,
+ chain.Leaf.ExtKeyUsage,
+ ), true, nil
+ }
+
+ case EKUConstrainedIntermediate:
+ // The LEAF is blameless, which is what separates this from the leaf
+ // level fault above. Both come back as Reason 4 and are otherwise
+ // indistinguishable to the target.
+ //
+ // The length check is load-bearing. An EMPTY ExtKeyUsage on a CA means
+ // UNCONSTRAINED, not "no server auth", so testing serverAuth alone
+ // confirmed this trap against khaos's own honest intermediate, which
+ // enumerates nothing. The inert control caught it.
+ if len(chain.Issuer.ExtKeyUsage) > 0 &&
+ !serverAuth(chain.Issuer.ExtKeyUsage) &&
+ serverAuth(chain.Leaf.ExtKeyUsage) {
+ return sprintf(
+ observedEKUAbove,
+ chain.Issuer.ExtKeyUsage,
+ ), true, nil
+ }
+
+ default:
+ // Unreachable: observeChainFault routes only the signing group here.
+ }
+
+ return "", false, nil
+}
+
+// observePolicy confirms the faults crypto/x509 ACCEPTS. There is no refusal to
+// read back, so the only evidence is the served material differing from the
+// control, which makes the control load-bearing rather than decorative here.
+func (a *Authority) observePolicy(
+ trap Trap,
+ chain, honest *Chain,
+) (string, bool, error) {
+ switch trap.Kind {
+ case WeakKey:
+ served, ok := modulus(chain.Leaf)
+ control, controlOK := modulus(honest.Leaf)
+
+ if ok && controlOK && served < control {
+ return sprintf(observedWeakKey, served, control), true, nil
+ }
+
+ case ExcessiveLifetime:
+ days := int(chain.Leaf.NotAfter.Sub(chain.Leaf.NotBefore).Hours() / 24)
+ if days > LifetimeCapDays {
+ return sprintf(observedLifetime, days, LifetimeCapDays), true, nil
+ }
+
+ case KeyUsageWithoutDigitalSignature:
+ if chain.Leaf.KeyUsage&x509.KeyUsageDigitalSignature == 0 &&
+ honest.Leaf.KeyUsage&x509.KeyUsageDigitalSignature != 0 {
+ return observedKeyUsage, true, nil
+ }
+
+ case CASwap:
+ // The confirmation is that the TRUSTED ROOT moved, not that the chain is
+ // odd. The chain is deliberately impeccable under the new anchor, which
+ // is the entire point: nothing in a client can detect this.
+ if a.TrustedRoot().Equal(a.rogueRoot.cert) {
+ return sprintf(
+ observedCASwap,
+ a.rogueRoot.cert.Subject.CommonName,
+ ), true, nil
+ }
+
+ default:
+ // Unreachable: Observe routes only the policy group here.
+ }
+
+ return "", false, nil
+}
+
+// observeStaple confirms the three faults that act on what the handshake
+// carries rather than on what a responder says.
+func (a *Authority) observeStaple(
+ trap Trap,
+ chain, honest *Chain,
+) (string, bool, error) {
+ switch trap.Kind {
+ case StapleGarbage:
+ if len(chain.Staple) == 0 {
+ return "", false, nil
+ }
+
+ // The parse FAILING is the confirmation: the staple is garbage, which is
+ // the fault. nilerr reads this as swallowing an error, and it is the
+ // opposite -- the error is the evidence.
+ if _, err := ocsp.ParseResponse(
+ chain.Staple,
+ chain.Issuer,
+ ); err != nil {
+ //nolint:nilerr // the parse failure IS the observable
+ return sprintf(observedStapleBad, len(chain.Staple)), true, nil
+ }
+
+ case StapleAbsent:
+ if len(chain.Staple) == 0 && len(honest.Staple) > 0 {
+ return sprintf(observedNoStaple, len(honest.Staple)), true, nil
+ }
+
+ case NoOCSPServer:
+ // The CRL pointer has to SURVIVE, or this is a total revocation outage
+ // rather than the end of OCSP that it models.
+ if len(chain.Leaf.OCSPServer) == 0 &&
+ len(chain.Leaf.CRLDistributionPoints) > 0 {
+ return sprintf(
+ observedNoOCSP,
+ chain.Leaf.CRLDistributionPoints[0],
+ ), true, nil
+ }
+
+ default:
+ // Unreachable: Observe routes only the stapling group here.
+ }
+
+ return "", false, nil
+}
+
+// names and permits are small readers over a certificate's identity, kept
+// separate so the branches above read as assertions rather than as parsing.
+type nameSet []string
+
+func names(cert *x509.Certificate) nameSet {
+ return cert.DNSNames
+}
+
+func (n nameSet) has(want string) bool {
+ for _, each := range n {
+ if each == want {
+ return true
+ }
+ }
+
+ return false
+}
+
+func permits(ca *x509.Certificate, host string) bool {
+ for _, domain := range ca.PermittedDNSDomains {
+ if domain == host {
+ return true
+ }
+ }
+
+ return false
+}
+
+func serverAuth(usages []x509.ExtKeyUsage) bool {
+ for _, usage := range usages {
+ if usage == x509.ExtKeyUsageServerAuth ||
+ usage == x509.ExtKeyUsageAny {
+ return true
+ }
+ }
+
+ return false
+}
+
+func modulus(cert *x509.Certificate) (int, bool) {
+ key, ok := cert.PublicKey.(*rsa.PublicKey)
+ if !ok {
+ return 0, false
+ }
+
+ return key.N.BitLen(), true
+}
+
+func sprintf(format string, args ...any) string {
+ return fmt.Sprintf(format, args...)
+}
+
+// health is the control for both unreachable traps. Its whole job is to still
+// answer while one endpoint refuses, because "khaos broke one endpoint" and
+// "khaos fell over" are different claims and only the first is a fault.
+func (a *Authority) health(ctx context.Context) (int, error) {
+ base, err := a.Addr()
+ if err != nil {
+ return 0, err
+ }
+
+ status, err := a.probe(ctx, schemeHTTP+base+RouteHealth)
+ if err != nil {
+ return 0, fmt.Errorf(errAuthDown, ErrTrapNotObserved, err)
+ }
+
+ if status != http.StatusOK {
+ return status, fmt.Errorf(
+ errAuthDown,
+ ErrTrapNotObserved,
+ status,
+ )
+ }
+
+ return status, nil
+}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_revocation.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_revocation.go
new file mode 100644
index 00000000..7d774c09
--- /dev/null
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_revocation.go
@@ -0,0 +1,306 @@
+// ©AngelaMos | 2026
+// observe_revocation.go
+
+package pki
+
+import (
+ "context"
+ "crypto/x509"
+ "errors"
+ "io"
+ "net/http"
+ "time"
+
+ "golang.org/x/crypto/ocsp"
+)
+
+const maxReadBack = 1 << 20
+
+// observeRevocation confirms the faults that act on revocation rather than on
+// the certificate.
+//
+// Every one of these serves a chain crypto/x509 accepts, so there is no refusal
+// anywhere to read back and nothing in the certificate differs from the
+// control. The ONLY evidence is what khaos's own endpoints answer, which is why
+// this reads them over HTTP exactly as a target would rather than inspecting
+// the state that produced them.
+func (a *Authority) observeRevocation(
+ ctx context.Context,
+ trap Trap,
+ chain *Chain,
+) (string, bool, error) {
+ base, err := a.Addr()
+ if err != nil {
+ return "", false, err
+ }
+
+ root := schemeHTTP + base
+
+ switch trap.Kind {
+ case CRLUnreachable, OCSPUnreachable:
+ return a.observeUnreachable(ctx, trap, root)
+
+ case RevokedViaCRL, StaleCRL:
+ return a.observeCRL(ctx, trap, chain, root)
+
+ default:
+ return a.observeResponder(ctx, trap, chain, root)
+ }
+}
+
+// observeUnreachable confirms that ONE endpoint refuses while the health route
+// still answers. Both halves are required: an authority that fell over would
+// satisfy the first on its own, and khaos would be reporting its own crash as a
+// fault it injected.
+func (a *Authority) observeUnreachable(
+ ctx context.Context,
+ trap Trap,
+ root string,
+) (string, bool, error) {
+ route := RouteCRL
+ if trap.Kind == OCSPUnreachable {
+ route = RouteOCSP
+ }
+
+ if _, err := a.probe(ctx, root+route); err == nil {
+ return "", false, nil
+ }
+
+ status, err := a.health(ctx)
+ if err != nil {
+ return "", false, err
+ }
+
+ return sprintf(observedUnreached, route, status), true, nil
+}
+
+// observeCRL reads the list khaos serves. The two CRL faults are distinguished
+// HERE and not by what they were asked to do: one lists the serial in a fresh
+// list, the other omits it from a stale one, and a mix-up either way makes one
+// of them inert.
+func (a *Authority) observeCRL(
+ ctx context.Context,
+ trap Trap,
+ chain *Chain,
+ root string,
+) (string, bool, error) {
+ // Every failure below returns NOT CONFIRMED rather than an error, and that
+ // is the same discipline the identity provider's oracle uses: khaos being
+ // unable to read its own fault back is a refusal to confirm, which makes
+ // the engine abort the run. Returning the read error instead would make
+ // khaos fail with a plumbing complaint when the honest answer is "khaos
+ // could not see this fault land".
+ der, err := a.read(ctx, root+RouteCRL)
+ if err != nil {
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
+ }
+
+ list, err := x509.ParseRevocationList(der)
+ if err != nil {
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
+ }
+
+ if err := list.CheckSignatureFrom(chain.Issuer); err != nil {
+ // A list a correct client would discard proves nothing about the
+ // target: it would refuse for khaos's defect rather than the fault's.
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
+ }
+
+ now := a.clock()
+ listed := revoked(list, chain.Leaf)
+
+ if trap.Kind == RevokedViaCRL {
+ if listed && list.NextUpdate.After(now) {
+ return sprintf(
+ observedRevoked,
+ chain.Leaf.SerialNumber,
+ ), true, nil
+ }
+
+ return "", false, nil
+ }
+
+ // StaleCRL. The serial must be ABSENT, or a client that ignores freshness
+ // still finds it and refuses, and the fault catches nothing.
+ if !listed && list.NextUpdate.Before(now) {
+ return sprintf(
+ observedStale,
+ "CRL",
+ now.Sub(list.NextUpdate).Round(time.Second),
+ ), true, nil
+ }
+
+ return "", false, nil
+}
+
+// observeResponder reads what the OCSP endpoint answers. Each branch asserts
+// the ONE property its fault corrupts, so a responder that was wrong in some
+// other way cannot confirm a trap it is not producing.
+func (a *Authority) observeResponder(
+ ctx context.Context,
+ trap Trap,
+ chain *Chain,
+ root string,
+) (string, bool, error) {
+ der, err := a.read(ctx, root+RouteOCSP)
+ if err != nil {
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
+ }
+
+ if trap.Kind == OCSPTryLater {
+ // TryLater is a RESPONSE status, so it must NOT parse as an answer. A
+ // successful parse here would mean khaos served a real verdict and the
+ // soft-fail trap never gets its chance.
+ var unusable ocsp.ResponseError
+ if _, parseErr := ocsp.ParseResponse(
+ der,
+ chain.Issuer,
+ ); errors.As(parseErr, &unusable) &&
+ unusable.Status == ocsp.TryLater {
+ return sprintf(observedOCSPSays, int(ocsp.TryLater)), true, nil
+ }
+
+ return "", false, nil
+ }
+
+ if trap.Kind == OCSPWrongSigner {
+ // Rejected when bound to the certificate is the whole fault. Parsing it
+ // successfully would mean the CA did issue the signer after all.
+ if _, bindErr := ocsp.ParseResponseForCert(
+ der,
+ chain.Leaf,
+ chain.Issuer,
+ ); bindErr != nil {
+ // The binding FAILING is the confirmation, not an error being
+ // swallowed: the CA never issued this signer, which is the fault.
+ //nolint:nilerr // the rejection IS the observable
+ return observedBadSigner, true, nil
+ }
+
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
+ }
+
+ // The remaining three answer about SOMETHING, so they have to parse. The
+ // loose call is used deliberately: ParseResponseForCert refuses the
+ // wrong-serial response, which is the fault khaos is trying to read back.
+ response, err := ocsp.ParseResponse(der, chain.Issuer)
+ if err != nil {
+ return "", false, nil //nolint:nilerr // not confirmed, not an error
+ }
+
+ return a.judgeResponse(trap, chain, response)
+}
+
+func (a *Authority) judgeResponse(
+ trap Trap,
+ chain *Chain,
+ response *ocsp.Response,
+) (string, bool, error) {
+ now := a.clock()
+
+ switch trap.Kind {
+ case OCSPRevoked:
+ if response.Status == ocsp.Revoked {
+ return sprintf(observedOCSPSays, response.Status), true, nil
+ }
+
+ case OCSPUnknown:
+ if response.Status == ocsp.Unknown {
+ return sprintf(observedOCSPSays, response.Status), true, nil
+ }
+
+ case OCSPStale:
+ // Good AND stale. A stale Revoked would be refused for its status, so a
+ // client refusing it would prove nothing about freshness.
+ if response.Status == ocsp.Good &&
+ response.NextUpdate.Before(now) {
+ return sprintf(
+ observedStale,
+ "OCSP response",
+ now.Sub(response.NextUpdate).Round(time.Second),
+ ), true, nil
+ }
+
+ case OCSPWrongSerial:
+ // Good, and about a DIFFERENT certificate. Both halves: a Revoked for
+ // the wrong serial would be refused on status by a client that never
+ // checks the binding.
+ if response.Status == ocsp.Good &&
+ response.SerialNumber.Cmp(chain.Leaf.SerialNumber) != 0 {
+ return sprintf(
+ observedOCSPOther,
+ response.SerialNumber,
+ chain.Leaf.SerialNumber,
+ ), true, nil
+ }
+
+ default:
+ // Unreachable: observeResponder handles the other kinds itself.
+ }
+
+ return "", false, nil
+}
+
+// probe and read are khaos's OWN requests, marked so the counters can subtract
+// them. Without the header, "the target consulted revocation" would be true for
+// every run in which khaos confirmed its own fault, and the UNSUPPORTED verdict
+// would never fire.
+func (a *Authority) probe(ctx context.Context, url string) (int, error) {
+ response, err := a.send(ctx, url)
+ if err != nil {
+ return 0, err
+ }
+
+ defer func() { _ = response.Body.Close() }()
+
+ _, _ = io.Copy(io.Discard, response.Body)
+
+ return response.StatusCode, nil
+}
+
+func (a *Authority) read(ctx context.Context, url string) ([]byte, error) {
+ response, err := a.send(ctx, url)
+ if err != nil {
+ return nil, err
+ }
+
+ defer func() { _ = response.Body.Close() }()
+
+ if response.StatusCode != http.StatusOK {
+ return nil, errors.New("khaos's own endpoint answered " +
+ response.Status)
+ }
+
+ return io.ReadAll(io.LimitReader(response.Body, maxReadBack))
+}
+
+func (a *Authority) send(
+ ctx context.Context,
+ url string,
+) (*http.Response, error) {
+ request, err := http.NewRequestWithContext(
+ ctx,
+ http.MethodGet,
+ url,
+ nil,
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ request.Header.Set(headerProbe, probeValue)
+
+ client := &http.Client{Timeout: observeTimeout}
+
+ return client.Do(request)
+}
+
+func revoked(list *x509.RevocationList, leaf *x509.Certificate) bool {
+ for _, entry := range list.RevokedCertificateEntries {
+ if entry.SerialNumber.Cmp(leaf.SerialNumber) == 0 {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_test.go
new file mode 100644
index 00000000..42e0129a
--- /dev/null
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe_test.go
@@ -0,0 +1,124 @@
+// ©AngelaMos | 2026
+// observe_test.go
+
+package pki
+
+import (
+ "context"
+ "testing"
+)
+
+// The census, and the oracle's own negative control.
+//
+// Every trap khaos advertises has to be confirmable by its own observable. A
+// trap that cannot be confirmed is a fault khaos would apply and then measure
+// without knowing it landed, which is the one thing the engine refuses to do.
+//
+// And every trap has to be UNCONFIRMABLE when the authority was never actually
+// armed. Without that half, an Observe gutted to `return true` passes the whole
+// file, and the identity family learned that the expensive way: gutting its
+// oracle left all seventeen packages and the Docker gate green.
+
+func everyKindTrap(kind Kind, host string) Trap {
+ return Trap{
+ Kind: kind,
+ Host: host,
+ Window: DefaultWindow,
+ Bits: DefaultWeakBits,
+ Days: DefaultExcessiveDays,
+ }
+}
+
+func TestEveryTrapIsConfirmedByItsOwnObservable(t *testing.T) {
+ for _, name := range Kinds() {
+ kind := Kind(name)
+
+ t.Run(name, func(t *testing.T) {
+ a := listening(t)
+
+ if err := a.Arm(everyKindTrap(kind, a.Host())); err != nil {
+ t.Fatalf("arm %s: %v", kind, err)
+ }
+
+ observable, confirmed, err := a.Observe(
+ context.Background(),
+ kind,
+ )
+ if err != nil {
+ t.Fatalf("observe %s: %v", kind, err)
+ }
+
+ if !confirmed {
+ t.Fatalf(
+ "%s could not be confirmed, so khaos would apply this fault and then measure a target without knowing the fault landed",
+ kind,
+ )
+ }
+
+ if observable == "" {
+ t.Fatalf(
+ "%s confirmed with no observable, so the run would claim a fault landed without saying what khaos saw",
+ kind,
+ )
+ }
+ })
+ }
+}
+
+// The negative control. The authority records the trap and builds nothing, so
+// the oracle runs its real observable against HONEST material and has to say
+// no.
+func TestNoTrapIsConfirmedByAnInertAuthority(t *testing.T) {
+ for _, name := range Kinds() {
+ kind := Kind(name)
+
+ t.Run(name, func(t *testing.T) {
+ a := listening(t)
+
+ a.Inert(true)
+
+ if err := a.Arm(everyKindTrap(kind, a.Host())); err != nil {
+ t.Fatalf("arm %s while inert: %v", kind, err)
+ }
+
+ _, confirmed, err := a.Observe(context.Background(), kind)
+ if err != nil {
+ // An error is a refusal to confirm, which is the right
+ // direction, but it means the branch under test was never
+ // reached and this control is weaker than it looks.
+ t.Fatalf(
+ "%s errored instead of declining (%v); the oracle short-circuited and its observable was never exercised",
+ kind,
+ err,
+ )
+ }
+
+ if confirmed {
+ t.Fatalf(
+ "%s was confirmed against an authority that armed nothing, so this oracle cannot tell a landed fault from no fault at all",
+ kind,
+ )
+ }
+ })
+ }
+}
+
+// Observe must refuse to confirm a DIFFERENT trap than the one armed. Without
+// this, an experiment whose build and whose mutator disagreed would confirm the
+// wrong fault and report a finding about something khaos never did.
+func TestObserveRefusesATrapItDidNotArm(t *testing.T) {
+ a := listening(t)
+
+ if err := a.Arm(everyKindTrap(LeafExpired, a.Host())); err != nil {
+ t.Fatalf("arm: %v", err)
+ }
+
+ if _, _, err := a.Observe(
+ context.Background(),
+ RevokedViaCRL,
+ ); err == nil {
+ t.Fatal(
+ "observing revoked-via-crl against an authority with leaf-expired armed returned no error",
+ )
+ }
+}
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go
index 06a4b53c..b57ad3af 100644
--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go
+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go
@@ -7,8 +7,6 @@ import (
"io"
"net/http"
"time"
-
- "golang.org/x/crypto/ocsp"
)
const (
@@ -59,17 +57,17 @@ func (a *Authority) serveHealth(w http.ResponseWriter, _ *http.Request) {
_, _ = io.WriteString(w, healthBody)
}
+// serveCRL and serveOCSP serve what the ARMED CHAIN carries, and dispatch on
+// nothing.
+//
+// Neither reads the trap. Everything either of them does was decided when the
+// chain was built, which is what keeps an authority that armed nothing serving
+// honest material: deriving the answer from the trap record here meant an inert
+// authority still published a revoked list, and thirteen traps confirmed
+// against a fault that had not happened.
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)
@@ -77,9 +75,9 @@ func (a *Authority) serveCRL(w http.ResponseWriter, r *http.Request) {
return
}
- der, err := a.CRLFor(trap, chain, a.clock())
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
+ der, reachable := chain.CRL()
+ if !reachable {
+ refuse(w)
return
}
@@ -92,29 +90,6 @@ func (a *Authority) serveCRL(w http.ResponseWriter, r *http.Request) {
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)
@@ -122,9 +97,9 @@ func (a *Authority) serveOCSP(w http.ResponseWriter, r *http.Request) {
return
}
- der, err := a.ocspFor(trap, chain, a.clock())
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
+ der, reachable := chain.OCSP()
+ if !reachable {
+ refuse(w)
return
}