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): the tls. family, 32 experiments and a fourth injection tier
CarterPerez-dev3a80ec879013
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.goindex 2d4d4d77..1b422b1c 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment.go@@ -109,8 +109,11 @@ enforcing in the first place.`errIdPBind = "khaos could not bind its identity provider on %s, which is where the range's verifier gateway is already looking for it: %w. Something else took that port since the range came up; bring the range down and up again to pick a new one"errIssuerPort = "%w: khaos's identity provider must bind the port its issuer names, and %q does not name a usable one (%v); pass --issuer as a URL with an explicit port, such as http://host.docker.internal:45000"msgIdPUp = "khaos's identity provider is listening on %s, issuing as %s"- errProxyBind = "khaos could not bind its fault proxy on %s, which is where the range's proxied gateway is already looking for it: %w. Something else took that port since the range came up; bring the range down and up again to pick a new one"- msgProxyUp = "khaos's fault proxy is listening on %s, forwarding to %s"++ errAuthorityBind = "khaos could not bind its certificate authority on %s, which is where the range's TLS gateway is already looking for it: %w. Something else took that port since the range came up; bring the range down and up again to pick a new one"+ msgAuthorityUp = "khaos's certificate authority is serving the dependency on %s and revocation on %s, minting for %s"+ errProxyBind = "khaos could not bind its fault proxy on %s, which is where the range's proxied gateway is already looking for it: %w. Something else took that port since the range came up; bring the range down and up again to pick a new one"+ msgProxyUp = "khaos's fault proxy is listening on %s, forwarding to %s"groupExperiments = "experiments"titleExperiments = "Experiments:"@@ -512,39 +515,12 @@ func runExperiment(return err}- // The proxy has to be up before the BASELINE, not before the fault. The- // baseline is measured through it, so a proxy that arrives at injection time- // would make the two phases travel different paths and the difference between- // them would be the proxy rather than the fault.- env := work.Env()-- if spec.ProxyFault != nil {- fault, err := startProxy(ctx, out, work.Docker, spec)- if err != nil {- return err- }- defer func() { _ = fault.Close() }()-- env.Proxy = fault- env.ProxyFault = *spec.ProxyFault+ env, closeTiers, err := standUpTiers(ctx, out, work, spec)+ if err != nil {+ return err}- // The provider has to be listening before the BASELINE for the same reason- // the proxy does: the baseline is measured through it, so a provider that- // arrived at injection time would make the two phases see different- // topologies and the difference between them would be khaos rather than the- // fault. The experiment already BUILT it, because its probes mint out of it- // and minting needs no listener; all that is left is to bind it where the- // target is already looking.- if spec.IdPTrap != nil {- if err := startProvider(ctx, out, work.Docker, spec); err != nil {- return err- }- defer func() { _ = spec.IdP.Close() }()-- env.IdP = spec.IdP- env.IdPTrap = *spec.IdPTrap- }+ defer closeTiers()session := run.NewSession(env, work.Journal, ttl)@@ -807,6 +783,10 @@ func rangeSupplies() []string {experiment.ParamIssuer,experiment.ParamProxyListen,experiment.ParamProxyUpstream,+ experiment.ParamAuthorityListen,+ experiment.ParamAuthorityTLS,+ experiment.ParamAuthorityBase,+ experiment.ParamCertHost,}}@@ -822,6 +802,7 @@ const (tierDirect tier = iotatierProxytierIdP+ tierTLS)func tierOf(kind string) tier {@@ -830,6 +811,8 @@ func tierOf(kind string) tier {return tierProxycase inject.NeedsIdP(kind):return tierIdP+ case inject.NeedsPKI(kind):+ return tierTLSdefault:return tierDirect}@@ -856,6 +839,23 @@ type rangeAnswers struct {// `range up` chose, for the reason recorded on proxyPortOf.ProxyListen stringProxyUpstream string++ // Where khaos binds its certificate authority's two listeners, and the URL+ // the TLS gateway reaches the revocation endpoints by.+ //+ // AuthorityBase is NOT derived from AuthorityListen. khaos binds the bridge+ // gateway's numeric address and the container addresses+ // `host.docker.internal`, so the two are different strings for the same+ // endpoint and conflating them is the identity provider's most expensive+ // bug.+ AuthorityListen string+ AuthorityTLS string+ AuthorityBase string++ // CertHost is the name the TLS gateway asks for, read back from its own+ // configuration for the same reason the issuer is: khaos has to mint for+ // the name the target expects, character for character.+ CertHost string}func rangeDefaults(@@ -880,6 +880,15 @@ func rangeDefaults(url = lab.VerifierProtectedURL()target = rangelab.VerifierGatewayName+ case tierTLS:+ // The TLS gateway, for the same reason the identity tier names the+ // verifier gateway: the fault is applied to khaos's own authority and+ // the gateway is both the subject and the thing khaos needs consent+ // for. Naming the dependency would ask consent for a container this+ // experiment never touches.+ url = lab.TLSProtectedURL()+ target = rangelab.TLSGatewayName+default:// The direct tier probes the protected URL and names the provider// container, both of which are already set above.@@ -895,6 +904,11 @@ func rangeDefaults(experiment.ParamProxyListen: answers.ProxyListen,experiment.ParamProxyUpstream: answers.ProxyUpstream,++ experiment.ParamAuthorityListen: answers.AuthorityListen,+ experiment.ParamAuthorityTLS: answers.AuthorityTLS,+ experiment.ParamAuthorityBase: answers.AuthorityBase,+ experiment.ParamCertHost: answers.CertHost,}}@@ -1115,6 +1129,119 @@ func startProvider(return nil}+// standUpTiers starts whichever of khaos's own in-process tiers this experiment+// needs, and returns a closer for all of them.+//+// Every one of them has to be answering before the BASELINE, not before the+// fault, and that is the same reason three times over: the baseline is measured+// through them, so a proxy, a provider or an authority that arrived at+// injection time would make the two phases travel different paths and the+// difference between them would be KHAOS rather than the fault.+//+// The closer is returned rather than deferred here, because deferring inside+// this function would tear the tiers down before the run that measures through+// them has started.+func standUpTiers(+ ctx context.Context,+ out io.Writer,+ work *workspace.Workspace,+ spec experiment.Experiment,+) (inject.Env, func(), error) {+ env := work.Env()++ var closers []func()++ closeAll := func() {+ for _, close := range closers {+ close()+ }+ }++ if spec.ProxyFault != nil {+ fault, err := startProxy(ctx, out, work.Docker, spec)+ if err != nil {+ return env, closeAll, err+ }++ closers = append(closers, func() { _ = fault.Close() })++ env.Proxy = fault+ env.ProxyFault = *spec.ProxyFault+ }++ // The experiment already BUILT the provider, because its probes mint out of+ // it and minting needs no listener. All that is left is to bind it where the+ // target is already looking.+ if spec.IdPTrap != nil {+ if err := startProvider(ctx, out, work.Docker, spec); err != nil {+ return env, closeAll, err+ }++ closers = append(closers, func() { _ = spec.IdP.Close() })++ env.IdP = spec.IdP+ env.IdPTrap = *spec.IdPTrap+ }++ // The authority plays the dependency the target dials, so without it the+ // baseline measures a dependency that is simply absent.+ if spec.PKITrap != nil {+ if err := startAuthority(out, spec); err != nil {+ return env, closeAll, err+ }++ closers = append(closers, func() { _ = spec.Authority.Close() })++ env.Authority = spec.Authority+ env.PKITrap = *spec.PKITrap+ }++ return env, closeAll, nil+}++// startAuthority stands khaos's certificate authority up on BOTH of its+// listeners, before the baseline.+//+// Before the baseline and not before the fault, for the same reason the proxy+// and the provider are: the baseline is measured through this authority, so one+// that arrived at injection time would make the two phases see different+// topologies and the difference between them would be khaos rather than the+// fault.+//+// Both addresses come from the experiment's parameters, which the range answers+// and an operator can override. Nothing here is discovered, because the TLS+// gateway is already dialling a specific address and khaos does not get to pick+// a different one.+func startAuthority(+ out io.Writer,+ spec experiment.Experiment,+) error {+ if err := spec.Authority.Listen(spec.AuthorityListen); err != nil {+ return fmt.Errorf(errAuthorityBind, spec.AuthorityListen, err)+ }++ if err := spec.Authority.ListenTLS(spec.AuthorityTLS); err != nil {+ return fmt.Errorf(errAuthorityBind, spec.AuthorityTLS, err)+ }++ // An HONEST chain, minted before anything is probed. Without it the+ // authority has nothing armed, the baseline handshake falls back to a chain+ // built per connection, and the leaf's serial changes under the target+ // while khaos is trying to revoke it.+ if err := spec.Authority.Disarm(); err != nil {+ return err+ }++ note(out, fmt.Sprintf(+ msgAuthorityUp,+ spec.AuthorityTLS,+ spec.AuthorityListen,+ spec.Authority.Host(),+ ))++ return nil+}+// portOf reads the port an issuer names. It is the one thing khaos needs from// the issuer beyond minting under it, and a missing or unusable port is a// refusal by name rather than a bind to something arbitrary.@@ -1187,5 +1314,23 @@ func askTheRange(answers.Authority = authority}+ // All four together, because a certificate experiment needs every one of+ // them and asking for them separately would let a run start with khaos+ // bound where the gateway is not looking.+ if want(experiment.ParamAuthorityListen) ||+ want(experiment.ParamAuthorityTLS) ||+ want(experiment.ParamAuthorityBase) ||+ want(experiment.ParamCertHost) {+ wiring, err := lab.AuthorityEndpoint(ctx, reader)+ if err != nil {+ return rangeAnswers{}, err+ }++ answers.AuthorityListen = wiring.Listen+ answers.AuthorityTLS = wiring.TLS+ answers.AuthorityBase = wiring.Base+ answers.CertHost = wiring.Host+ }+return answers, nil}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.goindex 3a971d28..98293f36 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/cli/experiment_test.go@@ -29,6 +29,14 @@ var testAnswers = rangeAnswers{Authority: "http://127.0.0.1:30009",ProxyListen: "10.0.0.1:30003",ProxyUpstream: "172.20.0.5:8080",++ // The base URL is NOT the listen address, deliberately. khaos binds a+ // bridge address and the container addresses host.docker.internal, so a+ // fixture that made them equal would agree with a bug.+ AuthorityListen: "10.0.0.1:30006",+ AuthorityTLS: "10.0.0.1:30007",+ AuthorityBase: "http://host.docker.internal:30006",+ CertHost: "dependency.khaos.invalid",}// refuser fails the test if khaos goes looking for a range it was never meant to@@ -133,7 +141,7 @@ func TestRangeSuppliesIsExactlyTheKeySetOfRangeDefaults(t *testing.T) {// allTiers is every tier the range serves. A test that iterated only the two it// knew about would go on passing while a whole gateway's answers drifted.func allTiers() []tier {- return []tier{tierDirect, tierProxy, tierIdP}+ return []tier{tierDirect, tierProxy, tierIdP, tierTLS}}func tierName(at tier) string {@@ -142,6 +150,8 @@ func tierName(at tier) string {return "through the proxy"case tierIdP:return "against khaos's own provider"+ case tierTLS:+ return "against khaos's own certificate authority"default:return "direct"}@@ -157,6 +167,11 @@ func fullLab() rangelab.Lab {VerifierPort: 30004,IdPPort: 30005,Issuer: "http://host.docker.internal:30005",++ TLSPort: 30008,+ Dependency: "https://host.docker.internal:30007",+ AuthorityBase: "http://host.docker.internal:30006",+ CertHost: "dependency.khaos.invalid",}}@@ -692,13 +707,14 @@ func TestTheRangeCanSatisfyEveryExperimentsRequiredParameters(t *testing.T) {}}-// The range carries THREE gateways and they are not interchangeable. Each one+// The range carries FOUR gateways and they are not interchangeable. Each one// exists so one injection tier is measured on a path nothing else contaminates:// a proxy-tier experiment arms a fault on the path only the proxied gateway-// uses, and an identity-tier one arms a provider only the verifier gateway-// resolves keys from. Pointing either at the wrong gateway measures a service-// with no causal connection to the fault and reports a clean survival over an-// armed fault.+// uses, an identity-tier one arms a provider only the verifier gateway resolves+// keys from, and a certificate-tier one arms an authority only the TLS gateway+// dials. Pointing any of them at the wrong gateway measures a service with no+// causal connection to the fault and reports a clean survival over an armed+// fault.func TestEveryExperimentIsPointedAtTheGatewayItsFaultActuallyAffects(t *testing.T,) {@@ -708,6 +724,7 @@ func TestEveryExperimentIsPointedAtTheGatewayItsFaultActuallyAffects(tierDirect: lab.ProtectedURL(),tierProxy: lab.ProxiedProtectedURL(),tierIdP: lab.VerifierProtectedURL(),+ tierTLS: lab.TLSProtectedURL(),}seen := map[string]tier{}@@ -736,12 +753,21 @@ func TestEveryExperimentIsPointedAtTheGatewayItsFaultActuallyAffects(definition.Name, definition.FaultKind, answered, want[at])}- // The identity tier's target is the gateway rather than the+ // The two in-process tiers name their GATEWAY rather than the// dependency, because that is the container khaos needs consent for- // and the one it actually measures.+ // and the one it actually measures. The fault lands on khaos's own+ // provider or authority, which is not a container at all, so naming+ // the dependency would ask consent for something this experiment+ // never touches and leave the measured service unchecked.wantTarget := rangelab.IDPName- if at == tierIdP {++ switch at {+ case tierIdP:wantTarget = rangelab.VerifierGatewayName+ case tierTLS:+ wantTarget = rangelab.TLSGatewayName+ default:+ // The direct and proxy tiers fault the dependency itself.}if answered := defaults[experiment.ParamTarget]; answered != wantTarget {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.goindex aa96773c..4c982f52 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/catalog.go@@ -14,6 +14,7 @@ import ("github.com/CarterPerez-dev/khaos/internal/idp""github.com/CarterPerez-dev/khaos/internal/inject""github.com/CarterPerez-dev/khaos/internal/inject/proxy"+ "github.com/CarterPerez-dev/khaos/internal/pki""github.com/CarterPerez-dev/khaos/internal/probe")@@ -69,6 +70,21 @@ type Shape struct {IdP *idp.ProviderIdPTrap *idp.Trap+ // Authority and PKITrap are set only by an experiment that arms khaos's own+ // certificate authority, which plays the dependency whose certificate is+ // under test.+ Authority *pki.Authority+ PKITrap *pki.Trap++ // AuthorityBase is the URL the TARGET uses to reach the authority's CRL and+ // OCSP endpoints, and AuthorityListen is where khaos binds them. They are+ // separate because the target addresses khaos by a name khaos cannot see+ // from its own listener, and deriving one from the other is the identity+ // provider's most expensive bug.+ AuthorityBase string+ AuthorityListen string+ AuthorityTLS string+// Defect names what khaos did to the credential, for the verdict's wording.Defect string@@ -251,15 +267,21 @@ func Build(ProxyUpstream: shape.ProxyUpstream,IdP: shape.IdP,IdPTrap: shape.IdPTrap,- Defect: shape.Defect,- HeldCaveat: shape.HeldCaveat,- Consulted: shape.Consulted,- ConsultedWhat: shape.ConsultedWhat,- Unsupportable: shape.Unsupportable,- IdleFor: shape.IdleFor,- Act: shape.Act,- ActDetail: shape.ActDetail,- Timing: timing,++ Authority: shape.Authority,+ PKITrap: shape.PKITrap,+ AuthorityBase: shape.AuthorityBase,+ AuthorityListen: shape.AuthorityListen,+ AuthorityTLS: shape.AuthorityTLS,+ Defect: shape.Defect,+ HeldCaveat: shape.HeldCaveat,+ Consulted: shape.Consulted,+ ConsultedWhat: shape.ConsultedWhat,+ Unsupportable: shape.Unsupportable,+ IdleFor: shape.IdleFor,+ Act: shape.Act,+ ActDetail: shape.ActDetail,+ Timing: timing,}if shape.Condition != "" {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.goindex 1b6d29fa..7e09fddb 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go@@ -12,6 +12,7 @@ import ("github.com/CarterPerez-dev/khaos/internal/idp""github.com/CarterPerez-dev/khaos/internal/inject/proxy"+ "github.com/CarterPerez-dev/khaos/internal/pki""github.com/CarterPerez-dev/khaos/internal/probe")@@ -133,6 +134,16 @@ type Experiment struct {IdP *idp.ProviderIdPTrap *idp.Trap+ // Authority and PKITrap are non-nil only for an experiment that arms+ // khaos's own certificate authority. AuthorityBase is the URL the TARGET+ // reaches its revocation endpoints by, which is pinned rather than derived+ // from wherever khaos binds.+ Authority *pki.Authority+ PKITrap *pki.Trap+ AuthorityBase string+ AuthorityListen string+ AuthorityTLS string+// Defect names what khaos did to the credential the finding is about, in// words, so the verdict can state the actual observation rather than a// constant that is only true of one experiment.diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tls.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tls.gonew file mode 100644index 00000000..4bebbc13--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tls.go@@ -0,0 +1,373 @@+// ©AngelaMos | 2026+// tls.go++package experiment++import "github.com/CarterPerez-dev/khaos/internal/pki"++// FamilyTLS is the family name every certificate experiment carries, which+// `khaos catalog` groups by.+const FamilyTLS = "tls"++// The `tls.` family. One experiment per certificate trap, named for what khaos+// does rather than for what it hopes to find.+//+// The summaries say what the fault CATCHES, because that is the only thing that+// makes an entry in `khaos catalog` worth reading. Several of them catch the+// same client-side error and are told apart only by what khaos knows it served:+// self-signed, untrusted-CA and missing-intermediate all produce+// `x509: certificate signed by unknown authority`, and the two extended+// key-usage faults both produce Reason 4, measured on go1.26.5.+const (+ NameLeafExpired = "tls.leaf_expired"+ NameLeafNotYetValid = "tls.leaf_not_yet_valid"+ NameIntermediateExpired = "tls.intermediate_expired"++ NameWrongSAN = "tls.wrong_san"+ NameCommonNameOnly = "tls.common_name_only"+ NameNoIPSAN = "tls.no_ip_san"++ NameSelfSigned = "tls.self_signed"+ NameUntrustedCA = "tls.untrusted_ca"+ NameMissingIntermediate = "tls.missing_intermediate"+ NameIssuerNotCA = "tls.issuer_not_ca"+ NameNameConstraint = "tls.name_constraint_violation"+ NamePathLength = "tls.path_length_exceeded"++ NameSHA1Signature = "tls.sha1_signature"+ NameEKUClientOnly = "tls.eku_client_auth_only"+ NameEKUConstrained = "tls.eku_constrained_intermediate"++ NameWeakKey = "tls.weak_key"+ NameExcessiveLifetime = "tls.excessive_lifetime"+ NameNoDigitalSig = "tls.key_usage_no_digital_signature"++ NameRevokedViaCRL = "tls.revoked_via_crl"+ NameStaleCRL = "tls.stale_crl"+ NameCRLUnreachable = "tls.crl_unreachable"++ NameOCSPRevoked = "tls.ocsp_revoked"+ NameOCSPUnknown = "tls.ocsp_unknown"+ NameOCSPTryLater = "tls.ocsp_try_later"+ NameOCSPUnreachable = "tls.ocsp_unreachable"+ NameOCSPStale = "tls.ocsp_stale"+ NameOCSPWrongSerial = "tls.ocsp_wrong_serial"+ NameOCSPWrongSigner = "tls.ocsp_wrong_signer"+ NameNoOCSPServer = "tls.no_ocsp_server"++ NameStapleGarbage = "tls.staple_garbage"+ NameStapleAbsent = "tls.staple_absent"++ NameCASwap = "tls.ca_swap"+)++const (+ sumLeafExpired = "serve an expired certificate, which finds a client that ignores expiry, a proxy serving a stale certificate from cache, and an application that catches the error and retries over plain HTTP"+ sumLeafNotYetValid = "serve a certificate that is not valid yet, which finds a clock-skew tolerance set wide enough to accept anything"+ sumInterExpired = "serve a valid leaf under an expired intermediate, which finds monitoring that watches leaf expiry only"++ sumWrongSAN = "serve a certificate for a different host, which finds a client that kept its chain check and dropped its hostname check"+ sumCommonNameOnly = "serve a certificate naming the host only in the legacy CommonName, which finds a client that reimplemented hostname matching or re-enabled the fallback Go removed"+ sumNoIPSAN = "serve a certificate with no IP SANs to a client dialling by address, which finds a service reached by pod IP with verification disabled because it is internal"++ sumSelfSigned = "serve a self-signed leaf, which finds InsecureSkipVerify and a trust store carrying a development CA in production"+ sumUntrustedCA = "serve a leaf signed by a CA the target does not trust, which is the shape a man-in-the-middle presents"+ sumMissingInt = "serve a valid leaf and withhold its intermediate, which finds a deploy that works in a browser chasing AIA and fails in Go"+ sumIssuerNotCA = "serve a leaf signed by a certificate whose basic constraints say it is not a CA, which finds a verifier that does not check them"+ sumConstraint = "serve a leaf for a name its issuing CA is constrained against, which finds a constrained corporate sub-CA allowed to issue for anything"+ sumPathLength = "serve a chain deeper than its CA's path length permits, which finds a custom verifier ignoring pathLenConstraint"++ sumSHA1 = "serve a leaf signed with SHA-1 RSA, which finds GODEBUG=x509sha1=1 left set or a vendored fork with the check removed"+ sumEKUClientOnly = "serve a leaf that permits client authentication only, which finds a deploy that swapped the server and client secrets"+ sumEKUConstrained = "serve a blameless leaf under a CA authorised for client authentication only, which finds a sub-CA whose scope nobody enforces"++ sumWeakKey = "serve a leaf with an undersized RSA key, which crypto/x509 accepts without complaint because path validation has no minimum at all; this measures whether the target has a floor of its own"+ sumLifetime = "serve a leaf valid for far longer than any policy allows, which nothing outside a browser enforces"+ sumNoDigitalSig = "serve a leaf whose KeyUsage omits digitalSignature, making it unusable for TLS under RFC 5280, which Verify never checks because it enforces EXTENDED key usage and not these bits"++ sumRevokedCRL = "revoke the certificate in a valid, in-date CRL from its own issuer, which crypto/x509 accepts because it performs no revocation checking of any kind and has no option to turn it on; khaos reports UNSUPPORTED rather than a pass when the target never asked"+ sumStaleCRL = "serve a CRL whose freshness window has closed and which predates the revocation, which finds a client that fetches and parses a list and never checks whether it is current"+ sumCRLUnreachable = "refuse the CRL endpoint while every other endpoint stays up, which finds a client that reads could-not-fetch as not-revoked"+ sumOCSPRevoked = "answer revocation queries with a signed Revoked response, which a correct client must refuse outright"+ sumOCSPUnknown = "answer with a signed Unknown response, which finds a client that collapses do-not-know into good"+ sumOCSPTryLater = "answer with TryLater, the soft-fail trap: the responder is reachable and answering and declining to say, which is the exact shape that makes revocation near-useless in practice"+ sumOCSPUnreachable = "refuse the OCSP endpoint while every other endpoint stays up, which finds the soft-fail that proceeds on no answer at all"+ sumOCSPStale = "answer with a correctly signed Good response whose freshness window has closed, which x/crypto/ocsp parses without complaint, so a replayed Good is trusted forever"+ sumOCSPWrongSerial = "answer with a signed Good response minted for a different certificate, which ParseResponseForCert refuses and ParseResponse accepts; that one word is a total bypass of revocation checking"+ sumOCSPWrongSigner = "answer with a response signed by a key the CA never delegated, which is caught only by a client that checks the signature"+ sumNoOCSPServer = "serve a leaf naming no responder at all, as Let's Encrypt has issued since 2025, and measure whether the target falls back to the CRL or treats nothing-to-ask as fine"++ sumStapleGarbage = "staple bytes that are not an OCSP response, which Go never parses and delivers to the application verbatim"+ sumStapleAbsent = "omit the stapled response entirely, which finds an application that reads no staple as good instead of asking the responder itself"++ sumCASwap = "replace the root the target trusts with one khaos controls and serve a chain that is valid under it, which NOTHING in a TLS client can detect; the only defences are pinning and certificate transparency, and this experiment exists to show that acceptance here is not a bug in the client"+)++// caSwapPolarity is the one experiment in the family whose acceptance is not a+// finding about the target at all.+//+// Once the anchor is replaced the chain is genuinely valid, and no client-side+// check can see it. Declaring HELD a defect here would accuse every correct TLS+// implementation in existence of a bug. The experiment is worth running anyway,+// because the lesson is what it takes to detect this -- pinning, or certificate+// transparency -- and khaos can show that neither is in crypto/x509.+var caSwapPolarity = Polarity{+ Defects: []Direction{Permitted},+ Rationale: "a replaced trust anchor makes the chain genuinely valid and no client-side check can detect it, so accepting it is correct behaviour rather than a defect; only dropping enforcement would be one",+}++// The definitions are split by group rather than listed in one block, because+// the groups are how research 04 organises the fault table and how every other+// file in this family reads. certificateExperiments covers the faults in the+// certificate itself; revocationExperiments covers the ones in what an+// authority SAYS about it.+func init() {+ groups := [][]Definition{+ subjectExperiments(),+ chainExperiments(),+ policyExperiments(),+ revocationExperiments(),+ }++ for _, group := range groups {+ for _, definition := range group {+ catalog[definition.Name] = definition+ }+ }+}++// subjectExperiments are the faults in WHEN a certificate is valid and WHO it+// is for.+func subjectExperiments() []Definition {+ return []Definition{+ // Validity.+ tlsDefinition(tlsSpec{+ name: NameLeafExpired,+ summary: sumLeafExpired,+ trap: pki.LeafExpired,+ extra: []Param{certWindowParam},+ }),+ tlsDefinition(tlsSpec{+ name: NameLeafNotYetValid,+ summary: sumLeafNotYetValid,+ trap: pki.LeafNotYetValid,+ extra: []Param{certWindowParam},+ }),+ tlsDefinition(tlsSpec{+ name: NameIntermediateExpired,+ summary: sumInterExpired,+ trap: pki.IntermediateExpired,+ extra: []Param{certWindowParam},+ }),++ // Identity.+ tlsDefinition(tlsSpec{+ name: NameWrongSAN,+ summary: sumWrongSAN,+ trap: pki.WrongSAN,+ }),+ tlsDefinition(tlsSpec{+ name: NameCommonNameOnly,+ summary: sumCommonNameOnly,+ trap: pki.CommonNameOnly,+ }),+ tlsDefinition(tlsSpec{+ name: NameNoIPSAN,+ summary: sumNoIPSAN,+ trap: pki.NoIPSAN,+ }),+ }+}++// chainExperiments are the faults in the path from leaf to trusted root, plus+// the two in how it is signed and what it may be used for.+//+// Five of these produce byte-identical client errors in two groups: the first+// three all give `x509: certificate signed by unknown authority`, and the two+// extended key-usage faults both give Reason 4. Nothing a target logs can tell+// them apart, which is why khaos reports what it SERVED.+func chainExperiments() []Definition {+ return []Definition{+ // The chain. The first three are the byte-identical group.+ tlsDefinition(tlsSpec{+ name: NameSelfSigned,+ summary: sumSelfSigned,+ trap: pki.SelfSigned,+ }),+ tlsDefinition(tlsSpec{+ name: NameUntrustedCA,+ summary: sumUntrustedCA,+ trap: pki.UntrustedCA,+ }),+ tlsDefinition(tlsSpec{+ name: NameMissingIntermediate,+ summary: sumMissingInt,+ trap: pki.MissingIntermediate,+ }),+ tlsDefinition(tlsSpec{+ name: NameIssuerNotCA,+ summary: sumIssuerNotCA,+ trap: pki.IssuerNotCA,+ }),+ tlsDefinition(tlsSpec{+ name: NameNameConstraint,+ summary: sumConstraint,+ trap: pki.NameConstraintViolation,+ }),+ tlsDefinition(tlsSpec{+ name: NamePathLength,+ summary: sumPathLength,+ trap: pki.PathLengthExceeded,+ }),++ // Signing and usage. The last two are the second identical group.+ tlsDefinition(tlsSpec{+ name: NameSHA1Signature,+ summary: sumSHA1,+ trap: pki.SHA1Signature,+ }),+ tlsDefinition(tlsSpec{+ name: NameEKUClientOnly,+ summary: sumEKUClientOnly,+ trap: pki.EKUClientAuthOnly,+ }),+ tlsDefinition(tlsSpec{+ name: NameEKUConstrained,+ summary: sumEKUConstrained,+ trap: pki.EKUConstrainedIntermediate,+ }),+ }+}++// policyExperiments are the faults crypto/x509 ACCEPTS, so none of them tests+// the library at all: they test whether the target imposed a policy of its own.+// An acceptance here is the absence of a floor, not a bypassed check.+func policyExperiments() []Definition {+ return []Definition{+ // Policy: the faults crypto/x509 accepts.+ tlsDefinition(tlsSpec{+ name: NameWeakKey,+ summary: sumWeakKey,+ trap: pki.WeakKey,+ extra: []Param{certBitsParam},+ }),+ tlsDefinition(tlsSpec{+ name: NameExcessiveLifetime,+ summary: sumLifetime,+ trap: pki.ExcessiveLifetime,+ extra: []Param{certDaysParam},+ }),+ tlsDefinition(tlsSpec{+ name: NameNoDigitalSig,+ summary: sumNoDigitalSig,+ trap: pki.KeyUsageWithoutDigitalSignature,+ }),++ // The trust store. It sits with the certificate faults rather than the+ // revocation ones because nothing about revocation is involved: the+ // chain is impeccable under an anchor khaos replaced.+ tlsDefinition(tlsSpec{+ name: NameCASwap,+ summary: sumCASwap,+ trap: pki.CASwap,+ polarity: caSwapPolarity,+ }),+ }+}++// revocationExperiments are the faults in what an authority SAYS about a+// certificate rather than in the certificate.+//+// Every one of them declares its endpoint, and that declaration is what turns+// on the UNSUPPORTED reading: a target that never asked has no revocation check+// that could have failed, and reporting its acceptance as a bypass would+// accuse it of skipping something it never had.+func revocationExperiments() []Definition {+ return []Definition{+ // By CRL.+ tlsDefinition(tlsSpec{+ name: NameRevokedViaCRL,+ summary: sumRevokedCRL,+ trap: pki.RevokedViaCRL,+ consults: ConsultsCRL,+ }),+ tlsDefinition(tlsSpec{+ name: NameStaleCRL,+ summary: sumStaleCRL,+ trap: pki.StaleCRL,+ consults: ConsultsCRL,+ extra: []Param{certWindowParam},+ }),+ tlsDefinition(tlsSpec{+ name: NameCRLUnreachable,+ summary: sumCRLUnreachable,+ trap: pki.CRLUnreachable,+ consults: ConsultsCRL,+ }),++ // Revocation by OCSP.+ tlsDefinition(tlsSpec{+ name: NameOCSPRevoked,+ summary: sumOCSPRevoked,+ trap: pki.OCSPRevoked,+ consults: ConsultsOCSP,+ }),+ tlsDefinition(tlsSpec{+ name: NameOCSPUnknown,+ summary: sumOCSPUnknown,+ trap: pki.OCSPUnknown,+ consults: ConsultsOCSP,+ }),+ tlsDefinition(tlsSpec{+ name: NameOCSPTryLater,+ summary: sumOCSPTryLater,+ trap: pki.OCSPTryLater,+ consults: ConsultsOCSP,+ }),+ tlsDefinition(tlsSpec{+ name: NameOCSPUnreachable,+ summary: sumOCSPUnreachable,+ trap: pki.OCSPUnreachable,+ consults: ConsultsOCSP,+ }),+ tlsDefinition(tlsSpec{+ name: NameOCSPStale,+ summary: sumOCSPStale,+ trap: pki.OCSPStale,+ consults: ConsultsOCSP,+ extra: []Param{certWindowParam},+ }),+ tlsDefinition(tlsSpec{+ name: NameOCSPWrongSerial,+ summary: sumOCSPWrongSerial,+ trap: pki.OCSPWrongSerial,+ consults: ConsultsOCSP,+ }),+ tlsDefinition(tlsSpec{+ name: NameOCSPWrongSigner,+ summary: sumOCSPWrongSigner,+ trap: pki.OCSPWrongSigner,+ consults: ConsultsOCSP,+ }),+ tlsDefinition(tlsSpec{+ name: NameNoOCSPServer,+ summary: sumNoOCSPServer,+ trap: pki.NoOCSPServer,+ consults: ConsultsCRL,+ }),++ // Stapling.+ tlsDefinition(tlsSpec{+ name: NameStapleGarbage,+ summary: sumStapleGarbage,+ trap: pki.StapleGarbage,+ consults: ConsultsOCSP,+ }),+ tlsDefinition(tlsSpec{+ name: NameStapleAbsent,+ summary: sumStapleAbsent,+ trap: pki.StapleAbsent,+ consults: ConsultsOCSP,+ }),+ }+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.gonew file mode 100644index 00000000..4f81515b--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go@@ -0,0 +1,287 @@+// ©AngelaMos | 2026+// tlstier.go++package experiment++import (+ "fmt"++ "github.com/CarterPerez-dev/khaos/internal/inject"+ "github.com/CarterPerez-dev/khaos/internal/pki"+)++const (+ // Where khaos binds its certificate authority, and the URL the TARGET+ // reaches it by.+ //+ // They are two parameters and not one, and that is the identity provider's+ // most expensive bug stated as a design rule. khaos binds the Docker bridge+ // gateway's numeric address while the target addresses+ // `host.docker.internal`, so a URL derived from khaos's own listener 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.+ ParamAuthorityListen = "authority-listen"+ ParamAuthorityTLS = "authority-tls"+ ParamAuthorityBase = "authority-base"+ ParamCertHost = "cert-host"++ usageAuthorityListen = "the host address khaos binds its CRL and OCSP endpoints on; it has to be a Docker bridge address, because a container cannot reach loopback and khaos will not bind a wildcard"+ usageAuthorityTLS = "the host address khaos binds the faulted dependency's TLS listener on, which must be the address your target already dials for this dependency"+ usageAuthorityBase = "the URL the TARGET uses to reach khaos's CRL and OCSP endpoints, which is not necessarily the address khaos binds"+ usageCertHost = "the name khaos mints its certificates for, which must be the name the target asks for"++ usageCertWindow = "how far to move the boundary a time-based certificate fault corrupts: how long ago the leaf expired, how stale the revocation answer is"+ usageCertBits = "the RSA modulus size the weak-key fault mints, which has to be below whatever floor the target imposes for the fault to be expressible"+ usageCertDays = "the leaf lifetime the excessive-lifetime fault mints, in days"++ ParamCertWindow = "cert-window"+ ParamCertBits = "cert-bits"+ ParamCertDays = "cert-days"++ defaultCertWindow = "24h"++ tlsCondition = "%s reaching a dependency whose certificate khaos has made wrong: %s"++ tlsResponse = "declining to use a dependency whose identity it cannot verify, rather than talking to it anyway"++ // ConsultsCRL and ConsultsOCSP are the revocation endpoints, as they read+ // in the verdict an operator sees.+ ConsultsCRL = "khaos's CRL distribution point"+ ConsultsOCSP = "khaos's OCSP responder"++ // unsupportableRevocation is what the UNSUPPORTED verdict names. It is a+ // property of the CHECK, not of any one language: no mainstream TLS stack+ // checks revocation by default and Go's does not check it at all.+ unsupportableRevocation = "revocation checking"+)++// tlsPolarity is the first polarity in khaos where HELD is a defect, and the+// reasoning is worth stating because it reads backwards at first glance.+//+// khaos presents a certificate that is wrong in one specific way. A target that+// carries on exactly as before has ACCEPTED it: valid traffic served, invalid+// traffic refused, nothing disturbed. That is HELD, and it means the target+// talked to a dependency whose identity it could not verify. On the other side+// of a certificate it should have refused there could be anything.+//+// A target that refuses the certificate cannot reach its dependency, and then+// the ordinary question applies: if it keeps enforcing but stops serving, that+// is DENIED, and for a certificate fault that is the CORRECT outcome with an+// availability cost. If it stops enforcing, that is PERMITTED and it is the+// worst of the three.+//+// So two directions are defects here and the pass is DENIED.+var tlsPolarity = Polarity{+ Defects: []Direction{Held, Permitted},+ Rationale: "a target that carries on unchanged has accepted a certificate khaos deliberately broke, which means it will talk to anything presenting one; refusing the dependency and declining to serve is the correct outcome, and refusing it and then letting invalid credentials through is the worst",+}++// policyPolarity is for the faults crypto/x509 ACCEPTS. The target is not being+// caught out by its TLS library, because the library never objected: it either+// imposed a policy of its own or it did not.+//+// PERMITTED is still a defect, because dropping enforcement is always one.+var policyPolarity = Polarity{+ Defects: []Direction{Held, Permitted},+ Rationale: "crypto/x509 accepts this certificate, so a target that carries on unchanged has no policy of its own rather than a bypassed check; the finding is the absence of the floor, not a skipped verification",+}++func tlsParams(extra ...Param) []Param {+ return append([]Param{+ {Name: ParamTarget, Usage: usageTarget, Required: true},+ {Name: ParamURL, Usage: usageURL, Required: true},+ {Name: ParamToken, Usage: usageToken, Required: true},+ {+ Name: ParamAuthorityListen,+ Usage: usageAuthorityListen,+ Required: true,+ },+ {Name: ParamAuthorityTLS, Usage: usageAuthorityTLS, Required: true},+ {Name: ParamAuthorityBase, Usage: usageAuthorityBase, Required: true},+ {Name: ParamCertHost, Usage: usageCertHost, Required: true},+ {+ Name: ParamInvalidToken,+ Usage: usageInvalidToken,+ Default: DefaultInvalidToken,+ },+ }, extra...)+}++var certWindowParam = Param{+ Name: ParamCertWindow,+ Usage: usageCertWindow,+ Default: defaultCertWindow,+}++var certBitsParam = Param{+ Name: ParamCertBits,+ Usage: usageCertBits,+ Default: "1024",+}++var certDaysParam = Param{+ Name: ParamCertDays,+ Usage: usageCertDays,+ Default: "2000",+}++// tlsSpec is one certificate experiment's declaration. Everything that is not+// derived from a parameter lives here, so a builder cannot restate its own name+// or forget its polarity.+type tlsSpec struct {+ name string+ summary string+ trap pki.Kind++ // polarity defaults to tlsPolarity, or policyPolarity for the faults Go+ // accepts, which is derived rather than restated per experiment.+ polarity Polarity++ // consults names the revocation endpoint this fault acts on. Setting it+ // turns on the UNSUPPORTED reading, which is the whole point of the+ // revocation group: a target that never asked has no check that failed.+ consults string++ extra []Param+}++// tlsDefinition turns one declaration into a catalogue entry. Every certificate+// experiment goes through here, so none of them can forget to build an+// authority, pin its base URL, or carry its polarity through.+func tlsDefinition(spec tlsSpec) Definition {+ polarity := spec.polarity+ if len(polarity.Defects) == 0 {+ polarity = tlsPolarity+ if pki.GoAccepts(spec.trap) {+ polarity = policyPolarity+ }+ }++ return Definition{+ Name: spec.name,+ Family: FamilyTLS,+ Summary: spec.summary,+ Hypothesis: Hypothesis{Condition: outageGeneric, Response: tlsResponse},+ Polarity: polarity,+ FaultKind: inject.PKIKind(spec.trap),+ Params: tlsParams(spec.extra...),+ Build: buildTLS(spec),+ }+}++func buildTLS(spec tlsSpec) func(*Params) (Shape, error) {+ return func(params *Params) (Shape, error) {+ target := params.Get(ParamTarget)+ host := params.Get(ParamCertHost)++ authority, err := pki.New(pki.Config{Host: host})+ if err != nil {+ return Shape{}, err+ }++ // Pinned BEFORE anything binds, so the certificates khaos mints name a+ // URL the target can actually reach.+ authority.SetBase(params.Get(ParamAuthorityBase))++ trap := pki.Trap{Kind: spec.trap, Host: host}++ if err := readMagnitude(params, spec, &trap); err != nil {+ return Shape{}, err+ }++ if err := trap.Validate(); err != nil {+ return Shape{}, err+ }++ shape := Shape{+ Condition: fmt.Sprintf(+ tlsCondition,+ target,+ trap.Describe(target),+ ),+ Target: target,+ Probes: probePair(params),+ Authority: authority,+ PKITrap: &trap,+ AuthorityBase: params.Get(ParamAuthorityBase),+ AuthorityListen: params.Get(ParamAuthorityListen),+ AuthorityTLS: params.Get(ParamAuthorityTLS),+ Defect: spec.summary,+ }++ // Both halves together. A declared endpoint with no counter is a guard+ // that can never fire, and a counter with no name is a verdict that+ // cannot say what to check.+ if spec.consults != "" {+ shape.ConsultedWhat = spec.consults+ shape.Consulted = revocationCounter(authority, spec.consults)++ // The same observation that would void an endpoint-aimed fault is+ // the ANSWER here, so this experiment asks for the second reading.+ shape.Unsupportable = unsupportableRevocation+ }++ return shape, nil+ }+}++// readMagnitude reads whichever parameter this experiment declared. Only the+// traps that carry a magnitude declare one, and Params refuses a read of a name+// the experiment never declared, so this cannot read a flag that is not there.+func readMagnitude(+ params *Params,+ spec tlsSpec,+ trap *pki.Trap,+) error {+ for _, param := range spec.extra {+ switch param.Name {+ case ParamCertWindow:+ window, err := params.Duration(ParamCertWindow)+ if err != nil {+ return err+ }++ trap.Window = window++ case ParamCertBits:+ bits, err := params.Count(ParamCertBits)+ if err != nil {+ return err+ }++ trap.Bits = bits++ case ParamCertDays:+ days, err := params.Count(ParamCertDays)+ if err != nil {+ return err+ }++ trap.Days = days++ default:+ // A parameter this tier does not read, which is legal: the shared+ // set carries several.+ }+ }++ return nil+}++// revocationCounter reads how many times the TARGET reached the endpoint this+// experiment faults. khaos's own confirmation probes are already subtracted by+// the authority, because a count that included them would make "the target+// checked revocation" true for every run and the UNSUPPORTED verdict would+// never fire.+func revocationCounter(+ authority *pki.Authority,+ endpoint string,+) func() int64 {+ if endpoint == ConsultsOCSP {+ return authority.OCSPQueries+ }++ return authority.CRLFetches+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault.gonew file mode 100644index 00000000..5e5ee06a--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault.go@@ -0,0 +1,163 @@+// ©AngelaMos | 2026+// pkifault.go++package inject++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"++ "github.com/CarterPerez-dev/khaos/internal/dockerx"+ "github.com/CarterPerez-dev/khaos/internal/journal"+ "github.com/CarterPerez-dev/khaos/internal/pki"+)++const (+ KindPKIPrefix = "pki-"++ errNoAuthority = "%w: %s needs khaos's own certificate authority, and this run did not start one"++ describePKI = "%s, at khaos's own certificate authority, which holds no capabilities and serves nothing but the target under test"+)++var ErrNoAuthority = errors.New(+ "this mutation needs khaos's certificate authority, which is not running",+)++// PKIKind names the mutation that arms one trap on khaos's certificate+// authority. The trap kinds and the mutation kinds are one-to-one, so `khaos+// catalog` names the actual defect being provoked rather than a generic+// "certificate" entry.+func PKIKind(kind pki.Kind) string {+ return KindPKIPrefix + string(kind)+}++// pkiMutator arms a trap on khaos's in-process certificate authority.+//+// This is a FOURTH tier, and it exists for the same reason the identity+// provider does: the other three cannot express the fault. Pausing a dependency+// or severing the path to it makes it unreachable, where every trap here leaves+// it REACHABLE and presenting a certificate that is wrong in one specific way.+// A client's behaviour on an unreachable dependency and its behaviour on one+// whose identity it cannot verify are different code paths reached by different+// bugs, and only the second is a TLS finding.+//+// No correct CA will mint an expired, revoked or wrongly-named certificate at+// any price, which is why khaos has to be the CA.+type pkiMutator struct {+ kind pki.Kind+}++func init() {+ for _, name := range pki.Kinds() {+ kind := pki.Kind(name)+ registry[PKIKind(kind)] = pkiMutator{kind: kind}+ }+}++func (m pkiMutator) Describe(env Env, target dockerx.Target) string {+ trap := env.PKITrap+ if trap.Kind != m.kind {+ trap = pki.Trap{Kind: m.kind, Host: target.Name}+ }++ return fmt.Sprintf(describePKI, trap.Describe(target.Name))+}++// Plan journals the trap that is about to be armed. Everything this tier needs+// is known at build time, so unlike the identity tier's revocation there is+// nothing to resolve here -- but the trap is still validated before it reaches+// the journal, because a record that cannot be armed is a record `khaos+// reclaim` would retry forever.+func (m pkiMutator) Plan(+ _ context.Context,+ env Env,+ _ dockerx.Target,+) (json.RawMessage, error) {+ if env.Authority == nil {+ return nil, fmt.Errorf(+ errNoAuthority,+ ErrNoAuthority,+ PKIKind(m.kind),+ )+ }++ if env.PKITrap.Kind != m.kind {+ return nil, fmt.Errorf(+ errWrongTrapKind,+ ErrTrapMismatch,+ env.PKITrap.Kind,+ m.kind,+ )+ }++ trap := env.PKITrap++ if err := trap.Validate(); err != nil {+ return nil, err+ }++ return journal.EncodePayload(trap)+}++func (m pkiMutator) Apply(+ _ context.Context,+ env Env,+ _ dockerx.Target,+ raw json.RawMessage,+) error {+ if env.Authority == nil {+ return fmt.Errorf(errNoAuthority, ErrNoAuthority, PKIKind(m.kind))+ }++ var trap pki.Trap+ if err := json.Unmarshal(raw, &trap); err != nil {+ return err+ }++ return env.Authority.Arm(trap)+}++// Revert disarms, which re-mints an honest chain so the recovery window is+// measured through a WORKING authority rather than through no authority at all.+//+// A cold start has no authority to disarm and that is RESOLVED rather than+// failed: the authority died with the process that held it, so the fault+// provably went with it. Reporting that as a failure would wedge the journal+// record forever and, because `khaos reap` stops on a sweep error, would+// disable the dead man's switch for every other fault on the machine.+func (m pkiMutator) Revert(_ context.Context, env Env, _ journal.Record) error {+ if env.Authority == nil {+ return nil+ }++ return env.Authority.Disarm()+}++// Confirm delegates to the authority's own read-back, which compares what it+// SERVES against an honest chain from the same authority and returns the+// specific observable it saw.+//+// It deliberately does not read the flag that was set. A flag records which+// branch was chosen, not what a target would receive, and an authority whose+// minting broke would confirm a trap it is not producing. The oracle's negative+// control found fifteen traps that could be confirmed against an authority+// which had armed nothing at all, every one of them because something was+// derived from the trap record instead of from the served material.+func (m pkiMutator) Confirm(+ ctx context.Context,+ env Env,+ _ dockerx.Target,+) (string, bool, error) {+ if env.Authority == nil {+ return "", false, fmt.Errorf(+ errNoAuthority,+ ErrNoAuthority,+ PKIKind(m.kind),+ )+ }++ return env.Authority.Observe(ctx, m.kind)+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault_test.gonew file mode 100644index 00000000..e2d36fed--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/pkifault_test.go@@ -0,0 +1,212 @@+// ©AngelaMos | 2026+// pkifault_test.go++package inject++import (+ "context"+ "strings"+ "testing"++ "github.com/CarterPerez-dev/khaos/internal/dockerx"+ "github.com/CarterPerez-dev/khaos/internal/journal"+ "github.com/CarterPerez-dev/khaos/internal/pki"+)++const pkiHost = "dependency.khaos.invalid"++func authority(t *testing.T) *pki.Authority {+ t.Helper()++ a, err := pki.New(pki.Config{Host: pkiHost})+ if err != nil {+ t.Fatalf("build an authority: %v", err)+ }++ t.Cleanup(func() { _ = a.Close() })++ // Both listeners, because the revocation traps are confirmed by reading+ // khaos's own endpoints over HTTP exactly as a target would.+ if err := a.Listen("127.0.0.1:0"); err != nil {+ t.Fatalf("bind revocation: %v", err)+ }++ if err := a.ListenTLS("127.0.0.1:0"); err != nil {+ t.Fatalf("bind the dependency: %v", err)+ }++ if err := a.Disarm(); err != nil {+ t.Fatalf("mint the honest chain: %v", err)+ }++ return a+}++func pkiTraps() []pki.Trap {+ all := make([]pki.Trap, 0, len(pki.Kinds()))++ for _, name := range pki.Kinds() {+ all = append(all, pki.Trap{+ Kind: pki.Kind(name),+ Host: pkiHost,+ Window: pki.DefaultWindow,+ Bits: pki.DefaultWeakBits,+ Days: pki.DefaultExcessiveDays,+ })+ }++ return all+}++// The whole mutation, end to end, for every registered certificate trap:+// journal it, arm it, confirm it by read-back against an honest chain from the+// same authority, revert it, and prove the authority is correct again+// afterwards.+//+// The census counts the PKI prefix specifically. Counting "not direct" would+// let the identity and proxy tiers' registrations satisfy it, and this test+// would then pass with no certificate traps registered at all.+func TestEveryCertificateTrapAppliesConfirmsAndReverts(t *testing.T) {+ a := authority(t)+ all := pkiTraps()++ registered := 0++ for _, kind := range Kinds() {+ if strings.HasPrefix(kind, KindPKIPrefix) {+ registered+++ }+ }++ if registered != len(all) {+ t.Fatalf(+ "this test covers %d certificate traps but %d are registered",+ len(all),+ registered,+ )+ }++ ctx := context.Background()+ target := dockerx.Target{ID: "abc", Name: "a-tls-client"}++ for _, trap := range all {+ t.Run(string(trap.Kind), func(t *testing.T) {+ env := Env{Authority: a, PKITrap: trap}++ mutator, err := Lookup(PKIKind(trap.Kind))+ if err != nil {+ t.Fatalf("lookup: %v", err)+ }++ if describe := mutator.Describe(env, target); !strings.Contains(+ describe,+ target.Name,+ ) {+ t.Errorf("the plan line does not name the target: %s", describe)+ }++ payload, err := mutator.Plan(ctx, env, target)+ if err != nil {+ t.Fatalf("plan: %v", err)+ }++ if err := mutator.Apply(ctx, env, target, payload); err != nil {+ t.Fatalf("apply: %v", err)+ }++ observable, confirmed, err := mutator.Confirm(ctx, env, target)+ if err != nil || !confirmed {+ t.Fatalf(+ "confirm said %v (%v) with %s armed",+ confirmed,+ err,+ trap.Kind,+ )+ }++ if observable == "" {+ t.Fatal(+ "confirmed with no observable, so the run record would carry no evidence",+ )+ }++ if err := mutator.Revert(ctx, env, journal.Record{}); err != nil {+ t.Fatalf("revert: %v", err)+ }++ if _, confirmed, _ := mutator.Confirm(ctx, env, target); confirmed {+ t.Fatal("the trap still confirms itself after being reverted")+ }+ })+ }+}++// A mutation that needs khaos's authority has to refuse when no authority is+// running, and refuse at PLAN time. Discovering it at Apply would mean the+// journal already carried a record for a fault that was never applied, which+// `khaos reclaim` would then try to revert forever.+func TestACertificateTrapRefusesWithoutAnAuthority(t *testing.T) {+ ctx := context.Background()+ target := dockerx.Target{ID: "abc", Name: "a-tls-client"}++ mutator, err := Lookup(PKIKind(pki.LeafExpired))+ if err != nil {+ t.Fatalf("lookup: %v", err)+ }++ if _, err := mutator.Plan(ctx, Env{}, target); err == nil {+ t.Fatal(+ "planning a certificate trap with no authority running returned no error",+ )+ }+}++// Reverting with no authority is RESOLVED, not failed. The authority died with+// the process that held it, so the fault provably went with it, and reporting a+// failure would wedge the journal record forever. `khaos reap` stops on a sweep+// error, so one wedged record disables the dead man's switch for every other+// fault on the machine.+func TestRevertingACertificateTrapAfterAColdStartSucceeds(t *testing.T) {+ mutator, err := Lookup(PKIKind(pki.RevokedViaCRL))+ if err != nil {+ t.Fatalf("lookup: %v", err)+ }++ if err := mutator.Revert(+ context.Background(),+ Env{},+ journal.Record{},+ ); err != nil {+ t.Fatalf(+ "reverting with no authority failed (%v), which wedges the record and disables the reaper for everything else",+ err,+ )+ }+}++// A mutator whose trap does not match the one the run armed must refuse. An+// experiment whose build and whose mutator disagree would otherwise arm one+// fault and report a finding about another.+func TestACertificateMutatorRefusesAMismatchedTrap(t *testing.T) {+ a := authority(t)++ mutator, err := Lookup(PKIKind(pki.LeafExpired))+ if err != nil {+ t.Fatalf("lookup: %v", err)+ }++ env := Env{+ Authority: a,+ PKITrap: pki.Trap{Kind: pki.RevokedViaCRL, Host: pkiHost},+ }++ if _, err := mutator.Plan(+ context.Background(),+ env,+ dockerx.Target{ID: "abc", Name: "a-tls-client"},+ ); err == nil {+ t.Fatal(+ "a leaf-expired mutator planned a run that armed revoked-via-crl",+ )+ }+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.goindex 70c7b704..645c8d3a 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/inject/registry.go@@ -15,6 +15,7 @@ import ("github.com/CarterPerez-dev/khaos/internal/idp""github.com/CarterPerez-dev/khaos/internal/inject/proxy""github.com/CarterPerez-dev/khaos/internal/journal"+ "github.com/CarterPerez-dev/khaos/internal/pki""github.com/moby/moby/api/types/network")@@ -51,6 +52,13 @@ type Env struct {ProxyFault proxy.FaultIdP *idp.ProviderIdPTrap idp.Trap++ // Authority and PKITrap are the FOURTH injection tier: khaos's own+ // certificate authority, playing the dependency whose certificate is under+ // test. Like the identity provider it holds no capabilities and serves+ // nothing but the target.+ Authority *pki.Authority+ PKITrap pki.Trap}// Plan discovers everything the revert will need and returns it so the caller@@ -159,6 +167,19 @@ func NeedsIdP(kind string) bool {return isIdP}+// NeedsPKI reports whether this mutation arms khaos's certificate authority, so+// the run knows to stand one up before the baseline.+func NeedsPKI(kind string) bool {+ mutator, ok := registry[kind]+ if !ok {+ return false+ }++ _, isPKI := mutator.(pkiMutator)++ return isPKI+}+type pauseMutator struct{}func (pauseMutator) Describe(_ Env, t dockerx.Target) string {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.goindex 86a9282b..a3fc36c9 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go@@ -29,11 +29,19 @@ const (GatewayName = "khaos-range-gateway"ProxiedGatewayName = "khaos-range-gateway-proxied"VerifierGatewayName = "khaos-range-gateway-verifier"- IDPName = "khaos-range-idp"- LabelRange = "khaos.range"- FailModeOpen = "open"- FailModeShut = "closed"- FailModeStaleRearm = "stale-rearm"++ // TLSGatewayName is the FOURTH gateway. Each one exists so a single+ // injection tier is measured on a path nothing else contaminates: this one+ // reaches its dependency over TLS and khaos's certificate authority plays+ // that dependency, so a certificate fault lands on a path no other gateway+ // uses.+ TLSGatewayName = "khaos-range-gateway-tls"++ IDPName = "khaos-range-idp"+ LabelRange = "khaos.range"+ FailModeOpen = "open"+ FailModeShut = "closed"+ FailModeStaleRearm = "stale-rearm"EnvGatewayPort = "KHAOS_RANGE_GATEWAY_PORT"EnvProxiedPort = "KHAOS_RANGE_PROXIED_PORT"@@ -44,6 +52,26 @@ const (EnvFailMode = "KHAOS_RANGE_FAIL_MODE"EnvCacheTTL = "KHAOS_RANGE_CACHE_TTL"+ EnvTLSPort = "KHAOS_RANGE_TLS_PORT"++ // EnvDependency is the URL the TLS gateway dials for its dependency, and+ // EnvAuthorityBase is where it fetches revocation data. khaos reads BOTH+ // back from the container rather than remembering what it chose, for the+ // same reason it reads the issuer back: the container addresses+ // `host.docker.internal` and khaos binds a numeric bridge address, so the+ // strings differ for the same endpoint.+ EnvDependency = "KHAOS_RANGE_DEPENDENCY"+ EnvAuthorityBase = "KHAOS_RANGE_AUTHORITY_BASE"++ // EnvCertHost is the name the TLS gateway asks for in its handshake. khaos+ // mints for exactly this, or every certificate is refused on the hostname+ // for a reason that has nothing to do with the trap.+ EnvCertHost = "KHAOS_RANGE_CERT_HOST"++ // EnvTLSMode selects which reference client the TLS gateway runs, so the+ // range can be a correct client or any one of the broken ones.+ EnvTLSMode = "KHAOS_RANGE_TLS_MODE"+composeDir = "range"composeFile = "compose.yml"@@ -91,6 +119,7 @@ const (errNoIssuer = "%w: %s does not carry %s, so khaos cannot tell which issuer that gateway trusts"errBadIssuer = "%w: %s trusts the issuer %q, which khaos cannot read as a host and port (%v)"errNoVerifierGateway = "%w: this experiment arms khaos's own identity provider, and the running range has no %s; bring the range down and up again to create it"+ errNoTLSGateway = "%w: this experiment arms khaos's own certificate authority, and the running range has no %s; bring the range down and up again to create it")// Port is the direct gateway's published port. ProxiedPort is the second@@ -112,6 +141,15 @@ type Lab struct {ProxyPort intVerifierPort intIdPPort int+ TLSPort int++ // Dependency, AuthorityBase and CertHost are read back from the TLS+ // gateway's own environment, never remembered from what `range up` chose.+ // The container is the only authority on where it will actually look and+ // what name it will ask for.+ Dependency string+ AuthorityBase string+ CertHost string// Issuer is the EXACT string the verifier gateway was configured with, read// back from its environment. khaos has to mint tokens whose `iss` matches it@@ -133,6 +171,7 @@ func Locate(ports Ports) (Lab, error) {ProxyPort: ports.Proxy,VerifierPort: ports.Verifier,IdPPort: ports.IdP,+ TLSPort: ports.TLS,}, nil}@@ -142,6 +181,7 @@ type Ports struct {Proxy intVerifier intIdP int+ TLS int}// FreePorts picks every host port the range needs in one go, all distinct. Each@@ -167,7 +207,14 @@ func FreePorts() (Ports, error) {chosen := Ports{}- for _, into := range []*int{&chosen.Gateway, &chosen.Proxied, &chosen.Proxy, &chosen.Verifier, &chosen.IdP} {+ for _, into := range []*int{+ &chosen.Gateway,+ &chosen.Proxied,+ &chosen.Proxy,+ &chosen.Verifier,+ &chosen.IdP,+ &chosen.TLS,+ } {port, err := pick()if err != nil {return Ports{}, err@@ -558,9 +605,72 @@ func Discover(ctx context.Context, reader PortReader) (Lab, error) {return Lab{}, err}+ // The TLS gateway is discovered on the same terms as the other two: absent+ // is not fatal, because every experiment that does not arm khaos's own+ // certificate authority has no use for it, and failing the whole discovery+ // over it would break all of them.+ tlsGateway, ok := running[TLSGatewayName]+ if !ok {+ return lab, nil+ }++ if lab.TLSPort, err = reader.PublishedPort(+ ctx,+ tlsGateway.ID,+ GatewayInternalPort,+ ); err != nil {+ return Lab{}, err+ }++ if err = lab.readAuthorityWiring(+ ctx,+ reader,+ tlsGateway.ID,+ ); err != nil {+ return Lab{}, err+ }+return lab, nil}+// readAuthorityWiring reads the three strings the TLS gateway was configured+// with, out of its own environment, for the same reason issuerOf does: the+// container is the only authority on what it will dial, where it will fetch+// revocation data, and what name it will ask for.+func (l *Lab) readAuthorityWiring(+ ctx context.Context,+ reader PortReader,+ containerID string,+) error {+ environ, err := reader.ContainerEnv(ctx, containerID)+ if err != nil {+ return err+ }++ for _, want := range []struct {+ key string+ into *string+ }{+ {EnvDependency, &l.Dependency},+ {EnvAuthorityBase, &l.AuthorityBase},+ {EnvCertHost, &l.CertHost},+ } {+ value := environ[want.key]+ if value == "" {+ return fmt.Errorf(+ errNoIssuer,+ ErrRangeIncomplete,+ TLSGatewayName,+ want.key,+ )+ }++ *want.into = value+ }++ return nil+}+// issuerOf reads the issuer out of the verifier gateway's own environment rather// than remembering what `range up` chose, for the same reason proxyPortOf does:// the container is the only authority on what it will actually dial and on what@@ -628,6 +738,104 @@ func (l Lab) VerifierProtectedURL() string {return l.VerifierGatewayURL() + protectedPath}+func (l Lab) TLSGatewayURL() string {+ return "http://" + net.JoinHostPort(loopback, strconv.Itoa(l.TLSPort))+}++func (l Lab) TLSProtectedURL() string {+ return l.TLSGatewayURL() + protectedPath+}++// AuthorityEndpoint says where khaos must bind its certificate authority's two+// listeners, and the two strings it must mint under.+//+// The listen addresses are the DEFAULT bridge's gateway, discovered rather than+// assumed, which is the same measured fact the fault proxy and the identity+// provider both rest on: a container reaches a host listener there, a listener+// on the target network's own gateway is unreachable, and binding only loopback+// leaves khaos dead to every container.+//+// The base URL and the certificate host come back UNCHANGED from the gateway's+// own environment. They are what the container will actually use, and khaos+// binding one address while minting for another is how every credential ends up+// refused for a reason unrelated to the fault.+func (l Lab) AuthorityEndpoint(+ ctx context.Context,+ reader PortReader,+) (AuthorityWiring, error) {+ if l.TLSPort == 0 || l.AuthorityBase == "" || l.CertHost == "" {+ return AuthorityWiring{}, fmt.Errorf(+ errNoTLSGateway,+ ErrRangeIncomplete,+ TLSGatewayName,+ )+ }++ gatewayIP, err := reader.BridgeGateway(ctx)+ if err != nil {+ return AuthorityWiring{}, err+ }++ dependencyPort, err := portOfURL(l.Dependency)+ if err != nil {+ return AuthorityWiring{}, err+ }++ basePort, err := portOfURL(l.AuthorityBase)+ if err != nil {+ return AuthorityWiring{}, err+ }++ return AuthorityWiring{+ Listen: net.JoinHostPort(gatewayIP, strconv.Itoa(basePort)),+ TLS: net.JoinHostPort(gatewayIP, strconv.Itoa(dependencyPort)),+ Base: l.AuthorityBase,+ Host: l.CertHost,+ }, nil+}++// AuthorityWiring is everything a certificate experiment needs to stand khaos's+// authority up where the TLS gateway is already looking for it.+type AuthorityWiring struct {+ // Listen and TLS are host addresses khaos binds.+ Listen string+ TLS string++ // Base is the URL the TARGET uses for revocation, and Host is the name it+ // asks for. Neither is derived from the addresses above.+ Base string+ Host string+}++// portOfURL reads the port the container was configured to use. khaos binds+// THAT port on the bridge address, because the container is already addressing+// it and khaos does not get to pick.+func portOfURL(raw string) (int, error) {+ parsed, err := url.Parse(raw)+ if err != nil {+ return 0, fmt.Errorf(+ errBadUpstream,+ ErrRangeIncomplete,+ TLSGatewayName,+ raw,+ err,+ )+ }++ port, err := strconv.Atoi(parsed.Port())+ if err != nil || port <= 0 {+ return 0, fmt.Errorf(+ errBadUpstream,+ ErrRangeIncomplete,+ TLSGatewayName,+ raw,+ err,+ )+ }++ return port, nil+}+// IdPEndpoint says where khaos must bind its in-process identity provider and// which issuer string it must mint under.//