From 955aa7e2d219f076d9dea3503e3eb435e44ea6bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damir=20Jeli=C4=87?= Date: Thu, 24 Jan 2019 15:29:25 +0100 Subject: [PATCH] contrib: Add the matrix_decrypt helper. This helper decrypts uploaded files and passes the file to a plumber (rifle from ranger by default). --- contrib/matrix_decrypt | 81 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100755 contrib/matrix_decrypt diff --git a/contrib/matrix_decrypt b/contrib/matrix_decrypt new file mode 100755 index 0000000..6adc8b1 --- /dev/null +++ b/contrib/matrix_decrypt @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# matrix_decrypt - Download and decrypt an encrypted attachment +# from a matrix server + +# Copyright © 2019 Damir Jelić +# +# Permission to use, copy, modify, and/or distribute this software for +# any purpose with or without fee is hereby granted, provided that the +# above copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER +# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF +# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import argparse +import requests +import tempfile +import subprocess + +from urllib.parse import urlparse, parse_qs +from nio.crypto import decrypt_attachment + + +def save_file(data): + """Save data to a temporary file and return its name.""" + tmp_dir = tempfile.gettempdir() + + with tempfile.NamedTemporaryFile( + prefix='plumber-', + dir=tmp_dir, + delete=False + ) as f: + f.write(data) + f.flush() + return f.name + + +def main(): + parser = argparse.ArgumentParser( + description='Download and decrypt matrix attachments' + ) + parser.add_argument('url', help='the url of the attachment') + parser.add_argument('--plumber', + help='program that gets called with the ' + 'dowloaded file') + + args = parser.parse_args() + url = urlparse(args.url) + query = parse_qs(url.query) + + if not query["key"] or not query["iv"] or not query["hash"]: + print("Missing decryption argument") + return -1 + + key = query["key"][0] + iv = query["iv"][0] + hash = query["hash"][0] + + http_url = "https://{}{}".format(url.netloc, url.path) + + request = requests.get(http_url) + + if not request.ok: + print("Error downloading file") + return -2 + + plumber = args.plumber or "/usr/bin/rifle" + plaintext = decrypt_attachment(request.content, key, hash, iv) + file_name = save_file(plaintext) + + subprocess.run([plumber, "{file}".format(file=file_name)]) + + return 0 + + +if __name__ == "__main__": + main()