-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathdeserialize.py
386 lines (345 loc) · 15.3 KB
/
deserialize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
"""Components for handling AWS Encryption SDK message deserialization."""
from __future__ import division
import io
import logging
import struct
from cryptography.exceptions import InvalidTag
from aws_encryption_sdk.exceptions import NotSupportedError, SerializationError, UnknownIdentityError
from aws_encryption_sdk.identifiers import (
Algorithm, ContentType, ObjectType, SequenceIdentifier, SerializationVersion
)
from aws_encryption_sdk.internal.crypto.encryption import decrypt
from aws_encryption_sdk.internal.defaults import MAX_FRAME_SIZE
from aws_encryption_sdk.internal.formatting.encryption_context import deserialize_encryption_context
from aws_encryption_sdk.internal.str_ops import to_str
from aws_encryption_sdk.internal.structures import (
EncryptedData, MessageFooter,
MessageFrameBody, MessageHeaderAuthentication
)
from aws_encryption_sdk.internal.utils.streams import TeeStream
from aws_encryption_sdk.structures import EncryptedDataKey, MasterKeyInfo, MessageHeader
_LOGGER = logging.getLogger(__name__)
def validate_header(header, header_auth, raw_header, data_key):
"""Validates the header using the header authentication data.
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param header_auth: Deserialized header auth
:type header_auth: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
:type stream: io.BytesIO
:param bytes raw_header: Raw header bytes
:param bytes data_key: Data key with which to perform validation
:raises SerializationError: if header authorization fails
"""
_LOGGER.debug('Starting header validation')
try:
decrypt(
algorithm=header.algorithm,
key=data_key,
encrypted_data=EncryptedData(header_auth.iv, b'', header_auth.tag),
associated_data=raw_header
)
except InvalidTag:
raise SerializationError('Header authorization failed')
def deserialize_header(stream):
"""Deserializes the header from a source stream
:param stream: Source data stream
:type stream: io.BytesIO
:returns: Deserialized MessageHeader object
:rtype: :class:`aws_encryption_sdk.structures.MessageHeader` and bytes
:raises NotSupportedError: if unsupported data types are found
:raises UnknownIdentityError: if unknown data types are found
:raises SerializationError: if IV length does not match algorithm
"""
_LOGGER.debug('Starting header deserialization')
tee = io.BytesIO()
tee_stream = TeeStream(stream, tee)
version_id, message_type_id = unpack_values('>BB', tee_stream)
try:
message_type = ObjectType(message_type_id)
except ValueError as error:
raise NotSupportedError(
'Unsupported type {} discovered in data stream'.format(message_type_id),
error
)
try:
version = SerializationVersion(version_id)
except ValueError as error:
raise NotSupportedError('Unsupported version {}'.format(version_id), error)
header = {'version': version, 'type': message_type}
algorithm_id, message_id, ser_encryption_context_length = unpack_values('>H16sH', tee_stream)
try:
alg = Algorithm.get_by_id(algorithm_id)
except KeyError as error:
raise UnknownIdentityError('Unknown algorithm {}'.format(algorithm_id), error)
if not alg.allowed:
raise NotSupportedError('Unsupported algorithm: {}'.format(alg))
header['algorithm'] = alg
header['message_id'] = message_id
header['encryption_context'] = deserialize_encryption_context(
tee_stream.read(ser_encryption_context_length)
)
(encrypted_data_key_count,) = unpack_values('>H', tee_stream)
encrypted_data_keys = set([])
for _ in range(encrypted_data_key_count):
(key_provider_length,) = unpack_values('>H', tee_stream)
(key_provider_identifier,) = unpack_values(
'>{}s'.format(key_provider_length),
tee_stream
)
(key_provider_information_length,) = unpack_values('>H', tee_stream)
(key_provider_information,) = unpack_values(
'>{}s'.format(key_provider_information_length),
tee_stream
)
(encrypted_data_key_length,) = unpack_values('>H', tee_stream)
encrypted_data_key = tee_stream.read(encrypted_data_key_length)
encrypted_data_keys.add(EncryptedDataKey(
key_provider=MasterKeyInfo(
provider_id=to_str(key_provider_identifier),
key_info=key_provider_information
),
encrypted_data_key=encrypted_data_key
))
header['encrypted_data_keys'] = encrypted_data_keys
(content_type_id,) = unpack_values('>B', tee_stream)
try:
content_type = ContentType(content_type_id)
except ValueError as error:
raise UnknownIdentityError(
'Unknown content type {}'.format(content_type_id),
error
)
header['content_type'] = content_type
(content_aad_length,) = unpack_values('>I', tee_stream)
if content_aad_length != 0:
raise SerializationError(
'Content AAD length field is currently unused, its value must be always 0'
)
header['content_aad_length'] = 0
(iv_length,) = unpack_values('>B', tee_stream)
if iv_length != alg.iv_len:
raise SerializationError(
'Specified IV length ({length}) does not match algorithm IV length ({alg})'.format(
length=iv_length,
alg=alg
)
)
header['header_iv_length'] = iv_length
(frame_length,) = unpack_values('>I', tee_stream)
if content_type == ContentType.FRAMED_DATA and frame_length > MAX_FRAME_SIZE:
raise SerializationError('Specified frame length larger than allowed maximum: {found} > {max}'.format(
found=frame_length,
max=MAX_FRAME_SIZE
))
elif content_type == ContentType.NO_FRAMING and frame_length != 0:
raise SerializationError('Non-zero frame length found for non-framed message')
header['frame_length'] = frame_length
return MessageHeader(**header), tee.getvalue()
def deserialize_header_auth(stream, algorithm, verifier=None):
"""Deserializes a MessageHeaderAuthentication object from a source stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param algorithm: The Algorithm object type contained in the header
:type algorith: aws_encryption_sdk.identifiers.Algorithm
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized MessageHeaderAuthentication object
:rtype: aws_encryption_sdk.internal.structures.MessageHeaderAuthentication
"""
_LOGGER.debug('Starting header auth deserialization')
format_string = '>{iv_len}s{tag_len}s'.format(
iv_len=algorithm.iv_len,
tag_len=algorithm.tag_len
)
return MessageHeaderAuthentication(*unpack_values(format_string, stream, verifier))
def deserialize_non_framed_values(stream, header, verifier=None):
"""Deserializes the IV and Tag from a non-framed stream.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: IV, Tag, and Data Length values for body
:rtype: tuple of bytes, bytes, and int
"""
_LOGGER.debug('Starting non-framed body iv/tag deserialization')
(data_iv, data_length) = unpack_values(
'>{}sQ'.format(header.algorithm.iv_len),
stream,
verifier
)
body_start = stream.tell()
stream.seek(data_length, 1)
(data_tag,) = unpack_values(
format_string='>{auth_len}s'.format(auth_len=header.algorithm.auth_len),
stream=stream,
verifier=None
)
stream.seek(body_start, 0)
return data_iv, data_tag, data_length
def update_verifier_with_tag(stream, header, verifier):
"""Updates verifier with data for authentication tag.
.. note::
This is meant to be used in conjunction with deserialize_non_framed_values
to update the verifier over information which has already been retrieved.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Data authentication tag value
:rtype: bytes
"""
return unpack_values(
'>{auth_len}s'.format(auth_len=header.algorithm.auth_len),
stream,
verifier
)
def deserialize_frame(stream, header, verifier=None):
"""Deserializes a frame from a body.
:param stream: Source data stream
:type stream: io.BytesIO
:param header: Deserialized header
:type header: aws_encryption_sdk.structures.MessageHeader
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized frame and a boolean stating if this is the final frame
:rtype: :class:`aws_encryption_sdk.internal.structures.MessageFrameBody` and bool
"""
_LOGGER.debug('Starting frame deserialization')
frame_data = {}
final_frame = False
(sequence_number,) = unpack_values('>I', stream, verifier)
if sequence_number == SequenceIdentifier.SEQUENCE_NUMBER_END.value:
_LOGGER.debug('Deserializing final frame')
(sequence_number,) = unpack_values('>I', stream, verifier)
final_frame = True
else:
_LOGGER.debug('Deserializing frame sequence number %s', int(sequence_number))
frame_data['final_frame'] = final_frame
frame_data['sequence_number'] = sequence_number
(frame_iv,) = unpack_values(
'>{iv_len}s'.format(iv_len=header.algorithm.iv_len),
stream,
verifier
)
frame_data['iv'] = frame_iv
if final_frame is True:
(content_length,) = unpack_values('>I', stream, verifier)
if content_length >= header.frame_length:
raise SerializationError('Invalid final frame length: {final} >= {normal}'.format(
final=content_length,
normal=header.frame_length
))
else:
content_length = header.frame_length
(frame_content, frame_tag) = unpack_values(
'>{content_len}s{auth_len}s'.format(
content_len=content_length,
auth_len=header.algorithm.auth_len
),
stream,
verifier
)
frame_data['ciphertext'] = frame_content
frame_data['tag'] = frame_tag
return MessageFrameBody(**frame_data), final_frame
def deserialize_footer(stream, verifier=None):
"""Deserializes a footer.
:param stream: Source data stream
:type stream: io.BytesIO
:param verifier: Signature verifier object (optional)
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Deserialized footer
:rtype: aws_encryption_sdk.internal.structures.MessageFooter
:raises SerializationError: if verifier supplied and no footer found
"""
_LOGGER.debug('Starting footer deserialization')
signature = b''
if verifier is None:
return MessageFooter(signature=signature)
try:
(sig_len,) = unpack_values('>H', stream)
(signature,) = unpack_values(
'>{sig_len}s'.format(sig_len=sig_len),
stream
)
except SerializationError:
raise SerializationError('No signature found in message')
if verifier:
verifier.verify(signature)
return MessageFooter(signature=signature)
def unpack_values(format_string, stream, verifier=None):
"""Helper function to unpack struct data from a stream and update the signature verifier.
:param str format_string: Struct format string
:param stream: Source data stream
:type stream: io.BytesIO
:param verifier: Signature verifier object
:type verifier: aws_encryption_sdk.internal.crypto.Verifier
:returns: Unpacked values
:rtype: tuple
"""
try:
message_bytes = stream.read(struct.calcsize(format_string))
if verifier:
verifier.update(message_bytes)
values = struct.unpack(format_string, message_bytes)
except struct.error as error:
raise SerializationError('Unexpected deserialization error', type(error), error.args)
return values
def deserialize_wrapped_key(wrapping_algorithm, wrapping_key_id, wrapped_encrypted_key):
"""Extracts and deserializes EncryptedData from a Wrapped EncryptedDataKey.
:param wrapping_algorithm: Wrapping Algorithm with which to wrap plaintext_data_key
:type wrapping_algorithm: aws_encryption_sdk.identifiers.WrappingAlgorithm
:param bytes wrapping_key_id: Key ID of wrapping MasterKey
:param wrapped_encrypted_key: Raw Wrapped EncryptedKey
:type wrapped_encrypted_key: aws_encryption_sdk.structures.EncryptedDataKey
:returns: EncryptedData of deserialized Wrapped EncryptedKey
:rtype: aws_encryption_sdk.internal.structures.EncryptedData
:raises SerializationError: if wrapping_key_id does not match deserialized wrapping key id
:raises SerializationError: if wrapping_algorithm IV length does not match deserialized IV length
"""
if wrapping_key_id == wrapped_encrypted_key.key_provider.key_info:
encrypted_wrapped_key = EncryptedData(
iv=None,
ciphertext=wrapped_encrypted_key.encrypted_data_key,
tag=None
)
else:
if not wrapped_encrypted_key.key_provider.key_info.startswith(wrapping_key_id):
raise SerializationError('Master Key mismatch for wrapped data key')
_key_info = wrapped_encrypted_key.key_provider.key_info[len(wrapping_key_id):]
try:
tag_len, iv_len = struct.unpack('>II', _key_info[:8])
except struct.error:
raise SerializationError('Malformed key info: key info missing data')
tag_len //= 8 # Tag Length is stored in bits, not bytes
if iv_len != wrapping_algorithm.algorithm.iv_len:
raise SerializationError('Wrapping Algorithm mismatch for wrapped data key')
iv = _key_info[8:]
if len(iv) != iv_len:
raise SerializationError('Malformed key info: incomplete iv')
ciphertext = wrapped_encrypted_key.encrypted_data_key[:-1 * tag_len]
tag = wrapped_encrypted_key.encrypted_data_key[-1 * tag_len:]
if not ciphertext or len(tag) != tag_len:
raise SerializationError('Malformed key info: incomplete ciphertext or tag')
encrypted_wrapped_key = EncryptedData(
iv=iv,
ciphertext=ciphertext,
tag=tag
)
return encrypted_wrapped_key