Skip to content

Correct exceptional short Weierstrass point arithmetic - #386

Draft
epard0 wants to merge 1 commit into
tlsfuzzer:masterfrom
epard0:fix-exceptional-point-arithmetic
Draft

epard0 wants to merge 1 commit into
tlsfuzzer:masterfrom
epard0:fix-exceptional-point-arithmetic

Conversation

@epard0

@epard0 epard0 commented Nov 21, 2026

Copy link
Copy Markdown

Affine doubling incorrectly returns infinity for a horizontal tangent. On y²=x³+1 over GF(17), doubling (0,1) should give (0,16). Jacobian multiplication also treats every zero-Y point as infinity, losing finite order-two points. Equivalent projective coordinates can take the wrong addition branch, and affine negation can return a noncanonical coordinate.

This patch handles vertical tangents before inversion, applies scalar parity to finite order-two points, reduces coordinate differences before testing for equal Jacobian points, and returns canonical affine negations. It preserves the existing off-curve zero-point compatibility test.

Regression and independent validation

Validated against upstream master 71e3fc7 (still current at submission):

  • Unmodified source: 19 of the 34 new regression cases fail; 15 pass.
  • Patched source: all 430 tests pass across the new regressions and upstream elliptic-curve, Jacobian and number-theory suites on Linux, Hypothesis seed 20261121. Two upstream deprecation warnings remain.
  • SageMath 10.9 small-curve grid: 238,420 products on 175 curve models and 1,834 curve-point pairs, affine and Jacobian representations, every scalar -32 through 32.
  • SageMath 10.9 expanded sampling: 41,914 comparisons across 24 named domains and four larger toy fields, 204 point samples, signed scalar/order boundaries, projective scales, supplied/unspecified orders and precomputation.
  • Both Sage runs: zero mismatches, noncanonical outputs or arithmetic exceptions; loaded arithmetic source verified by SHA-256. Named-domain tuples independently checked against SEC 2 and RFC 5639. These are bounded samples.
  • Standalone PoC: six incorrect outcomes reproduced on the base, all six corrected by the patch.

These are recorded local validation results; GitHub CI is separate. The uploaded source and regression file were byte-compared with the validated local files. Arithmetic module SHA-256: 70bfd96a17e646af484a93d08fbe16df21ba5256358c657f64a19766538d67df.

Impact

Confirmed effects are incorrect arithmetic and false positive/false negative subgroup decisions on the custom 18-point curve. Its finite order-three members are (0,1) and (0,16): the base affine calculation misses both, while the base Jacobian calculation also admits (16,0), an order-two point. Point orders are unspecified in this check.

Applications relying on these low-level paths for custom or cofactor-bearing curves may make incorrect decisions. Source inspection identifies the multiplication-based subgroup test in ecdsa.Public_key.__init__ as a potential propagation path; end-to-end exploitation through that path has not been demonstrated. Deployment impact, practical standard-curve reachability, signature forgery and key recovery remain unverified.

Report, PoC and evidence

The attached bundle includes the full bug report and impact analysis, runnable arithmetic PoC, before/after outputs, patch, source identities, regression receipts, both original Sage harnesses and results, authoritative parameter tuples, and replay instructions. JUnit hostname attributes were removed for publication; test outcomes are unchanged. MANIFEST.json records the published files’ SHA-256 digests.

python-ecdsa-arithmetic-evidence.zip

@mathewOracle mathewOracle left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI hasn't run on this PR yet, so I ran some independent checks.

  • Test suite: on this branch the full suite gives 2045 passed and 33 skipped. black --line-length 79 (22.3.0) and flake8 (6.1.0), the versions pinned in tox.ini, are clean on the changed files.

  • Differential test: I compared Point and PointJacobi against a plain textbook affine group law, for every point on every non-singular curve y^2 = x^3 + ax + b over p in {5, 7, 11, 13, 17, 19}. I covered * for k in -7..7, +, double() and mul_add (small scalars, p <= 11 only), each with and without order= / generator=True. That's about 1.74M comparisons.

    • master: about 40k mismatches. They show up in every operation except Jacobian + and double(), and that includes mul_add, which Public_key.verifies uses.
    • this branch: zero mismatches, apart from the case below.
    • The harness only uses reduced coordinates, so the _add_with_z_1 change for unreduced inputs is covered only by your test, not by this one.
  • Remaining failure: the one failure left is pre-existing and identical on master. PointJacobi(..., order=n, generator=True) * k raises AttributeError: 'Point' object has no attribute 'scale' whenever n is even. _maybe_precompute() keeps doubling, and once a doubling reaches infinity it gets the affine INFINITY back and calls .scale() on it. This can't happen for odd orders, because 2^i * G != O when n is odd, so the named curves aren't affected. Since this PR is about cofactor curves, it could be handled here or left as a follow-up:

    from ecdsa.ellipticcurve import CurveFp, PointJacobi
    g = PointJacobi(CurveFp(5, 1, 2), 1, 2, 1, order=4, generator=True)
    g * 3  # AttributeError on master and on this branch
  • Speed: NIST256p.generator * k showed no measurable change (0.047 s vs 0.048 s for 200 multiplications).

