247CTF // Mechanical Turk - 100 CAPTCHAs in 30 Seconds

247CTF // Mechanical Turk - 100 CAPTCHAs in 30 Seconds

Category: automation engineering, OCR, protocol optimization, rate-limit games

Stack: PHP sessions, GD/PNG CAPTCHA, token-bucket throttle at the LB


STEPS
  1. Characterize the CAPTCHA: two integers joined by one +, noise drawn in a single flat gray - threshold one step below it for exact denoise
  2. Bootstrap a classifier from rendered font templates; submit reads; keep only server-accepted images as labeled ground truth
  3. Build a KNN glyph bank from the verified samples (trim to <=25/char, float32, two-stage chamfer) - ~4ms per image
  4. Fire POST and GET on two separate connections in the same instant - the requests overlap server-side (~180ms vs ~450ms serialized)
  5. Recover from race losses by re-reading the paired image - a failed POST never rotates the code
  6. Rotate connections when the 3-cycle average degrades, and sprint within one 30s window

1. The contract

Solve our custom CAPTCHA addition equation 100 times in 30 seconds.

Each request pair (fetch image, submit answer) is session-bound; wrong answers don't

reset the counter; the window is strict. The instance sits behind a platform LB with a

per-IP token bucket (~180 requests per fresh instance+IP, refilling ~1/s) plus

per-connection shaping.

This writeup is the engineering log. The CAPTCHA itself was the easy third.

2. Characterizing the CAPTCHA

Fetch a few dozen images and look at them before touching OCR:

  • The equation is exactly two integers joined by one + - e.g. 30570+15247.

Every early misread that produced "many small numbers" was noise fragments being

read as digits.

  • The noise is drawn in a single flat gray (uniform RGB 140). There is no gradient,

no dither. A threshold at <140 deletes all of it without touching glyph strokes.

That single observation kills the entire "OCR problem": tesseract on noisy input was

~10% accurate; threshold-then-segment is ~97%.

Segmentation

Column-projection on the binarized image: find runs of non-empty columns, each run is

a glyph. Fragments occasionally split a digit (a light noise line crossing a stroke

survives at some thresholds); this is handled by classification voting, not by

smarter segmentation.

Classification without training data

Render candidate templates locally (DejaVu Serif, Liberation Serif at 24px, normalized

to a fixed height with aspect preserved) and score each glyph by **symmetric chamfer

distance** - the mean distance from glyph points to template points plus the reverse.

Occlusion-tolerant, scale-tolerant, and ~free of dependencies.

But rendered fonts only correlate ~90% with the actual CAPTCHA face. The fix is the

best training-data trick in the whole challenge: **the server labels your data for

you.**

Server-verified ground truth

  1. 1. Fetch an image, OCR it with the template classifier, submit the answer.
  2. 2. If the server says correct, your *parse was right* - store every glyph crop from

that image in a labeled bank keyed by character.

  1. 3. After a few hundred accepted images the bank covers all 11 character classes

with dozens of verified examples each.

Now the classifier is k-nearest-neighbour against the real font. Trim the bank to

<=25 examples per class (round-robin), store the distance transforms as float32, and

score in two stages: cheap forward-chamfer against everything, expensive symmetric

score only for the top-10. ~4ms per image.

Voting across binarization thresholds (100/120/140/160) for ambiguous glyphs pushes

first-shot accuracy to ~97%, and the retry channel below absorbs the rest.

3. The protocol: why two connections change everything

Naive loop:


GET /mturk.php      -> img N

POST / (answer N)   -> verdict

GET /mturk.php      -> img N+1

...

Two serialized round trips per solve. At ~450ms per cycle, 100 solves needs 45s -

already over the 30s window before any other optimization.

The key measurement: pipelined GETs run concurrently on the server (8 back-to-back

image fetches complete in ~90ms each), but a POST and a GET on the *same* connection

serialize behind PHP's session file lock - POST holds the lock for its whole lifetime.

So: **two connections. POST the answer on A, GET the next image on B, in the same

instant.**


A: POST /  (answer N)     B: GET /mturk.php  (img N+1)

Sent together, the server processes them concurrently - ~180ms per cycle instead of

