mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-03 14:35:09 +00:00
350 lines
14 KiB
Python
350 lines
14 KiB
Python
"""Decrypt a BBTS file: an MPEG-TS whose video NAL units a sparse AES-128-CTR cipher encrypts.
|
|
|
|
The cipher follows bbtsdecrypt (https://github.com/ReiDoBrega/bbtsdecrypt, MIT licence). The output matches the
|
|
bbtsdecrypt binary, which differs from that source: the IV field, no refill of the removed emulation-prevention
|
|
bytes, and dropped delimiters and cipher padding.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import itertools
|
|
import re
|
|
import zlib
|
|
from collections.abc import Callable
|
|
from pathlib import Path
|
|
|
|
from Cryptodome.Cipher import AES
|
|
from Cryptodome.Util.strxor import strxor
|
|
|
|
PACKET = 188
|
|
SYNC = 0x47
|
|
PID_PAT = 0x0000
|
|
PID_SDT = 0x0011
|
|
PID_PMT = 0x1000
|
|
VIDEO_PID = 0x0100
|
|
AUDIO_PID = 0x0101
|
|
H264 = 0x1B
|
|
START_CODE = b"\x00\x00\x01"
|
|
START_CODES = re.compile(re.escape(START_CODE))
|
|
IV_FIELD = re.compile(rb"\|v([0-9A-Fa-f]{32})\|")
|
|
HEX_IV = re.compile(rb"([0-9A-Fa-f]{32})")
|
|
AUD = {True: 9, False: 35}
|
|
SEI = {True: (6,), False: (39, 40)}
|
|
DOVI_RPU = 62
|
|
BIT_REVERSED = bytes(int(f"{i:08b}"[::-1], 2) for i in range(256))
|
|
|
|
|
|
def decrypt_bbts(src: Path, dst: Path, key: bytes) -> None:
|
|
"""Write the clear MPEG-TS of the BBTS file ``src`` to ``dst``; only the video PES packets change."""
|
|
if len(key) != 16:
|
|
raise ValueError(f"BBTS needs a 16-byte key, got {len(key)}")
|
|
with src.open("rb") as reader, dst.open("wb") as writer:
|
|
_Decrypter(key, writer.write).run(reader.read)
|
|
|
|
|
|
def renumber_continuity(path: Path) -> None:
|
|
"""Give each TS packet of ``path`` the continuity counter that ISO/IEC 13818-1 expects, in place.
|
|
|
|
A BBTS decrypter keeps the counter of a packet that it empties, so the counter steps where it must not and FFmpeg
|
|
marks the next frame corrupt. A duplicate packet keeps its counter.
|
|
"""
|
|
last: dict[int, int] = {}
|
|
original: dict[int, int] = {}
|
|
with path.open("r+b") as f:
|
|
while chunk := bytearray(f.read(PACKET * 65536)):
|
|
changed = False
|
|
for i in range(0, len(chunk) - PACKET + 1, PACKET):
|
|
pid = (chunk[i + 1] & 0x1F) << 8 | chunk[i + 2]
|
|
header = chunk[i + 3]
|
|
cc = header & 0x0F
|
|
if pid == 0x1FFF:
|
|
continue
|
|
if pid in last:
|
|
payload = header & 0x10 and cc != original[pid]
|
|
original[pid] = cc
|
|
cc = (last[pid] + 1) & 0x0F if payload else last[pid]
|
|
if cc != header & 0x0F:
|
|
chunk[i + 3] = header & 0xF0 | cc
|
|
changed = True
|
|
else:
|
|
original[pid] = cc
|
|
last[pid] = cc
|
|
if changed:
|
|
f.seek(-len(chunk), 1)
|
|
f.write(chunk)
|
|
|
|
|
|
class _Keystream:
|
|
"""The keystream of one IV. Each NAL unit starts again at IV + 1, so one keystream serves every NAL unit of a PES.
|
|
|
|
Block 0, every tenth block and the last block XOR with AES-ECB of the counter; every other block XORs with the
|
|
counter bytes themselves.
|
|
"""
|
|
|
|
def __init__(self, key: bytes, iv: bytes) -> None:
|
|
self.key = key
|
|
self.counter = int.from_bytes(iv, "big") + 1
|
|
self.encrypted = b""
|
|
self.sparse = b""
|
|
|
|
def get(self, size: int) -> bytes:
|
|
"""The keystream of a NAL unit of ``size`` bytes."""
|
|
if size > len(self.encrypted):
|
|
self._grow(max(size, 2 * len(self.encrypted), 4096))
|
|
last = (size - 1) // 16 * 16
|
|
return self.sparse[:last] + self.encrypted[last:size]
|
|
|
|
def _grow(self, size: int) -> None:
|
|
size = -(-size // 160) * 160
|
|
encrypted = AES.new(self.key, AES.MODE_CTR, nonce=b"", initial_value=self.counter).encrypt(bytes(size))
|
|
# AES-ECB decryption of the CTR keystream gives back the counter blocks, all in C.
|
|
counters = int.from_bytes(AES.new(self.key, AES.MODE_ECB).decrypt(encrypted), "big")
|
|
every_tenth = int.from_bytes((b"\xff" * 16 + bytes(144)) * (size // 160), "big")
|
|
mixed = counters ^ ((counters ^ int.from_bytes(encrypted, "big")) & every_tenth)
|
|
self.encrypted, self.sparse = encrypted, mixed.to_bytes(size, "big")
|
|
|
|
|
|
def _decrypt_payload(data: bytes, keystream: _Keystream) -> bytes:
|
|
"""The clear bytes of a NAL payload: its emulation-prevention bytes removed, then the keystream XORed in."""
|
|
raw = data.replace(b"\x00\x00\x03", b"\x00\x00")
|
|
return strxor(raw, keystream.get(len(raw)))
|
|
|
|
|
|
def _sei_ends_at_stop_bit(rbsp: bytes) -> bool:
|
|
"""Whether the SEI messages of an RBSP end exactly on its final stop-bit byte."""
|
|
pos, last = 0, len(rbsp) - 1
|
|
while pos < last:
|
|
while pos < last and rbsp[pos] == 0xFF:
|
|
pos += 1
|
|
pos += 1
|
|
size = 0
|
|
while pos < last and rbsp[pos] == 0xFF:
|
|
size, pos = size + 255, pos + 1
|
|
if pos >= last:
|
|
return False
|
|
pos += 1 + size + rbsp[pos]
|
|
return pos == last and rbsp[last] == 0x80
|
|
|
|
|
|
def _padded(nal: bytes, kind: int, h264: bool) -> bool:
|
|
"""Whether a SEI or Dolby Vision RPU NAL unit is whole without its last 4 bytes, which the cipher appended."""
|
|
sei = kind in SEI[h264]
|
|
if not sei and (h264 or kind != DOVI_RPU):
|
|
return False
|
|
rbsp = nal[(1 if h264 else 2) : -4].replace(b"\x00\x00\x03", b"\x00\x00")
|
|
if len(rbsp) < 2:
|
|
return False
|
|
if sei:
|
|
return _sei_ends_at_stop_bit(rbsp)
|
|
# An RPU ends with a CRC-32/MPEG-2 of the bytes after its 0x19 prefix, then the stop-bit byte.
|
|
return rbsp[0] == 0x19 and rbsp[-1] == 0x80 and zlib.crc32(rbsp[1:-1].translate(BIT_REVERSED)) == 0xFFFFFFFF
|
|
|
|
|
|
def _decrypt_pes(pes: bytes, stream_type: int, keystream: _Keystream) -> bytes:
|
|
"""Decrypt each NAL unit of a video PES packet and drop what the cipher added.
|
|
|
|
Start codes, NAL headers and the last 2 bytes of a NAL unit stay clear. Access unit delimiters go, and so do the
|
|
4 bytes the cipher appends to a SEI message or a Dolby Vision RPU.
|
|
"""
|
|
header_end = 9 + pes[8]
|
|
if header_end > len(pes):
|
|
return pes
|
|
h264 = stream_type == H264
|
|
skip = 3 + (1 if h264 else 2)
|
|
end = len(pes)
|
|
bounds = [header_end, *(found.start() for found in START_CODES.finditer(pes, header_end + 1)), end]
|
|
out = [pes[:header_end]]
|
|
for start, stop in itertools.pairwise(bounds):
|
|
# A zero byte before the next start code belongs to that 4-byte start code.
|
|
nal_end = stop - 1 if stop < end and pes[stop - 1] == 0 else stop
|
|
if nal_end - start <= 3 or pes[start : start + 3] != START_CODE:
|
|
out.append(pes[start:stop])
|
|
continue
|
|
cut = nal_end - 2
|
|
if cut > start + skip:
|
|
nal = (
|
|
pes[start + 3 : start + skip] + _decrypt_payload(pes[start + skip : cut], keystream) + pes[cut:nal_end]
|
|
)
|
|
else:
|
|
nal = pes[start + 3 : nal_end]
|
|
kind = nal[0] & 0x1F if h264 else nal[0] >> 1 & 0x3F
|
|
if kind == AUD[h264]:
|
|
out.append(pes[nal_end:stop])
|
|
continue
|
|
if len(nal) > 4 and _padded(nal, kind, h264):
|
|
nal = nal[:-4]
|
|
out += [START_CODE, nal, pes[nal_end:stop]]
|
|
clear = b"".join(out)
|
|
if pes[4:6] != b"\x00\x00":
|
|
clear = clear[:4] + (len(clear) - 6).to_bytes(2, "big") + clear[6:]
|
|
return clear
|
|
|
|
|
|
def _payload_offset(packet: bytes) -> int:
|
|
"""Where the payload of a TS packet starts, or PACKET when it has none."""
|
|
control = (packet[3] >> 4) & 3
|
|
if control == 1:
|
|
return 4
|
|
if control == 3:
|
|
return 5 + packet[4]
|
|
return PACKET
|
|
|
|
|
|
def _stuffed(header: bytes, extra: int, empty: bool) -> bytes:
|
|
"""A TS packet header whose adaptation field grows by ``extra`` stuffing bytes; with no payload left, it says so."""
|
|
control = 0x20 if empty else 0x30
|
|
if header[3] & 0x20:
|
|
length = header[4]
|
|
stuffing = b"\xff" * extra if length else b"\x00" + b"\xff" * (extra - 1)
|
|
return header[:3] + bytes([header[3] & 0xCF | control, length + extra]) + header[5:] + stuffing
|
|
stuffing = b"\x00" + b"\xff" * (extra - 2) if extra > 1 else b""
|
|
return header[:3] + bytes([header[3] & 0xCF | control, extra - 1]) + stuffing
|
|
|
|
|
|
class _Section:
|
|
"""Reassembles the PSI sections of one PID."""
|
|
|
|
def __init__(self) -> None:
|
|
self.buffer: bytes | None = None
|
|
|
|
def push(self, packet: bytes) -> bytes | None:
|
|
"""Add a packet; return the section it completes."""
|
|
offset = _payload_offset(packet)
|
|
if offset >= PACKET:
|
|
return None
|
|
payload = packet[offset:]
|
|
if packet[1] & 0x40:
|
|
pointer = payload[0]
|
|
if pointer > len(payload) - 1:
|
|
return None
|
|
payload = payload[1 + pointer :]
|
|
self.buffer = b""
|
|
if self.buffer is None:
|
|
return None
|
|
self.buffer += payload
|
|
if len(self.buffer) >= 3 and len(self.buffer) >= (total := 3 + ((self.buffer[1] & 0x0F) << 8 | self.buffer[2])):
|
|
section, self.buffer = self.buffer[:total], None
|
|
return section
|
|
return None
|
|
|
|
|
|
def _sdt_iv(section: bytes) -> bytes | None:
|
|
"""The IV of a service-name descriptor (tag 0x48) that holds "mdcm|".
|
|
|
|
The IV is an inner "|" field of "v" and 32 hex digits, else a fourth "|" field of 32 hex digits.
|
|
"""
|
|
if len(section) < 16 or section[0] != 0x42:
|
|
return None
|
|
end = len(section)
|
|
pos = 11
|
|
while pos + 5 <= end - 4:
|
|
loop_end = pos + 5 + ((section[pos + 3] & 0x0F) << 8 | section[pos + 4])
|
|
at = pos + 5
|
|
while at + 2 <= loop_end and at + 2 <= end - 4:
|
|
tag, length = section[at], section[at + 1]
|
|
at += 2
|
|
if at + length > len(section):
|
|
break
|
|
body = section[at : at + length]
|
|
at += length
|
|
if tag != 0x48 or len(body) < 3 or 2 + body[1] >= len(body):
|
|
continue
|
|
name_at = 2 + body[1]
|
|
name = body[name_at + 1 : name_at + 1 + body[name_at]]
|
|
if b"mdcm|" not in name:
|
|
continue
|
|
fields = name.split(b"|")
|
|
if field := IV_FIELD.search(name) or (len(fields) > 3 and HEX_IV.fullmatch(fields[3])):
|
|
return bytes.fromhex(field[1].decode())[:12] + bytes(4)
|
|
pos = loop_end
|
|
return None
|
|
|
|
|
|
def _pmt_streams(section: bytes) -> list[tuple[int, int]]:
|
|
"""The PID and ``stream_type`` of each elementary stream of a PMT section."""
|
|
if len(section) < 12 or section[0] != 0x02:
|
|
return []
|
|
end = len(section)
|
|
pos = 12 + ((section[10] & 0x0F) << 8 | section[11])
|
|
streams = []
|
|
while pos + 5 <= end - 4:
|
|
streams.append((((section[pos + 1] & 0x1F) << 8) | section[pos + 2], section[pos]))
|
|
pos += 5 + ((section[pos + 3] & 0x0F) << 8 | section[pos + 4])
|
|
return streams
|
|
|
|
|
|
class _Decrypter:
|
|
"""One pass over a BBTS file. Each video PES packet decrypts with the IV of the last SDT before it starts."""
|
|
|
|
def __init__(self, key: bytes, write: Callable[[bytes], object]) -> None:
|
|
self.key = key
|
|
self.write = write
|
|
self.sdt, self.pmt = _Section(), _Section()
|
|
self.iv: bytes | None = None
|
|
self.keystream: _Keystream | None = None
|
|
self.streams: list[tuple[int, int]] = []
|
|
self.pes = bytearray()
|
|
self.headers: list[bytes] = []
|
|
self.pes_pid = 0
|
|
|
|
def flush(self) -> None:
|
|
"""Write the held PES packet back into the TS packets it came from; a shorter one ends in stuffing."""
|
|
if not self.headers:
|
|
return
|
|
pes = bytes(self.pes)
|
|
if len(pes) > 8 and pes[3] == 0xE0 and self.keystream:
|
|
stream_type = next((kind for pid, kind in self.streams if pid == self.pes_pid), 0)
|
|
pes = _decrypt_pes(pes, stream_type, self.keystream)
|
|
pos, out = 0, []
|
|
for header in self.headers:
|
|
size = PACKET - len(header)
|
|
payload = pes[pos : pos + size]
|
|
pos += size
|
|
if len(payload) < size:
|
|
header = _stuffed(header, size - len(payload), not payload)
|
|
out += [header, payload]
|
|
self.write(b"".join(out))
|
|
self.pes.clear()
|
|
self.headers.clear()
|
|
|
|
def run(self, read: Callable[[int], bytes]) -> None:
|
|
"""Decrypt every packet that ``read`` gives."""
|
|
while len(packet := read(PACKET)) == PACKET:
|
|
self.packet(packet)
|
|
self.flush()
|
|
|
|
def packet(self, packet: bytes) -> None:
|
|
"""Take one TS packet."""
|
|
if packet[0] != SYNC:
|
|
self.write(packet)
|
|
return
|
|
pid = (packet[1] & 0x1F) << 8 | packet[2]
|
|
if pid in (PID_PAT, PID_SDT, PID_PMT):
|
|
self.flush()
|
|
if pid == PID_SDT and (section := self.sdt.push(packet)) and (iv := _sdt_iv(section)):
|
|
if iv != self.iv:
|
|
self.iv, self.keystream = iv, _Keystream(self.key, iv)
|
|
elif pid == PID_PMT and (section := self.pmt.push(packet)):
|
|
self.streams = _pmt_streams(section)
|
|
self.write(packet)
|
|
return
|
|
if not self.keystream:
|
|
self.write(packet)
|
|
return
|
|
offset = _payload_offset(packet) if pid in (VIDEO_PID, AUDIO_PID) else PACKET
|
|
if offset >= PACKET:
|
|
self.flush()
|
|
self.write(packet)
|
|
return
|
|
starts = (
|
|
offset + 8 < PACKET and packet[offset : offset + 3] == START_CODE and packet[offset + 3] in (0xC0, 0xE0)
|
|
)
|
|
if starts:
|
|
self.flush()
|
|
elif not self.headers:
|
|
self.write(packet)
|
|
return
|
|
self.pes += packet[offset:]
|
|
self.headers.append(packet[:offset])
|
|
self.pes_pid = pid
|