-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathFooter.dfy
408 lines (376 loc) · 16.9 KB
/
Footer.dfy
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
include "../Model/AwsCryptographyDbEncryptionSdkStructuredEncryptionTypes.dfy"
include "Util.dfy"
include "Header.dfy"
/*
Intended usage :
For encryption
footer := CreateFooter();
footerAttribute := footer.makeTerminal();
For decryption
footer :- Footer.DeserializeFooter();
footer.validate()
*/
module StructuredEncryptionFooter {
import opened Wrappers
import opened StandardLibrary
import opened StandardLibrary.UInt
import opened AwsCryptographyDbEncryptionSdkStructuredEncryptionTypes
import opened StructuredEncryptionUtil
import Primitives = AtomicPrimitives
import Materials
import Header = StructuredEncryptionHeader
import CMP = AwsCryptographyMaterialProvidersTypes
import Prim = AwsCryptographyPrimitivesTypes
import UTF8
import Digest
import StandardLibrary.String
import Seq
const RecipientTagSize := 48
//const SignatureSize := 96
const SignatureSize := 103
type RecipientTag = x : Bytes | |x| == RecipientTagSize witness *
type Signature = x : Bytes | |x| == SignatureSize witness *
//= specification/structured-encryption/footer.md#footer-format
//= type=implication
//# The [Terminal Value](./structures.md#terminal-value) of the footer MUST be
// | Field | Length (bytes) | Interpreted as |
// | ----- | -------------- | -------------- |
// | [Recipient Tags](#recipient-tags) | Variable. 48 bytes per Encrypted Data Key in the header | Bytes |
// | [Signature](#signature) | 0 or 103 | Signature, if signatures are enabled |
datatype Footer = Footer (
tags : seq<RecipientTag>,
sig : Option<Signature>
) {
function method serialize()
: Bytes
{
SerializeTags(tags) + SerializeSig(sig)
}
function method makeTerminal()
: (ret : StructuredDataTerminal)
//= specification/structured-encryption/encrypt-path-structure.md#footer-field
//= type=implication
//# The Footer Field TypeID MUST be 0xFFFF
ensures ret.typeId == BYTES_TYPE_ID
//= specification/structured-encryption/encrypt-path-structure.md#footer-field
//= type=implication
//# The Footer Field Value MUST be the serialized [footer](footer.md).
ensures ret.value == serialize()
{
ValueToData(serialize(), BYTES_TYPE_ID)
}
method validate(
client: Primitives.AtomicPrimitivesClient,
mat : CMP.DecryptionMaterials,
edks : CMP.EncryptedDataKeyList,
data : CanonCryptoList,
header : Bytes)
returns (ret : Result<bool, Error>)
requires Materials.DecryptionMaterialsWithPlaintextDataKey(mat)
requires ValidSuite(mat.algorithmSuite)
requires Header.ValidEncryptionContext(mat.encryptionContext)
//= specification/structured-encryption/decrypt-path-structure.md#verify-signatures
//= type=implication
//# The number of [HMACs in the footer](./footer.md#hmacs)
//# MUST be the number of [Encrypted Data Keys in the header](./header.md#encrypted-data-keys).
ensures ret.Success? ==>
|edks| == |tags|
modifies client.Modifies
requires client.ValidState()
ensures client.ValidState()
{
:- Need(|edks| == |tags|, E("There are a different number of recipient tags in the stored header than there are in the decryption materials."));
var canonicalHash :- CanonHash(data, header, mat.encryptionContext);
var input := Prim.HMacInput (
digestAlgorithm := mat.algorithmSuite.symmetricSignature.HMAC,
key := mat.symmetricSigningKey.value,
message := canonicalHash
);
var hashR := client.HMac(input);
var hash :- hashR.MapFailure(e => AwsCryptographyPrimitives(e));
// is there any way to get "48" from alg.symmetricSignature.HMAC?
:- Need(|hash| == 48, E("Bad hash length"));
var foundTag := false;
for i := 0 to |tags| {
//= specification/structured-encryption/footer.md#recipient-tag-verification
//# Recipient Tag comparisons MUST be constant time operations.
if ConstantTimeEquals(hash, tags[i]) {
foundTag := true;
break;
}
}
//= specification/structured-encryption/footer.md#recipient-tag-verification
//# Verification MUST fail unless at least one of the [Recipient Tags](#recipient-tags)
//# matches a calculated recipient tag using the provided symmetricSigningKey.
:- Need(foundTag, E("Signature of record does not match the signature computed when the record was encrypted."));
:- Need(sig.Some? == mat.algorithmSuite.signature.ECDSA?, E("Internal error. Signature both does and does not exist."));
//= specification/structured-encryption/footer.md#signature-verification
//# If the footer contains a signature, this signature MUST be verified using the
//# [asymmetric signature algorithm](../../submodules/MaterialProviders/aws-encryption-sdk-specification/framework/algorithm-suites.md#algorithm-suites-signature-settings)
//# indicated by the algorithm suite.
if sig.Some? {
var verInput := Prim.ECDSAVerifyInput(
signatureAlgorithm := mat.algorithmSuite.signature.ECDSA.curve,
verificationKey := mat.verificationKey.value,
message := canonicalHash,
signature := sig.value
);
var verR := client.ECDSAVerify(verInput);
var ver :- verR.MapFailure(e => AwsCryptographyPrimitives(e));
:- Need(ver, E("Signature did not verify"));
}
return Success(true);
}
}
// Given a StructuredDataTerminal, return the canonical value for the type, for use in the footer checksum calculations
function method GetCanonicalType(value : StructuredDataTerminal, isEncrypted : bool)
: Result<Bytes, Error>
{
if isEncrypted then
:- Need(2 <= |value.value| < UINT64_LIMIT, E("Bad length."));
Success(UInt64ToSeq((|value.value| - 2) as uint64) + UTF8.EncodeAscii("ENCRYPTED"))
else
:- Need(|value.value| < UINT64_LIMIT, E("Bad length."));
Success(UInt64ToSeq((|value.value|) as uint64) + UTF8.EncodeAscii("PLAINTEXT") + value.typeId)
}
function method GetCanonicalEncryptedField(fieldName : CanonicalPath, value : StructuredDataTerminal)
: (ret : Result<Bytes, Error>)
ensures ret.Success? ==>
//= specification/structured-encryption/footer.md#canonical-encrypted-field
//= type=implication
//# The canonical form of an encrypted field MUST be
//# | Field | Length (bytes) | Interpreted as |
//# | ----- | -------------- | -------------- |
//# | The [canonical path](./header.md#canonical-path) of the field name | Variable | Bytes |
//# | encrypted data length - 2 | 8 | 64-bit integer |
//# | "ENCRYPTED" | 9 | Literal Ascii text |
//# | TypeID | 2 | the type ID of the unencrypted Terminal |
//# | value | Variable | the encrypted Terminal value |
&& 2 <= |value.value| < UINT64_LIMIT
&& ret.value ==
fieldName
+ UInt64ToSeq((|value.value| - 2) as uint64)
+ UTF8.EncodeAscii("ENCRYPTED")
+ value.value // this is 2 bytes of unencrypted type, followed by encrypted value
{
:- Need(2 <= |value.value| < UINT64_LIMIT, E("Bad length."));
Success(
fieldName
+ UInt64ToSeq((|value.value| - 2) as uint64)
+ UTF8.EncodeAscii("ENCRYPTED")
+ value.value
)
}
function method GetCanonicalPlaintextField(fieldName : CanonicalPath, value : StructuredDataTerminal)
: (ret : Result<Bytes, Error>)
ensures ret.Success? ==>
//= specification/structured-encryption/footer.md#canonical-plaintext-field
//= type=implication
//# The canonical form of a plaintext field MUST be
//# | Field | Length (bytes) | Interpreted as |
//# | ----- | -------------- | -------------- |
//# | The [canonical path](./header.md#canonical-path) of the field name | Variable | Bytes |
//# | data length | 8 | 64-bit integer |
//# | "PLAINTEXT" | 9 | Literal Ascii text |
//# | TypeID | 2 | the type ID of the Terminal |
//# | value | Variable | the Terminal value |
&& |value.value| < UINT64_LIMIT
&& ret.value ==
fieldName
+ UInt64ToSeq((|value.value|) as uint64)
+ UTF8.EncodeAscii("PLAINTEXT")
+ value.typeId
+ value.value
{
:- Need(|value.value| < UINT64_LIMIT, E("Bad length."));
Success(
fieldName
+ UInt64ToSeq((|value.value|) as uint64)
+ UTF8.EncodeAscii("PLAINTEXT")
+ value.typeId
+ value.value
)
}
// Given a key value pair, return the canonical value for use in the footer checksum calculations
function method GetCanonicalItem(data : CanonCryptoItem)
: (ret : Result<Bytes, Error>)
{
if data.action == ENCRYPT_AND_SIGN then
GetCanonicalEncryptedField(data.key, data.data)
else
GetCanonicalPlaintextField(data.key, data.data)
}
function method CanonContent (
data : CanonCryptoList, // remaining fields to be canonized
canonized : Bytes := [] // output
) : Result<Bytes, Error>
{
if |data| == 0 then
Success(canonized)
else if data[0].action == DO_NOTHING then
CanonContent(data[1..], canonized)
else
var newPart :- GetCanonicalItem(data[0]);
CanonContent(data[1..], canonized + newPart)
}
function method CanonRecord (
data : CanonCryptoList,
header : Bytes,
enc : Header.CMPEncryptionContext
) : (ret : Result<Bytes, Error>)
ensures ret.Success? ==>
//= specification/structured-encryption/footer.md#canonical-record
//= type=implication
//# The canonical form of a record MUST be
//# | Field | Length (bytes) | Interpreted as |
//# | ----- | -------------- | -------------- |
//# | header | Variable | The full serialized header with commitment |
//# | AAD Length | 8 | 64-bit integer, the length of the following AAD data |
//# | AAD | Variable | The serialization of the Encryption Context from the Encryption Materials |
//# | Field Data | Variable | For each [signed field](#signed-fields), ordered lexicographically by [canonical path](./header.md#canonical-path), the [canonical field](#canonical-field).
&& CanonContent(data).Success?
&& var canon := CanonContent(data).value;
&& var AAD := Header.SerializeContext(enc);
&& |AAD| < UINT64_LIMIT
&& var len := UInt64ToSeq(|AAD| as uint64);
&& ret.value ==
header
+ len
+ AAD
+ canon
{
var canon :- CanonContent(data);
var AAD := Header.SerializeContext(enc);
:- Need(|AAD| < UINT64_LIMIT, E("AAD too long."));
var len := UInt64ToSeq(|AAD| as uint64);
Success(header + len + AAD + canon)
}
method CanonHash (
data : CanonCryptoList,
header : Bytes,
enc : Header.CMPEncryptionContext
) returns (ret : Result<Bytes, Error>)
ensures ret.Success? ==>
|ret.value| == 48
//= specification/structured-encryption/footer.md#hash-calculation
//= type=implication
//# The canonical hash of a record MUST be the SHA384 of the canonical form of the record.
{
var data :- CanonRecord(data, header, enc);
var resultR := Digest.Digest(Prim.DigestInput(digestAlgorithm := Prim.SHA_384, message := data));
return resultR.MapFailure(e => AwsCryptographyPrimitives(e));
}
// return the footer value for the StructuredData
method CreateFooter(
client: Primitives.AtomicPrimitivesClient,
mat : CMP.EncryptionMaterials,
data : CanonCryptoList,
header : Bytes)
returns (ret : Result<Footer, Error>)
requires ValidSuite(mat.algorithmSuite)
requires Materials.EncryptionMaterialsHasPlaintextDataKey(mat)
requires Header.ValidEncryptionContext(mat.encryptionContext)
ensures (ret.Success? && mat.algorithmSuite.signature.ECDSA?) ==>
//= specification/structured-encryption/footer.md#signature
//= type=implication
//# The `signature`, if it exists, MUST be calculated using the
//# [asymmetric signature algorithm](../../submodules/MaterialProviders/aws-encryption-sdk-specification/framework/algorithm-suites.md#algorithm-suites-signature-settings)
//# indicated by the algorithm suite.
&& var history := client.History.ECDSASign;
&& 0 < |history|
&& var signInput := Seq.Last(history).input;
&& signInput.signatureAlgorithm == mat.algorithmSuite.signature.ECDSA.curve
// Can't do signInput.message == cHash, because SHA is a method, not a function
modifies client.Modifies
requires client.ValidState()
ensures client.ValidState()
{
var canonicalHash :- CanonHash(data, header, mat.encryptionContext);
var tags : seq<RecipientTag> := [];
for i := 0 to |mat.encryptedDataKeys|
invariant |tags| == i
{
//= specification/structured-encryption/footer.md#recipient-tags
//# the Recipient Tag MUST be MUST be calculated over the [Canonical Hash](#canonical-hash)
//# using the [symmetric signature algorithm](../../submodules/MaterialProviders/aws-encryption-sdk-specification/framework/algorithm-suites.md#algorithm-suites-signature-settings)
//# indicated in the algorithm suite,
//# and the
//# [symmetric signing keys](../../submodules/MaterialProviders/aws-encryption-sdk-specification/framework/structures.md#symmetric-signing-keys)
//# in the encryption materials.
var input := Prim.HMacInput (
digestAlgorithm := mat.algorithmSuite.symmetricSignature.HMAC,
key := mat.symmetricSigningKeys.value[i],
message := canonicalHash
);
var hashR := client.HMac(input);
var hash :- hashR.MapFailure(e => AwsCryptographyPrimitives(e));
// is there any way to get "48" from alg.symmetricSignature.HMAC?
:- Need(|hash| == 48, E("Bad hash length"));
//= specification/structured-encryption/footer.md#recipient-tags
//# the HMAC values MUST have the same order as the
//# [symmetric signing keys](../../submodules/MaterialProviders/aws-encryption-sdk-specification/framework/structures.md#symmetric-signing-keys)
//# used to calculate them.
tags := tags + [hash];
}
//= specification/structured-encryption/footer.md#recipient-tags
//= type=implication
//# There MUST be one Recipient Tag for each Encrypted Data Key in the [header](./header.md#encrypted-data-keys)
assert |tags| == |mat.encryptedDataKeys|;
if mat.algorithmSuite.signature.ECDSA? {
//= specification/structured-encryption/footer.md#signature
//# The `signature`, if it exists, MUST be calculated over the [Canonical Hash](#canonical-hash),
//# using the asymmetric signing key in the encryption materials.
var verInput := Prim.ECDSASignInput(
signatureAlgorithm := mat.algorithmSuite.signature.ECDSA.curve,
signingKey := mat.signingKey.value,
message := canonicalHash
);
var sigR := client.ECDSASign(verInput);
var sig :- sigR.MapFailure(e => AwsCryptographyPrimitives(e));
//assert |sig| == SignatureSize;
:- Need(|sig| == SignatureSize, E("Signature is " + String.Base10Int2String(|sig|) + " bytes, should have been " + String.Base10Int2String(SignatureSize) + " bytes."));
return Success(Footer(tags, Some(sig)));
} else {
return Success(Footer(tags, None));
}
}
function method SerializeTags(tags : seq<RecipientTag>)
: Bytes
{
if |tags| == 0 then
[]
else
tags[0] + SerializeTags(tags[1..])
}
function method SerializeSig(sig : Option<Signature>)
: Bytes
{
if sig.Some? then
sig.value
else
[]
}
function method GatherTags(data : Bytes)
: seq<RecipientTag>
requires |data| % RecipientTagSize == 0
{
if |data| == 0 then
[]
else
[data[0..RecipientTagSize]] + GatherTags(data[RecipientTagSize..])
}
function method DeserializeFooter(data : Bytes, hasSig : bool)
: Result<Footer, Error>
{
if hasSig then
:- Need((|data| - SignatureSize) % RecipientTagSize == 0, E("Mangled signed footer has strange size"));
:- Need(|data| >= RecipientTagSize + SignatureSize, E("Footer too short."));
Success(Footer(GatherTags(data[..|data|-SignatureSize]), Some(data[|data|-SignatureSize..])))
else
:- Need(|data| % RecipientTagSize == 0, E("Mangled unsigned footer has strange size"));
:- Need(|data| >= RecipientTagSize, E("Footer too short."));
Success(Footer(GatherTags(data), None))
}
}