98 lines
3.8 KiB
Python
98 lines
3.8 KiB
Python
"""Package encryption: AES-256-GCM in chunks, key from the passphrase with scrypt.
|
|||
|
|
|
||
|
|
File layout:
|
||
|
|
magic "OVPBAKE1" | log2(N) 1 byte | r 1 byte | p 1 byte | salt 16 | nonce prefix 8 (header, 35 bytes)
|
||
|
|
then chunks of CHUNK bytes of plaintext, each stored as ciphertext + 16 byte tag.
|
||
|
|
Chunk i uses the nonce prefix || i (4 bytes, big endian). The header and a "final chunk" flag
|
||
|
|
are authenticated data of every chunk, so a truncated, reordered or modified file is rejected.
|
||
|
|
"""
|
||
|
|
import os
|
||
|
|
import struct
|
||
|
|
|
||
|
|
from cryptography.exceptions import InvalidTag
|
||
|
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||
|
|
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
||
|
|
|
||
|
|
from . import BackupError
|
||
|
|
|
||
|
|
MAGIC = b"OVPBAKE1"
|
||
|
|
HEADER_LEN = len(MAGIC) + 3 + 16 + 8
|
||
|
|
CHUNK = 1024 * 1024
|
||
|
|
TAG = 16
|
||
|
|
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P = 15, 8, 1 # about 32 MiB of memory
|
||
|
|
# Bounds for the parameters read from a file: a crafted header must not exhaust memory or CPU
|
||
|
|
MAX_LOG_N, MAX_R, MAX_P = 20, 16, 4
|
||
|
|
|
||
|
|
|
||
|
|
class WrongPassphrase(BackupError):
|
||
|
|
"""Wrong passphrase, or the file is damaged (AES-GCM cannot tell the two apart)."""
|
||
|
|
|
||
|
|
|
||
|
|
def is_encrypted(path: str) -> bool:
|
||
|
|
try:
|
||
|
|
with open(path, "rb") as f:
|
||
|
|
return f.read(len(MAGIC)) == MAGIC
|
||
|
|
except OSError:
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
def _derive(passphrase: str, salt: bytes, log_n: int, r: int, p: int) -> bytes:
|
||
|
|
return Scrypt(salt=salt, length=32, n=2 ** log_n, r=r, p=p).derive(passphrase.encode("utf-8"))
|
||
|
|
|
||
|
|
|
||
|
|
def _nonce(prefix: bytes, index: int) -> bytes:
|
||
|
|
return prefix + struct.pack(">I", index)
|
||
|
|
|
||
|
|
|
||
|
|
def _aad(header: bytes, final: bool) -> bytes:
|
||
|
|
return header + (b"\x01" if final else b"\x00")
|
||
|
|
|
||
|
|
|
||
|
|
def encrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||
|
|
if not passphrase:
|
||
|
|
raise BackupError("Passphrase is empty")
|
||
|
|
salt, prefix = os.urandom(16), os.urandom(8)
|
||
|
|
header = MAGIC + bytes([SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P]) + salt + prefix
|
||
|
|
aes = AESGCM(_derive(passphrase, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P))
|
||
|
|
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||
|
|
with open(src, "rb") as fin, os.fdopen(fd, "wb") as fout:
|
||
|
|
fout.write(header)
|
||
|
|
index = 0
|
||
|
|
block = fin.read(CHUNK)
|
||
|
|
while True:
|
||
|
|
nxt = fin.read(CHUNK)
|
||
|
|
final = not nxt
|
||
|
|
fout.write(aes.encrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||
|
|
if final:
|
||
|
|
break
|
||
|
|
block, index = nxt, index + 1
|
||
|
|
|
||
|
|
|
||
|
|
def decrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||
|
|
if not passphrase:
|
||
|
|
raise WrongPassphrase("Passphrase is required for an encrypted package")
|
||
|
|
with open(src, "rb") as fin:
|
||
|
|
header = fin.read(HEADER_LEN)
|
||
|
|
if len(header) != HEADER_LEN or not header.startswith(MAGIC):
|
||
|
|
raise BackupError("Not an encrypted package (bad header)")
|
||
|
|
log_n, r, p = header[8], header[9], header[10]
|
||
|
|
if not (1 <= log_n <= MAX_LOG_N and 1 <= r <= MAX_R and 1 <= p <= MAX_P):
|
||
|
|
raise BackupError("Encrypted package has unsupported key derivation parameters")
|
||
|
|
salt, prefix = header[11:27], header[27:35]
|
||
|
|
aes = AESGCM(_derive(passphrase, salt, log_n, r, p))
|
||
|
|
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||
|
|
with os.fdopen(fd, "wb") as fout:
|
||
|
|
index = 0
|
||
|
|
block = fin.read(CHUNK + TAG)
|
||
|
|
if not block:
|
||
|
|
raise BackupError("Encrypted package is truncated")
|
||
|
|
while True:
|
||
|
|
nxt = fin.read(CHUNK + TAG)
|
||
|
|
final = not nxt
|
||
|
|
try:
|
||
|
|
fout.write(aes.decrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||
|
|
except InvalidTag:
|
||
|
|
raise WrongPassphrase("Wrong passphrase, or the package is damaged") from None
|
||
|
|
if final:
|
||
|
|
break
|
||
|
|
block, index = nxt, index + 1
|