Harness (run from a checkout with PYTHONPATH=src python diff_test.py 5 7 11 13)
"""Differential test: python-ecdsa point arithmetic vs a naive affine group law.

Run from a python-ecdsa checkout: PYTHONPATH=src python diff_test.py
"""
import collections
import itertools
import sys

from ecdsa.ellipticcurve import INFINITY, CurveFp, Point, PointJacobi

PRIMES = [int(a) for a in sys.argv[1:]] or [5, 7, 11, 13]
SCALARS = range(-7, 8)
MUL_ADD_SCALARS = range(0, 5)


# ---- reference implementation (affine, None is the point at infinity) ----
def ref_add(P, Q, p, a):
    if P is None:
        return Q
    if Q is None:
        return P
    (x1, y1), (x2, y2) = P, Q
    if x1 == x2 and (y1 + y2) % p == 0:
        return None
    if P == Q:
        lam = (3 * x1 * x1 + a) * pow(2 * y1, -1, p) % p
    else:
        lam = (y2 - y1) * pow(x2 - x1, -1, p) % p
    x3 = (lam * lam - x1 - x2) % p
    return x3, (lam * (x1 - x3) - y1) % p


def ref_mul(k, P, p, a):
    if k < 0:
        k, P = -k, (None if P is None else (P[0], -P[1] % p))
    R = None
    for _ in range(k):
        R = ref_add(R, P, p, a)
    return R


def ref_order(P, p, a):
    k, R = 1, P
    while R is not None:
        R, k = ref_add(R, P, p, a), k + 1
    return k


# ---- normalisation of library results ----
def norm(R, p):
    if R is INFINITY or R == INFINITY:
        return None
    return R.x() % p, R.y() % p


stats = collections.Counter()
examples = collections.defaultdict(list)


def check(op, curve_desc, got_fn, expected, p):
    try:
        got = norm(got_fn(), p)
    except Exception as exc:  # noqa: BLE001 - we want to count every failure
        got = "%s" % type(exc).__name__
    key = "ok" if got == expected else "MISMATCH " + op
    stats[key] += 1
    if key != "ok" and len(examples[op]) < 3:
        examples[op].append("%s expected=%s got=%s" % (curve_desc, expected, got))


for p in PRIMES:
    for a, b in itertools.product(range(p), repeat=2):
        if (4 * a**3 + 27 * b**2) % p == 0:
            continue  # singular
        curve = CurveFp(p, a, b)
        pts = [(x, y) for x in range(p) for y in range(p) if (y * y - x**3 - a * x - b) % p == 0]
        for (x, y) in pts:
            P = (x, y)
            n = ref_order(P, p, a)
            desc = "p=%d a=%d b=%d P=%s ord=%d" % (p, a, b, P, n)
            aff = Point(curve, x, y)
            jac = PointJacobi(curve, x, y, 1)
            jac_ord = PointJacobi(curve, x, y, 1, order=n)
            jac_gen = PointJacobi(curve, x, y, 1, order=n, generator=True)
            check("Point.double", desc, aff.double, ref_add(P, P, p, a), p)
            check("Jacobi.double", desc, jac.double, ref_add(P, P, p, a), p)
            for k in SCALARS:
                exp = ref_mul(k, P, p, a)
                if k >= 0:
                    check("Point*k", desc + " k=%d" % k, lambda: aff * k, exp, p)
                check("Jacobi*k", desc + " k=%d" % k, lambda: jac * k, exp, p)
                check("Jacobi(order)*k", desc + " k=%d" % k, lambda: jac_ord * k, exp, p)
                check("Jacobi(generator)*k", desc + " k=%d" % k, lambda: jac_gen * k, exp, p)
            for (x2, y2) in pts:
                Q = (x2, y2)
                exp = ref_add(P, Q, p, a)
                check("Point+Point", desc + " Q=%s" % (Q,), lambda: aff + Point(curve, x2, y2), exp, p)
                check("Jacobi+Jacobi", desc + " Q=%s" % (Q,), lambda: jac + PointJacobi(curve, x2, y2, 1), exp, p)
                if p <= 11:
                    jq = PointJacobi(curve, x2, y2, 1)
                    for u, v in itertools.product(MUL_ADD_SCALARS, repeat=2):
                        exp = ref_add(ref_mul(u, P, p, a), ref_mul(v, Q, p, a), p, a)
                        check("Jacobi.mul_add", desc + " Q=%s u=%d v=%d" % (Q, u, v),
                              lambda: jac.mul_add(u, jq, v), exp, p)

print("primes", PRIMES)
for key, count in sorted(stats.items()):
    print("  %-32s %d" % (key, count))
for op, lines in sorted(examples.items()):
    print("  e.g.", op)
    for line in lines:
        print("     ", line)

I used an AI assistant to help write the harness and run these checks. I've reviewed the results.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants