Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
22e80cb
GCM support
reaperhulk Nov 21, 2013
cf60326
fix buffer size bug for gcm tag fetch
reaperhulk Nov 21, 2013
65c4e0a
gcm doc fixes
reaperhulk Nov 21, 2013
a5e1081
add tag as abstractproperty for modewithaad
reaperhulk Nov 21, 2013
cc9ec98
rename NotFinalized exception to NotYetFinalized because alex is right
reaperhulk Nov 21, 2013
24316fd
_AEADCipherContext refactor
reaperhulk Nov 22, 2013
6331daa
gcm doc improvements
reaperhulk Nov 22, 2013
ce9c611
enforce AEAD add_data before update
reaperhulk Nov 22, 2013
a4bfc08
invalidtag exception for gcm
reaperhulk Nov 23, 2013
2631c2b
gcm doc fixes (per review from alex)
reaperhulk Nov 24, 2013
bc31fb2
rename add_data to authenticate_additional_data for clarity (hopefully)
reaperhulk Nov 24, 2013
4664108
simplify code for wrapping ciphercontext/aeadciphercontext
reaperhulk Nov 24, 2013
0092c20
raise TypeError if you attempt to get the tag attribute on a decrypt
reaperhulk Nov 24, 2013
a8b35f4
make _CipherContext in backend.py compliant with AEADCipherContext
reaperhulk Nov 24, 2013
86699be
narrow the potential cases where invalidtag can be raised
reaperhulk Nov 24, 2013
67abc86
document tag param for GCM object
reaperhulk Nov 25, 2013
26c8c6a
begin adding warnings to GCM mode
reaperhulk Nov 29, 2013
e0b5bb1
explicit backend fix for gcm docs
reaperhulk Nov 29, 2013
5a40896
create AEADEncryptionContext and DecryptionContext
reaperhulk Nov 29, 2013
5b828b1
attempt to document the new interfaces for AEAD
reaperhulk Nov 29, 2013
89d19a4
rename ModeWithAAD to ModeWithAuthenticationTag
reaperhulk Dec 3, 2013
128b948
remove AEADDecryptionContext per review.
reaperhulk Dec 3, 2013
5578c66
improve language for gcm docs
reaperhulk Dec 3, 2013
cd28a7c
remove AEADDecryptionContext references from GCM docs
reaperhulk Dec 4, 2013
6728437
link to NIST GCM PDF where NIST recommends 96-bit IV for perf with GCM
reaperhulk Dec 4, 2013
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions cryptography/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,15 @@ class UnsupportedAlgorithm(Exception):

class AlreadyFinalized(Exception):
pass


class AlreadyUpdated(Exception):
pass


class NotYetFinalized(Exception):
pass


class InvalidTag(Exception):
pass
56 changes: 52 additions & 4 deletions cryptography/hazmat/bindings/openssl/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import cffi

from cryptography import utils
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.exceptions import UnsupportedAlgorithm, InvalidTag
from cryptography.hazmat.bindings.interfaces import (
CipherBackend, HashBackend, HMACBackend
)
Expand All @@ -28,7 +28,7 @@
AES, Blowfish, Camellia, CAST5, TripleDES, ARC4,
)
from cryptography.hazmat.primitives.ciphers.modes import (
CBC, CTR, ECB, OFB, CFB
CBC, CTR, ECB, OFB, CFB, GCM,
)


Expand Down Expand Up @@ -186,15 +186,22 @@ def _register_default_ciphers(self):
type(None),
GetCipherByName("rc4")
)
self.register_cipher_adapter(
AES,
GCM,
GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
)

def create_symmetric_encryption_ctx(self, cipher, mode):
return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)

def create_symmetric_decryption_ctx(self, cipher, mode):
return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT)

def _handle_error(self):
def _handle_error(self, mode):
code = self.lib.ERR_get_error()
if not code and isinstance(mode, GCM):
raise InvalidTag
assert code != 0
lib = self.lib.ERR_GET_LIB(code)
func = self.lib.ERR_GET_FUNC(code)
Expand Down Expand Up @@ -231,13 +238,18 @@ def __call__(self, backend, cipher, mode):


@utils.register_interface(interfaces.CipherContext)
@utils.register_interface(interfaces.AEADCipherContext)
@utils.register_interface(interfaces.AEADEncryptionContext)
class _CipherContext(object):
_ENCRYPT = 1
_DECRYPT = 0

def __init__(self, backend, cipher, mode, operation):
self._backend = backend
self._cipher = cipher
self._mode = mode
self._operation = operation
self._tag = None

