More languages
How to solve AWS WAF CAPTCHA in Go
AWS WAF replies to a challenged request with a puzzle page instead of content. This guide wraps a Go http.Client so it notices the puzzle, gets an aws-waf-token cookie from the API at $1.40 per 1,000, stores it in a cookie jar and retries.
The flow in Go terms
A challenged request comes back with a small HTML page, usually status 405, that defines gokuProps with key, iv and context. A browser would run the challenge and receive the aws-waf-token cookie. Your Go program gets that cookie from the API instead, puts it in the client's cookiejar, and repeats the request. Every later request through the same client carries the cookie automatically until it expires. The AWS WAF CAPTCHA entry describes the check in more detail.
Everything here uses the standard library: net/http, net/http/cookiejar, encoding/json and regexp. Go 1.21 or newer is assumed.
Recognize the puzzle response
Check the status and look for gokuProps in the body. Some deployments use other statuses for the challenge, so the body test is the reliable one. The guide on finding AWS WAF parameters lists further markers.
package wafjar
import (
"encoding/json"
"regexp"
)
var gokuRe = regexp.MustCompile(`(?s)gokuProps\s*=\s*(\{.*?\})\s*;`)
type goku struct {
Key string `json:"key"`
Iv string `json:"iv"`
Context string `json:"context"`
}
// parseGoku returns the challenge values, or ok=false when the page is not a WAF puzzle.
func parseGoku(status int, body []byte) (g goku, ok bool) {
m := gokuRe.FindSubmatch(body)
if m == nil {
return g, false
}
_ = json.Unmarshal(m[1], &g) // values are optional for the task
return g, status == 405 || g.Key != ""
}
If the JSON fails to parse, the function still reports a puzzle when the status is 405, because the task also works with only the page URL.
Ask the API for the cookie
package wafjar
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"time"
)
type apiOut struct {
EID int `json:"errorId"`
ECode string `json:"errorCode"`
TID string `json:"taskId"`
Stat string `json:"status"`
Sol struct{ Cookie string } `json:"solution"`
}
func callAPI(ctx context.Context, key, route string, in map[string]any) (apiOut, error) {
var out apiOut
in["clientKey"] = key
b, _ := json.Marshal(in)
rq, _ := http.NewRequestWithContext(ctx, "POST", "https://gatesolver.com/"+route, bytes.NewReader(b))
rq.Header.Add("content-type", "application/json; charset=utf-8")
rs, err := http.DefaultClient.Do(rq)
if err != nil {
return out, err
}
defer rs.Body.Close()
err = json.NewDecoder(rs.Body).Decode(&out)
if err == nil && out.EID != 0 {
err = errors.New(route + ": " + out.ECode)
}
return out, err
}
func wafCookie(ctx context.Context, key, pageURL string, g goku) (string, error) {
task := map[string]any{"type": "AntiAwsWafTaskProxyLess", "websiteURL": pageURL}
if g.Key != "" {
task["awsKey"], task["awsIv"], task["awsContext"] = g.Key, g.Iv, g.Context
}
payload := map[string]any{"task": task}
opened, err := callAPI(ctx, key, "createTask", payload)
if err != nil {
return "", err
}
for i := 0; i < 40; i++ {
time.Sleep(3 * time.Second)
st, err := callAPI(ctx, key, "getTaskResult", map[string]any{"taskId": opened.TID})
if err != nil {
return "", err
}
if st.Stat == "ready" {
return st.Sol.Cookie, nil
}
if st.Stat == "failed" {
return "", errors.New("waf task failed, not charged")
}
}
return "", errors.New("waf cookie not ready in time")
}
The anonymous struct struct{ Cookie string } on the Sol field relies on encoding/json matching field names case insensitively, so the cookie key fills Cookie without a tag.
Store the cookie in the jar and retry
The wrapper below is what the rest of your program calls. It performs the request, and if the puzzle appears, it solves, writes the cookie into the jar for the request's URL, and sends the request once more.
type Client struct {
HTTP *http.Client // must have a Jar
APIKey string
}
func NewClient(apiKey string) (*Client, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &Client{APIKey: apiKey, HTTP: &http.Client{Jar: jar, Timeout: 30 * time.Second}}, nil
}
func (c *Client) Get(ctx context.Context, target string) ([]byte, int, error) {
for attempt := 0; attempt < 2; attempt++ {
rq, _ := http.NewRequestWithContext(ctx, "GET", target, nil)
rq.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36")
rs, err := c.HTTP.Do(rq)
if err != nil {
return nil, 0, err
}
body, _ := io.ReadAll(rs.Body)
rs.Body.Close()
g, puzzle := parseGoku(rs.StatusCode, body)
if !puzzle || attempt == 1 {
return body, rs.StatusCode, nil
}
val, err := wafCookie(ctx, c.APIKey, target, g)
if err != nil {
return nil, rs.StatusCode, err
}
u, _ := url.Parse(target)
c.HTTP.Jar.SetCookies(u, []*http.Cookie{{Name: "aws-waf-token", Value: val, Path: "/"}})
}
return nil, 0, errors.New("unreachable")
}
Add io, net/url and net/http/cookiejar to the imports. The loop allows exactly one solve per call, so a page that keeps returning the puzzle cannot cause a solve loop. The User-Agent stays identical across both attempts, which matters because the cookie is tied to the visit that earned it.
Using the client
cl, _ := wafjar.NewClient(os.Getenv("GATESOLVER_KEY"))
for _, sku := range []string{"A100", "A101", "A102"} {
page, code, err := cl.Get(ctx, "https://catalog.example.com/item/"+sku)
if err != nil {
log.Printf("%s: %v", sku, err)
continue
}
log.Printf("%s: %d, %d bytes", sku, code, len(page))
}
Usually only the first item triggers a solve. The jar then holds the cookie, and the next items load directly. That makes the cost per page a small fraction of the per solve price.
Proxies and identity
If the client sends traffic through a proxy (Transport: &http.Transport{Proxy: http.ProxyURL(p)}) and the site refuses cookies earned elsewhere, switch to AntiAwsWafTask and pass the same proxy as http://user:pass@host:port. Keep one client per proxy and identity so cookies never cross between them.
When the retry still shows the puzzle
- Compare User-Agents between the first request and the retry; they must match.
- Make sure the cookie was set for the right host.
SetCookiesuses the URL you pass. - Try the proxy task type if your traffic goes through a proxy.
- If the page shows images to pick instead of the plain check, that is AWS WAF Image Classification, a different task.
Why a cookie jar instead of a header
You could add the cookie as a raw Cookie header on each request, but the jar handles details you would otherwise write yourself: it merges the WAF cookie with any session cookies the site sets, scopes it to the right host, and drops it when it expires if the site sends an updated one. When AWS WAF refreshes the token through a Set-Cookie on a later response, the jar picks up the new value automatically, and your code never notices.
One jar per identity is the rule. If your program talks to the same site through several proxies or with several User-Agents, create a separate Client for each, so a cookie earned by one identity is never sent by another.
Concurrency and cost
http.Client and cookiejar.Jar are safe for concurrent use, so many goroutines can share one Client. Be careful at start up, though: if fifty goroutines fire their first request at once, all fifty may see the puzzle and start fifty solves. Guard the solve with a sync.Mutex or singleflight.Group keyed by host, so the first goroutine solves and the others wait and then reuse the cookie from the jar. That turns fifty charges into one.
Testing the detection
Save one real puzzle page from your target to a file and write a table test for parseGoku with it, a normal page and a page with a 405 but no props. Detection is the part most likely to break when the site changes, so a quick test pays off.
Reading the response body safely
The wrapper reads the whole body to look for gokuProps. For HTML pages that is harmless, but if the same client downloads large files, check the Content-Type header first and skip the scan for anything that is not HTML. You can also cap the read with io.LimitReader when scanning, since the puzzle page is small, and stream large bodies directly to their destination instead.
Costs over a long run
With the cookie kept in the jar, a crawl of a few thousand product pages on one site often needs only a handful of solves, one at the start and one each time the cookie expires. Count solves and pages in your metrics; the ratio tells you what each page really costs and warns you early if something forces extra solves, such as an identity mismatch.
Common questions
Why is the AWS WAF response a 405?
AWS WAF commonly answers challenged requests with 405 and a small challenge page. Some setups use other codes, so also look for gokuProps.
Does the cookie work for later requests?
Yes. It stays valid for the same site and identity until it expires, so the jar sends it automatically.
Are awsKey, awsIv and awsContext mandatory?
No. They are optional. The wrapper sends them when the page provides them.
Why allow only one solve per call?
It prevents a loop if the site keeps returning the puzzle, which usually means an identity or proxy mismatch.
Is the http.Client safe to share across goroutines?
Yes. http.Client and cookiejar.Jar are safe for concurrent use.
Keep reading
- AWS WAF solver$1.40 per 1,000 tasks, answers under 3 seconds.
- Find AWS WAF CAPTCHA parametersWhere key, iv and context sit on the AWS WAF puzzle page, and how each value maps to a task field.
- AWS WAF CAPTCHAThe CAPTCHA and Challenge actions in Amazon's web firewall, the aws-waf-token cookie, and the page values a solve can use.
- CookieSmall values a site stores in the client, which carry sessions and the clearance proof issued after a passed challenge.