Skip to content

std.http/std.tls: https_get_response returns -1 for every host (github, example.com, zlib.net); TCP connects, handshake fails #883

Closed

Description

@ehartford

Symptom

use std.http
let r = https_get_response("https://example.com/", 0)
print(f"status={r.status} body_len={r.body.len()}")

→ status=-1 body_len=0 — for github.com, example.com, and zlib.net alike.
curl -sI gets HTTP/2 200 from all three on the same machine at the same
time, so it is not the network.

std.net.tcp_connect("example.com", 443) returns a valid fd, so the failure
is inside std.tls's handshake (lib/std/tls.w:780 tls_handshake), which
returns <0 and tls_connect closes the socket.

Bisect

Identical on every archived seed:

seed result
v0.15.1.5-ddfe55a5 (2026-08-20 morning) -1
cff5156, 7d72cf4, 17b54dc, 4a83a55 -1

So it predates all of today's runtime decl work (#761 tranches), including the
with_fill_random len widening in tls.w (which the bisect clears).

Impact

build/https_fetch.w — the pcre2-reference fetch helper — cannot download
the pcre2 tarball, so a clean out/ cannot run pcre2-migrate → build → test → promote. That blocks re-migrating pcre2 for #880. (zlib-reference uses
plain HTTP and is unaffected.)

Debugging notes

  • lldb line breakpoints in http.w/tls.w don't resolve in a user binary:
    embedded-std code carries <embedded-std>/std/tls.w paths and the handshake
    is inlined into https_get_once. breakpoint set -n tls_handshake does
    stop, but finish on the inlined frame doesn't yield the return value.
  • std.tls exports nothing pub, so a probe can't call tls_connect /
    tls_handshake directly (symbol 'tls_connect' is private).
  • Most likely classes, in order: the server rejecting the ClientHello
    (cipher suite / extension set no longer accepted — TLS 1.2-only client
    against 2026 server configs), a certificate-chain verification path that
    now fails closed, or a record-layer read that misparses a
    HelloRetryRequest / TLS 1.3 ServerHello. The four return -1 sites in
    tls_handshake (tls.w:790, 807, 812, 817) are where to start — a
    temporary eprint of which branch fires, or making the handshake result
    an enum, would localize it in one run.

