#!/usr/bin/env python3
"""Decrypt .xmenc files created by File Crypt (https://xmgr.de/filecrypt/).

Usage:   python3 decrypt.py FILE [OUTPUT]
Needs:   pip install cryptography

Without OUTPUT, the original file name stored inside the file is used.
The file is processed chunk by chunk, so it works for files of any size.

File format, version 1 (integers big-endian):

  Header, 47 bytes:
     0  9  magic "XMENCFILE"
     9  1  version (1)
    10  1  key derivation (1 = PBKDF2-HMAC-SHA256, 32-byte key)
    11  4  iterations
    15  4  chunk size (plaintext bytes per full chunk)
    19 16  salt
    35  8  nonce prefix
    43  4  length of the encrypted metadata chunk

  Then the metadata chunk (UTF-8 JSON: name, type, size, modified),
  then the data chunks.

  Every chunk is AES-256-GCM (16-byte tag appended) with
    nonce           = nonce prefix || uint32 counter (metadata = 0, data = 1, 2, ...)
    additional data = header || last flag (1 for the final data chunk, else 0)
  The key is PBKDF2-HMAC-SHA256 of the NFC-normalized UTF-8 password.
  The final data chunk is the one with at most chunk size + 16 bytes left;
  it may be empty (16 bytes, tag only).
"""

import getpass
import hashlib
import json
import os
import struct
import sys
import unicodedata

try:
    from cryptography.exceptions import InvalidTag
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
except ImportError:
    sys.exit('Missing package, install it with: pip install cryptography')

HEADER = struct.Struct('>9sBBII16s8sI')
MAGIC = b'XMENCFILE'
TAG = 16


def fail(msg, tmp=None):
    if tmp and os.path.exists(tmp):
        os.remove(tmp)
    sys.exit('Error: ' + msg)


def main():
    if len(sys.argv) not in (2, 3):
        sys.exit(__doc__)
    src = sys.argv[1]
    size = os.path.getsize(src)

    with open(src, 'rb') as f:
        header = f.read(HEADER.size)
        if len(header) < HEADER.size:
            fail('not a File Crypt file (too short)')
        magic, version, kdf, iterations, chunk, salt, prefix, meta_len = HEADER.unpack(header)
        if magic != MAGIC:
            fail('not a File Crypt file')
        if version != 1:
            fail(f'unsupported format version {version}')
        if kdf != 1:
            fail(f'unsupported key derivation ({kdf})')
        if not 1000 <= iterations <= 10_000_000:
            fail(f'unsupported iteration count {iterations}')
        if not 1024 <= chunk <= 64 << 20 or not TAG <= meta_len <= 65536 or HEADER.size + meta_len > size:
            fail('the file is damaged')

        password = getpass.getpass('Password: ')
        key = hashlib.pbkdf2_hmac('sha256', unicodedata.normalize('NFC', password).encode('utf-8'),
                                  salt, iterations, 32)
        gcm = AESGCM(key)

        def open_chunk(counter, data, last):
            return gcm.decrypt(prefix + struct.pack('>I', counter), data, header + bytes([last]))

        try:
            meta = json.loads(open_chunk(0, f.read(meta_len), 0))
        except (InvalidTag, ValueError):
            fail('wrong password, or the file is damaged')

        name = os.path.basename(str(meta.get('name') or 'decrypted').replace('\\', '/')) or 'decrypted'
        out = sys.argv[2] if len(sys.argv) == 3 else name
        if os.path.exists(out):
            fail(f'{out} already exists, pass another output name')

        tmp = out + '.part'
        total = size - HEADER.size - meta_len
        pos = written = 0
        counter = 1
        last = False
        with open(tmp, 'wb') as o:
            while not last:
                rest = total - pos
                last = rest <= chunk + TAG
                length = rest if last else chunk + TAG
                if length < TAG:
                    o.close()
                    fail('the file is damaged', tmp)
                try:
                    plain = open_chunk(counter, f.read(length), 1 if last else 0)
                except InvalidTag:
                    o.close()
                    fail('the file is damaged or was modified', tmp)
                o.write(plain)
                written += len(plain)
                pos += length
                counter += 1

        if isinstance(meta.get('size'), int) and written != meta['size']:
            fail('the file is damaged (size mismatch)', tmp)
        os.replace(tmp, out)
        print(f'Decrypted to {out} ({written} bytes)')


if __name__ == '__main__':
    main()
