#!/usr/bin/env python3
"""SingleShot seal tools: check a signed file without SingleShot, using OpenSSL.

  python3 seal-tools.py extract FILE OUTDIR

writes, into OUTDIR:
  seal.p7s            the signature: a standard CMS SignedData (DER)
  signed-content.bin  exactly the bytes that were signed
  info.json           what SingleShot recorded (address, times, seal ID, edits...)
  signature-value.bin, timestamp.tst   when the seal carries a timestamp

then check them with OpenSSL:

  # 1. the file is unchanged and the signature was made by the key in the certificate
  openssl cms -verify -inform DER -in OUTDIR/seal.p7s -binary \\
      -content OUTDIR/signed-content.bin -noverify -out /dev/null
  #    (replace -noverify with -CAfile org-root.pem to check the signer's chain as well)

  # 2. who signed, and every signed attribute
  openssl cms -cmsout -print -inform DER -in OUTDIR/seal.p7s

  # 3. the independent timestamp, if any
  openssl ts -verify -in OUTDIR/timestamp.tst -token_in \\
      -data OUTDIR/signature-value.bin -CApath /etc/ssl/certs

PDF files carry a standard PDF signature instead: check them with Adobe Acrobat
or Reader, or `pdfsig FILE` (poppler).

An evidence locker package (a ZIP) needs no tool at all: unpack it, then

  sha256sum -c SHA256SUMS.txt        every file in it is the one that was sealed
  openssl cms -verify -inform DER -in SHA256SUMS.txt.p7s -binary \\
      -content SHA256SUMS.txt -noverify -out /dev/null       the list itself is as signed

`extract` on a package writes the same seal.p7s, signed-content.bin (the list)
and info.json as for a single file. Each captured file in the package also
carries its own seal: extract and check it like any other file.

What is signed (see docs/signed-files.md):
  JPEG, HTML, MHTML  the file's bytes before the seal, which is the last
                     "<!--SingleShot-Seal:1:BASE64-->" at the very end of the file
  locker package     SHA256SUMS.txt in the ZIP: the SHA-256 of manifest.json and of
                     every captured file. The seal is SHA256SUMS.txt.p7s beside it.
  PNG                the pixels: for each band of 256 rows, the SHA-256 of its
                     RGBA bytes with the lowest bit of R, G and B set to 0 in the
                     seal strip (the bottom rows); signed-content.bin is those
                     band hashes, one after another. The seal itself is hidden in
                     those lowest bits, bottom row first, read left to right,
                     R then G then B, most significant bit first:
                     "SSEAL1", strip height (2 bytes), length (4 bytes), seal.
                     Needs Pillow (pip install pillow).
"""

import base64
import hashlib
import json
import os
import re
import sys
import zipfile

TRAILER_START = b'<!--SingleShot-Seal:1:'
TRAILER_END = b'-->'
INFO_OID = '2.25.137678260334167949696166497197904475670'
TS_OID = '1.2.840.113549.1.9.16.2.14'


# ---------------------------------------------------------------- a little DER

def der(buf, at=0):
    """(tag, start of contents, end) of the element at `at`."""
    tag = buf[at]
    n = buf[at + 1]
    p = at + 2
    if n & 0x80:
        k = n & 0x7f
        n = int.from_bytes(buf[p:p + k], 'big')
        p += k
    return tag, p, p + n


def kids(buf, start, end):
    out = []
    while start < end:
        t, s, e = der(buf, start)
        out.append((t, start, s, e))
        start = e
    return out


def oid(buf, s, e):
    b = buf[s:e]
    parts, v = [], 0
    for x in b:
        v = (v << 7) | (x & 0x7f)
        if not x & 0x80:
            if not parts:
                first = min(v // 40, 2)
                parts += [first, v - first * 40]
            else:
                parts.append(v)
            v = 0
    return '.'.join(map(str, parts))


def signer_parts(cms):
    """(signature value, timestamp token or None, info JSON text or None) from a SingleShot seal."""
    _, s, e = der(cms)
    ct = kids(cms, s, e)
    _, _, s, e = ct[1]                       # [0] EXPLICIT
    _, s, e = der(cms, s)                    # SignedData
    sd = kids(cms, s, e)
    _, _, s, e = sd[-1]                      # signerInfos SET
    _, _, s, e = kids(cms, s, e)[0]          # the one SignerInfo
    si = kids(cms, s, e)
    signature, token, info = None, None, None
    for t, at, s, e in si:
        if t == 0xa0:                        # signed attributes
            for _, _, a_s, a_e in kids(cms, s, e):
                (_, _, os_, oe), (_, _, vs, ve) = kids(cms, a_s, a_e)
                if oid(cms, os_, oe) == INFO_OID:
                    _, s2, e2 = der(cms, vs)
                    info = cms[s2:e2].decode('utf-8')
        elif t == 0x04:
            signature = cms[s:e]
        elif t == 0xa1:                      # unsigned attributes
            for _, _, a_s, a_e in kids(cms, s, e):
                (_, _, os_, oe), (_, _, vs, ve) = kids(cms, a_s, a_e)
                if oid(cms, os_, oe) == TS_OID:
                    _, ts_at, _, ts_e = kids(cms, vs, ve)[0]
                    token = cms[ts_at:ts_e]
    return signature, token, info


# ---------------------------------------------------------------- finding the seal

def from_trailer(data):
    at = data.rfind(TRAILER_START)
    if at < 0 or not data.endswith(TRAILER_END):
        sys.exit('No SingleShot seal at the end of this file (or something was added after it).')
    return base64.b64decode(data[at + len(TRAILER_START):-len(TRAILER_END)]), data[:at]


def from_png(path):
    try:
        from PIL import Image
    except ImportError:
        sys.exit('PNG files need Pillow: pip install pillow')
    im = Image.open(path)
    w, h = im.size
    px = bytearray(im.convert('RGBA').tobytes())

    def read(count):
        out = bytearray(count)
        bit = 0
        total = count * 8
        for r in range(h - 1, -1, -1):
            row = r * w * 4
            for x in range(w):
                p = row + x * 4
                for ch in range(3):
                    if bit >= total:
                        return bytes(out)
                    out[bit >> 3] |= (px[p + ch] & 1) << (7 - (bit & 7))
                    bit += 1
        return bytes(out)

    head = read(12)
    if head[:6] != b'SSEAL1':
        sys.exit('This PNG has no SingleShot seal.')
    strip = int.from_bytes(head[6:8], 'big')
    length = int.from_bytes(head[8:12], 'big')
    cms = read(12 + length)[12:]
    for i in range((h - strip) * w * 4, h * w * 4, 4):
        px[i] &= 0xfe
        px[i + 1] &= 0xfe
        px[i + 2] &= 0xfe
    bands = b''.join(hashlib.sha256(px[y * w * 4:min(h, y + 256) * w * 4]).digest() for y in range(0, h, 256))
    return cms, bands


def from_package(path):
    with zipfile.ZipFile(path) as z:
        names = z.namelist()
        if 'SHA256SUMS.txt' not in names or 'SHA256SUMS.txt.p7s' not in names:
            sys.exit('This ZIP file is not a SingleShot locker package (no SHA256SUMS.txt and SHA256SUMS.txt.p7s in it).')
        sums = z.read('SHA256SUMS.txt')
        bad = []
        for line in sums.decode('utf-8').splitlines():
            m = re.match(r'^([0-9a-f]{64}) [ *](.+)$', line)
            if m and (m.group(2) not in names or hashlib.sha256(z.read(m.group(2))).hexdigest() != m.group(1)):
                bad.append(m.group(2))
        if bad:
            print('NOT as sealed (missing or changed): ' + ', '.join(bad), file=sys.stderr)
        else:
            print('Every file in the package matches SHA256SUMS.txt.')
        return z.read('SHA256SUMS.txt.p7s'), sums


def main():
    if len(sys.argv) != 4 or sys.argv[1] != 'extract':
        sys.exit(__doc__)
    path, out = sys.argv[2], sys.argv[3]
    with open(path, 'rb') as f:
        data = f.read()
    if data.startswith(b'%PDF-'):
        sys.exit('PDF files carry a standard PDF signature: check them with Adobe Acrobat or Reader, or `pdfsig FILE`.')
    if data.startswith(b'PK\x03\x04'):
        cms, content = from_package(path)
    else:
        cms, content = from_png(path) if data.startswith(b'\x89PNG') else from_trailer(data)
    os.makedirs(out, exist_ok=True)
    with open(os.path.join(out, 'seal.p7s'), 'wb') as f:
        f.write(cms)
    with open(os.path.join(out, 'signed-content.bin'), 'wb') as f:
        f.write(content)
    signature, token, info = signer_parts(cms)
    if info:
        with open(os.path.join(out, 'info.json'), 'w', encoding='utf-8') as f:
            json.dump(json.loads(info), f, indent=2, ensure_ascii=False)
    if token:
        with open(os.path.join(out, 'timestamp.tst'), 'wb') as f:
            f.write(token)
        with open(os.path.join(out, 'signature-value.bin'), 'wb') as f:
            f.write(signature)
    print(f'Wrote {out}/seal.p7s, signed-content.bin' + (', info.json' if info else '') + (', timestamp.tst, signature-value.bin' if token else ''))


if __name__ == '__main__':
    main()
