shellzapy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shellzapy-0.1.0.dist-info/METADATA +112 -0
- shellzapy-0.1.0.dist-info/RECORD +345 -0
- shellzapy-0.1.0.dist-info/WHEEL +4 -0
- shellzapy-0.1.0.dist-info/licenses/LICENSE +21 -0
- shellzapy-0.1.0.dist-info/licenses/NOTICE +9 -0
- zapy/__init__.py +58 -0
- zapy/_appstate/__init__.py +59 -0
- zapy/_appstate/constants.py +82 -0
- zapy/_appstate/crypto/__init__.py +17 -0
- zapy/_appstate/crypto/app_state_crypto.py +401 -0
- zapy/_appstate/parsers/__init__.py +23 -0
- zapy/_appstate/parsers/encoding.py +157 -0
- zapy/_appstate/parsers/response_parser.py +135 -0
- zapy/_appstate/sync/__init__.py +11 -0
- zapy/_appstate/sync/sync_client.py +1559 -0
- zapy/_appstate/types.py +137 -0
- zapy/_appstate/utils.py +100 -0
- zapy/_auth/__init__.py +3 -0
- zapy/_auth/auth_client.py +618 -0
- zapy/_auth/credentials_flow.py +290 -0
- zapy/_auth/pairing/__init__.py +3 -0
- zapy/_auth/pairing/companion_host.py +239 -0
- zapy/_auth/pairing/flow.py +808 -0
- zapy/_auth/pairing/pairing_code_crypto.py +143 -0
- zapy/_auth/pairing/qr_flow.py +123 -0
- zapy/_auth/pairing/shortcake_crypto.py +122 -0
- zapy/_auth/pairing/shortcake_flow.py +393 -0
- zapy/_auth/types.py +110 -0
- zapy/_client/__init__.py +26 -0
- zapy/_client/client.py +972 -0
- zapy/_client/connection/__init__.py +6 -0
- zapy/_client/connection/manager.py +525 -0
- zapy/_client/connection/receipt_queue.py +74 -0
- zapy/_client/coordinators/__init__.py +81 -0
- zapy/_client/coordinators/ab_props.py +260 -0
- zapy/_client/coordinators/app_state_mutation.py +2538 -0
- zapy/_client/coordinators/bot.py +830 -0
- zapy/_client/coordinators/broadcast_list.py +101 -0
- zapy/_client/coordinators/business.py +247 -0
- zapy/_client/coordinators/email.py +158 -0
- zapy/_client/coordinators/group.py +1478 -0
- zapy/_client/coordinators/incoming_node.py +758 -0
- zapy/_client/coordinators/low_level.py +119 -0
- zapy/_client/coordinators/message.py +1153 -0
- zapy/_client/coordinators/message_dispatch.py +1637 -0
- zapy/_client/coordinators/newsletter.py +110 -0
- zapy/_client/coordinators/offline_resume.py +271 -0
- zapy/_client/coordinators/passive_tasks.py +447 -0
- zapy/_client/coordinators/presence.py +103 -0
- zapy/_client/coordinators/privacy.py +623 -0
- zapy/_client/coordinators/profile.py +1024 -0
- zapy/_client/coordinators/retry.py +1878 -0
- zapy/_client/coordinators/status.py +132 -0
- zapy/_client/coordinators/stream_control.py +260 -0
- zapy/_client/coordinators/trusted_contact_token.py +417 -0
- zapy/_client/events/__init__.py +266 -0
- zapy/_client/events/abprops.py +58 -0
- zapy/_client/events/appstate_mutation.py +248 -0
- zapy/_client/events/business.py +565 -0
- zapy/_client/events/call.py +144 -0
- zapy/_client/events/chatstate.py +41 -0
- zapy/_client/events/devices.py +122 -0
- zapy/_client/events/dirty.py +384 -0
- zapy/_client/events/group.py +655 -0
- zapy/_client/events/identity.py +40 -0
- zapy/_client/events/incoming.py +1079 -0
- zapy/_client/events/mex_notification.py +317 -0
- zapy/_client/events/offline.py +123 -0
- zapy/_client/events/picture.py +67 -0
- zapy/_client/events/presence.py +74 -0
- zapy/_client/events/privacy.py +187 -0
- zapy/_client/events/privacy_token.py +72 -0
- zapy/_client/events/receipt.py +109 -0
- zapy/_client/events/registration.py +70 -0
- zapy/_client/events/username.py +76 -0
- zapy/_client/factory.py +2020 -0
- zapy/_client/media.py +829 -0
- zapy/_client/newsletter/__init__.py +90 -0
- zapy/_client/newsletter/admin.py +323 -0
- zapy/_client/newsletter/content.py +499 -0
- zapy/_client/newsletter/discovery.py +233 -0
- zapy/_client/newsletter/messaging.py +396 -0
- zapy/_client/newsletter/mex.py +99 -0
- zapy/_client/newsletter/parse.py +406 -0
- zapy/_client/newsletter/types.py +393 -0
- zapy/_client/persistence/__init__.py +89 -0
- zapy/_client/persistence/companion_host.py +133 -0
- zapy/_client/persistence/ephemeral_setting.py +245 -0
- zapy/_client/persistence/group_history.py +361 -0
- zapy/_client/persistence/history_blob.py +169 -0
- zapy/_client/persistence/history_sync.py +646 -0
- zapy/_client/persistence/mailbox.py +232 -0
- zapy/_client/persistence/write_behind_persistence.py +368 -0
- zapy/_client/plugins/__init__.py +23 -0
- zapy/_client/plugins/define.py +44 -0
- zapy/_client/plugins/install.py +254 -0
- zapy/_client/plugins/types.py +64 -0
- zapy/_client/tokens/__init__.py +21 -0
- zapy/_client/tokens/cs_token.py +47 -0
- zapy/_client/tokens/tc_token.py +43 -0
- zapy/_client/types.py +988 -0
- zapy/_crypto/__init__.py +65 -0
- zapy/_crypto/core/__init__.py +62 -0
- zapy/_crypto/core/hkdf.py +41 -0
- zapy/_crypto/core/keys.py +51 -0
- zapy/_crypto/core/nonce.py +25 -0
- zapy/_crypto/core/primitives.py +179 -0
- zapy/_crypto/core/random.py +32 -0
- zapy/_crypto/core/xeddsa.py +72 -0
- zapy/_crypto/curves/__init__.py +3 -0
- zapy/_crypto/curves/constants.py +10 -0
- zapy/_crypto/curves/ed25519.py +61 -0
- zapy/_crypto/curves/types.py +18 -0
- zapy/_crypto/curves/x25519.py +117 -0
- zapy/_crypto/math/__init__.py +3 -0
- zapy/_crypto/math/constants.py +35 -0
- zapy/_crypto/math/edwards.py +174 -0
- zapy/_crypto/math/fe.py +120 -0
- zapy/_crypto/math/le.py +13 -0
- zapy/_crypto/math/mod.py +15 -0
- zapy/_crypto/math/prime.py +11 -0
- zapy/_crypto/math/types.py +25 -0
- zapy/_crypto/native_backend.py +40 -0
- zapy/_infra/__init__.py +3 -0
- zapy/_infra/log.py +142 -0
- zapy/_infra/perf.py +77 -0
- zapy/_media/__init__.py +64 -0
- zapy/_media/constants.py +133 -0
- zapy/_media/container.py +110 -0
- zapy/_media/crypto/__init__.py +19 -0
- zapy/_media/crypto/crypto.py +633 -0
- zapy/_media/crypto/media_retry.py +107 -0
- zapy/_media/processor.py +100 -0
- zapy/_media/sticker/__init__.py +8 -0
- zapy/_media/sticker/pack.py +188 -0
- zapy/_media/transfer/__init__.py +15 -0
- zapy/_media/transfer/client.py +635 -0
- zapy/_media/transfer/conn.py +48 -0
- zapy/_media/types.py +169 -0
- zapy/_message/__init__.py +121 -0
- zapy/_message/addons/__init__.py +5 -0
- zapy/_message/addons/link_preview/__init__.py +54 -0
- zapy/_message/addons/link_preview/builder.py +56 -0
- zapy/_message/addons/link_preview/detect.py +72 -0
- zapy/_message/addons/link_preview/fetcher.py +553 -0
- zapy/_message/addons/link_preview/types.py +100 -0
- zapy/_message/client.py +486 -0
- zapy/_message/context_info.py +424 -0
- zapy/_message/crypto/__init__.py +71 -0
- zapy/_message/crypto/addon_crypto.py +656 -0
- zapy/_message/crypto/icdc.py +138 -0
- zapy/_message/crypto/phash.py +87 -0
- zapy/_message/crypto/reporting_token.py +498 -0
- zapy/_message/crypto/use_case_secret.py +113 -0
- zapy/_message/encode/__init__.py +84 -0
- zapy/_message/encode/content.py +636 -0
- zapy/_message/encode/device_sent.py +88 -0
- zapy/_message/encode/media_payload.py +122 -0
- zapy/_message/encode/padding.py +27 -0
- zapy/_message/kinds/__init__.py +1 -0
- zapy/_message/kinds/bot.py +179 -0
- zapy/_message/kinds/group_history.py +206 -0
- zapy/_message/kinds/newsletter.py +388 -0
- zapy/_message/kinds/sticker_pack.py +74 -0
- zapy/_message/messaging/__init__.py +336 -0
- zapy/_message/messaging/companion_host.py +117 -0
- zapy/_message/messaging/fanout.py +311 -0
- zapy/_message/messaging/group_metadata.py +444 -0
- zapy/_message/messaging/ignore_key.py +264 -0
- zapy/_message/messaging/key_protocol.py +217 -0
- zapy/_message/messaging/link_preview.py +448 -0
- zapy/_message/messaging/messages.py +1429 -0
- zapy/_message/primitives/__init__.py +1 -0
- zapy/_message/primitives/ack.py +232 -0
- zapy/_message/primitives/incoming.py +1141 -0
- zapy/_message/primitives/media_retry.py +451 -0
- zapy/_message/primitives/peer_data_operation.py +271 -0
- zapy/_message/types.py +434 -0
- zapy/_proto/WAProto_pb2.py +2584 -0
- zapy/_proto/__init__.py +1 -0
- zapy/_protocol/__init__.py +3 -0
- zapy/_protocol/abprops_spec.py +6216 -0
- zapy/_protocol/auth.py +17 -0
- zapy/_protocol/browser.py +57 -0
- zapy/_protocol/defaults.py +38 -0
- zapy/_protocol/device_identity.py +54 -0
- zapy/_protocol/jid.py +241 -0
- zapy/_protocol/message.py +127 -0
- zapy/_protocol/nodes.py +144 -0
- zapy/_protocol/notification.py +18 -0
- zapy/_retry/__init__.py +77 -0
- zapy/_retry/codec.py +209 -0
- zapy/_retry/constants.py +28 -0
- zapy/_retry/parse.py +132 -0
- zapy/_retry/reason.py +65 -0
- zapy/_retry/replay.py +483 -0
- zapy/_retry/tracker.py +161 -0
- zapy/_retry/types.py +122 -0
- zapy/_signal/__init__.py +171 -0
- zapy/_signal/api/__init__.py +133 -0
- zapy/_signal/api/codec.py +164 -0
- zapy/_signal/api/constants.py +14 -0
- zapy/_signal/api/device_sync.py +915 -0
- zapy/_signal/api/digest_sync.py +363 -0
- zapy/_signal/api/identity_sync.py +250 -0
- zapy/_signal/api/missing_pre_keys_sync.py +267 -0
- zapy/_signal/api/prekeys.py +191 -0
- zapy/_signal/api/result_map.py +40 -0
- zapy/_signal/api/rotate_key.py +111 -0
- zapy/_signal/api/session_sync.py +297 -0
- zapy/_signal/attestation.py +145 -0
- zapy/_signal/constants.py +22 -0
- zapy/_signal/encoding.py +78 -0
- zapy/_signal/group/__init__.py +35 -0
- zapy/_signal/group/chain.py +139 -0
- zapy/_signal/group/codec.py +78 -0
- zapy/_signal/group/encoding.py +166 -0
- zapy/_signal/group/manager.py +361 -0
- zapy/_signal/registration/__init__.py +44 -0
- zapy/_signal/registration/keygen.py +46 -0
- zapy/_signal/registration/reg_encoding.py +66 -0
- zapy/_signal/registration/reg_utils.py +52 -0
- zapy/_signal/session/__init__.py +114 -0
- zapy/_signal/session/encoding.py +385 -0
- zapy/_signal/session/protocol.py +590 -0
- zapy/_signal/session/ratchet.py +381 -0
- zapy/_signal/session/resolver.py +630 -0
- zapy/_signal/session/serializer.py +96 -0
- zapy/_signal/session/session.py +272 -0
- zapy/_signal/types.py +214 -0
- zapy/_store/__init__.py +118 -0
- zapy/_store/cache/__init__.py +166 -0
- zapy/_store/cache/identity.py +130 -0
- zapy/_store/cache/privacy_token.py +116 -0
- zapy/_store/cache/sender_key.py +168 -0
- zapy/_store/cache/session.py +142 -0
- zapy/_store/contracts/__init__.py +84 -0
- zapy/_store/contracts/appstate.py +82 -0
- zapy/_store/contracts/auth.py +16 -0
- zapy/_store/contracts/chat_metadata.py +29 -0
- zapy/_store/contracts/contact.py +31 -0
- zapy/_store/contracts/device_list.py +35 -0
- zapy/_store/contracts/group_metadata.py +33 -0
- zapy/_store/contracts/identity.py +18 -0
- zapy/_store/contracts/message.py +36 -0
- zapy/_store/contracts/message_secret.py +41 -0
- zapy/_store/contracts/pre_key.py +32 -0
- zapy/_store/contracts/privacy_token.py +32 -0
- zapy/_store/contracts/retry.py +47 -0
- zapy/_store/contracts/sender_key.py +37 -0
- zapy/_store/contracts/session.py +21 -0
- zapy/_store/contracts/signal.py +23 -0
- zapy/_store/contracts/thread.py +35 -0
- zapy/_store/create_store.py +890 -0
- zapy/_store/locks.py +1154 -0
- zapy/_store/memory/__init__.py +40 -0
- zapy/_store/memory/appstate.py +200 -0
- zapy/_store/memory/auth.py +24 -0
- zapy/_store/memory/chat_metadata.py +124 -0
- zapy/_store/memory/contact.py +125 -0
- zapy/_store/memory/device_list.py +161 -0
- zapy/_store/memory/group_metadata.py +125 -0
- zapy/_store/memory/identity.py +86 -0
- zapy/_store/memory/message.py +85 -0
- zapy/_store/memory/message_secret.py +145 -0
- zapy/_store/memory/pre_key.py +112 -0
- zapy/_store/memory/privacy_token.py +103 -0
- zapy/_store/memory/retry.py +250 -0
- zapy/_store/memory/sender_key.py +162 -0
- zapy/_store/memory/session.py +111 -0
- zapy/_store/memory/signal.py +45 -0
- zapy/_store/memory/thread.py +66 -0
- zapy/_store/noop.py +279 -0
- zapy/_transport/__init__.py +3 -0
- zapy/_transport/binary/__init__.py +77 -0
- zapy/_transport/binary/constants.py +80 -0
- zapy/_transport/binary/decoder.py +260 -0
- zapy/_transport/binary/encoder.py +279 -0
- zapy/_transport/binary/tokens.py +1289 -0
- zapy/_transport/comms.py +759 -0
- zapy/_transport/keepalive/__init__.py +3 -0
- zapy/_transport/keepalive/keep_alive.py +252 -0
- zapy/_transport/node/__init__.py +3 -0
- zapy/_transport/node/builders/__init__.py +9 -0
- zapy/_transport/node/builders/abprops.py +33 -0
- zapy/_transport/node/builders/account_sync.py +120 -0
- zapy/_transport/node/builders/bot.py +56 -0
- zapy/_transport/node/builders/business.py +261 -0
- zapy/_transport/node/builders/chatstate.py +74 -0
- zapy/_transport/node/builders/community.py +116 -0
- zapy/_transport/node/builders/device.py +30 -0
- zapy/_transport/node/builders/email.py +181 -0
- zapy/_transport/node/builders/global_.py +74 -0
- zapy/_transport/node/builders/group.py +279 -0
- zapy/_transport/node/builders/media.py +21 -0
- zapy/_transport/node/builders/message.py +436 -0
- zapy/_transport/node/builders/mobile.py +227 -0
- zapy/_transport/node/builders/newsletter.py +293 -0
- zapy/_transport/node/builders/offline.py +20 -0
- zapy/_transport/node/builders/pairing.py +130 -0
- zapy/_transport/node/builders/passive.py +28 -0
- zapy/_transport/node/builders/prekeys.py +215 -0
- zapy/_transport/node/builders/presence.py +100 -0
- zapy/_transport/node/builders/privacy.py +243 -0
- zapy/_transport/node/builders/privacy_token.py +94 -0
- zapy/_transport/node/builders/profile.py +176 -0
- zapy/_transport/node/builders/retry.py +156 -0
- zapy/_transport/node/builders/shortcake.py +87 -0
- zapy/_transport/node/builders/tos.py +92 -0
- zapy/_transport/node/builders/usync.py +185 -0
- zapy/_transport/node/helpers.py +201 -0
- zapy/_transport/node/orchestrator.py +210 -0
- zapy/_transport/node/query.py +82 -0
- zapy/_transport/node/transport.py +105 -0
- zapy/_transport/node/usync.py +33 -0
- zapy/_transport/node/xml.py +38 -0
- zapy/_transport/noise/__init__.py +7 -0
- zapy/_transport/noise/cert.py +85 -0
- zapy/_transport/noise/client_payload.py +344 -0
- zapy/_transport/noise/constants.py +12 -0
- zapy/_transport/noise/frame_codec.py +120 -0
- zapy/_transport/noise/handshake.py +92 -0
- zapy/_transport/noise/session.py +493 -0
- zapy/_transport/noise/socket.py +45 -0
- zapy/_transport/noise/types.py +66 -0
- zapy/_transport/noise/version.json +3 -0
- zapy/_transport/proxy.py +35 -0
- zapy/_transport/types.py +19 -0
- zapy/_transport/wa_version_fetcher.py +159 -0
- zapy/_transport/web_socket.py +602 -0
- zapy/_util/__init__.py +3 -0
- zapy/_util/bytes.py +131 -0
- zapy/_util/coercion.py +29 -0
- zapy/_util/collections.py +45 -0
- zapy/_util/primitives.py +49 -0
- zapy/client.py +840 -0
- zapy/errors.py +148 -0
- zapy/events.py +564 -0
- zapy/jid.py +140 -0
- zapy/py.typed +0 -0
- zapy/stores/__init__.py +50 -0
- zapy/stores/base.py +1627 -0
- zapy/stores/json_file.py +359 -0
- zapy/stores/memory.py +322 -0
- zapy/stores/sqlite.py +343 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Noise certificate chain verification against the production root CA."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from google.protobuf.message import DecodeError
|
|
8
|
+
|
|
9
|
+
from zapy._crypto import xeddsa_verify
|
|
10
|
+
from zapy._proto import WAProto_pb2
|
|
11
|
+
from zapy._transport.noise import constants as _c
|
|
12
|
+
from zapy._util.bytes import hex_to_bytes
|
|
13
|
+
from zapy._util.bytes import uint8_equal
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True, slots=True)
|
|
17
|
+
class WaNoiseRootCa:
|
|
18
|
+
"""A Noise root CA: 32-byte raw X25519 public key plus its serial."""
|
|
19
|
+
|
|
20
|
+
public_key: bytes
|
|
21
|
+
serial: int = 0
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
PRODUCTION_ROOT_CA = WaNoiseRootCa(
|
|
25
|
+
public_key=hex_to_bytes(_c.ROOT_CA_PUBLIC_KEY_HEX),
|
|
26
|
+
serial=_c.ROOT_CA_SERIAL,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class _ParsedCertificate:
|
|
32
|
+
serial: int
|
|
33
|
+
issuer_serial: int
|
|
34
|
+
key: bytes
|
|
35
|
+
details: bytes
|
|
36
|
+
signature: bytes
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _parse_certificate(
|
|
40
|
+
certificate: WAProto_pb2.CertChain.NoiseCertificate,
|
|
41
|
+
) -> _ParsedCertificate:
|
|
42
|
+
details_raw = bytes(certificate.details)
|
|
43
|
+
signature = bytes(certificate.signature)
|
|
44
|
+
if len(signature) != 64:
|
|
45
|
+
raise ValueError("invalid certificate signature size")
|
|
46
|
+
details = WAProto_pb2.CertChain.NoiseCertificate.Details.FromString(details_raw)
|
|
47
|
+
return _ParsedCertificate(
|
|
48
|
+
serial=details.serial,
|
|
49
|
+
issuer_serial=details.issuerSerial,
|
|
50
|
+
key=bytes(details.key),
|
|
51
|
+
details=details_raw,
|
|
52
|
+
signature=signature,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def verify_noise_certificate_chain(
|
|
57
|
+
certificate_chain: bytes | bytearray,
|
|
58
|
+
server_static: bytes | bytearray,
|
|
59
|
+
root_ca: WaNoiseRootCa | None = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
"""Validate a certificate chain and confirm the leaf binds ``server_static``.
|
|
62
|
+
|
|
63
|
+
Throws on structural mismatch, bad signature, or unexpected issuer serial.
|
|
64
|
+
"""
|
|
65
|
+
root = root_ca if root_ca is not None else PRODUCTION_ROOT_CA
|
|
66
|
+
try:
|
|
67
|
+
chain = WAProto_pb2.CertChain.FromString(bytes(certificate_chain))
|
|
68
|
+
except DecodeError as error:
|
|
69
|
+
raise ValueError(f"noise certificate chain decode failed: {error}") from error
|
|
70
|
+
if not chain.HasField("leaf") or not chain.HasField("intermediate"):
|
|
71
|
+
raise ValueError("noise certificate chain is missing leaf/intermediate")
|
|
72
|
+
|
|
73
|
+
intermediate = _parse_certificate(chain.intermediate)
|
|
74
|
+
if intermediate.issuer_serial != root.serial:
|
|
75
|
+
raise ValueError("intermediate certificate issuer mismatch")
|
|
76
|
+
if not xeddsa_verify(root.public_key, intermediate.details, intermediate.signature):
|
|
77
|
+
raise ValueError("intermediate certificate signature is invalid")
|
|
78
|
+
|
|
79
|
+
leaf = _parse_certificate(chain.leaf)
|
|
80
|
+
if leaf.issuer_serial != intermediate.serial:
|
|
81
|
+
raise ValueError("leaf certificate issuer mismatch")
|
|
82
|
+
if not xeddsa_verify(intermediate.key, leaf.details, leaf.signature):
|
|
83
|
+
raise ValueError("leaf certificate signature is invalid")
|
|
84
|
+
if not uint8_equal(leaf.key, bytes(server_static)):
|
|
85
|
+
raise ValueError("leaf certificate key mismatch with server static key")
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Login/registration handshake payloads (mirrors ``WaClientPayload.ts``).
|
|
2
|
+
|
|
3
|
+
Version strings default to the vendored ``version.json`` shipped inside
|
|
4
|
+
this package, exactly like the TS ``WA_VERSION`` import.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import locale
|
|
11
|
+
import re
|
|
12
|
+
import sys
|
|
13
|
+
from importlib import resources as _resources
|
|
14
|
+
|
|
15
|
+
from zapy._crypto.core.primitives import md5_bytes
|
|
16
|
+
from zapy._proto import WAProto_pb2
|
|
17
|
+
from zapy._transport.noise.types import (
|
|
18
|
+
WaLoginPayloadConfig,
|
|
19
|
+
WaRegistrationPayloadConfig,
|
|
20
|
+
)
|
|
21
|
+
from zapy._util.bytes import int_to_bytes
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _load_wa_version() -> str:
|
|
25
|
+
"""Read the vendored WhatsApp Web version (ships inside the wheel)."""
|
|
26
|
+
data = json.loads(
|
|
27
|
+
_resources.files("zapy._transport.noise")
|
|
28
|
+
.joinpath("version.json")
|
|
29
|
+
.read_text(encoding="utf-8")
|
|
30
|
+
)
|
|
31
|
+
version = data.get("waWeb")
|
|
32
|
+
if not isinstance(version, str) or not version:
|
|
33
|
+
raise ValueError("vendored version.json has no waWeb version string")
|
|
34
|
+
return version
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_WA_VERSION: str = _load_wa_version()
|
|
38
|
+
|
|
39
|
+
_MAX_SAFE_INTEGER = 2**53 - 1
|
|
40
|
+
_OS_VERSION_RE = re.compile(r"^[0-9.]+$")
|
|
41
|
+
_INT_PREFIX_RE = re.compile(r"\s*[+-]?\d+")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _parse_int_prefix(text: str) -> int | None:
|
|
45
|
+
match = _INT_PREFIX_RE.match(text)
|
|
46
|
+
return int(match.group(0)) if match else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _is_safe(value: int | None) -> bool:
|
|
50
|
+
return (
|
|
51
|
+
value is not None
|
|
52
|
+
and not isinstance(value, bool)
|
|
53
|
+
and abs(value) <= _MAX_SAFE_INTEGER
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _parse_version(version_base: str) -> dict[str, int | None]:
|
|
58
|
+
parts = version_base.split(".")
|
|
59
|
+
primary = _parse_int_prefix(parts[0])
|
|
60
|
+
secondary = _parse_int_prefix(parts[1]) if len(parts) > 1 else 3000
|
|
61
|
+
tertiary = _parse_int_prefix(parts[2]) if len(parts) > 2 else 0
|
|
62
|
+
quaternary = _parse_int_prefix(parts[3]) if len(parts) > 3 else None
|
|
63
|
+
quinary = _parse_int_prefix(parts[4]) if len(parts) > 4 else None
|
|
64
|
+
for value in (primary, secondary, tertiary):
|
|
65
|
+
if not _is_safe(value):
|
|
66
|
+
raise ValueError(f"invalid versionBase: {version_base}")
|
|
67
|
+
if len(parts) > 3 and (quaternary is None or not _is_safe(quaternary)):
|
|
68
|
+
raise ValueError(f"invalid versionBase: {version_base}")
|
|
69
|
+
if len(parts) > 4 and (quinary is None or not _is_safe(quinary)):
|
|
70
|
+
raise ValueError(f"invalid versionBase: {version_base}")
|
|
71
|
+
return {
|
|
72
|
+
"primary": primary,
|
|
73
|
+
"secondary": secondary,
|
|
74
|
+
"tertiary": tertiary,
|
|
75
|
+
"quaternary": quaternary,
|
|
76
|
+
"quinary": quinary,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _resolve_locale() -> tuple[str, str]:
|
|
81
|
+
name = (locale.getlocale()[0] or "en-US").replace("_", "-")
|
|
82
|
+
parts = name.split("-")
|
|
83
|
+
language = (parts[0] if parts else "en") or "en"
|
|
84
|
+
country = (parts[1] if len(parts) > 1 else "US") or "US"
|
|
85
|
+
return language.lower(), country.upper()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _parse_os_version(os_version: str | None) -> dict[str, int] | None:
|
|
89
|
+
if os_version is None or not _OS_VERSION_RE.match(os_version):
|
|
90
|
+
return None
|
|
91
|
+
parts = os_version.split(".")
|
|
92
|
+
if not parts[0]:
|
|
93
|
+
return None
|
|
94
|
+
primary = int(parts[0])
|
|
95
|
+
if abs(primary) > _MAX_SAFE_INTEGER:
|
|
96
|
+
return None
|
|
97
|
+
out: dict[str, int] = {"primary": primary}
|
|
98
|
+
if len(parts) > 1 and parts[1]:
|
|
99
|
+
secondary = int(parts[1])
|
|
100
|
+
if abs(secondary) <= _MAX_SAFE_INTEGER:
|
|
101
|
+
out["secondary"] = secondary
|
|
102
|
+
if len(parts) > 2 and parts[2]:
|
|
103
|
+
tertiary = int(parts[2])
|
|
104
|
+
if abs(tertiary) <= _MAX_SAFE_INTEGER:
|
|
105
|
+
out["tertiary"] = tertiary
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
_PLATFORM_BY_BROWSER = {
|
|
110
|
+
"chrome": "CHROME",
|
|
111
|
+
"firefox": "FIREFOX",
|
|
112
|
+
"ie": "IE",
|
|
113
|
+
"opera": "OPERA",
|
|
114
|
+
"safari": "SAFARI",
|
|
115
|
+
"edge": "EDGE",
|
|
116
|
+
"electron": "DESKTOP",
|
|
117
|
+
"desktop": "DESKTOP",
|
|
118
|
+
"ipad": "IPAD",
|
|
119
|
+
"tablet": "ANDROID_TABLET",
|
|
120
|
+
"android tablet": "ANDROID_TABLET",
|
|
121
|
+
"ohana": "OHANA",
|
|
122
|
+
"aloha": "ALOHA",
|
|
123
|
+
"catalina": "CATALINA",
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _default_user_agent(
|
|
128
|
+
version_base: str, version: dict[str, int | None] | None = None
|
|
129
|
+
) -> dict[str, object]:
|
|
130
|
+
parsed = version if version is not None else _parse_version(version_base)
|
|
131
|
+
language, country = _resolve_locale()
|
|
132
|
+
app_version: dict[str, int] = {
|
|
133
|
+
"primary": parsed["primary"], # type: ignore[dict-item]
|
|
134
|
+
"secondary": parsed["secondary"], # type: ignore[dict-item]
|
|
135
|
+
"tertiary": parsed["tertiary"], # type: ignore[dict-item]
|
|
136
|
+
}
|
|
137
|
+
if parsed["quaternary"] is not None:
|
|
138
|
+
app_version["quaternary"] = parsed["quaternary"]
|
|
139
|
+
if parsed["quinary"] is not None:
|
|
140
|
+
app_version["quinary"] = parsed["quinary"]
|
|
141
|
+
return {
|
|
142
|
+
"platform": int(WAProto_pb2.ClientPayload.UserAgent.Platform.WEB),
|
|
143
|
+
"releaseChannel": int(
|
|
144
|
+
WAProto_pb2.ClientPayload.UserAgent.ReleaseChannel.RELEASE
|
|
145
|
+
),
|
|
146
|
+
"appVersion": app_version,
|
|
147
|
+
"mcc": "000",
|
|
148
|
+
"mnc": "000",
|
|
149
|
+
"osVersion": "0.1",
|
|
150
|
+
"manufacturer": "",
|
|
151
|
+
"device": "Desktop",
|
|
152
|
+
"osBuildNumber": "0.1",
|
|
153
|
+
"localeLanguageIso6391": language,
|
|
154
|
+
"localeCountryIso31661Alpha2": country,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _default_device_props(
|
|
159
|
+
device_browser: str | None,
|
|
160
|
+
device_os_display_name: str | None,
|
|
161
|
+
device_os_version: str | None,
|
|
162
|
+
require_full_sync: bool,
|
|
163
|
+
) -> bytes:
|
|
164
|
+
os_version = _parse_os_version(
|
|
165
|
+
device_os_version if device_os_version is not None else get_runtime_os_version()
|
|
166
|
+
)
|
|
167
|
+
fields: dict[str, object] = {
|
|
168
|
+
"os": device_os_display_name
|
|
169
|
+
if device_os_display_name is not None
|
|
170
|
+
else sys.platform,
|
|
171
|
+
"platformType": resolve_device_props_platform_type(device_browser),
|
|
172
|
+
"requireFullSync": require_full_sync,
|
|
173
|
+
"historySyncConfig": {
|
|
174
|
+
"storageQuotaMb": 114149,
|
|
175
|
+
"inlineInitialPayloadInE2EeMsg": True,
|
|
176
|
+
"supportCallLogHistory": True,
|
|
177
|
+
"supportBotUserAgentChatHistory": True,
|
|
178
|
+
"supportCagReactionsAndPolls": True,
|
|
179
|
+
"supportBizHostedMsg": True,
|
|
180
|
+
"supportRecentSyncChunkMessageCountTuning": True,
|
|
181
|
+
"supportHostedGroupMsg": True,
|
|
182
|
+
"supportFbidBotChatHistory": True,
|
|
183
|
+
"supportMessageAssociation": True,
|
|
184
|
+
"supportGroupHistory": True,
|
|
185
|
+
"thumbnailSyncDaysLimit": 60,
|
|
186
|
+
"supportManusHistory": True,
|
|
187
|
+
"supportHatchHistory": True,
|
|
188
|
+
"supportedBotChannelFbids": [],
|
|
189
|
+
},
|
|
190
|
+
}
|
|
191
|
+
if os_version is not None:
|
|
192
|
+
fields["version"] = os_version
|
|
193
|
+
return bytes(WAProto_pb2.DeviceProps(**fields).SerializeToString())
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _build_common_payload(
|
|
197
|
+
version_base: str | None,
|
|
198
|
+
passive: bool,
|
|
199
|
+
pull: bool | None,
|
|
200
|
+
default_pull: bool,
|
|
201
|
+
user_agent: object,
|
|
202
|
+
web_info: object,
|
|
203
|
+
version: dict[str, int | None] | None = None,
|
|
204
|
+
) -> dict[str, object]:
|
|
205
|
+
base = version_base if version_base is not None else _WA_VERSION
|
|
206
|
+
return {
|
|
207
|
+
"passive": passive,
|
|
208
|
+
"pull": default_pull if pull is None else pull,
|
|
209
|
+
"connectType": int(WAProto_pb2.ClientPayload.ConnectType.WIFI_UNKNOWN),
|
|
210
|
+
"connectReason": int(WAProto_pb2.ClientPayload.ConnectReason.USER_ACTIVATED),
|
|
211
|
+
"userAgent": user_agent
|
|
212
|
+
if user_agent is not None
|
|
213
|
+
else _default_user_agent(base, version),
|
|
214
|
+
"webInfo": web_info
|
|
215
|
+
if web_info is not None
|
|
216
|
+
else {
|
|
217
|
+
"webSubPlatform": int(
|
|
218
|
+
WAProto_pb2.ClientPayload.WebInfo.WebSubPlatform.WEB_BROWSER
|
|
219
|
+
)
|
|
220
|
+
},
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def resolve_device_props_platform_type(device_browser: str | None) -> int:
|
|
225
|
+
"""Map a browser label to the ``DeviceProps.PlatformType`` number."""
|
|
226
|
+
normalized = (device_browser or "").strip().lower()
|
|
227
|
+
name = _PLATFORM_BY_BROWSER.get(normalized, "UNKNOWN")
|
|
228
|
+
return int(getattr(WAProto_pb2.DeviceProps.PlatformType, name))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def build_login_payload(config: WaLoginPayloadConfig) -> bytes:
|
|
232
|
+
"""Build the login (returning-device) handshake payload."""
|
|
233
|
+
if (
|
|
234
|
+
isinstance(config.username, bool)
|
|
235
|
+
or not isinstance(config.username, int)
|
|
236
|
+
or config.username <= 0
|
|
237
|
+
or abs(config.username) > _MAX_SAFE_INTEGER
|
|
238
|
+
):
|
|
239
|
+
raise ValueError("login payload requires a valid numeric username")
|
|
240
|
+
common = _build_common_payload(
|
|
241
|
+
config.version_base,
|
|
242
|
+
config.passive,
|
|
243
|
+
config.pull,
|
|
244
|
+
True,
|
|
245
|
+
config.user_agent,
|
|
246
|
+
config.web_info,
|
|
247
|
+
)
|
|
248
|
+
message = WAProto_pb2.ClientPayload(
|
|
249
|
+
username=config.username,
|
|
250
|
+
device=config.device if config.device is not None else 0,
|
|
251
|
+
lc=config.login_counter if config.login_counter is not None else 0,
|
|
252
|
+
connectAttemptCount=config.connect_attempt_count
|
|
253
|
+
if config.connect_attempt_count is not None
|
|
254
|
+
else 0,
|
|
255
|
+
lidDbMigrated=config.lid_db_migrated,
|
|
256
|
+
**common,
|
|
257
|
+
)
|
|
258
|
+
return bytes(message.SerializeToString())
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def build_registration_payload(config: WaRegistrationPayloadConfig) -> bytes:
|
|
262
|
+
"""Build the first-pairing registration handshake payload."""
|
|
263
|
+
info = config.registration_info
|
|
264
|
+
if (
|
|
265
|
+
info is None
|
|
266
|
+
or isinstance(info.registration_id, bool)
|
|
267
|
+
or not isinstance(info.registration_id, int)
|
|
268
|
+
or abs(info.registration_id) > _MAX_SAFE_INTEGER
|
|
269
|
+
or info.registration_id <= 0
|
|
270
|
+
):
|
|
271
|
+
raise ValueError("registration payload requires a valid registrationId")
|
|
272
|
+
registration_id = info.registration_id
|
|
273
|
+
signed_pre_key = config.signed_pre_key
|
|
274
|
+
if (
|
|
275
|
+
signed_pre_key is None
|
|
276
|
+
or isinstance(signed_pre_key.key_id, bool)
|
|
277
|
+
or not isinstance(signed_pre_key.key_id, int)
|
|
278
|
+
or abs(signed_pre_key.key_id) > _MAX_SAFE_INTEGER
|
|
279
|
+
or signed_pre_key.key_id <= 0
|
|
280
|
+
):
|
|
281
|
+
raise ValueError("registration payload requires a valid signedPreKeyId")
|
|
282
|
+
|
|
283
|
+
if config.version_base is not None:
|
|
284
|
+
version_base = config.version_base
|
|
285
|
+
else:
|
|
286
|
+
version_base = _WA_VERSION
|
|
287
|
+
version = _parse_version(version_base)
|
|
288
|
+
common = _build_common_payload(
|
|
289
|
+
version_base,
|
|
290
|
+
config.passive,
|
|
291
|
+
config.pull,
|
|
292
|
+
False,
|
|
293
|
+
config.user_agent,
|
|
294
|
+
config.web_info,
|
|
295
|
+
version,
|
|
296
|
+
)
|
|
297
|
+
pairing = {
|
|
298
|
+
"buildHash": config.build_hash
|
|
299
|
+
if config.build_hash is not None
|
|
300
|
+
else md5_bytes(version_base),
|
|
301
|
+
"deviceProps": config.device_props
|
|
302
|
+
if config.device_props is not None
|
|
303
|
+
else _default_device_props(
|
|
304
|
+
config.device_browser,
|
|
305
|
+
config.device_os_display_name,
|
|
306
|
+
config.device_os_version,
|
|
307
|
+
config.require_full_sync,
|
|
308
|
+
),
|
|
309
|
+
"eRegid": int_to_bytes(4, registration_id),
|
|
310
|
+
"eKeytype": int_to_bytes(1, 5),
|
|
311
|
+
"eIdent": bytes(info.identity_key_pair.pub_key),
|
|
312
|
+
"eSkeyId": int_to_bytes(3, signed_pre_key.key_id),
|
|
313
|
+
"eSkeyVal": bytes(signed_pre_key.key_pair.pub_key),
|
|
314
|
+
"eSkeySig": bytes(signed_pre_key.signature),
|
|
315
|
+
}
|
|
316
|
+
message = WAProto_pb2.ClientPayload(devicePairingData=pairing, **common)
|
|
317
|
+
return bytes(message.SerializeToString())
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def get_runtime_os_version() -> str | None:
|
|
321
|
+
"""Best-effort OS version, mirroring the TS runtime helper."""
|
|
322
|
+
import platform
|
|
323
|
+
|
|
324
|
+
raw = platform.release()
|
|
325
|
+
if not raw:
|
|
326
|
+
return None
|
|
327
|
+
if sys.platform == "win32":
|
|
328
|
+
chunks = raw.split(".")
|
|
329
|
+
major = chunks[0] if chunks else ""
|
|
330
|
+
if major == "10":
|
|
331
|
+
build = int(chunks[2]) if len(chunks) > 2 and chunks[2].isdigit() else 0
|
|
332
|
+
return "11" if build >= 22000 else "10"
|
|
333
|
+
return major or None
|
|
334
|
+
if sys.platform == "darwin":
|
|
335
|
+
chunks = raw.split(".")
|
|
336
|
+
try:
|
|
337
|
+
darwin_major = int(chunks[0])
|
|
338
|
+
except ValueError:
|
|
339
|
+
return raw
|
|
340
|
+
if darwin_major >= 20:
|
|
341
|
+
minor = chunks[1] if len(chunks) > 1 else "0"
|
|
342
|
+
return f"{darwin_major - 9}.{minor}"
|
|
343
|
+
return raw
|
|
344
|
+
return raw
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Noise protocol constants (copied verbatim from the oracle)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
WA_PROTO_HEADER: bytes = bytes([87, 65, 6, 3])
|
|
6
|
+
NOISE_XX_NAME: bytes = "Noise_XX_25519_AESGCM_SHA256\0\0\0\0".encode("utf-8")
|
|
7
|
+
NOISE_IK_NAME: bytes = "Noise_IK_25519_AESGCM_SHA256\0\0\0\0".encode("utf-8")
|
|
8
|
+
NOISE_XX_FALLBACK_NAME: bytes = "Noise_XXfallback_25519_AESGCM_SHA256".encode("utf-8")
|
|
9
|
+
ROOT_CA_SERIAL: int = 0
|
|
10
|
+
ROOT_CA_PUBLIC_KEY_HEX: str = (
|
|
11
|
+
"142375574d0a587166aae71ebe516437c4a28b73e3695c6ce1f7f9545da8ee6b"
|
|
12
|
+
)
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""3-byte big-endian length-prefixed frame codec.
|
|
2
|
+
|
|
3
|
+
Reassembles frames split across wire chunks and multiple frames merged into
|
|
4
|
+
one chunk. The intro frame (protocol header) is prepended once, on the first
|
|
5
|
+
encode. Raises on frames larger than ``max_frame_length``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
_MAX_FRAME_LENGTH = (1 << 24) - 1
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _frame_length(header: bytes | bytearray) -> int:
|
|
14
|
+
return (header[0] << 16) | (header[1] << 8) | header[2]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class WaFrameCodec:
|
|
18
|
+
"""Length-prefixed frame encoder/decoder with reassembly state."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
intro_frame: bytes | bytearray | None = None,
|
|
23
|
+
max_frame_length: int = _MAX_FRAME_LENGTH,
|
|
24
|
+
) -> None:
|
|
25
|
+
if (
|
|
26
|
+
isinstance(max_frame_length, bool)
|
|
27
|
+
or not isinstance(max_frame_length, int)
|
|
28
|
+
or max_frame_length <= 0
|
|
29
|
+
):
|
|
30
|
+
raise ValueError("maxFrameLength must be a positive safe integer")
|
|
31
|
+
if max_frame_length >= 1 << 24:
|
|
32
|
+
raise ValueError(
|
|
33
|
+
"maxFrameLength must be lower than protocol limit (16777216)"
|
|
34
|
+
)
|
|
35
|
+
intro = bytes(intro_frame) if intro_frame is not None else b""
|
|
36
|
+
self._intro_frame = intro if intro else None
|
|
37
|
+
self._max_frame_length = max_frame_length
|
|
38
|
+
self._intro_sent = False
|
|
39
|
+
self._buffered = bytearray()
|
|
40
|
+
|
|
41
|
+
def _assert_frame_length(self, length: int) -> None:
|
|
42
|
+
if length > self._max_frame_length:
|
|
43
|
+
raise ValueError(
|
|
44
|
+
f"incoming frame is too large: {length} bytes "
|
|
45
|
+
f"(max allowed: {self._max_frame_length})"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def _append_buffered(self, chunk: bytes | bytearray) -> None:
|
|
49
|
+
if chunk:
|
|
50
|
+
self._buffered.extend(chunk)
|
|
51
|
+
|
|
52
|
+
def encode_frame(self, frame: bytes | bytearray) -> bytes:
|
|
53
|
+
"""Encode one frame, prepending the intro frame on the first call."""
|
|
54
|
+
raw = bytes(frame)
|
|
55
|
+
if len(raw) > self._max_frame_length:
|
|
56
|
+
raise ValueError(
|
|
57
|
+
f"frame is too large: {len(raw)} bytes "
|
|
58
|
+
f"(max allowed: {self._max_frame_length})"
|
|
59
|
+
)
|
|
60
|
+
header = bytes(
|
|
61
|
+
[(len(raw) >> 16) & 0xFF, (len(raw) >> 8) & 0xFF, len(raw) & 0xFF]
|
|
62
|
+
)
|
|
63
|
+
if not self._intro_sent and self._intro_frame is not None:
|
|
64
|
+
self._intro_sent = True
|
|
65
|
+
return self._intro_frame + header + raw
|
|
66
|
+
self._intro_sent = True
|
|
67
|
+
return header + raw
|
|
68
|
+
|
|
69
|
+
def push_wire_chunk(self, chunk: bytes | bytearray) -> list[bytes]:
|
|
70
|
+
"""Feed wire bytes; returns every complete frame now available."""
|
|
71
|
+
data = bytes(chunk)
|
|
72
|
+
if not data:
|
|
73
|
+
return []
|
|
74
|
+
frames: list[bytes] = []
|
|
75
|
+
offset = 0
|
|
76
|
+
if self._buffered:
|
|
77
|
+
buffered = bytes(self._buffered)
|
|
78
|
+
if len(buffered) < 3:
|
|
79
|
+
missing = 3 - len(buffered)
|
|
80
|
+
if len(data) < missing:
|
|
81
|
+
self._append_buffered(data)
|
|
82
|
+
return frames
|
|
83
|
+
self._append_buffered(data[:missing])
|
|
84
|
+
buffered = bytes(self._buffered)
|
|
85
|
+
length = _frame_length(buffered)
|
|
86
|
+
self._assert_frame_length(length)
|
|
87
|
+
rest = data[missing:]
|
|
88
|
+
if len(rest) < length:
|
|
89
|
+
self._append_buffered(rest)
|
|
90
|
+
return frames
|
|
91
|
+
frames.append(rest[:length])
|
|
92
|
+
offset = missing + length
|
|
93
|
+
else:
|
|
94
|
+
length = _frame_length(buffered)
|
|
95
|
+
self._assert_frame_length(length)
|
|
96
|
+
payload_have = len(buffered) - 3
|
|
97
|
+
missing = length - payload_have
|
|
98
|
+
if missing > len(data):
|
|
99
|
+
self._append_buffered(data)
|
|
100
|
+
return frames
|
|
101
|
+
if missing == 0:
|
|
102
|
+
frames.append(buffered[3 : 3 + length])
|
|
103
|
+
elif payload_have == 0:
|
|
104
|
+
frames.append(data[:missing])
|
|
105
|
+
else:
|
|
106
|
+
frames.append(buffered[3:] + data[:missing])
|
|
107
|
+
offset = missing
|
|
108
|
+
self._buffered = bytearray()
|
|
109
|
+
rest = data[offset:]
|
|
110
|
+
pos = 0
|
|
111
|
+
while len(rest) - pos >= 3:
|
|
112
|
+
length = _frame_length(rest[pos : pos + 3])
|
|
113
|
+
self._assert_frame_length(length)
|
|
114
|
+
if len(rest) - pos - 3 < length:
|
|
115
|
+
break
|
|
116
|
+
start = pos + 3
|
|
117
|
+
frames.append(rest[start : start + length])
|
|
118
|
+
pos = start + length
|
|
119
|
+
self._buffered = bytearray(rest[pos:])
|
|
120
|
+
return frames
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Noise XX-style handshake state: transcript hash, chaining key, cipher key.
|
|
2
|
+
|
|
3
|
+
Synchronous throughout (the crypto underneath is fast); call ``finish`` to
|
|
4
|
+
produce the post-handshake channel.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from zapy._crypto import (
|
|
10
|
+
aes_gcm_decrypt,
|
|
11
|
+
aes_gcm_encrypt,
|
|
12
|
+
hkdf_split,
|
|
13
|
+
sha256,
|
|
14
|
+
write_nonce_counter,
|
|
15
|
+
)
|
|
16
|
+
from zapy._transport.noise.socket import WaNoiseSocket
|
|
17
|
+
|
|
18
|
+
_EMPTY = b""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class WaNoiseHandshake:
|
|
22
|
+
"""One side of the Noise handshake message exchange."""
|
|
23
|
+
|
|
24
|
+
def __init__(self) -> None:
|
|
25
|
+
self._handshake_hash = _EMPTY
|
|
26
|
+
self._chaining_key = _EMPTY
|
|
27
|
+
self._cipher_key: bytes | None = None
|
|
28
|
+
self._nonce = 0
|
|
29
|
+
self._nonce_scratch = bytearray(12)
|
|
30
|
+
|
|
31
|
+
def start(
|
|
32
|
+
self, protocol_name: bytes | bytearray, prologue: bytes | bytearray
|
|
33
|
+
) -> None:
|
|
34
|
+
"""Initialize from the protocol name (hashed unless already 32 bytes)."""
|
|
35
|
+
name = bytes(protocol_name)
|
|
36
|
+
seed = name if len(name) == 32 else sha256(name)
|
|
37
|
+
self._handshake_hash = seed
|
|
38
|
+
self._chaining_key = seed
|
|
39
|
+
self._cipher_key = seed
|
|
40
|
+
self.authenticate(bytes(prologue))
|
|
41
|
+
|
|
42
|
+
def authenticate(self, data: bytes | bytearray) -> None:
|
|
43
|
+
"""Mix data into the transcript hash."""
|
|
44
|
+
self._handshake_hash = sha256([self._handshake_hash, bytes(data)])
|
|
45
|
+
|
|
46
|
+
def mix_into_key(self, key_material: bytes | bytearray) -> None:
|
|
47
|
+
"""Mix key material into the chaining key and derive the next cipher key."""
|
|
48
|
+
self._nonce = 0
|
|
49
|
+
new_chaining_key, next_cipher_key = hkdf_split(
|
|
50
|
+
bytes(key_material), self._chaining_key, _EMPTY
|
|
51
|
+
)
|
|
52
|
+
self._chaining_key = new_chaining_key
|
|
53
|
+
self._cipher_key = next_cipher_key
|
|
54
|
+
|
|
55
|
+
def encrypt(self, plaintext: bytes | bytearray) -> bytes:
|
|
56
|
+
"""Encrypt (and authenticate into the transcript)."""
|
|
57
|
+
if self._cipher_key is None:
|
|
58
|
+
raise ValueError("noise handshake cipher key is not initialized")
|
|
59
|
+
write_nonce_counter(self._nonce_scratch, self._nonce)
|
|
60
|
+
self._nonce += 1
|
|
61
|
+
ciphertext = aes_gcm_encrypt(
|
|
62
|
+
self._cipher_key,
|
|
63
|
+
bytes(self._nonce_scratch),
|
|
64
|
+
bytes(plaintext),
|
|
65
|
+
self._handshake_hash,
|
|
66
|
+
)
|
|
67
|
+
self.authenticate(ciphertext)
|
|
68
|
+
return ciphertext
|
|
69
|
+
|
|
70
|
+
def decrypt(self, ciphertext: bytes | bytearray) -> bytes:
|
|
71
|
+
"""Decrypt (and authenticate into the transcript)."""
|
|
72
|
+
if self._cipher_key is None:
|
|
73
|
+
raise ValueError("noise handshake cipher key is not initialized")
|
|
74
|
+
write_nonce_counter(self._nonce_scratch, self._nonce)
|
|
75
|
+
self._nonce += 1
|
|
76
|
+
plaintext = aes_gcm_decrypt(
|
|
77
|
+
self._cipher_key,
|
|
78
|
+
bytes(self._nonce_scratch),
|
|
79
|
+
bytes(ciphertext),
|
|
80
|
+
self._handshake_hash,
|
|
81
|
+
)
|
|
82
|
+
self.authenticate(bytes(ciphertext))
|
|
83
|
+
return plaintext
|
|
84
|
+
|
|
85
|
+
def finish(self) -> WaNoiseSocket:
|
|
86
|
+
"""Derive the post-handshake channel and wipe the handshake state."""
|
|
87
|
+
write_key, read_key = hkdf_split(_EMPTY, self._chaining_key, _EMPTY)
|
|
88
|
+
self._handshake_hash = _EMPTY
|
|
89
|
+
self._chaining_key = _EMPTY
|
|
90
|
+
self._cipher_key = None
|
|
91
|
+
self._nonce = 0
|
|
92
|
+
return WaNoiseSocket(write_key, read_key)
|