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
fix(khaos): the weak-key size khaos accepted and could not generate
CarterPerez-devd1c3beb6d9b7
diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.goindex 926d8a9e..7578ab73 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/dockerx/actions.go@@ -200,7 +200,9 @@ func (c *Client) NetworkAddress(// BridgeGateway is the address a container reaches the host on: the DEFAULT// bridge's gateway, discovered rather than assumed, since it is not 172.17.0.1-// on every host and a user-defined network's own gateway is not reachable.+// on every host. A user-defined network's own gateway is that network's default+// route and answers a ping, but a HOST LISTENER bound on it is refused from+// containers on the network, which is why this is not that address.func (c *Client) BridgeGateway(ctx context.Context) (string, error) {result, err := c.api.NetworkInspect(ctx,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.goindex 216345b2..d20494b3 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/experiment.go@@ -110,10 +110,11 @@ type Experiment struct {IdP *idp.ProviderIdPTrap *idp.Trap+ Authority *pki.Authority+ PKITrap *pki.Trap+// AuthorityBase is the URL the TARGET reaches the revocation endpoints by,// which is pinned rather than derived from wherever khaos binds.- Authority *pki.Authority- PKITrap *pki.TrapAuthorityBase stringAuthorityListen stringAuthorityTLS stringdiff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.goindex 67cf0270..1d38b628 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier.go@@ -5,6 +5,7 @@ package experimentimport ("fmt"+ "strconv""github.com/CarterPerez-dev/khaos/internal/inject""github.com/CarterPerez-dev/khaos/internal/pki"@@ -85,16 +86,19 @@ var certWindowParam = Param{Default: defaultCertWindow,}+// Derived, not restated: the authority falls back to these same constants when+// a trap carries no magnitude, and a default that drifts below pki.MinimumBits+// would make every weak-key run fail validation instead of serving a fault.var certBitsParam = Param{Name: ParamCertBits,Usage: usageCertBits,- Default: "1024",+ Default: strconv.Itoa(pki.DefaultWeakBits),}var certDaysParam = Param{Name: ParamCertDays,Usage: usageCertDays,- Default: "2000",+ Default: strconv.Itoa(pki.DefaultExcessiveDays),}type tlsSpec struct {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier_test.gonew file mode 100644index 00000000..30d0b363--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/tlstier_test.go@@ -0,0 +1,98 @@+// ©AngelaMos | 2026+// tlstier_test.go++package experiment++import (+ "strconv"+ "testing"+ "time"++ "github.com/CarterPerez-dev/khaos/internal/pki"+)++// The CLI's advertised default and the authority's own fallback are two copies+// of the same magnitude, and only one of them is validated at arm time. Two of+// the three are derived from the pki constant; cert-window cannot be, because a+// time.Duration renders as "24h0m0s" and the help text should read "24h". This+// asserts the invariant instead, so a drift fails here rather than in front of+// an operator.+func TestCertDefaultsSurviveTheAuthoritysOwnValidation(t *testing.T) {+ cases := []struct {+ param Param+ trap pki.Trap+ }{+ {+ param: certBitsParam,+ trap: pki.Trap{Kind: pki.WeakKey, Host: pki.DefaultHost},+ },+ {+ param: certDaysParam,+ trap: pki.Trap{+ Kind: pki.ExcessiveLifetime,+ Host: pki.DefaultHost,+ },+ },+ }++ for _, c := range cases {+ t.Run(c.param.Name, func(t *testing.T) {+ magnitude, err := strconv.Atoi(c.param.Default)+ if err != nil {+ t.Fatalf(+ "%s default %q is not a number: %v",+ c.param.Name,+ c.param.Default,+ err,+ )+ }++ trap := c.trap+ switch trap.Kind {+ case pki.WeakKey:+ trap.Bits = magnitude+ case pki.ExcessiveLifetime:+ trap.Days = magnitude+ default:+ t.Fatalf("no magnitude field for %s", trap.Kind)+ }++ if err := trap.Validate(); err != nil {+ t.Fatalf(+ "the advertised default for %s cannot be armed: %v",+ c.param.Name,+ err,+ )+ }+ })+ }+}++func TestCertWindowDefaultMatchesTheAuthoritysFallback(t *testing.T) {+ parsed, err := time.ParseDuration(certWindowParam.Default)+ if err != nil {+ t.Fatalf(+ "cert-window default %q does not parse: %v",+ certWindowParam.Default,+ err,+ )+ }++ if parsed != pki.DefaultWindow {+ t.Fatalf(+ "cert-window advertises %s where the authority falls back to %s",+ parsed,+ pki.DefaultWindow,+ )+ }++ trap := pki.Trap{+ Kind: pki.LeafExpired,+ Host: pki.DefaultHost,+ Window: parsed,+ }++ if err := trap.Validate(); err != nil {+ t.Fatalf("the advertised cert-window cannot be armed: %v", err)+ }+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.goindex e26d1091..15db4398 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/experiment/verdict.go@@ -576,7 +576,10 @@ func diagnose(observation Observation, reasons []string) (Cause, []string) {// credential and a never-valid one are different streams, and diagnosing the// wrong one would report the pause's effect on something that never leaked.//- // It is read with the same order-sensitive test the fault window uses, and+ // It is read with the same order-sensitive test the fault window uses: a+ // window that starts accepted and settles into refusal is a cache that+ // LAPSED, where "ever accepted after the pause" would call the same window+ // NO-EXPIRY and invert both the diagnosis and the fix.if revokedHonoured(observation) > 0 {return resolveCause(observation.Resumed.Revoked,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.goindex 3f2c6cf9..1b1bf9b6 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/mint.go@@ -218,7 +218,8 @@ func (p *Provider) mintSignatureTrap(}}-// A nil key means the current signing key; a nil signer means the key's alg.+// A nil key means the current signing key; a nil signer signs with the alg the+// HEADER declares, which Key.Sign refuses if the key disagrees.func (p *Provider) serialize(header Header,claims Claims,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.goindex c9709f4b..1596e2af 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/observe.go@@ -84,8 +84,9 @@ func (p *Provider) Observe(return p.observeEndpoint(ctx, trap)}-// observeForgery mints on BOTH paths and requires them to differ. The honest-// token is the control: khaos has to be able to mint a correct one.+// observeForgery mints on BOTH paths. The honest token is the control: khaos+// has to be able to mint a correct one for the forgery to mean anything, and+// the kinds whose fault IS a divergence also require the two to differ.func (p *Provider) observeForgery(trap Trap) (string, bool, error) {honest, err := p.mintHonestForControl()if err != nil {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.goindex 0510f3ac..97dcde30 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/provider.go@@ -130,7 +130,8 @@ type Config struct {Now func() time.Time}-// New generates every key up front, so arming a trap is a pointer swap.+// New generates every key up front, so arming a trap is a pointer swap for all+// but the two rotation traps, which mint a fresh key inside Arm.func New(config Config) (*Provider, error) {if config.Audience == "" {config.Audience = DefaultAudiencediff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.goindex 443b2c8e..31aeae25 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/idp/token.go@@ -196,7 +196,8 @@ func Retarget(token Token, kid string) string {}// LooksLikeJWS tests the SHAPE, because choosing on "did my parser succeed"-// rejects a legal array `aud` and then introspects it as though it were opaque.+// makes a verifier whose `aud` field is a plain string reject a legal array one+// and then introspect it as though it were opaque.func LooksLikeJWS(credential string) bool {parts := strings.Split(credential, segmentSep)if len(parts) != jwsSegments {diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.goindex d1c582b8..3577af93 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/authority.go@@ -99,8 +99,9 @@ type Authority struct {closed chan struct{}}-// New builds every CA up front, so a trap that cannot be armed is its own-// fault and never a key generation that failed mid-experiment.+// New builds every CA and intermediate up front, so the issuer hierarchy a trap+// needs is already there when it is armed. The LEAF key is still generated per+// arm, which is why Trap.Validate refuses a size crypto/rsa would reject.func New(cfg Config) (*Authority, error) {a := &Authority{clock: cfg.Now,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.goindex 9a928c64..d47f63b7 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/catalog.go@@ -12,6 +12,10 @@ import (const (StrongBits = 2048+ // crypto/rsa refuses to GENERATE below this, so a smaller size is not a+ // weak key khaos can serve, it is an arm that fails with a mint error.+ MinimumBits = 1024+// The CA/Browser Forum cap, which nothing outside a browser enforces.LifetimeCapDays = 200@@ -34,13 +38,15 @@ const ()const (- // RouteHealth keeps answering while CRL or OCSP refuses, so khaos can show- // it broke one endpoint rather than fell over.+ // RouteCRL, RouteOCSP and RouteHealth are the authority's HTTP surface.+ // Health keeps answering while CRL or OCSP refuses, so khaos can show it+ // broke one endpoint rather than fell over.RouteCRL = "/crl"RouteOCSP = "/ocsp"RouteHealth = "/healthz"- // Read per request, because CASwap replaces the anchor at arm time.+ // RouteRoot is read per request, because CASwap replaces the anchor at arm+ // time.RouteRoot = "/root")diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.goindex 6cb5b9ff..34017ccd 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/defect.go@@ -26,8 +26,9 @@ func (a *Authority) build(trap Trap) (*Chain, error) {return nil, err}- // EVERY chain staples, not just the stapling traps, or StapleAbsent would- // serve exactly what the baseline serves and the fault would be inert.+ // The BASELINE staples, or StapleAbsent would serve exactly what the+ // baseline serves and the fault would be inert. staple decides per kind,+ // and four of them deliberately staple nothing.if chain, err = a.staple(trap, chain, now); err != nil {return nil, err}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.goindex f4bfe48a..744a1287 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/mutual.go@@ -12,7 +12,8 @@ import ()const (- // khaos is the CA for both ends, the only way it can make this wrong.+ // RouteIdentity issues the target's client certificate. khaos is the CA for+ // both ends, which is the only way it can make this wrong.RouteIdentity = "/identity"nameClient = "khaos range client"diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.goindex 7d1f251e..12a42c0f 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/observe.go@@ -57,8 +57,10 @@ const ()// Observe confirms khaos's own fault landed by reading back what the authority-// serves. Every branch asserts the served material carries the defect AND that-// an HONEST chain does not, so an unarmed authority cannot confirm a trap.+// serves, never the trap record. Every branch asserts the served material+// carries the defect, and the branches whose fault is a DEVIATION also require+// an honest chain not to. An unarmed authority confirms nothing either way: it+// builds no trapped material, so the defect assertion alone fails on it.func (a *Authority) Observe(ctx context.Context,expected Kind,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.goindex 9286c924..88c5d442 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/routes.go@@ -56,8 +56,10 @@ func (a *Authority) serveHealth(w http.ResponseWriter, _ *http.Request) {_, _ = io.WriteString(w, healthBody)}-// Both handlers serve what the ARMED CHAIN carries and read no trap, which-// keeps an authority that armed nothing serving honest material.+// Both handlers serve what the ARMED CHAIN carries and read no trap, so they+// cannot invent a fault the chain does not have. With nothing ever armed there+// is no chain and both answer 503, unlike getCertificate, which falls back to+// building an honest one.func (a *Authority) serveCRL(w http.ResponseWriter, r *http.Request) {a.countCRL(r)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.goindex 1b337c08..af452e8d 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/server.go@@ -105,7 +105,9 @@ func (a *Authority) Listen(addr string) error {return nil}-// Resolved per handshake, so arming takes effect on the next connection.+// ListenTLS binds the endpoint where khaos plays the dependency. The+// certificate is resolved per handshake rather than fixed at bind time, so+// arming takes effect on the next connection.func (a *Authority) ListenTLS(addr string) error {a.listener.mu.Lock()defer a.listener.mu.Unlock()diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.goindex d7a2274b..edde93cc 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap.go@@ -136,7 +136,7 @@ const (const (errNeedsDelay = "%w: %s has no magnitude, and a window of zero is indistinguishable from no fault at all"errNeedsHost = "%w: %s has to name the host its certificate is served for"- errBadBits = "%w: %s needs an RSA size below %d bits to be a weak key at all, got %d"+ errBadBits = "%w: %s needs an RSA size of at least %d bits, which is the smallest crypto/rsa will generate, and below %d to be a weak key at all, got %d"errBadDays = "%w: %s needs a lifetime longer than %d days to exceed anything, got %d"errUnknown = "%w: %q (known traps: %s)"trapSep = ", "@@ -176,11 +176,12 @@ func (t Trap) Validate() error {}case WeakKey:- if t.Bits <= 0 || t.Bits >= StrongBits {+ if t.Bits < MinimumBits || t.Bits >= StrongBits {return fmt.Errorf(errBadBits,ErrInvalidTrap,t.Kind,+ MinimumBits,StrongBits,t.Bits,)diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap_test.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap_test.gonew file mode 100644index 00000000..1f79bb95--- /dev/null+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/pki/trap_test.go@@ -0,0 +1,118 @@+// ©AngelaMos | 2026+// trap_test.go++package pki++import (+ "crypto/rand"+ "crypto/rsa"+ "errors"+ "strconv"+ "strings"+ "testing"+)++func TestWeakKeyRefusesASizeCryptoRSAWillNotGenerate(t *testing.T) {+ cases := []struct {+ bits int+ accept bool+ }{+ {0, false},+ {512, false},+ {MinimumBits - 1, false},+ {MinimumBits, true},+ {DefaultWeakBits, true},+ {StrongBits - 1, true},+ {StrongBits, false},+ {StrongBits * 2, false},+ }++ for _, c := range cases {+ t.Run(strconv.Itoa(c.bits), func(t *testing.T) {+ // Host is set on EVERY case, including the refused ones. Validate+ // also refuses a missing host, so a trap without one is rejected+ // either way and the bits check would be alibied by it.+ err := Trap{+ Kind: WeakKey,+ Bits: c.bits,+ Host: DefaultHost,+ }.Validate()++ if c.accept && err != nil {+ t.Fatalf("%d bits was refused: %v", c.bits, err)+ }++ if !c.accept {+ if err == nil {+ t.Fatalf("%d bits was accepted", c.bits)+ }++ if !errors.Is(err, ErrInvalidTrap) {+ t.Fatalf(+ "%d bits refused without ErrInvalidTrap: %v",+ c.bits,+ err,+ )+ }+ }+ })+ }+}++// The differential that keeps MinimumBits honest. Validate restating a number+// proves nothing; what matters is that crypto/rsa agrees, so every size+// Validate ACCEPTS has to generate and every size it refuses for being too+// small has to fail. If Go moves its floor, this fails here rather than at arm+// time in front of an operator.+func TestValidateAgreesWithCryptoRSAAboutTheFloor(t *testing.T) {+ generates := func(bits int) bool {+ _, err := rsa.GenerateKey(rand.Reader, bits)++ return err == nil+ }++ if !generates(MinimumBits) {+ t.Fatalf(+ "MinimumBits=%d is above crypto/rsa's floor, so the weakest "++ "key khaos advertises cannot be served",+ MinimumBits,+ )+ }++ if generates(MinimumBits - 1) {+ t.Fatalf(+ "crypto/rsa generates %d bits, so MinimumBits=%d refuses a "++ "size khaos could actually serve",+ MinimumBits-1,+ MinimumBits,+ )+ }++ accepted := Trap{+ Kind: WeakKey,+ Bits: MinimumBits,+ Host: DefaultHost,+ }.Validate()+ if accepted != nil {+ t.Fatalf("Validate refuses the floor it defines: %v", accepted)+ }+}++func TestWeakKeyRefusalNamesBothBounds(t *testing.T) {+ err := Trap{Kind: WeakKey, Bits: 512, Host: DefaultHost}.Validate()+ if err == nil {+ t.Fatal("512 bits was accepted")+ }++ message := err.Error()++ for _, want := range []string{+ strconv.Itoa(MinimumBits),+ strconv.Itoa(StrongBits),+ "512",+ } {+ if !strings.Contains(message, want) {+ t.Fatalf("refusal does not name %q: %s", want, message)+ }+ }+}diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.goindex c766b208..ea05c8d2 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/rangelab/rangelab.go@@ -778,8 +778,9 @@ func (l Lab) TLSProtectedURL() string {return l.TLSGatewayURL() + protectedPath}-// AuthorityEndpoint binds on the DEFAULT bridge's gateway, since the range-// network's own gateway and loopback are both unreachable from a container.+// AuthorityEndpoint binds on the DEFAULT bridge's gateway, since a listener on+// the range network's own gateway is refused from a container on it, and a+// container's loopback is its own rather than the host's.func (l Lab) AuthorityEndpoint(ctx context.Context,reader PortReader,diff --git a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.goindex 47a62ca0..9a5984c4 100644--- a/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go+++ b/PROJECTS/intermediate/chaos-engineering-tool/internal/verifier/verifier.go@@ -257,7 +257,7 @@ func (v *Verifier) validate(token idp.Token) Decision {}}- // RFC 7515 registers `none` as "no signature or MAC performed".+ // RFC 7518 registers `none` as "No digital signature or MAC performed".if alg == string(idp.None) {return v.claims(token,