File size: 4,245 Bytes
07f9ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
"""Verify App Store (StoreKit 2) signed data without any Apple API key.

StoreKit 2 transactions and App Store Server Notifications are JWS strings
signed by Apple. The header carries the certificate chain (x5c): leaf,
intermediate, root. A transaction is genuine when

  1. the root certificate is exactly Apple Root CA - G3 (pinned by SHA-256),
  2. the intermediate is signed by that root and the leaf by the intermediate,
     and both carry Apple's marker extensions,
  3. the JWS signature (ES256) verifies with the leaf's public key.

https://developer.apple.com/documentation/appstoreserverapi/jwstransaction
"""
from __future__ import annotations

import base64
import hashlib
import json
import uuid
from datetime import datetime, timezone

from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature

# SHA-256 of Apple Root CA - G3 (DER), from https://www.apple.com/certificateauthority/
APPLE_ROOT_G3_SHA256 = "63343abfb89a6a03ebb57e9b3f5fa7be7c4f5c756f3017b3a8c488c3653e9179"
# Marker extensions Apple puts on its App Store signing certificates.
_OID_INTERMEDIATE = x509.ObjectIdentifier("1.2.840.113635.100.6.2.1")
_OID_LEAF = x509.ObjectIdentifier("1.2.840.113635.100.6.11.1")


class AppleJWSError(Exception):
    pass


def _b64url(data: str) -> bytes:
    return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))


def _has_ext(cert: x509.Certificate, oid: x509.ObjectIdentifier) -> bool:
    try:
        cert.extensions.get_extension_for_oid(oid)
        return True
    except x509.ExtensionNotFound:
        return False


def verify_jws(jws: str, root_sha256: str = APPLE_ROOT_G3_SHA256, now: datetime | None = None) -> dict:
    """Return the decoded payload of an Apple-signed JWS, or raise AppleJWSError."""
    try:
        header_b64, payload_b64, sig_b64 = jws.split(".")
        header = json.loads(_b64url(header_b64))
    except Exception:
        raise AppleJWSError("not a JWS")
    if header.get("alg") != "ES256":
        raise AppleJWSError("unexpected algorithm")
    chain = header.get("x5c") or []
    if len(chain) != 3:
        raise AppleJWSError("certificate chain must have 3 certificates")
    try:
        leaf, inter, root = (x509.load_der_x509_certificate(base64.b64decode(c)) for c in chain)
    except Exception:
        raise AppleJWSError("bad certificate in chain")

    if hashlib.sha256(root.public_bytes(_der())).hexdigest() != root_sha256:
        raise AppleJWSError("root certificate is not Apple Root CA - G3")
    try:
        inter.verify_directly_issued_by(root)
        leaf.verify_directly_issued_by(inter)
    except Exception:
        raise AppleJWSError("certificate chain does not verify")
    if not (_has_ext(inter, _OID_INTERMEDIATE) and _has_ext(leaf, _OID_LEAF)):
        raise AppleJWSError("certificates are not App Store signing certificates")
    at = now or datetime.now(timezone.utc)
    for c in (leaf, inter, root):
        if not (c.not_valid_before_utc <= at <= c.not_valid_after_utc):
            raise AppleJWSError("certificate expired or not yet valid")

    raw = _b64url(sig_b64)
    if len(raw) != 64:
        raise AppleJWSError("bad signature length")
    der_sig = encode_dss_signature(int.from_bytes(raw[:32], "big"), int.from_bytes(raw[32:], "big"))
    pub = leaf.public_key()
    if not isinstance(pub, ec.EllipticCurvePublicKey):
        raise AppleJWSError("leaf key is not EC")
    try:
        pub.verify(der_sig, f"{header_b64}.{payload_b64}".encode(), ec.ECDSA(hashes.SHA256()))
    except Exception:
        raise AppleJWSError("signature does not verify")
    try:
        return json.loads(_b64url(payload_b64))
    except Exception:
        raise AppleJWSError("payload is not JSON")


def _der():
    from cryptography.hazmat.primitives.serialization import Encoding
    return Encoding.DER


def account_token(firebase_uid: str) -> str:
    """The appAccountToken the app attaches to purchases: a UUID derived from
    the Firebase uid, so a transaction can only be redeemed by its buyer."""
    return str(uuid.uuid5(uuid.NAMESPACE_URL, f"narratifai:{firebase_uid}"))