|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/hmac" |
| 5 | + "crypto/sha256" |
| 6 | + "crypto/sha512" |
| 7 | + _ "embed" |
| 8 | + "encoding/base64" |
| 9 | + "encoding/json" |
| 10 | + "hash" |
| 11 | + "net/http" |
| 12 | + "runtime" |
| 13 | + "strings" |
| 14 | + "sync" |
| 15 | + "sync/atomic" |
| 16 | + |
| 17 | + "github.com/gin-gonic/gin" |
| 18 | +) |
| 19 | + |
| 20 | +// defaultJWTSecrets is the bundled common-secret wordlist used by the JWT |
| 21 | +// brute-force endpoint when the caller does not opt out. It is embedded so the |
| 22 | +// feature works without depending on the external Wordlists submodule. |
| 23 | +// |
| 24 | +//go:embed jwt_secrets.txt |
| 25 | +var defaultJWTSecrets string |
| 26 | + |
| 27 | +// maxJWTCandidates caps how many secrets a single brute request will try, so a |
| 28 | +// huge pasted wordlist can't pin the CPU indefinitely. |
| 29 | +const maxJWTCandidates = 2_000_000 |
| 30 | + |
| 31 | +type jwtBruteRequest struct { |
| 32 | + Token string `json:"token"` |
| 33 | + // Secrets is an optional caller-supplied list (newline- or comma-separated) |
| 34 | + // tried in addition to (or instead of) the bundled default list. |
| 35 | + Secrets string `json:"secrets"` |
| 36 | + // UseDefault toggles the bundled wordlist. Defaults to true when omitted. |
| 37 | + UseDefault *bool `json:"use_default"` |
| 38 | +} |
| 39 | + |
| 40 | +// apiJWTBrute attempts to recover the HMAC secret of a pasted JWT by trying a |
| 41 | +// wordlist of candidate secrets. Only HS256/HS384/HS512 (symmetric HMAC) tokens |
| 42 | +// can be cracked this way — asymmetric algorithms (RS*/ES*/PS*/EdDSA) are |
| 43 | +// rejected with a clear message. Cracking happens in parallel across CPU cores. |
| 44 | +func apiJWTBrute(c *gin.Context) { |
| 45 | + // Cap the request body so a giant pasted wordlist can't exhaust memory. |
| 46 | + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<20) // 16 MiB |
| 47 | + var req jwtBruteRequest |
| 48 | + if err := c.ShouldBindJSON(&req); err != nil { |
| 49 | + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"}) |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + token := strings.TrimSpace(req.Token) |
| 54 | + parts := strings.Split(token, ".") |
| 55 | + if len(parts) != 3 || parts[0] == "" || parts[1] == "" || parts[2] == "" { |
| 56 | + c.JSON(http.StatusBadRequest, gin.H{"error": "not a valid JWT (expected header.payload.signature)"}) |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + headerJSON, err := base64.RawURLEncoding.DecodeString(parts[0]) |
| 61 | + if err != nil { |
| 62 | + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JWT header encoding"}) |
| 63 | + return |
| 64 | + } |
| 65 | + var header struct { |
| 66 | + Alg string `json:"alg"` |
| 67 | + } |
| 68 | + if err := json.Unmarshal(headerJSON, &header); err != nil { |
| 69 | + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JWT header JSON"}) |
| 70 | + return |
| 71 | + } |
| 72 | + |
| 73 | + alg := strings.ToUpper(strings.TrimSpace(header.Alg)) |
| 74 | + var newHash func() hash.Hash |
| 75 | + switch alg { |
| 76 | + case "HS256": |
| 77 | + newHash = sha256.New |
| 78 | + case "HS384": |
| 79 | + newHash = sha512.New384 |
| 80 | + case "HS512": |
| 81 | + newHash = sha512.New |
| 82 | + default: |
| 83 | + c.JSON(http.StatusOK, gin.H{ |
| 84 | + "found": false, |
| 85 | + "alg": header.Alg, |
| 86 | + "error": "only HMAC algorithms (HS256/HS384/HS512) can be brute-forced; this token uses \"" + header.Alg + "\"", |
| 87 | + }) |
| 88 | + return |
| 89 | + } |
| 90 | + |
| 91 | + wantSig, err := base64.RawURLEncoding.DecodeString(parts[2]) |
| 92 | + if err != nil { |
| 93 | + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JWT signature encoding"}) |
| 94 | + return |
| 95 | + } |
| 96 | + signingInput := []byte(parts[0] + "." + parts[1]) |
| 97 | + |
| 98 | + candidates := buildJWTSecretCandidates(req) |
| 99 | + if len(candidates) > maxJWTCandidates { |
| 100 | + candidates = candidates[:maxJWTCandidates] |
| 101 | + } |
| 102 | + |
| 103 | + found, secret, tried := bruteForceJWTSecret(signingInput, wantSig, newHash, candidates) |
| 104 | + |
| 105 | + resp := gin.H{"alg": header.Alg, "tried": tried, "found": found} |
| 106 | + if found { |
| 107 | + resp["secret"] = secret |
| 108 | + } |
| 109 | + c.JSON(http.StatusOK, resp) |
| 110 | +} |
| 111 | + |
| 112 | +// buildJWTSecretCandidates merges the bundled wordlist (unless disabled) with any |
| 113 | +// caller-supplied secrets, de-duplicating and always including the empty secret. |
| 114 | +func buildJWTSecretCandidates(req jwtBruteRequest) []string { |
| 115 | + seen := make(map[string]struct{}) |
| 116 | + out := make([]string, 0, 512) |
| 117 | + add := func(s string) { |
| 118 | + if _, ok := seen[s]; ok { |
| 119 | + return |
| 120 | + } |
| 121 | + seen[s] = struct{}{} |
| 122 | + out = append(out, s) |
| 123 | + } |
| 124 | + |
| 125 | + useDefault := req.UseDefault == nil || *req.UseDefault |
| 126 | + if useDefault { |
| 127 | + for _, line := range strings.Split(defaultJWTSecrets, "\n") { |
| 128 | + t := strings.TrimSpace(strings.TrimRight(line, "\r")) |
| 129 | + if t == "" || strings.HasPrefix(t, "#") { |
| 130 | + continue |
| 131 | + } |
| 132 | + add(t) |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + if strings.TrimSpace(req.Secrets) != "" { |
| 137 | + normalized := strings.NewReplacer(",", "\n").Replace(req.Secrets) |
| 138 | + for _, line := range strings.Split(normalized, "\n") { |
| 139 | + if t := strings.TrimSpace(line); t != "" { |
| 140 | + add(t) |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + add("") // empty-key check (CVE-2018-1000531 class) |
| 146 | + return out |
| 147 | +} |
| 148 | + |
| 149 | +// bruteForceJWTSecret recomputes the HMAC signature for each candidate secret in |
| 150 | +// parallel and returns the first match. Workers always drain the job channel |
| 151 | +// (skipping work once a match is found) so the producer can never deadlock. |
| 152 | +func bruteForceJWTSecret(signingInput, wantSig []byte, newHash func() hash.Hash, candidates []string) (bool, string, int) { |
| 153 | + workers := runtime.NumCPU() |
| 154 | + if workers < 2 { |
| 155 | + workers = 2 |
| 156 | + } |
| 157 | + |
| 158 | + jobs := make(chan string, 2048) |
| 159 | + var found atomic.Bool |
| 160 | + var tried atomic.Int64 |
| 161 | + var secret atomic.Value |
| 162 | + var wg sync.WaitGroup |
| 163 | + |
| 164 | + for i := 0; i < workers; i++ { |
| 165 | + wg.Add(1) |
| 166 | + go func() { |
| 167 | + defer wg.Done() |
| 168 | + for cand := range jobs { |
| 169 | + if found.Load() { |
| 170 | + continue // drain remaining jobs without hashing |
| 171 | + } |
| 172 | + tried.Add(1) |
| 173 | + mac := hmac.New(newHash, []byte(cand)) |
| 174 | + mac.Write(signingInput) |
| 175 | + if hmac.Equal(mac.Sum(nil), wantSig) { |
| 176 | + if !found.Swap(true) { |
| 177 | + secret.Store(cand) |
| 178 | + } |
| 179 | + } |
| 180 | + } |
| 181 | + }() |
| 182 | + } |
| 183 | + |
| 184 | + for _, cand := range candidates { |
| 185 | + if found.Load() { |
| 186 | + break |
| 187 | + } |
| 188 | + jobs <- cand |
| 189 | + } |
| 190 | + close(jobs) |
| 191 | + wg.Wait() |
| 192 | + |
| 193 | + s, _ := secret.Load().(string) |
| 194 | + return found.Load(), s, int(tried.Load()) |
| 195 | +} |
0 commit comments