From 81f029d39e510e72d35828868bb0ead727d34020 Mon Sep 17 00:00:00 2001 From: redshiftzero Date: Fri, 18 May 2018 17:46:37 -0700 Subject: [PATCH] Secure tempfile: Only call decryptor.finalize() when we are done --- securedrop/secure_tempfile.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/securedrop/secure_tempfile.py b/securedrop/secure_tempfile.py index 3921cde662e..6fbf1005b92 100644 --- a/securedrop/secure_tempfile.py +++ b/securedrop/secure_tempfile.py @@ -5,6 +5,7 @@ from tempfile import _TemporaryFileWrapper from gnupg._util import _STREAMLIKE_TYPES +from cryptography.exceptions import AlreadyFinalized from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers.modes import CTR @@ -70,6 +71,7 @@ def initialize_cipher(self): """ self.cipher = Cipher(AES(self.key), CTR(self.iv), default_backend()) self.encryptor = self.cipher.encryptor() + self.decryptor = self.cipher.decryptor() def write(self, data): """Write `data` to the secure temporary file. This method may be @@ -110,17 +112,18 @@ def read(self, count=None): self.seek(0, 0) self.last_action = 'read' - decryptor = self.cipher.decryptor() - if count: - return ( - decryptor.update(self.file.read(count)) + decryptor.finalize() - ) + return self.decryptor.update(self.file.read(count)) else: - return ( - decryptor.update(self.file.read()) + decryptor.finalize() - ) + return self.decryptor.update(self.file.read()) + + def close(self): + try: + self.decryptor.finalize() + except AlreadyFinalized: + pass + super(SecureTemporaryFile, self).close() # python-gnupg will not recognize our SecureTemporaryFile as a stream-like type # and will attempt to call encode on it, thinking it's a string-like type. To