Protect a web app #

What is new: the protections the TensorChain web app runs on are a library you can put under your own app. A session is bound to a key the browser cannot export, so a stolen cookie is useless; every request is signed and used once; a request is bound to what the user actually saw; and secret fields are sealed in the browser so a proxy that terminates TLS sees only ciphertext.

Why it matters: these are the attacks real apps lose to: session theft, replay, a page tricked into sending a field somewhere else, and middleboxes logging card numbers. Each is refused here by a check, not by hope. The browser side (tc-session.js, tc-bind.js, tc-seal.js) was tested in headless Chromium; this page drives the same checks from Python so you can read them.

import hashlib, secrets, time
from tensorchain import httpsig, issuers, session, sign
from tensorchain.workspace import Workspace

reg = issuers.Registry("issuers")
reg.create("host:shop")
ws = Workspace("shop.sqlite", actor="agent:docs").__enter__()
device = secrets.token_bytes(32)                                  # in a browser: a non-extractable WebCrypto key
s = session.start(ws, reg, "host:shop", sign.public_key(device).hex())
print("cookie:", s["set_cookie"].split("=")[0], " flags:", "; ".join(s["set_cookie"].split("; ")[1:-1]))

url = "https://shop.example/orders"
def request(key, nonce):
    h = {"Cookie": "%s=%s" % (session.COOKIE, s["session"])}
    h.update(httpsig.sign_request(key, "GET", url, h, b"", keyid=s["session"], created=int(time.time()), nonce=nonce))
    return h

honest = request(device, "n1")
print("honest:     ", session.verify(ws, reg, "GET", url, honest, b"")["code"])
print("replayed:   ", session.verify(ws, reg, "GET", url, honest, b"")["code"])
thief = request(secrets.token_bytes(32), "n2")                    # the stolen cookie, signed by another key
print("stolen:     ", session.verify(ws, reg, "GET", url, thief, b"")["code"])
assert "HttpOnly" in s["set_cookie"] and "SameSite=Strict" in s["set_cookie"]
assert session.verify(ws, reg, "GET", url, request(device, "n3"), b"")["code"] == "accepted"
assert session.verify(ws, reg, "GET", url, honest, b"")["code"] == "replay"
assert session.verify(ws, reg, "GET", url, thief, b"")["code"] == "signature_invalid"
Output (captured at build)
cookie: __Host-tc_session  flags: Path=/; Secure; HttpOnly; SameSite=Strict
honest:      accepted
replayed:    replay
stolen:      signature_invalid

A request bound to the screen #

The host attests what a payment screen shows and which field may go where. A request is accepted only if it names that screen, its action, and only the fields that action may carry.

from tensorchain import bound

spec = {"format": "tensorchain.bound-surface.v1",
        "components": [{"id": "t1", "kind": "text", "text": "Pay Alice for invoice 42"},
                       {"id": "card", "kind": "input", "label": "Card number", "path": "/pay/card"},
                       {"id": "note", "kind": "input", "label": "Note (kept on this device)", "path": "/pay/note"},
                       {"id": "go", "kind": "button", "text": "Pay 10 EUR"}],
        "actions": [{"id": "pay", "button": "go", "method": "POST", "endpoint": "https://shop.example/pay",
                     "carries": ["card"]}]}
cfg = bound.client_config(ws, bound.attest_surface(ws, reg, "host:shop", spec))

def send(payload, carries=("card",), screen=None):
    body = bound.canonical(payload)
    b = {"surface": cfg["surface"], "action": "pay", "screen": screen or cfg["screen_sha256"],
         "body": hashlib.sha256(body).hexdigest(), "carries": sorted(carries)}
    return bound.verify_request(ws, reg, "POST", "https://shop.example/pay",
                                {"X-TensorChain-Bind": bound.encode_binding(b)}, body)["code"]

print("as shown:            ", send({"/pay/card": "4111"}))
print("the private note too:", send({"/pay/card": "4111", "/pay/note": "my PIN"}, carries=("card", "note")))
print("a different screen:  ", send({"/pay/card": "4111"}, screen="0" * 64))
assert send({"/pay/card": "4111"}) == "accepted"
assert send({"/pay/card": "4111", "/pay/note": "my PIN"}, carries=("card", "note")) == "input_not_allowed"
assert send({"/pay/card": "4111"}, screen="0" * 64) == "screen_mismatch"
Output (captured at build)
as shown:             accepted
the private note too: input_not_allowed
a different screen:   screen_mismatch

A sealed field #

In the browser, tc-seal.js seals a field to the host's key before the request is built. The context names the surface and the field, so a ciphertext cannot be moved to another field.

from tensorchain import seal

keys = seal.SealKeys("issuers")
pub, sec = keys.public("host:shop"), keys.secret("host:shop")
sealed = seal.seal(pub, b"4111-2222-3333-4444", "%s|/pay/card" % cfg["surface"])
print("on the wire: a", sealed["seal"], "object;", " card digits visible:", "4111" in str(sealed))
print("opened by the host:", seal.open_(sec, sealed, "%s|/pay/card" % cfg["surface"]).decode())
try:
    seal.open_(sec, sealed, "%s|/pay/note" % cfg["surface"])
    moved = "opened"
except seal.SealError:
    moved = "refused"
print("moved to another field:", moved)
assert "4111" not in str(sealed)
assert moved == "refused"
ws.__exit__(None, None, None)
Output (captured at build)
on the wire: a tensorchain.seal.v1 object;  card digits visible: False
opened by the host: 4111-2222-3333-4444
moved to another field: refused