Skip to content

Commit

Permalink
Secure tempfile: Only call decryptor.finalize() when we are done
Browse files Browse the repository at this point in the history
  • Loading branch information
redshiftzero committed May 19, 2018
1 parent 117acb6 commit 81f029d
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions securedrop/secure_tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 81f029d

Please sign in to comment.