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,633 @@
|
|
|
1
|
+
"""WhatsApp media payload encryption (mirrors ``src/media/crypto/``).
|
|
2
|
+
|
|
3
|
+
AES-256-CBC + HMAC-SHA-256 + SHA-256 hashes + streaming sidecar, with
|
|
4
|
+
buffer-only and streaming variants for upload, download, and disk-staged
|
|
5
|
+
encryption. All primitives are synchronous (the oracle's ``async`` only
|
|
6
|
+
wraps a thread pool); the streaming pumps are ``async`` because they drive
|
|
7
|
+
byte iterators and temp files.
|
|
8
|
+
|
|
9
|
+
The HKDF ``info`` table is a verbatim copy of the ``WA_MEDIA_HKDF_INFO``
|
|
10
|
+
rows in ``src/protocol/media.ts`` (kept here because that protocol module
|
|
11
|
+
is outside this layer's scope).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import hashlib
|
|
18
|
+
import hmac
|
|
19
|
+
import os
|
|
20
|
+
import tempfile
|
|
21
|
+
from collections.abc import AsyncIterator
|
|
22
|
+
from typing import BinaryIO
|
|
23
|
+
|
|
24
|
+
from cryptography.hazmat.primitives import padding as symmetric_padding
|
|
25
|
+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
26
|
+
|
|
27
|
+
from zapy._crypto.core.hkdf import hkdf
|
|
28
|
+
from zapy._crypto.core.primitives import (
|
|
29
|
+
aes_cbc_decrypt,
|
|
30
|
+
aes_cbc_encrypt_with_trailer,
|
|
31
|
+
hmac_sha256_sign,
|
|
32
|
+
sha256,
|
|
33
|
+
)
|
|
34
|
+
from zapy._crypto.core.random import random_bytes
|
|
35
|
+
from zapy._media.constants import (
|
|
36
|
+
ENC_KEY_END,
|
|
37
|
+
ENC_KEY_START,
|
|
38
|
+
HMAC_TRUNCATED_SIZE,
|
|
39
|
+
IV_SIZE,
|
|
40
|
+
MAC_KEY_END,
|
|
41
|
+
MAC_KEY_START,
|
|
42
|
+
MEDIA_HKDF_SIZE,
|
|
43
|
+
SIDECAR_CHUNK_SIZE,
|
|
44
|
+
SIDECAR_HMAC_SIZE,
|
|
45
|
+
)
|
|
46
|
+
from zapy._media.container import WaStreamableScanner, scan_streamable
|
|
47
|
+
from zapy._media.types import (
|
|
48
|
+
WaMediaDecryptionResult,
|
|
49
|
+
WaMediaDecryptReadableOptions,
|
|
50
|
+
WaMediaDerivedKeys,
|
|
51
|
+
WaMediaEncryptionResult,
|
|
52
|
+
WaMediaFileEncryptionResult,
|
|
53
|
+
WaMediaReadableDecryptionResult,
|
|
54
|
+
WaMediaReadableDecryptionResultMetadata,
|
|
55
|
+
WaMediaReadableEncryptionMetadata,
|
|
56
|
+
WaMediaReadableEncryptionResult,
|
|
57
|
+
)
|
|
58
|
+
from zapy._util.bytes import assert_byte_length, uint8_timing_safe_equal
|
|
59
|
+
|
|
60
|
+
_AES_BLOCK_SIZE: int = 16
|
|
61
|
+
_CHUNK_SIZE: int = 65_536
|
|
62
|
+
|
|
63
|
+
# Verbatim ``WA_MEDIA_HKDF_INFO`` rows from ``src/protocol/media.ts``.
|
|
64
|
+
_MEDIA_HKDF_INFO: dict[str, bytes] = {
|
|
65
|
+
"document": "WhatsApp Document Keys".encode("utf-8"),
|
|
66
|
+
"image": "WhatsApp Image Keys".encode("utf-8"),
|
|
67
|
+
"sticker": "WhatsApp Image Keys".encode("utf-8"),
|
|
68
|
+
"xma-image": "WhatsApp Image Keys".encode("utf-8"),
|
|
69
|
+
"video": "WhatsApp Video Keys".encode("utf-8"),
|
|
70
|
+
"gif": "WhatsApp Video Keys".encode("utf-8"),
|
|
71
|
+
"audio": "WhatsApp Audio Keys".encode("utf-8"),
|
|
72
|
+
"ptt": "WhatsApp Audio Keys".encode("utf-8"),
|
|
73
|
+
"md-app-state": "WhatsApp App State Keys".encode("utf-8"),
|
|
74
|
+
"md-msg-hist": "WhatsApp History Keys".encode("utf-8"),
|
|
75
|
+
"history": "WhatsApp History Keys".encode("utf-8"),
|
|
76
|
+
"group-history": "Group History".encode("utf-8"),
|
|
77
|
+
"sticker-pack": "WhatsApp Sticker Pack Keys".encode("utf-8"),
|
|
78
|
+
"thumbnail-sticker-pack": "WhatsApp Sticker Pack Thumbnail Keys".encode("utf-8"),
|
|
79
|
+
"thumbnail-link": "WhatsApp Link Thumbnail Keys".encode("utf-8"),
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _get_wa_media_hkdf_info(media_type: str) -> bytes:
|
|
84
|
+
"""HKDF ``info`` for a media type (mirrors ``getWaMediaHkdfInfo``)."""
|
|
85
|
+
info = _MEDIA_HKDF_INFO.get(media_type)
|
|
86
|
+
if info is None:
|
|
87
|
+
raise ValueError(f"unsupported media type: {media_type}")
|
|
88
|
+
return info
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _media_type_to_hkdf_info(media_type: str) -> bytes:
|
|
92
|
+
if media_type == "ptv":
|
|
93
|
+
return _get_wa_media_hkdf_info("video")
|
|
94
|
+
if media_type == "history":
|
|
95
|
+
return _get_wa_media_hkdf_info("md-msg-hist")
|
|
96
|
+
return _get_wa_media_hkdf_info(media_type)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _compute_first_frame_sidecar(
|
|
100
|
+
mac_key: bytes, iv: bytes, ciphertext: bytes, first_frame_length: int
|
|
101
|
+
) -> bytes:
|
|
102
|
+
aligned = (first_frame_length + _AES_BLOCK_SIZE - 1) // _AES_BLOCK_SIZE
|
|
103
|
+
aligned *= _AES_BLOCK_SIZE
|
|
104
|
+
digest = hmac_sha256_sign(mac_key, [iv, ciphertext[:aligned]])
|
|
105
|
+
return digest[:SIDECAR_HMAC_SIZE]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _SidecarAccumulator:
|
|
109
|
+
"""Incremental streaming-sidecar builder (mirrors ``SidecarAccumulator``)."""
|
|
110
|
+
|
|
111
|
+
def __init__(self, mac_key: bytes, estimated_size: int = 0) -> None:
|
|
112
|
+
self._mac_key = bytes(mac_key)
|
|
113
|
+
safe = estimated_size if estimated_size > 0 else 0
|
|
114
|
+
estimated = max((safe + SIDECAR_CHUNK_SIZE - 1) // SIDECAR_CHUNK_SIZE + 1, 16)
|
|
115
|
+
self._result = bytearray(estimated * SIDECAR_HMAC_SIZE)
|
|
116
|
+
self._result_offset = 0
|
|
117
|
+
self._total_pushed = 0
|
|
118
|
+
self._window = bytearray(IV_SIZE + SIDECAR_CHUNK_SIZE)
|
|
119
|
+
self._window_offset = 0
|
|
120
|
+
self._next_chunk_start = 0
|
|
121
|
+
|
|
122
|
+
def push(self, data: bytes | bytearray) -> None:
|
|
123
|
+
src_offset = 0
|
|
124
|
+
while src_offset < len(data):
|
|
125
|
+
window_end = self._next_chunk_start + IV_SIZE + SIDECAR_CHUNK_SIZE
|
|
126
|
+
remaining = window_end - self._total_pushed
|
|
127
|
+
to_copy = min(remaining, len(data) - src_offset)
|
|
128
|
+
self._window[self._window_offset : self._window_offset + to_copy] = data[
|
|
129
|
+
src_offset : src_offset + to_copy
|
|
130
|
+
]
|
|
131
|
+
self._window_offset += to_copy
|
|
132
|
+
self._total_pushed += to_copy
|
|
133
|
+
src_offset += to_copy
|
|
134
|
+
if self._total_pushed == window_end:
|
|
135
|
+
self._flush_chunk()
|
|
136
|
+
|
|
137
|
+
def finish(self) -> bytes:
|
|
138
|
+
if self._window_offset > 0:
|
|
139
|
+
self._flush_chunk()
|
|
140
|
+
return bytes(self._result[: self._result_offset])
|
|
141
|
+
|
|
142
|
+
def _flush_chunk(self) -> None:
|
|
143
|
+
digest = hmac.new(
|
|
144
|
+
self._mac_key, bytes(self._window[: self._window_offset]), hashlib.sha256
|
|
145
|
+
).digest()
|
|
146
|
+
if self._result_offset + SIDECAR_HMAC_SIZE > len(self._result):
|
|
147
|
+
grown = bytearray(len(self._result) * 2)
|
|
148
|
+
grown[: len(self._result)] = self._result
|
|
149
|
+
self._result = grown
|
|
150
|
+
self._result[self._result_offset : self._result_offset + SIDECAR_HMAC_SIZE] = (
|
|
151
|
+
digest[:SIDECAR_HMAC_SIZE]
|
|
152
|
+
)
|
|
153
|
+
self._result_offset += SIDECAR_HMAC_SIZE
|
|
154
|
+
|
|
155
|
+
self._next_chunk_start += SIDECAR_CHUNK_SIZE
|
|
156
|
+
overlap = bytes(
|
|
157
|
+
self._window[self._window_offset - IV_SIZE : self._window_offset]
|
|
158
|
+
)
|
|
159
|
+
self._window[0:IV_SIZE] = overlap
|
|
160
|
+
self._window_offset = IV_SIZE
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class WaMediaCrypto:
|
|
164
|
+
"""WhatsApp media payload encryption/decryption (mirrors ``WaMediaCrypto``)."""
|
|
165
|
+
|
|
166
|
+
@staticmethod
|
|
167
|
+
def generate_media_key() -> bytes:
|
|
168
|
+
"""Generate a fresh 32-byte media key for :meth:`derive_keys`."""
|
|
169
|
+
return random_bytes(32)
|
|
170
|
+
|
|
171
|
+
@staticmethod
|
|
172
|
+
def derive_keys(
|
|
173
|
+
media_type: str, media_key: bytes | bytearray
|
|
174
|
+
) -> WaMediaDerivedKeys:
|
|
175
|
+
"""Derive the per-type AES IV, AES key and MAC key from ``media_key``."""
|
|
176
|
+
key = bytes(media_key)
|
|
177
|
+
assert_byte_length(key, 32, f"invalid media key length {len(key)}, expected 32")
|
|
178
|
+
expanded = hkdf(
|
|
179
|
+
key, None, _media_type_to_hkdf_info(media_type), MEDIA_HKDF_SIZE
|
|
180
|
+
)
|
|
181
|
+
return WaMediaDerivedKeys(
|
|
182
|
+
iv=expanded[:IV_SIZE],
|
|
183
|
+
enc_key=expanded[ENC_KEY_START:ENC_KEY_END],
|
|
184
|
+
mac_key=expanded[MAC_KEY_START:MAC_KEY_END],
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
@staticmethod
|
|
188
|
+
def encrypt_bytes(
|
|
189
|
+
media_type: str,
|
|
190
|
+
media_key: bytes | bytearray,
|
|
191
|
+
plaintext: bytes | bytearray,
|
|
192
|
+
sidecar: bool = True,
|
|
193
|
+
first_frame_length: int | None = None,
|
|
194
|
+
) -> WaMediaEncryptionResult:
|
|
195
|
+
"""Encrypt a buffer, with sidecar (unless disabled) and first-frame sidecar."""
|
|
196
|
+
plain = bytes(plaintext)
|
|
197
|
+
keys = WaMediaCrypto.derive_keys(media_type, media_key)
|
|
198
|
+
padded = aes_cbc_encrypt_with_trailer(
|
|
199
|
+
keys.enc_key, keys.iv, plain, HMAC_TRUNCATED_SIZE
|
|
200
|
+
)
|
|
201
|
+
cipher_length = len(padded) - HMAC_TRUNCATED_SIZE
|
|
202
|
+
ciphertext = padded[:cipher_length]
|
|
203
|
+
|
|
204
|
+
mac = hmac_sha256_sign(keys.mac_key, [keys.iv, ciphertext])
|
|
205
|
+
ciphertext_hmac = ciphertext + mac[:HMAC_TRUNCATED_SIZE]
|
|
206
|
+
|
|
207
|
+
streaming_sidecar: bytes | None = None
|
|
208
|
+
if sidecar and scan_streamable(plain) is not False:
|
|
209
|
+
acc = _SidecarAccumulator(keys.mac_key, len(plain))
|
|
210
|
+
acc.push(keys.iv)
|
|
211
|
+
acc.push(ciphertext)
|
|
212
|
+
acc.push(mac[:HMAC_TRUNCATED_SIZE])
|
|
213
|
+
streaming_sidecar = acc.finish()
|
|
214
|
+
|
|
215
|
+
first_frame_sidecar: bytes | None = None
|
|
216
|
+
if first_frame_length is not None:
|
|
217
|
+
first_frame_sidecar = _compute_first_frame_sidecar(
|
|
218
|
+
keys.mac_key, keys.iv, ciphertext, first_frame_length
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
return WaMediaEncryptionResult(
|
|
222
|
+
ciphertext_hmac=ciphertext_hmac,
|
|
223
|
+
file_sha256=sha256(plain),
|
|
224
|
+
file_enc_sha256=sha256(ciphertext_hmac),
|
|
225
|
+
streaming_sidecar=streaming_sidecar,
|
|
226
|
+
first_frame_sidecar=first_frame_sidecar,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
@staticmethod
|
|
230
|
+
def decrypt_bytes(
|
|
231
|
+
media_type: str,
|
|
232
|
+
media_key: bytes | bytearray,
|
|
233
|
+
ciphertext_hmac: bytes | bytearray,
|
|
234
|
+
expected_file_sha256: bytes | bytearray | None = None,
|
|
235
|
+
expected_file_enc_sha256: bytes | bytearray | None = None,
|
|
236
|
+
skip_mac_verification: bool = False,
|
|
237
|
+
) -> WaMediaDecryptionResult:
|
|
238
|
+
"""Decrypt a ``ciphertext||mac`` buffer, verifying hashes and the MAC."""
|
|
239
|
+
raw = bytes(ciphertext_hmac)
|
|
240
|
+
if len(raw) < HMAC_TRUNCATED_SIZE:
|
|
241
|
+
raise ValueError(f"ciphertext too short: {len(raw)}")
|
|
242
|
+
|
|
243
|
+
if expected_file_enc_sha256 is not None:
|
|
244
|
+
computed = sha256(raw)
|
|
245
|
+
if not uint8_timing_safe_equal(computed, bytes(expected_file_enc_sha256)):
|
|
246
|
+
raise ValueError("encrypted file hash mismatch")
|
|
247
|
+
|
|
248
|
+
keys = WaMediaCrypto.derive_keys(media_type, media_key)
|
|
249
|
+
ciphertext = raw[: len(raw) - HMAC_TRUNCATED_SIZE]
|
|
250
|
+
expected_mac = raw[len(raw) - HMAC_TRUNCATED_SIZE :]
|
|
251
|
+
|
|
252
|
+
if not skip_mac_verification:
|
|
253
|
+
mac = hmac_sha256_sign(keys.mac_key, [keys.iv, ciphertext])
|
|
254
|
+
if not uint8_timing_safe_equal(mac[:HMAC_TRUNCATED_SIZE], expected_mac):
|
|
255
|
+
raise ValueError("media MAC mismatch")
|
|
256
|
+
|
|
257
|
+
plaintext = aes_cbc_decrypt(keys.enc_key, keys.iv, ciphertext)
|
|
258
|
+
file_sha256 = sha256(plaintext)
|
|
259
|
+
if expected_file_sha256 is not None and not uint8_timing_safe_equal(
|
|
260
|
+
file_sha256, bytes(expected_file_sha256)
|
|
261
|
+
):
|
|
262
|
+
raise ValueError("plaintext file hash mismatch")
|
|
263
|
+
|
|
264
|
+
file_enc_sha256 = (
|
|
265
|
+
bytes(expected_file_enc_sha256)
|
|
266
|
+
if expected_file_enc_sha256 is not None
|
|
267
|
+
else sha256(raw)
|
|
268
|
+
)
|
|
269
|
+
return WaMediaDecryptionResult(
|
|
270
|
+
plaintext=plaintext,
|
|
271
|
+
file_sha256=file_sha256,
|
|
272
|
+
file_enc_sha256=file_enc_sha256,
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
async def encrypt_readable(
|
|
277
|
+
media_type: str,
|
|
278
|
+
media_key: bytes | bytearray,
|
|
279
|
+
plaintext: AsyncIterator[bytes] | BinaryIO,
|
|
280
|
+
sidecar: bool = True,
|
|
281
|
+
first_frame_length: int | None = None,
|
|
282
|
+
expected_file_size: int | None = None,
|
|
283
|
+
) -> WaMediaReadableEncryptionResult:
|
|
284
|
+
"""Stream-encrypt; the metadata awaitable resolves after the stream ends."""
|
|
285
|
+
keys = WaMediaCrypto.derive_keys(media_type, media_key)
|
|
286
|
+
loop = asyncio.get_running_loop()
|
|
287
|
+
future: asyncio.Future[WaMediaReadableEncryptionMetadata] = loop.create_future()
|
|
288
|
+
|
|
289
|
+
async def _encrypted() -> AsyncIterator[bytes]:
|
|
290
|
+
holder: dict[str, WaMediaReadableEncryptionMetadata] = {}
|
|
291
|
+
try:
|
|
292
|
+
async for piece in _pump_encryption_collect(
|
|
293
|
+
_coerce_plain_chunks(plaintext),
|
|
294
|
+
keys,
|
|
295
|
+
sidecar,
|
|
296
|
+
first_frame_length,
|
|
297
|
+
expected_file_size,
|
|
298
|
+
holder,
|
|
299
|
+
):
|
|
300
|
+
yield piece
|
|
301
|
+
except BaseException as error:
|
|
302
|
+
if not future.done():
|
|
303
|
+
future.set_exception(error)
|
|
304
|
+
raise
|
|
305
|
+
if not future.done():
|
|
306
|
+
future.set_result(holder["metadata"])
|
|
307
|
+
|
|
308
|
+
return WaMediaReadableEncryptionResult(encrypted=_encrypted(), metadata=future)
|
|
309
|
+
|
|
310
|
+
@staticmethod
|
|
311
|
+
async def encrypt_to_file(
|
|
312
|
+
media_type: str,
|
|
313
|
+
media_key: bytes | bytearray,
|
|
314
|
+
plaintext: AsyncIterator[bytes] | BinaryIO,
|
|
315
|
+
sidecar: bool = True,
|
|
316
|
+
first_frame_length: int | None = None,
|
|
317
|
+
expected_file_size: int | None = None,
|
|
318
|
+
) -> WaMediaFileEncryptionResult:
|
|
319
|
+
"""Encrypt ``plaintext`` to a temp file; remove it on failure."""
|
|
320
|
+
keys = WaMediaCrypto.derive_keys(media_type, media_key)
|
|
321
|
+
fd, file_path = tempfile.mkstemp(prefix="zapy-enc-")
|
|
322
|
+
os.close(fd)
|
|
323
|
+
try:
|
|
324
|
+
metadata = await _pump_encryption_to_path(
|
|
325
|
+
_coerce_plain_chunks(plaintext),
|
|
326
|
+
keys,
|
|
327
|
+
file_path,
|
|
328
|
+
sidecar,
|
|
329
|
+
first_frame_length,
|
|
330
|
+
expected_file_size,
|
|
331
|
+
)
|
|
332
|
+
file_size = os.path.getsize(file_path)
|
|
333
|
+
return WaMediaFileEncryptionResult(
|
|
334
|
+
file_path=file_path,
|
|
335
|
+
file_size=file_size,
|
|
336
|
+
file_sha256=metadata.file_sha256,
|
|
337
|
+
file_enc_sha256=metadata.file_enc_sha256,
|
|
338
|
+
plaintext_length=metadata.plaintext_length,
|
|
339
|
+
streaming_sidecar=metadata.streaming_sidecar,
|
|
340
|
+
first_frame_sidecar=metadata.first_frame_sidecar,
|
|
341
|
+
)
|
|
342
|
+
except BaseException:
|
|
343
|
+
try:
|
|
344
|
+
os.unlink(file_path)
|
|
345
|
+
except OSError:
|
|
346
|
+
pass
|
|
347
|
+
raise
|
|
348
|
+
|
|
349
|
+
@staticmethod
|
|
350
|
+
async def cleanup_encrypted_file(file_path: str) -> None:
|
|
351
|
+
"""Remove a temp file from :meth:`encrypt_to_file` (missing files ignored)."""
|
|
352
|
+
try:
|
|
353
|
+
await asyncio.to_thread(os.unlink, file_path)
|
|
354
|
+
except OSError:
|
|
355
|
+
pass
|
|
356
|
+
|
|
357
|
+
@staticmethod
|
|
358
|
+
async def decrypt_readable(
|
|
359
|
+
encrypted: AsyncIterator[bytes] | BinaryIO,
|
|
360
|
+
options: WaMediaDecryptReadableOptions,
|
|
361
|
+
) -> WaMediaReadableDecryptionResult:
|
|
362
|
+
"""Stream-decrypt; the metadata awaitable resolves after the stream ends."""
|
|
363
|
+
keys = WaMediaCrypto.derive_keys(options.media_type, options.media_key)
|
|
364
|
+
loop = asyncio.get_running_loop()
|
|
365
|
+
future: asyncio.Future[WaMediaReadableDecryptionResultMetadata] = (
|
|
366
|
+
loop.create_future()
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
async def _plaintext() -> AsyncIterator[bytes]:
|
|
370
|
+
holder: dict[str, WaMediaReadableDecryptionResultMetadata] = {}
|
|
371
|
+
try:
|
|
372
|
+
async for piece in _pump_decryption_collect(
|
|
373
|
+
_coerce_plain_chunks(encrypted), keys, options, holder
|
|
374
|
+
):
|
|
375
|
+
yield piece
|
|
376
|
+
except BaseException as error:
|
|
377
|
+
if not future.done():
|
|
378
|
+
future.set_exception(error)
|
|
379
|
+
raise
|
|
380
|
+
if not future.done():
|
|
381
|
+
future.set_result(holder["metadata"])
|
|
382
|
+
|
|
383
|
+
return WaMediaReadableDecryptionResult(plaintext=_plaintext(), metadata=future)
|
|
384
|
+
|
|
385
|
+
@staticmethod
|
|
386
|
+
def encrypted_length(plaintext_length: int) -> int:
|
|
387
|
+
"""Ciphertext byte length (AES-CBC padded + 10-byte MAC)."""
|
|
388
|
+
if isinstance(plaintext_length, bool) or not isinstance(plaintext_length, int):
|
|
389
|
+
raise ValueError(f"invalid plaintext length {plaintext_length}")
|
|
390
|
+
if plaintext_length < 0:
|
|
391
|
+
raise ValueError(f"invalid plaintext length {plaintext_length}")
|
|
392
|
+
padded_length = ((plaintext_length + 1 + 15) // 16) * 16
|
|
393
|
+
return padded_length + HMAC_TRUNCATED_SIZE
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
async def _coerce_plain_chunks(
|
|
397
|
+
source: AsyncIterator[bytes] | BinaryIO,
|
|
398
|
+
) -> AsyncIterator[bytes]:
|
|
399
|
+
read = getattr(source, "read", None)
|
|
400
|
+
if callable(read):
|
|
401
|
+
while True:
|
|
402
|
+
chunk = await asyncio.to_thread(read, _CHUNK_SIZE)
|
|
403
|
+
if not chunk:
|
|
404
|
+
break
|
|
405
|
+
yield bytes(chunk)
|
|
406
|
+
return
|
|
407
|
+
if isinstance(source, AsyncIterator):
|
|
408
|
+
async for chunk in source:
|
|
409
|
+
if len(chunk) == 0:
|
|
410
|
+
continue
|
|
411
|
+
yield bytes(chunk)
|
|
412
|
+
return
|
|
413
|
+
raise ValueError("media crypto received unsupported source type")
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
async def _pump_encryption_collect(
|
|
417
|
+
plaintext: AsyncIterator[bytes],
|
|
418
|
+
keys: WaMediaDerivedKeys,
|
|
419
|
+
compute_sidecar: bool,
|
|
420
|
+
first_frame_length: int | None,
|
|
421
|
+
expected_file_size: int | None,
|
|
422
|
+
holder: dict[str, WaMediaReadableEncryptionMetadata],
|
|
423
|
+
) -> AsyncIterator[bytes]:
|
|
424
|
+
encryptor = Cipher(algorithms.AES(keys.enc_key), modes.CBC(keys.iv)).encryptor()
|
|
425
|
+
padder = symmetric_padding.PKCS7(_AES_BLOCK_SIZE * 8).padder()
|
|
426
|
+
plain_hash = hashlib.sha256()
|
|
427
|
+
enc_hash = hashlib.sha256()
|
|
428
|
+
mac = hmac.new(keys.mac_key, digestmod=hashlib.sha256)
|
|
429
|
+
sidecar = (
|
|
430
|
+
_SidecarAccumulator(keys.mac_key, expected_file_size or 0)
|
|
431
|
+
if compute_sidecar
|
|
432
|
+
else None
|
|
433
|
+
)
|
|
434
|
+
scanner = WaStreamableScanner() if compute_sidecar else None
|
|
435
|
+
ff_target = (
|
|
436
|
+
IV_SIZE
|
|
437
|
+
+ ((first_frame_length + _AES_BLOCK_SIZE - 1) // _AES_BLOCK_SIZE)
|
|
438
|
+
* _AES_BLOCK_SIZE
|
|
439
|
+
if first_frame_length is not None
|
|
440
|
+
else 0
|
|
441
|
+
)
|
|
442
|
+
ff_chunks: list[bytes] = [keys.iv] if ff_target > 0 else []
|
|
443
|
+
ff_collected = IV_SIZE if ff_target > 0 else 0
|
|
444
|
+
plaintext_length = 0
|
|
445
|
+
|
|
446
|
+
mac.update(keys.iv)
|
|
447
|
+
if sidecar is not None:
|
|
448
|
+
sidecar.push(keys.iv)
|
|
449
|
+
|
|
450
|
+
async def _consume(raw: bytes) -> AsyncIterator[bytes]:
|
|
451
|
+
nonlocal ff_collected, sidecar
|
|
452
|
+
if len(raw) == 0:
|
|
453
|
+
return
|
|
454
|
+
mac.update(raw)
|
|
455
|
+
enc_hash.update(raw)
|
|
456
|
+
if sidecar is not None:
|
|
457
|
+
sidecar.push(raw)
|
|
458
|
+
if ff_collected < ff_target:
|
|
459
|
+
need = ff_target - ff_collected
|
|
460
|
+
ff_chunks.append(raw[: min(need, len(raw))])
|
|
461
|
+
ff_collected += len(raw)
|
|
462
|
+
yield raw
|
|
463
|
+
|
|
464
|
+
try:
|
|
465
|
+
async for chunk in plaintext:
|
|
466
|
+
if len(chunk) == 0:
|
|
467
|
+
continue
|
|
468
|
+
plaintext_length += len(chunk)
|
|
469
|
+
plain_hash.update(chunk)
|
|
470
|
+
if scanner is not None and scanner.verdict is None:
|
|
471
|
+
scanner.push(chunk)
|
|
472
|
+
if scanner.verdict is False:
|
|
473
|
+
sidecar = None
|
|
474
|
+
encrypted_part = encryptor.update(padder.update(chunk))
|
|
475
|
+
async for piece in _consume(encrypted_part):
|
|
476
|
+
yield piece
|
|
477
|
+
tail = encryptor.update(padder.finalize()) + encryptor.finalize()
|
|
478
|
+
async for piece in _consume(tail):
|
|
479
|
+
yield piece
|
|
480
|
+
|
|
481
|
+
signature = mac.digest()[:HMAC_TRUNCATED_SIZE]
|
|
482
|
+
enc_hash.update(signature)
|
|
483
|
+
if sidecar is not None:
|
|
484
|
+
sidecar.push(signature)
|
|
485
|
+
yield signature
|
|
486
|
+
|
|
487
|
+
first_frame_sidecar: bytes | None = None
|
|
488
|
+
if ff_target > 0:
|
|
489
|
+
first_frame_sidecar = hmac_sha256_sign(keys.mac_key, ff_chunks)[
|
|
490
|
+
:SIDECAR_HMAC_SIZE
|
|
491
|
+
]
|
|
492
|
+
|
|
493
|
+
holder["metadata"] = WaMediaReadableEncryptionMetadata(
|
|
494
|
+
file_sha256=plain_hash.digest(),
|
|
495
|
+
file_enc_sha256=enc_hash.digest(),
|
|
496
|
+
plaintext_length=plaintext_length,
|
|
497
|
+
streaming_sidecar=sidecar.finish() if sidecar is not None else None,
|
|
498
|
+
first_frame_sidecar=first_frame_sidecar,
|
|
499
|
+
)
|
|
500
|
+
except BaseException:
|
|
501
|
+
# The caller-owned stream wrappers observe the failure via the future.
|
|
502
|
+
raise
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
async def _pump_encryption_to_path(
|
|
506
|
+
plaintext: AsyncIterator[bytes],
|
|
507
|
+
keys: WaMediaDerivedKeys,
|
|
508
|
+
file_path: str,
|
|
509
|
+
compute_sidecar: bool,
|
|
510
|
+
first_frame_length: int | None,
|
|
511
|
+
expected_file_size: int | None,
|
|
512
|
+
) -> WaMediaReadableEncryptionMetadata:
|
|
513
|
+
holder: dict[str, WaMediaReadableEncryptionMetadata] = {}
|
|
514
|
+
|
|
515
|
+
def _write(chunks: list[bytes]) -> None:
|
|
516
|
+
with open(file_path, "wb") as handle:
|
|
517
|
+
for piece in chunks:
|
|
518
|
+
handle.write(piece)
|
|
519
|
+
|
|
520
|
+
collected: list[bytes] = []
|
|
521
|
+
|
|
522
|
+
async def _collect() -> None:
|
|
523
|
+
async for piece in _pump_encryption_collect(
|
|
524
|
+
plaintext,
|
|
525
|
+
keys,
|
|
526
|
+
compute_sidecar,
|
|
527
|
+
first_frame_length,
|
|
528
|
+
expected_file_size,
|
|
529
|
+
holder,
|
|
530
|
+
):
|
|
531
|
+
collected.append(bytes(piece))
|
|
532
|
+
|
|
533
|
+
await _collect()
|
|
534
|
+
await asyncio.to_thread(_write, collected)
|
|
535
|
+
return holder["metadata"]
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
async def _pump_decryption_collect(
|
|
539
|
+
encrypted: AsyncIterator[bytes],
|
|
540
|
+
keys: WaMediaDerivedKeys,
|
|
541
|
+
options: WaMediaDecryptReadableOptions,
|
|
542
|
+
holder: dict[str, WaMediaReadableDecryptionResultMetadata],
|
|
543
|
+
) -> AsyncIterator[bytes]:
|
|
544
|
+
decryptor = Cipher(algorithms.AES(keys.enc_key), modes.CBC(keys.iv)).decryptor()
|
|
545
|
+
unpadder = symmetric_padding.PKCS7(_AES_BLOCK_SIZE * 8).unpadder()
|
|
546
|
+
plain_hash = hashlib.sha256()
|
|
547
|
+
enc_hash = hashlib.sha256()
|
|
548
|
+
mac = hmac.new(keys.mac_key, digestmod=hashlib.sha256)
|
|
549
|
+
trailing = bytearray(HMAC_TRUNCATED_SIZE)
|
|
550
|
+
trailing_length = 0
|
|
551
|
+
pending = bytearray()
|
|
552
|
+
|
|
553
|
+
async def _consume(part: bytes) -> AsyncIterator[bytes]:
|
|
554
|
+
# CBC outputs the padded tail, so the final block stays buffered
|
|
555
|
+
# until the end, where the PKCS#7 unpadder strips it at once.
|
|
556
|
+
mac.update(part)
|
|
557
|
+
pending.extend(part)
|
|
558
|
+
if len(pending) > _AES_BLOCK_SIZE:
|
|
559
|
+
take = (
|
|
560
|
+
(len(pending) - _AES_BLOCK_SIZE) // _AES_BLOCK_SIZE
|
|
561
|
+
) * _AES_BLOCK_SIZE
|
|
562
|
+
block = bytes(pending[:take])
|
|
563
|
+
del pending[:take]
|
|
564
|
+
decrypted = decryptor.update(block)
|
|
565
|
+
if len(decrypted) > 0:
|
|
566
|
+
plain_hash.update(decrypted)
|
|
567
|
+
yield decrypted
|
|
568
|
+
|
|
569
|
+
mac.update(keys.iv)
|
|
570
|
+
try:
|
|
571
|
+
async for chunk in encrypted:
|
|
572
|
+
if len(chunk) == 0:
|
|
573
|
+
continue
|
|
574
|
+
enc_hash.update(chunk)
|
|
575
|
+
total = trailing_length + len(chunk)
|
|
576
|
+
if total <= HMAC_TRUNCATED_SIZE:
|
|
577
|
+
trailing[trailing_length:total] = chunk
|
|
578
|
+
trailing_length = total
|
|
579
|
+
continue
|
|
580
|
+
|
|
581
|
+
cipher_length = total - HMAC_TRUNCATED_SIZE
|
|
582
|
+
from_trailing = min(trailing_length, cipher_length)
|
|
583
|
+
if from_trailing > 0:
|
|
584
|
+
async for piece in _consume(bytes(trailing[:from_trailing])):
|
|
585
|
+
yield piece
|
|
586
|
+
from_bytes = cipher_length - from_trailing
|
|
587
|
+
if from_bytes > 0:
|
|
588
|
+
async for piece in _consume(chunk[:from_bytes]):
|
|
589
|
+
yield piece
|
|
590
|
+
keep_from_trailing = trailing_length - from_trailing
|
|
591
|
+
if keep_from_trailing > 0:
|
|
592
|
+
trailing[0:keep_from_trailing] = trailing[from_trailing:trailing_length]
|
|
593
|
+
trailing[keep_from_trailing:HMAC_TRUNCATED_SIZE] = chunk[from_bytes:]
|
|
594
|
+
trailing_length = HMAC_TRUNCATED_SIZE
|
|
595
|
+
|
|
596
|
+
if trailing_length != HMAC_TRUNCATED_SIZE:
|
|
597
|
+
raise ValueError(f"ciphertext too short: {trailing_length}")
|
|
598
|
+
|
|
599
|
+
if not options.skip_mac_verification:
|
|
600
|
+
signature = mac.digest()[:HMAC_TRUNCATED_SIZE]
|
|
601
|
+
if not uint8_timing_safe_equal(signature, bytes(trailing)):
|
|
602
|
+
raise ValueError("media MAC mismatch")
|
|
603
|
+
|
|
604
|
+
head = bytes(pending[:-_AES_BLOCK_SIZE])
|
|
605
|
+
last = bytes(pending[-_AES_BLOCK_SIZE:])
|
|
606
|
+
pending.clear()
|
|
607
|
+
final_dec = (
|
|
608
|
+
decryptor.update(head) + decryptor.update(last) + decryptor.finalize()
|
|
609
|
+
)
|
|
610
|
+
unpadded = unpadder.update(final_dec) + unpadder.finalize()
|
|
611
|
+
if len(unpadded) > 0:
|
|
612
|
+
plain_hash.update(unpadded)
|
|
613
|
+
yield unpadded
|
|
614
|
+
|
|
615
|
+
file_sha256 = plain_hash.digest()
|
|
616
|
+
file_enc_sha256 = enc_hash.digest()
|
|
617
|
+
if options.expected_file_enc_sha256 is not None and not uint8_timing_safe_equal(
|
|
618
|
+
file_enc_sha256, bytes(options.expected_file_enc_sha256)
|
|
619
|
+
):
|
|
620
|
+
raise ValueError("encrypted file hash mismatch")
|
|
621
|
+
if options.expected_file_sha256 is not None and not uint8_timing_safe_equal(
|
|
622
|
+
file_sha256, bytes(options.expected_file_sha256)
|
|
623
|
+
):
|
|
624
|
+
raise ValueError("plaintext file hash mismatch")
|
|
625
|
+
|
|
626
|
+
holder["metadata"] = WaMediaReadableDecryptionResultMetadata(
|
|
627
|
+
file_sha256=file_sha256, file_enc_sha256=file_enc_sha256
|
|
628
|
+
)
|
|
629
|
+
except BaseException:
|
|
630
|
+
raise
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
__all__ = ["WaMediaCrypto"]
|