ctx = self._backend.lib.EVP_CIPHER_CTX_new()
ctx = self._backend.ffi.gc(ctx, self._backend.lib.EVP_CIPHER_CTX_free)
Expand Down Expand Up @@ -270,6 +282,20 @@ def __init__(self, backend, cipher, mode, operation):
ctx, len(cipher.key)
)
assert res != 0
if isinstance(mode, GCM):
res = self._backend.lib.EVP_CIPHER_CTX_ctrl(
ctx, self._backend.lib.Cryptography_EVP_CTRL_GCM_SET_IVLEN,
len(iv_nonce), self._backend.ffi.NULL
)
assert res != 0
if operation == self._DECRYPT:
assert mode.tag is not None
res = self._backend.lib.EVP_CIPHER_CTX_ctrl(
ctx, self._backend.lib.Cryptography_EVP_CTRL_GCM_SET_TAG,
len(mode.tag), mode.tag
)
assert res != 0

# pass key/iv
res = self._backend.lib.EVP_CipherInit_ex(ctx, self._backend.ffi.NULL,
self._backend.ffi.NULL,
Expand All @@ -296,12 +322,34 @@ def finalize(self):
outlen = self._backend.ffi.new("int *")
res = self._backend.lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
if res == 0:
self._backend._handle_error()
self._backend._handle_error(self._mode)

if (isinstance(self._mode, GCM) and
self._operation == self._ENCRYPT):
block_byte_size = self._cipher.block_size // 8
tag_buf = self._backend.ffi.new("unsigned char[]", block_byte_size)
res = self._backend.lib.EVP_CIPHER_CTX_ctrl(
self._ctx, self._backend.lib.Cryptography_EVP_CTRL_GCM_GET_TAG,
block_byte_size, tag_buf
)
assert res != 0
self._tag = self._backend.ffi.buffer(tag_buf)[:]

res = self._backend.lib.EVP_CIPHER_CTX_cleanup(self._ctx)
assert res == 1
return self._backend.ffi.buffer(buf)[:outlen[0]]

def authenticate_additional_data(self, data):
outlen = self._backend.ffi.new("int *")
res = self._backend.lib.EVP_CipherUpdate(
self._ctx, self._backend.ffi.NULL, outlen, data, len(data)
)
assert res != 0

@property
def tag(self):
return self._tag


@utils.register_interface(interfaces.HashContext)
class _HashContext(object):
Expand Down
63 changes: 58 additions & 5 deletions cryptography/hazmat/primitives/ciphers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
from __future__ import absolute_import, division, print_function

from cryptography import utils
from cryptography.exceptions import AlreadyFinalized
from cryptography.exceptions import (
AlreadyFinalized, NotYetFinalized, AlreadyUpdated,
)
from cryptography.hazmat.primitives import interfaces


Expand All @@ -28,14 +30,25 @@ def __init__(self, algorithm, mode, backend):
self._backend = backend

def encryptor(self):
return _CipherContext(self._backend.create_symmetric_encryption_ctx(
ctx = self._backend.create_symmetric_encryption_ctx(
self.algorithm, self.mode
))
)
return self._wrap_ctx(ctx, True)

def decryptor(self):
return _CipherContext(self._backend.create_symmetric_decryption_ctx(
ctx = self._backend.create_symmetric_decryption_ctx(
self.algorithm, self.mode
))
)
return self._wrap_ctx(ctx, False)

def _wrap_ctx(self, ctx, encrypt):
if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):
if encrypt:
return _AEADEncryptionContext(ctx)
else:
return _AEADCipherContext(ctx)
else:
return _CipherContext(ctx)


@utils.register_interface(interfaces.CipherContext)
Expand All @@ -54,3 +67,43 @@ def finalize(self):
data = self._ctx.finalize()
self._ctx = None
return data


@utils.register_interface(interfaces.AEADCipherContext)
@utils.register_interface(interfaces.CipherContext)
class _AEADCipherContext(object):
def __init__(self, ctx):
self._ctx = ctx
self._tag = None
self._updated = False

def update(self, data):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized")
self._updated = True
return self._ctx.update(data)

def finalize(self):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized")
data = self._ctx.finalize()
self._tag = self._ctx.tag
self._ctx = None
return data

def authenticate_additional_data(self, data):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized")
if self._updated:
raise AlreadyUpdated("Update has been called on this context")
self._ctx.authenticate_additional_data(data)


@utils.register_interface(interfaces.AEADEncryptionContext)
class _AEADEncryptionContext(_AEADCipherContext):
@property
def tag(self):
if self._ctx is not None:
raise NotYetFinalized("You must finalize encryption before "
"getting the tag")
return self._tag

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if I try to get the tag on a decryption?

11 changes: 11 additions & 0 deletions cryptography/hazmat/primitives/ciphers/modes.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,14 @@ class CTR(object):

def __init__(self, nonce):
self.nonce = nonce


@utils.register_interface(interfaces.Mode)
@utils.register_interface(interfaces.ModeWithInitializationVector)
@utils.register_interface(interfaces.ModeWithAuthenticationTag)
class GCM(object):
name = "GCM"

def __init__(self, initialization_vector, tag=None):
self.initialization_vector = initialization_vector
self.tag = tag
24 changes: 24 additions & 0 deletions cryptography/hazmat/primitives/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ def nonce(self):
"""


class ModeWithAuthenticationTag(six.with_metaclass(abc.ABCMeta)):
@abc.abstractproperty
def tag(self):
"""
The value of the tag supplied to the constructor of this mode.
"""


class CipherContext(six.with_metaclass(abc.ABCMeta)):
@abc.abstractmethod
def update(self, data):
Expand All @@ -70,6 +78,22 @@ def finalize(self):
"""


class AEADCipherContext(six.with_metaclass(abc.ABCMeta)):
@abc.abstractmethod
def authenticate_additional_data(self, data):
"""
authenticate_additional_data takes bytes and returns nothing.
"""


class AEADEncryptionContext(six.with_metaclass(abc.ABCMeta)):
@abc.abstractproperty
def tag(self):
"""
Returns tag bytes after finalizing encryption.
"""


class PaddingContext(six.with_metaclass(abc.ABCMeta)):
@abc.abstractmethod
def update(self, data):
Expand Down
12 changes: 12 additions & 0 deletions docs/exceptions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ Exceptions
This is raised when a context is used after being finalized.


.. class:: NotYetFinalized

This is raised when the AEAD tag property is accessed on a context
before it is finalized.


.. class:: AlreadyUpdated

This is raised when additional data is added to a context after update
has already been called.


.. class:: UnsupportedAlgorithm

This is raised when a backend doesn't support the requested algorithm (or
Expand Down
72 changes: 72 additions & 0 deletions docs/hazmat/primitives/symmetric-encryption.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,36 @@ an "encrypt-then-MAC" formulation as `described by Colin Percival`_.
:meth:`update` and :meth:`finalize` will raise
:class:`~cryptography.exceptions.AlreadyFinalized`.

.. class:: AEADCipherContext

When calling ``encryptor()`` or ``decryptor()`` on a ``Cipher`` object
with an AEAD mode you will receive a return object conforming to the
``AEADCipherContext`` interface (in addition to the ``CipherContext``
interface). If it is an encryption context it will additionally be an
``AEADEncryptionContext`` interface. ``AEADCipherContext`` contains an
additional method ``authenticate_additional_data`` for adding additional
authenticated but unencrypted data. You should call this before calls to
``update``. When you are done call ``finalize()`` to finish the operation.

.. method:: authenticate_additional_data(data)

:param bytes data: The data you wish to authenticate but not encrypt.
:raises: :class:`~cryptography.exceptions.AlreadyFinalized`

.. class:: AEADEncryptionContext

When creating an encryption context using ``encryptor()`` on a ``Cipher``
object with an AEAD mode you will receive a return object conforming to the
``AEADEncryptionContext`` interface (as well as ``AEADCipherContext``).
This interface provides one additional attribute ``tag``. ``tag`` can only
be obtained after ``finalize()``.

.. attribute:: tag

:return bytes: Returns the tag value as bytes.
:raises: :class:`~cryptography.exceptions.NotYetFinalized` if called
before the context is finalized.

.. _symmetric-encryption-algorithms:

Algorithms
Expand Down Expand Up @@ -295,6 +325,47 @@ Modes
reuse an ``initialization_vector`` with
a given ``key``.

.. class:: GCM(initialization_vector, tag=None)

.. danger::

When using this mode you MUST not use the decrypted data until every
byte has been decrypted. GCM provides NO guarantees of ciphertext
integrity until decryption is complete.

GCM (Galois Counter Mode) is a mode of operation for block ciphers. An
AEAD (authenticated encryption with additional data) mode is a type of
block cipher mode that encrypts the message as well as authenticating it
(and optionally additional data that is not encrypted) simultaneously.
Additional means of verifying integrity (like
:doc:`HMAC </hazmat/primitives/hmac>`) are not necessary.

:param bytes initialization_vector: Must be random bytes. They do not need
to be kept secret (they can be included
in a transmitted message). NIST
`recommends 96-bit IV length`_ for
performance critical situations, but it
can be up to 2\ :sup:`64` - 1 bits.
Do not reuse an ``initialization_vector``
with a given ``key``.

:param bytes tag: The tag bytes to verify during decryption. Must be provided
for decryption, but is ignored when encrypting.

.. doctest::

>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend)
>>> encryptor = cipher.encryptor()
>>> encryptor.authenticate_additional_data(b"authenticated but not encrypted payload")
>>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
>>> tag = encryptor.tag
>>> cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend)
>>> decryptor = cipher.decryptor()
>>> decryptor.authenticate_additional_data(b"authenticated but not encrypted payload")
>>> decryptor.update(ct) + decryptor.finalize()
'a secret message'


Insecure Modes
--------------
Expand All @@ -314,3 +385,4 @@ Insecure Modes


.. _`described by Colin Percival`: http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
.. _`recommends 96-bit IV length`: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-spec.pdf
Loading