Activity

  1. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Narrowed: fatal alert 20 (bad_record_mac) on the client's first encrypted record

    Instrumented tls_handshake step-by-step against example.com (TLS 1.2 +
    ECDHE, AES-128-GCM):

    • step 1 ClientHello — OK
    • step 2 recv ServerHello + cert + ECDH params — OK
    • step 3 send ClientKeyExchange + ChangeCipherSpec + Finished — OK
    • step 4 recv server ChangeCipherSpec + Finished — FAILS

    At step 4 the first record back is ct=21 (Alert), level=2 (fatal),
    desc=20 (bad_record_mac). So the server received our encrypted Finished
    and its GCM tag verification failed — our client's record-layer keys or
    AEAD are wrong. This is consistent across every host (example.com, github,
    zlib.net), i.e. it is not a server-version negotiation problem.

    What's ruled in / out

    • The handshake transcript up to the Finished works (ServerHello, cert, ECDH
      point all parse), so the failure is the derived session keys / AEAD, not
      the negotiation.
    • fill_random is fine — a probe shows different non-zero bytes each run, so
      the ephemeral P-256 key is good and the failure is deterministic in the
      crypto, not the RNG.
    • The GCM record framing in tls_send_encrypted (lib/std/tls.w:229) looks
      correct: nonce = client_write_iv(4)+seq(8), AAD = seq(8)+type(1)+0x0303+len(2),
      explicit-nonce ‖ ciphertext ‖ tag(16). So the defect is upstream of the
      framing: p256_ecdh (shared secret), tls_prf_sha256 (master secret / key
      block / verify_data), or the AesGcm primitive itself.

    Why it fails everywhere / has always failed

    There are no crypto vector tests in the suite — only
    behav_tls_module_compiles.w (compiles, never runs). lib/std/crypto/gcm.w
    (AES-GCM), lib/std/crypto/ec.w (P-256), sha256/hmac, and the TLS PRF were
    never validated against known-answer vectors. This is an incomplete feature,
    not a regression (it fails on every archived seed).

    Fix path

    Add known-answer vector tests, in order of self-containedness, to localize the
    broken primitive:

    1. SHA-256 + HMAC-SHA256 (NIST/RFC 4231 vectors)
    2. AES-128-GCM (NIST GCM test vectors) — the tag is what the server rejected
    3. P-256 ECDH (RFC 5903 / NIST CAVP)
    4. TLS 1.2 PRF (known master-secret vectors)

    The first one that fails is the bug. Then the TLS handshake completes and
    build/https_fetch.w can fetch the pcre2 tarball, unblocking #880's pcre2
    half.

  2. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Root cause isolated to P-256 ECDH (by known-answer vectors + logic review)

    Added temporary known-answer self-tests to each crypto primitive (reverted
    after):

    primitive vector result
    SHA-256 "abc" → ba7816bf… PASS
    HMAC-SHA256 RFC 4231 TC1 PASS
    AES-128-GCM NIST zero-key/IV, empty PT → tag 58e2fcce… PASS
    P-256 ECDH RFC 5903 §8.1 couldn't run (embed bug, below)

    And tls_derive_keys (lib/std/tls.w:622) is correct on review: master_secret
    = PRF(premaster, "master secret", client_random‖server_random); key_block =
    PRF(master_secret, "key expansion", server_random‖client_random) — labels,
    seed orders, and the AES-128-GCM key/iv distribution (no MAC keys) all match
    RFC 5246.

    The decisive logic: the alert is bad_record_mac (20), which is a GCM
    tag failure on the client's encrypted Finished — not a rejected
    verify_data (that would be decrypt_error/handshake_failure). A wrong tag with
    a verified-correct GCM primitive means a wrong client_write_key. Walking the
    derivation backward: key_block ← master_secret ← premaster, and the premaster
    is exactly the P-256 ECDH shared secret (p256_ecdh, lib/std/crypto/ec.w).
    Since every other input is verified correct, the P-256 shared secret is
    wrong
    .

    Next step

    Vector-test p256_compute_public (RFC 5903: private i → known giX/giY) and
    p256_ecdh (known shared xZ). The first that fails localizes the bug in
    ec.w (Jacobian point ops / i31 Montgomery math in bigint.w). Then the
    handshake completes and pcre2-reference can fetch.

    Side finding — a separate embed bug (filed to unblock the P-256 test)

    A program that DIRECTLY use std.crypto.ec makes the stage1 compiler fail to
    parse its own embedded std/string.w:235:

    $ echo 'use std.crypto.ec
    fn main: print("x")' > p.w
    $ with run p.w
    error: expected identifier  --> <embedded-std>/std/string.w:235:1
    

    Transitive use (via std.tls) is fine — the TLS handshake runs. Only a direct
    import trips it. This blocks writing a standalone P-256 vector test, so it
    needs fixing first (or the test lives inside a module already in the embed set).

  3. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Correction on the "embed bug"

    The <embedded-std>/std/string.w:235 parse error I noted does not
    reproduce on the clean installed compiler — use std.crypto.ec + fn main
    runs fine at d3c1df7. It was an artifact of my temporary self-test edits
    across multiple embedded crypto modules corrupting the embed snapshot for that
    build, not a standalone bug. Disregard it; a P-256 vector test works on a clean
    base (running now to confirm the ec.w defect empirically).

  4. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    The embed error is a rebuild artifact — P-256 stands by elimination

    Rebuilding :dev with any edit to ec.w (even one added pub fn)
    produces a stage1 whose embedded std/string.w fails to parse — but the clean
    compiler and a clean with build are fine, so it is an incremental
    embedded-std regeneration fragility (likely a size/boundary truncation),
    triggered only by the :dev rebuild path with a modified crypto module. It
    blocks running the P-256 KAT via a :dev stage1, but is not itself the TLS
    bug.

    Conclusion for #883: P-256 ECDH (p256_ecdh / p256_compute_public in
    lib/std/crypto/ec.w, over the i31 bigint in bigint.w) is the culprit, by
    elimination — SHA-256, HMAC-SHA256, AES-128-GCM all pass KATs; tls_derive_keys
    is correct on review; and bad_record_mac is a GCM-tag failure that walks back
    to the ECDH shared secret as the only unverified input. To confirm at the
    exact line
    , run the RFC 5903 P-256 vectors via a full with build (not
    :dev) or a test module already in the embed set, then step the Jacobian /
    Montgomery math where it diverges.

  5. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Correction: the "embed bug" was my own mistake, not a real bug

    The <embedded-std>/std/string.w:235 error I reported was caused by my
    temporary self-test using var pub: [u8; 65] — pub is a keyword, so parsing
    the embedded ec.w as code choked on it, and the error cascaded to the next
    module (string.w). There is no embed bug. Renamed the variable and the P-256
    vector test now runs; result below.

  6. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Major correction: it is NOT the crypto — all primitives pass KATs

    I was wrong to blame P-256 "by elimination" without testing it. I added
    temporary known-answer self-tests for every primitive and ran them
    (reverted after):

    component vector result
    SHA-256 "abc" PASS
    HMAC-SHA256 RFC 4231 TC1 PASS
    AES-128-GCM NIST zero-key/IV PASS
    P-256 compute_public RFC 5903 §8.1 PASS
    P-256 ECDH RFC 5903 §8.1 cross-check → shared Z PASS
    TLS 1.2 PRF (SHA-256) draft-ietf-tls-rfc4346-bis KAT PASS

    So the defect is in the TLS glue, not the math. bad_record_mac (a GCM tag
    failure on the client's first encrypted record) means a wrong
    client_write_key or a wrong record (nonce/AAD/ciphertext). I then read every
    readable link and each is correct:

    • client_random is generated into conn and the ClientHello is built from
      conn (sent == stored);
    • server_random is copied from ServerHello offset 2, 32 bytes;
    • the ServerKeyExchange ECDH point is read as 65 bytes from body offset 4
      (after curve_type(1)+named_curve(2)+len(1));
    • tls_derive_keys uses the right PRF labels and seed orders, and extracts
      client_write_key = key_block[0..16], client_write_iv = key_block[32..36];
    • tls_send_encrypted builds nonce = iv(4)+seq(8), AAD =
      seq(8)+type(1)+0x0303+len(2), record = explicit_nonce(8)+ct+tag(16).

    All standard. So the bug is a subtle glue mismatch that doesn't show on a
    read — the next step is to dump the actual client_write_key / nonce / AAD /
    plaintext from a live handshake and diff against a reference (openssl/python)
    driving the same ClientHello+ServerHello, or capture the wire bytes and replay.

    Net: #883 is much smaller than "TLS is broken" — the crypto is solid; it is one
    record-layer plumbing mismatch. (The earlier "embed bug" note was also mine —
    a var pub keyword clash in a temp test, not a real bug.)

  7. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Localized to one function: ghash_mult in lib/std/crypto/gcm.w

    The empty-plaintext AES-GCM KAT I ran earlier only computed E(j0) (GHASH
    state stays 0 when aad_len=ct_len=0), so it never exercised the GF multiply.
    Testing with real plaintext (NIST GCM case 2, 16-byte zero PT) fails:

    ciphertext = 0388dace60b6a392f328c2b971b2fe78   ✓ (exact — AES-CTR is correct)
    tag        = 777d5ee149e44a6ef7bb62ca16b8b0ff   ✗ (expected ab6e47d42cec13bdf53a67b21257bddf)
    

    Same wrong tag at -O0 and -O1, so it is a logic bug, not a miscompile.
    Drilling in with dumps:

    • H = E_K(0) = 66e94bd4ef8a2c3b884cfa59ca342b2e — correct.
    • GHASH state after the one ciphertext block (C_1 ⊗ H) = 4c11e03b83941c2b962bee35d04dae11.
    • j0 / E(j0) correct (the empty KAT passed).

    So AES, the key schedule, H, j0, the counter, and the record framing are all
    correct. The tag is wrong purely because the GHASH GF(2^128) multiply
    (ghash_mult, gcm.w:18) produces the wrong product for dense inputs. It reads
    as a textbook NIST right-shift multiply (process X MSB-first, shift V right,
    reduce with 0xe1 on carry) and gives correct results for sparse inputs
    (identity 0x80…, generator 0x40…), so the defect only shows once the
    reduction fires across many set bits — the case real data hits.

    This is the whole TLS bug

    bad_record_mac = the server rejecting the client's Finished because its GCM
    tag is wrong, exactly this. Fixing ghash_mult (or replacing it with a
    verified reduction) makes the handshake complete and unblocks pcre2 for #880.

    Next: cross-check ghash_mult(C_1, H) against a reference to get the correct
    C_1 ⊗ H, then step the reduction. A permanent AES-GCM-with-plaintext KAT (and
    the SHA/HMAC/P-256/PRF ones) should be added so crypto can't regress silently —
    today there are none.

  8. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Root cause — two bugs, both on the TLS record path

    The handshake never returned -1 at the network layer; it produced a
    bad_record_mac because AES-GCM tag verification failed on every record.
    Fixing that unmasked a second crash further along. Both are now fixed.

    1. GHASH GF(2^128) multiply produced wrong tags (lib/std/crypto/gcm.w)

    The right-shift loop bound let cur = v[j], overwrote v[j], then read
    cur & 1 for the shift carry. let cur = v[j] binds a live view into
    the array element (not a snapshot), so after the write cur reflected the
    shifted byte and the carry came from bit 1 of the original instead of bit 0.
    GHASH was correct for sparse inputs and wrong for dense ones — so every tag
    over real data was wrong. Reduced and filed as #887 (D27 element-view,
    cross-ref #740). Fixed by binding the cast result (let old = v[j] as u32),
    which materializes a snapshot. Verified against NIST SP 800-38D test case 2
    (ciphertext + tag exact).

    2. recv loop crashed on a punned str (lib/std/http.w)

    https_get_once built a str by writing {ptr,len} through &raw mut chunk
    into a stack buffer, then passed it to push_str. At -O1 the offset-0
    pointer store is dropped across the call boundary while offset-8 (len) is
    kept, so push_str dereferenced a stale pointer and crashed. This path had
    never run before, because the handshake always failed here first. Reduced
    and filed as #888 (&raw mut store-dropped miscompile). Fixed by dropping
    the punning and appending bytes directly.

    Verification

    • aes128_gcm_kat() (NIST case 2) passes; new behavior test
      test/behavior/behav_crypto_kats.w guards it (GCM + SHA-256).
    • End-to-end: https_get_response("https://example.com/", 0) → status=200,
      body 559 bytes.

    Fixed in 4479d32b (gcm) and f4103fa0 (http). This unblocks the pcre2
    tarball fetch for #880. Closing once the batch battery + reseed confirm green.

  9. ehartford commented on Aug 23, 2026

    @ehartford
    ContributorAuthor

    Fixed and reseeded. HTTPS from the installed compiler now returns 200 (github.com, the pcre2 tarball host). Root cause: two bugs on the TLS record path — the GHASH element-view aliasing (#887, fixed in 4479d32) and the &raw mut recv-loop str-punning (#888, fixed in f4103fa). Batch battery green (build/fixpoint/test/audit), reseeded. Unblocks the pcre2 fetch for #880.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions