#!/usr/bin/env python3
# Copyright (c) 2026 Kinode LLC. All rights reserved. Created by Brent Gordon.
"""Kinode Signing client: signs .exe, .dll and .drv files with a certificate profile of a Kinode
signing account. The file never leaves this computer: the client sends the service the SHA-256
digest of what is signed, gets back the signature and the certificates, and puts the standard PE
signature into the file, with a time stamp so the signature outlives the day's certificate.

    kinode_sign.py sign --account ACCOUNT --profile PROFILE [--endpoint URL] [--description TEXT]
                        [--no-timestamp] FILE...
    kinode_sign.py show FILE...

Credentials of an app of the account (Access control gives it the Certificate Profile Signer
role): --client-id and --client-secret, or KINODE_CLIENT_ID and KINODE_CLIENT_SECRET in the
environment. The endpoint defaults to https://dev.usekinode.app.

Python 3.8 or later, nothing else."""
import base64, hashlib, json, os, struct, sys, time, urllib.error, urllib.request

DEFAULT_ENDPOINT = 'https://dev.usekinode.app'


# ---------------- DER ----------------
def der(tag, body):
    n = len(body)
    if n < 0x80:
        ln = bytes([n])
    else:
        b = n.to_bytes((n.bit_length() + 7) // 8, 'big')
        ln = bytes([0x80 | len(b)]) + b
    return bytes([tag]) + ln + body


def seq(*p): return der(0x30, b''.join(p))
def set_of(*p): return der(0x31, b''.join(sorted(p)))
def octets(b): return der(0x04, b)
def integer(v): return der(0x02, v.to_bytes(v.bit_length() // 8 + 1, 'big'))
def ctx(n, body, constructed=True): return der((0xA0 if constructed else 0x80) | n, body)
NULL = b'\x05\x00'


def oid(dotted):
    parts = [int(x) for x in dotted.split('.')]
    body = bytearray()
    for v in [parts[0] * 40 + parts[1]] + parts[2:]:
        chunk = [v & 0x7F]
        v >>= 7
        while v:
            chunk.append(0x80 | (v & 0x7F))
            v >>= 7
        body += bytes(reversed(chunk))
    return der(0x06, bytes(body))


def read(b, i):
    tag, n = b[i], b[i + 1]
    i += 2
    if n & 0x80:
        k = n & 0x7F
        n = int.from_bytes(b[i:i + k], 'big')
        i += k
    return tag, i, i + n


def items(b, s, e):
    out = []
    while s < e:
        t, vs, ve = read(b, s)
        out.append((t, vs, ve, s))
        s = ve
    return out


OID_SHA256 = '2.16.840.1.101.3.4.2.1'
OID_ECDSA_SHA256 = '1.2.840.10045.4.3.2'
OID_SIGNED_DATA = '1.2.840.113549.1.7.2'
OID_CONTENT_TYPE = '1.2.840.113549.1.9.3'
OID_MESSAGE_DIGEST = '1.2.840.113549.1.9.4'
# object identifiers the PE signature format defines
OID_INDIRECT_DATA = '1.3.6.1.4.1.311.2.1.4'
OID_PE_IMAGE_DATA = '1.3.6.1.4.1.311.2.1.15'
OID_OPUS_INFO = '1.3.6.1.4.1.311.2.1.12'
OID_STATEMENT_TYPE = '1.3.6.1.4.1.311.2.1.11'
OID_COMMERCIAL = '1.3.6.1.4.1.311.2.1.22'
OID_RFC3161_ATTR = '1.3.6.1.4.1.311.3.3.1'


class SignError(Exception):
    pass


# ---------------- PE files ----------------
class PE:
    def __init__(self, data):
        if data[:2] != b'MZ':
            raise SignError('not a PE file')
        self.data = data
        pe = struct.unpack_from('<I', data, 0x3C)[0]
        if data[pe:pe + 4] != b'PE\0\0':
            raise SignError('not a PE file')
        nsec = struct.unpack_from('<H', data, pe + 6)[0]
        optsize = struct.unpack_from('<H', data, pe + 20)[0]
        opt = pe + 24
        magic = struct.unpack_from('<H', data, opt)[0]
        if magic not in (0x10B, 0x20B):
            raise SignError('unknown optional header')
        dd = opt + (96 if magic == 0x10B else 112)
        self.checksum_off = opt + 64
        self.cert_dir = dd + 32
        if struct.unpack_from('<I', data, dd - 4)[0] < 5:
            raise SignError('the file has no room for a certificate table entry')
        self.size_of_headers = struct.unpack_from('<I', data, opt + 60)[0]
        self.sections = []
        sh = opt + optsize
        for i in range(nsec):
            raw_size, raw_ptr = struct.unpack_from('<II', data, sh + 40 * i + 16)
            if raw_size:
                self.sections.append((raw_ptr, raw_size))
        self.sections.sort()
        self.cert_off, self.cert_size = struct.unpack_from('<II', data, self.cert_dir)

    def image_hash(self):
        d, h = self.data, hashlib.sha256()
        h.update(d[:self.checksum_off])
        h.update(d[self.checksum_off + 4:self.cert_dir])
        h.update(d[self.cert_dir + 8:self.size_of_headers])
        done = self.size_of_headers
        for ptr, size in self.sections:
            h.update(d[ptr:ptr + size])
            done += size
        end = len(d) - self.cert_size
        if end > done:
            h.update(d[done:end])
        return h.digest()


def pe_checksum(data, checksum_off):
    s, n = 0, len(data)
    padded = data + (b'\0' if n % 2 else b'')
    skip = checksum_off // 2
    for i, w in enumerate(struct.unpack('<%dH' % (len(padded) // 2), padded)):
        if i == skip or i == skip + 1:
            continue
        s += w
        s = (s & 0xFFFF) + (s >> 16)
    s = (s & 0xFFFF) + (s >> 16)
    return (s + n) & 0xFFFFFFFF


def strip_signature(data):
    data = bytearray(data)
    pe = PE(bytes(data))
    if pe.cert_size:
        if pe.cert_off + pe.cert_size != len(data):
            raise SignError('the existing signature is not at the end of the file')
        del data[pe.cert_off:]
        struct.pack_into('<II', data, pe.cert_dir, 0, 0)
    data += b'\0' * (-len(data) % 8)
    return bytes(data)


def bmp(s):
    return s.encode('utf-16-be')


def signed_attributes(image_digest, description=None):
    """(the SpcIndirectDataContent, the signed attributes as a SET OF): what the service signs is
    the SHA-256 of the second"""
    link = ctx(0, ctx(2, der(0x80, bmp('<<<Obsolete>>>'))))
    content = seq(seq(oid(OID_PE_IMAGE_DATA), seq(der(0x03, b'\x00'), link)), seq(seq(oid(OID_SHA256), NULL), octets(image_digest)))
    _, cs, ce = read(content, 0)
    opus = seq(ctx(0, der(0x80, bmp(description)))) if description else seq()
    attrs = set_of(
        seq(oid(OID_CONTENT_TYPE), set_of(oid(OID_INDIRECT_DATA))),
        seq(oid(OID_OPUS_INFO), set_of(opus)),
        seq(oid(OID_STATEMENT_TYPE), set_of(seq(oid(OID_COMMERCIAL)))),
        seq(oid(OID_MESSAGE_DIGEST), set_of(octets(hashlib.sha256(content[cs:ce]).digest()))),
    )
    return content, attrs


def cert_issuer_serial(c):
    """IssuerAndSerialNumber of a DER certificate"""
    top = items(c, 0, len(c))[0]
    tbs = items(c, top[1], top[2])[0]
    f = items(c, tbs[1], tbs[2])
    k = 1 if f[0][0] == 0xA0 else 0
    serial, issuer = f[k], f[k + 2]
    return seq(c[issuer[3]:issuer[2]], c[serial[3]:serial[2]])


def assemble(data, content, attrs, signature, chain, token=None):
    """the file with the PE signature in its certificate table"""
    unsigned = ctx(1, seq(oid(OID_RFC3161_ATTR), set_of(token))) if token else b''
    hdr = 2 if attrs[1] < 0x80 else 2 + (attrs[1] & 0x7F)
    signer = seq(integer(1), cert_issuer_serial(chain[0]), seq(oid(OID_SHA256), NULL), ctx(0, attrs[hdr:]),
                 seq(oid(OID_ECDSA_SHA256)), octets(signature), unsigned)
    sd = seq(integer(1), set_of(seq(oid(OID_SHA256), NULL)), seq(oid(OID_INDIRECT_DATA), ctx(0, content)),
             ctx(0, b''.join(chain)), set_of(signer))
    blob = seq(oid(OID_SIGNED_DATA), ctx(0, sd))
    blob += b'\0' * (-len(blob) % 8)
    out = bytearray(data)
    pe = PE(bytes(out))
    table = struct.pack('<IHH', 8 + len(blob), 0x0200, 0x0002) + blob
    struct.pack_into('<II', out, pe.cert_dir, len(out), len(table))
    out += table
    struct.pack_into('<I', out, pe.checksum_off, pe_checksum(bytes(out), pe.checksum_off))
    return bytes(out)


def timestamp_request(signature):
    nonce = int.from_bytes(os.urandom(8), 'big')
    return seq(integer(1), seq(seq(oid(OID_SHA256), NULL), octets(hashlib.sha256(signature).digest())), integer(nonce), der(0x01, b'\xff'))


def timestamp_from_reply(resp):
    top = items(resp, 0, len(resp))[0]
    f = items(resp, top[1], top[2])
    status = items(resp, f[0][1], f[0][2])
    code = int.from_bytes(resp[status[0][1]:status[0][2]], 'big')
    if code not in (0, 1) or len(f) < 2:
        raise SignError('the time-stamp service refused the request')
    return resp[f[1][3]:f[1][2]]


def sign_data(data, sign_fn, description=None, timestamp_fn=None):
    """sign_fn(attrs_digest) -> (signature, [leaf DER, authority DER]); timestamp_fn(signature) ->
    token or None. Returns the signed file."""
    data = strip_signature(data)
    content, attrs = signed_attributes(PE(data).image_hash(), description)
    signature, chain = sign_fn(hashlib.sha256(attrs).digest())
    token = timestamp_fn(signature) if timestamp_fn else None
    return assemble(data, content, attrs, signature, chain, token)


# ---------------- talking to the service ----------------
def call(url, body=None, headers=None, ctype='application/json'):
    h = dict(headers or {})
    if body is not None:
        h['Content-Type'] = ctype
    req = urllib.request.Request(url, data=body, headers=h)
    try:
        return urllib.request.urlopen(req, timeout=60).read()
    except urllib.error.HTTPError as e:
        try:
            msg = json.loads(e.read()).get('error', '')
        except Exception:
            msg = ''
        raise SignError('%s: %s' % (e.code, msg or e.reason))
    except urllib.error.URLError as e:
        raise SignError('the service could not be reached: %s' % e.reason)


class Client:
    def __init__(self, endpoint, client_id, client_secret):
        self.endpoint = endpoint.rstrip('/')
        r = json.loads(call(self.endpoint + '/api/v1/token', json.dumps({'client_id': client_id, 'client_secret': client_secret}).encode()))
        self.token = r['access_token']

    def signer(self, account, profile, file_name=''):
        def sign(digest):
            r = json.loads(call('%s/api/v1/accounts/%s/profiles/%s/sign' % (self.endpoint, account, profile),
                                json.dumps({'digest': digest.hex(), 'file': file_name}).encode(), {'Authorization': 'Bearer ' + self.token}))
            return base64.b64decode(r['signature']), [base64.b64decode(c) for c in r['chain']]
        return sign

    def timestamper(self):
        def ts(signature):
            return timestamp_from_reply(call(self.endpoint + '/tsa', timestamp_request(signature), ctype='application/timestamp-query'))
        return ts


# ---------------- showing a signature ----------------
def show(path):
    data = open(path, 'rb').read()
    pe = PE(data)
    if not pe.cert_size:
        return '%s: not signed' % path
    blob = data[pe.cert_off + 8:pe.cert_off + pe.cert_size]
    names = []
    i = 0
    while True:
        j = blob.find(b'\x06\x03\x55\x04\x03', i)       # common names, in certificate order
        if j < 0:
            break
        t, vs, ve = read(blob, j + 5)
        names.append(blob[vs:ve].decode('utf-8', 'replace'))
        i = ve
    stamped = oid(OID_RFC3161_ATTR) in blob
    return '%s: signed; names in the certificates: %s; %s' % (path, ', '.join(names), 'time stamped' if stamped else 'no time stamp')


def main(argv):
    if not argv or argv[0] not in ('sign', 'show'):
        print(__doc__)
        return 1
    cmd, a = argv[0], argv[1:]
    opts = {'endpoint': os.environ.get('KINODE_SIGNING_ENDPOINT', DEFAULT_ENDPOINT), 'account': None, 'profile': None,
            'client-id': os.environ.get('KINODE_CLIENT_ID'), 'client-secret': os.environ.get('KINODE_CLIENT_SECRET'),
            'description': None, 'no-timestamp': False}
    files = []
    while a:
        x = a.pop(0)
        if x == '--no-timestamp':
            opts['no-timestamp'] = True
        elif x.startswith('--') and x[2:] in opts:
            opts[x[2:]] = a.pop(0)
        else:
            files.append(x)
    if cmd == 'show':
        for f in files:
            print(show(f))
        return 0
    for k in ('account', 'profile', 'client-id', 'client-secret'):
        if not opts[k]:
            print('kinode_sign: --%s is needed' % k)
            return 1
    try:
        c = Client(opts['endpoint'], opts['client-id'], opts['client-secret'])
        for f in files:
            data = open(f, 'rb').read()
            out = sign_data(data, c.signer(opts['account'], opts['profile'], os.path.basename(f)), opts['description'],
                            None if opts['no-timestamp'] else c.timestamper())
            tmp = f + '.signing'
            open(tmp, 'wb').write(out)
            os.replace(tmp, f)
            print('signed', f)
    except (SignError, OSError) as e:
        print('kinode_sign:', e)
        return 1
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))
