diff options
-rw-r--r-- | encrypt.py | 68 | ||||
-rw-r--r-- | filecrypt.py | 71 | ||||
-rw-r--r-- | server.py | 46 |
3 files changed, 124 insertions, 61 deletions
@@ -1,73 +1,19 @@ #!/usr/bin/env python3 -import secrets -from Cryptodome.Cipher import AES -import base64 -import struct -import subprocess -import binascii +import os -def encrypt_file(filename_in, chunk_size=1000000//16): - file_id = secrets.token_urlsafe(22) - auth_secret = secrets.token_bytes(16) - key = secrets.token_bytes(16) - data_nonce = secrets.token_bytes(8) - - token_cipher = AES.new(auth_secret, AES.MODE_GCM) - ciphertext, token_tag = token_cipher.encrypt_and_digest(key) - token = base64.b64encode(ciphertext) - - with open(f'{file_id}.enc', 'wb') as fout, open(filename_in, 'rb') as fin: - fout.write(token_cipher.nonce) # 16 bytes - fout.write(token_tag) # 16 bytes - fout.write(auth_secret) # 16 bytes - fout.write(data_nonce) # 8 bytes - - cipher = AES.new(key, AES.MODE_CTR, - initial_value=struct.pack('<Q', 0), nonce=data_nonce) - - block = fin.read(cipher.block_size*chunk_size) - while block: - data = cipher.encrypt(block) - fout.write(data) - block = fin.read(cipher.block_size*chunk_size) - - return file_id, token - -def decrypt_generator(file_id, token, seek=0, chunk_size=1000000//16): - with open(f'{file_id}.enc', 'rb') as fin: - token_nonce = fin.read(16) - token_tag = fin.read(16) - auth_secret = fin.read(16) - data_nonce = fin.read(8) - - ciphertext = base64.b64decode(token) - token_cipher = AES.new(auth_secret, AES.MODE_GCM, nonce=token_nonce) - key = token_cipher.decrypt_and_verify(ciphertext, token_tag) - - # Use token cipher's block size assuming the two are the same - cipher = AES.new(key, AES.MODE_CTR, - initial_value=struct.pack('<Q', seek // token_cipher.block_size), nonce=data_nonce) - fin.seek(seek - seek % cipher.block_size, 1) - offset = seek % cipher.block_size - - block = fin.read(cipher.block_size*chunk_size) - while block: - data = cipher.decrypt(block) - yield data[offset:] - offset = 0 - block = fin.read(cipher.block_size*chunk_size) +from filecrypt import encrypt_file if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('infile') - parser.add_argument('outfile') args = parser.parse_args() + if not os.path.isfile(args.infile): + print(f'{infile} is not a file or directory, exiting.') + os.exit(2) + file_id, token = encrypt_file(args.infile) + print(f'/{file_id}/{token}/{os.path.basename(args.infile)}') - with open(args.outfile, 'wb', buffering=8192) as fout: - for data in decrypt_generator(file_id, token): - fout.write(data) - diff --git a/filecrypt.py b/filecrypt.py new file mode 100644 index 0000000..ce6e3a1 --- /dev/null +++ b/filecrypt.py @@ -0,0 +1,71 @@ +import secrets +from Cryptodome.Cipher import AES +import base64 +import struct +import subprocess +import binascii +import os + +FILE_ID_LENGTH = 22 +TOKEN_LENGTH = 22 + +def encrypt_file(filename_in, chunk_size=1000000//16): + file_id = secrets.token_urlsafe(16) + auth_secret = secrets.token_bytes(16) + key = secrets.token_bytes(16) + data_nonce = secrets.token_bytes(8) + + token_cipher = AES.new(auth_secret, AES.MODE_GCM) + ciphertext, token_tag = token_cipher.encrypt_and_digest(key) + token = base64.b64encode(ciphertext).rstrip(b'=').decode() + + with open(f'{file_id}.enc', 'wb') as fout, open(filename_in, 'rb') as fin: + fout.write(token_cipher.nonce) # 16 bytes + fout.write(token_tag) # 16 bytes + fout.write(auth_secret) # 16 bytes + fout.write(data_nonce) # 8 bytes + + cipher = AES.new(key, AES.MODE_CTR, + initial_value=struct.pack('<Q', 0), nonce=data_nonce) + + block = fin.read(cipher.block_size*chunk_size) + while block: + data = cipher.encrypt(block) + fout.write(data) + block = fin.read(cipher.block_size*chunk_size) + + return file_id, token + +def payload_size(path): + return os.stat(path).st_size - 56 + +def decrypt_generator(filename, token, seek=0, end=None, chunk_size=1000000//16): + with open(filename, 'rb') as fin: + token_nonce = fin.read(16) + token_tag = fin.read(16) + auth_secret = fin.read(16) + data_nonce = fin.read(8) + + ciphertext = base64.b64decode(token + '='*((3-len(token)%3)%3)) + token_cipher = AES.new(auth_secret, AES.MODE_GCM, nonce=token_nonce) + key = token_cipher.decrypt_and_verify(ciphertext, token_tag) + + # Use token cipher's block size assuming the two are the same + cipher = AES.new(key, AES.MODE_CTR, + initial_value=struct.pack('>Q', seek // token_cipher.block_size), nonce=data_nonce) + print('Seeking to position', seek, 'iv', seek // token_cipher.block_size, 'pos', seek - seek % + cipher.block_size, 'offset', seek % cipher.block_size) + fin.seek(seek - seek % cipher.block_size, 1) + offset = seek % cipher.block_size + + to_send = end - seek + 1 if end else None + block = fin.read(cipher.block_size*chunk_size) + while block and (to_send is None or to_send > 0): + data = cipher.decrypt(block) + out = data[offset:to_send] + yield out + if to_send is not None: + to_send -= len(out) + offset = 0 + block = fin.read(cipher.block_size*chunk_size) + diff --git a/server.py b/server.py new file mode 100644 index 0000000..9df3546 --- /dev/null +++ b/server.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 + +import re +import os + +from flask import Flask, abort, request, Response + +import filecrypt + +app = Flask(__name__) +BASE64_RE = re.compile('^[A-Za-z0-9+-_]+=*$') + +@app.route('/<file_id>/<token>/<filename>') +def download(file_id, token, filename): + if not BASE64_RE.match(file_id) or len(file_id) != filecrypt.FILE_ID_LENGTH: + abort(400, 'Invalid file ID format') + if not BASE64_RE.match(token) or len(token) != filecrypt.TOKEN_LENGTH: + abort(400, 'Invalid token format') + + path = f'{file_id}.enc' + size = filecrypt.payload_size(path) + + range_header = re.match('^bytes=([0-9]+)-([0-9]*)$', request.headers.get('Range', '')) + if not range_header: + response = Response( + filecrypt.decrypt_generator(path, token), + mimetype='application/octet-stream') + response.headers['Content-Length'] = size + else: + range_start, range_end = range_header.groups() + range_start = int(range_start) + range_end = int(range_end) if range_end else size-1 + if range_start < 0 or range_end >= size or range_start >= range_end: + abort(416) + + response = Response( + filecrypt.decrypt_generator(path, token, seek=range_start, end=range_end), + status = 206, + mimetype='application/octet-stream') + response.headers['Content-Range'] = f'bytes {range_start}-{range_end}/{size}' + response.headers['Content-Length'] = range_end - range_start + 1 + + response.headers['Accept-Ranges'] = 'bytes' + response.headers['Content-Disposition'] = f'attachment {filename}' + return response + |