450ms. 100 solves in ~18s.

The race, and losing it gracefully

Same-instant arrival means the GET occasionally wins the session lock first and

*rotates the CAPTCHA before your POST is checked*. Your answer - computed for the

previous image - is then "Invalid". Two properties turn this from a 13% failure rate

into a non-event:

  1. 1. A failed POST does not rotate the session's CAPTCHA. The check happens, fails,

the stored code stays whatever it was.

  1. 2. When the race is lost, the image riding back on connection B **is the code the

session now holds.** Re-OCR it and POST again - no extra fetch needed.

Expected cycle time with a 13% race-loss rate: ~200ms average. Comfortably inside the

window.

4. The throttle: token buckets, not villains

Two distinct layers emerged from measurement:

  • Per-connection shaping: a connection that has pushed ~60+ requests starts

responding at 2x, then 3x slower. Fresh connections are fast again - *if* the IP

bucket has tokens.

  • Per-IP token bucket: ~180 requests of burst allowance per fresh instance+IP,

refilling ~1/s. Draining it makes even fresh connections slow, and sustained abuse

eventually makes new TCP handshakes time out (a self-inflicted IP ban lasting tens

of minutes).

The winning discipline is therefore not "hammer harder" but budget management:

  • One quiet calibration pass (~250 requests), then rest ~60s to refill.
  • One ~25s sprint (~200 requests) starting with a full bucket.
  • The 30s window and the bucket are both consumables - spend each exactly once.
  • If the first sprint misses, a fresh instance URL grants a fresh bucket for your IP.

(The counter is per-session; nothing carries over.)

A note on geography: the instances are US-hosted. A transcontinental client eats

100ms+ of RTT per round trip - the same-instant trick hides most of it, but the

server's fast phase must still carry you. Running the sprint from a US egress turns

~65/window into ~100/window on identical code.

5. Error economics

Retries are not free - each costs ~170ms - so the accuracy math matters:

first-shot accuracyexpected solves per 100 attemptstime at 200ms/cycle
85%117 needed23s - fits, barely
90%11122s
97% (KNN + voting)~10421s
99% (more bank data)~10220.5s

The 97% configuration was sufficient; each missed solve triggers the cheap retry,

not a cycle restart.

6. Full architecture (pseudocode)


calibrate():

    bootstrap_classifier = chamfer(font_templates)

    bank = server_verified_labeled_glyphs(bootstrap_classifier)   # ~300 samples

    knn = build_two_stage_chamfer_bank(bank)                       # float32, <=25/char



solve_loop(session, deadline):

    img = get_image(conn_b)

    while now < deadline:

        cand = knn_read(img)                    # 4ms, thresholds vote

        if not well_formed(cand):               # ^\d{1,7}\+\d{1,7}$

            img = get_image(conn_a); continue   # don't spend a POST on garbage

        body = urlencode(answer(cand))

        send(conn_a, POST /, body)

        send(conn_b, GET /mturk.php)            # same instant, no sleep

        verdict, img = read_both()

        if flag in verdict: return flag

        if verdict == ok:

            continue

        # race lost or OCR miss: img IS the current captcha, retry with fresh read

        cands2 = knn_read(img, extra_thresholds)

        for alt in cands2[1:3]:

            if post(alt) == ok: break

Connection rotation: if the trailing 3-cycle average exceeds ~450ms, close both

sockets and open a fresh pair (costs ~100ms; escapes per-connection shaping).

7. What transfers

  • Vote, don't trust. Single measurements - of anything - are fiction. Threshold

votes for OCR, majority votes for timing oracles, median-of-N for latency.

  • Measure the bot/LB like an API. Concurrency of pipelined GETs, lock behavior,

bucket size, refill rate - all measurable with a dozen requests, all decisive for

design.

  • Same-instant pairing of dependent requests is a general pattern whenever a

session lock serializes server-side work you need overlapped.

  • Failed operations are state. "Wrong answer doesn't rotate the code" is an

accidental feature that makes the race recoverable. Always catalog what a failure

leaves behind.

  • Rate limits are part of the protocol. Treat them as a budget to be spent

deliberately, not as noise to be overpowered - overpowering them is how IPs die.

Comments

Popular Posts