-
Notifications
You must be signed in to change notification settings - Fork 735
/
Copy pathaes_gcm.rs
505 lines (445 loc) · 16.7 KB
/
aes_gcm.rs
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
// Copyright 2015-2025 Brian Smith.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use super::{
aes::{self, Counter, Overlapping, OverlappingPartialBlock, BLOCK_LEN, ZERO_BLOCK},
gcm,
overlapping::IndexError,
Aad, Nonce, Tag,
};
use crate::{
cpu,
error::{self, InputTooLongError},
polyfill::{slice, sliceutil::overwrite_at_start, usize_from_u64_saturated},
};
use core::ops::RangeFrom;
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86",
target_arch = "x86_64"
))]
use cpu::GetFeature as _;
mod aarch64;
mod aeshwclmulmovbe;
mod vaesclmulavx2;
#[derive(Clone)]
pub(super) struct Key(DynKey);
impl Key {
pub(super) fn new(
key: aes::KeyBytes,
cpu_features: cpu::Features,
) -> Result<Self, error::Unspecified> {
Ok(Self(DynKey::new(key, cpu_features)?))
}
}
#[derive(Clone)]
enum DynKey {
#[cfg(target_arch = "x86_64")]
VAesClMulAvx2(Combo<aes::hw::Key, gcm::vclmulavx2::Key>),
#[cfg(target_arch = "x86_64")]
AesHwClMulAvxMovbe(Combo<aes::hw::Key, gcm::clmulavxmovbe::Key>),
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
target_arch = "x86",
target_arch = "x86_64"
))]
AesHwClMul(Combo<aes::hw::Key, gcm::clmul::Key>),
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little")
))]
Simd(Combo<aes::vp::Key, gcm::neon::Key>),
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
Simd(Combo<aes::vp::Key, gcm::fallback::Key>),
Fallback(Combo<aes::fallback::Key, gcm::fallback::Key>),
}
impl DynKey {
fn new(key: aes::KeyBytes, cpu: cpu::Features) -> Result<Self, error::Unspecified> {
let cpu = cpu.values();
#[cfg(target_arch = "x86_64")]
if let Some((aes, gcm)) = cpu.get_feature() {
// 14.3.1 Detection of VEX-Encoded AES and VPCLMULQDQ
let aes_key = aes::hw::Key::new(key, aes, cpu.get_feature())?;
let gcm_key_value = derive_gcm_key_value(&aes_key);
let combo = if let Some(cpu) = cpu.get_feature() {
let gcm_key = gcm::vclmulavx2::Key::new(gcm_key_value, cpu);
Self::VAesClMulAvx2(Combo { aes_key, gcm_key })
} else if let Some(cpu) = cpu.get_feature() {
let gcm_key = gcm::clmulavxmovbe::Key::new(gcm_key_value, cpu);
Self::AesHwClMulAvxMovbe(Combo { aes_key, gcm_key })
} else {
let gcm_key = gcm::clmul::Key::new(gcm_key_value, gcm);
Self::AesHwClMul(Combo { aes_key, gcm_key })
};
return Ok(combo);
}
// x86_64 is handled above.
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
target_arch = "x86"
))]
if let (Some(aes), Some(gcm)) = (cpu.get_feature(), cpu.get_feature()) {
let aes_key = aes::hw::Key::new(key, aes, cpu.get_feature())?;
let gcm_key_value = derive_gcm_key_value(&aes_key);
let gcm_key = gcm::clmul::Key::new(gcm_key_value, gcm);
return Ok(Self::AesHwClMul(Combo { aes_key, gcm_key }));
}
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little")
))]
if let Some(cpu) = cpu.get_feature() {
return Self::new_neon(key, cpu);
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
if let Some(cpu) = cpu.get_feature() {
return Self::new_ssse3(key, cpu);
}
let _ = cpu;
Self::new_fallback(key)
}
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little")
))]
#[cfg_attr(target_arch = "aarch64", inline(never))]
fn new_neon(key: aes::KeyBytes, cpu: cpu::arm::Neon) -> Result<Self, error::Unspecified> {
let aes_key = aes::vp::Key::new(key, cpu)?;
let gcm_key_value = derive_gcm_key_value(&aes_key);
let gcm_key = gcm::neon::Key::new(gcm_key_value, cpu);
Ok(Self::Simd(Combo { aes_key, gcm_key }))
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[inline(never)]
fn new_ssse3(
key: aes::KeyBytes,
cpu: aes::vp::RequiredCpuFeatures,
) -> Result<Self, error::Unspecified> {
let aes_key = aes::vp::Key::new(key, cpu)?;
let gcm_key_value = derive_gcm_key_value(&aes_key);
let gcm_key = gcm::fallback::Key::new(gcm_key_value);
Ok(Self::Simd(Combo { aes_key, gcm_key }))
}
#[cfg_attr(
any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86",
target_arch = "x86_64",
),
inline(never)
)]
fn new_fallback(key: aes::KeyBytes) -> Result<Self, error::Unspecified> {
let aes_key = aes::fallback::Key::new(key)?;
let gcm_key_value = derive_gcm_key_value(&aes_key);
let gcm_key = gcm::fallback::Key::new(gcm_key_value);
Ok(Self::Fallback(Combo { aes_key, gcm_key }))
}
}
fn derive_gcm_key_value(aes_key: &impl aes::EncryptBlock) -> gcm::KeyValue {
gcm::KeyValue::new(aes_key.encrypt_block(ZERO_BLOCK))
}
const CHUNK_BLOCKS: usize = 3 * 1024 / 16;
#[inline(never)]
pub(super) fn seal(
Key(key): &Key,
nonce: Nonce,
aad: Aad<&[u8]>,
in_out: &mut [u8],
) -> Result<Tag, error::Unspecified> {
let mut ctr = Counter::one(nonce);
let tag_iv = ctr.increment();
match key {
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
DynKey::AesHwClMul(c) => {
seal_whole_partial(c, aad, in_out, ctr, tag_iv, aarch64::seal_whole)
}
#[cfg(target_arch = "x86_64")]
DynKey::VAesClMulAvx2(c) => seal_whole_partial(
c,
aad,
in_out,
ctr,
tag_iv,
vaesclmulavx2::seal_whole_vaes_clmul_avx2,
),
#[cfg(target_arch = "x86_64")]
DynKey::AesHwClMulAvxMovbe(Combo { aes_key, gcm_key }) => {
aeshwclmulmovbe::seal(aes_key, gcm_key, ctr, tag_iv, aad, in_out)
}
#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
DynKey::AesHwClMul(c) => seal_strided(c, aad, in_out, ctr, tag_iv),
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86_64",
target_arch = "x86"
))]
DynKey::Simd(c) => seal_strided(c, aad, in_out, ctr, tag_iv),
DynKey::Fallback(c) => seal_strided(c, aad, in_out, ctr, tag_iv),
}
}
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
target_arch = "x86_64"
))]
fn seal_whole_partial<A: aes::EncryptBlock, G: gcm::UpdateBlock>(
Combo { aes_key, gcm_key }: &Combo<A, G>,
aad: Aad<&[u8]>,
in_out: &mut [u8],
mut ctr: Counter,
tag_iv: aes::Iv,
seal_whole: impl FnOnce(&A, &mut gcm::Context<G>, &mut Counter, slice::AsChunksMut<u8, BLOCK_LEN>),
) -> Result<Tag, error::Unspecified> {
let mut auth = gcm::Context::new(gcm_key, aad, in_out.len())?;
let (whole, remainder) = slice::as_chunks_mut(in_out);
seal_whole(aes_key, &mut auth, &mut ctr, whole);
let remainder = OverlappingPartialBlock::new(remainder.into())
.unwrap_or_else(|InputTooLongError { .. }| unreachable!());
seal_finish(aes_key, auth, remainder, ctr, tag_iv)
}
#[cfg_attr(
any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86",
target_arch = "x86_64"
),
inline(never)
)]
#[cfg_attr(
any(
all(target_arch = "aarch64", target_endian = "little"),
target_arch = "x86_64"
),
cold
)]
fn seal_strided<
A: aes::EncryptBlock + aes::EncryptCtr32,
G: gcm::UpdateBlock + gcm::UpdateBlocks,
>(
Combo { aes_key, gcm_key }: &Combo<A, G>,
aad: Aad<&[u8]>,
in_out: &mut [u8],
mut ctr: Counter,
tag_iv: aes::Iv,
) -> Result<Tag, error::Unspecified> {
let mut auth = gcm::Context::new(gcm_key, aad, in_out.len())?;
let (mut whole, remainder) = slice::as_chunks_mut(in_out);
for mut chunk in whole.chunks_mut::<CHUNK_BLOCKS>() {
aes_key.ctr32_encrypt_within(chunk.as_flattened_mut().into(), &mut ctr);
auth.update_blocks(chunk.as_ref());
}
let remainder = OverlappingPartialBlock::new(remainder.into())
.unwrap_or_else(|InputTooLongError { .. }| unreachable!());
seal_finish(aes_key, auth, remainder, ctr, tag_iv)
}
fn seal_finish<A: aes::EncryptBlock, G: gcm::UpdateBlock>(
aes_key: &A,
mut auth: gcm::Context<G>,
remainder: OverlappingPartialBlock<'_>,
ctr: Counter,
tag_iv: aes::Iv,
) -> Result<Tag, error::Unspecified> {
let remainder_len = remainder.len();
if remainder_len > 0 {
let mut input = ZERO_BLOCK;
overwrite_at_start(&mut input, remainder.input());
let mut output = aes_key.encrypt_iv_xor_block(ctr.into(), input);
output[remainder_len..].fill(0);
auth.update_block(output);
remainder.overwrite_at_start(output);
}
Ok(finish(aes_key, auth, tag_iv))
}
#[inline(never)]
pub(super) fn open(
Key(key): &Key,
nonce: Nonce,
aad: Aad<&[u8]>,
in_out_slice: &mut [u8],
src: RangeFrom<usize>,
) -> Result<Tag, error::Unspecified> {
let mut ctr = Counter::one(nonce);
let tag_iv = ctr.increment();
match key {
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
DynKey::AesHwClMul(c) => {
open_whole_partial(c, aad, in_out_slice, src, ctr, tag_iv, aarch64::open_whole)
}
#[cfg(target_arch = "x86_64")]
DynKey::VAesClMulAvx2(c) => open_whole_partial(
c,
aad,
in_out_slice,
src,
ctr,
tag_iv,
vaesclmulavx2::open_whole_vaes_clmul_avx2,
),
#[cfg(target_arch = "x86_64")]
DynKey::AesHwClMulAvxMovbe(Combo { aes_key, gcm_key }) => {
aeshwclmulmovbe::open(aes_key, gcm_key, ctr, tag_iv, aad, in_out_slice, src)
}
#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
DynKey::AesHwClMul(c) => open_strided(c, aad, in_out_slice, src, ctr, tag_iv),
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little"),
target_arch = "x86_64",
target_arch = "x86"
))]
DynKey::Simd(c) => open_strided(c, aad, in_out_slice, src, ctr, tag_iv),
DynKey::Fallback(c) => open_strided(c, aad, in_out_slice, src, ctr, tag_iv),
}
}
#[cfg(any(
all(target_arch = "aarch64", target_endian = "little"),
target_arch = "x86_64"
))]
fn open_whole_partial<A: aes::EncryptBlock, G: gcm::UpdateBlock>(
Combo { aes_key, gcm_key }: &Combo<A, G>,
aad: Aad<&[u8]>,
in_out_slice: &mut [u8],
src: RangeFrom<usize>,
mut ctr: Counter,
tag_iv: aes::Iv,
open_whole: impl FnOnce(&A, &mut gcm::Context<G>, Overlapping, &mut Counter),
) -> Result<Tag, error::Unspecified> {
let in_out = Overlapping::new(in_out_slice, src.clone()).map_err(error::erase::<IndexError>)?;
let mut auth = gcm::Context::new(gcm_key, aad, in_out.len())?;
let remainder_len = in_out.len() % BLOCK_LEN;
let in_out_slice_len = in_out_slice.len();
let whole_in_out_slice = &mut in_out_slice[..(in_out_slice_len - remainder_len)];
let whole = Overlapping::new(whole_in_out_slice, src.clone())
.unwrap_or_else(|IndexError { .. }| unreachable!());
let whole_len = whole.len();
open_whole(aes_key, &mut auth, whole, &mut ctr);
let remainder = &mut in_out_slice[whole_len..];
let remainder =
Overlapping::new(remainder, src).unwrap_or_else(|IndexError { .. }| unreachable!());
let remainder = OverlappingPartialBlock::new(remainder)
.unwrap_or_else(|InputTooLongError { .. }| unreachable!());
open_finish(aes_key, auth, remainder, ctr, tag_iv)
}
#[cfg_attr(
any(
all(
any(
all(target_arch = "aarch64", target_endian = "little"),
all(target_arch = "arm", target_endian = "little")
),
target_feature = "neon"
),
all(
any(target_arch = "x86", target_arch = "x86_64"),
target_feature = "sse"
)
),
inline(never)
)]
#[cfg_attr(
any(
all(target_arch = "aarch64", target_endian = "little"),
target_arch = "x86_64"
),
cold
)]
fn open_strided<
A: aes::EncryptBlock + aes::EncryptCtr32,
G: gcm::UpdateBlock + gcm::UpdateBlocks,
>(
Combo { aes_key, gcm_key }: &Combo<A, G>,
aad: Aad<&[u8]>,
in_out_slice: &mut [u8],
src: RangeFrom<usize>,
mut ctr: Counter,
tag_iv: aes::Iv,
) -> Result<Tag, error::Unspecified> {
let in_out = Overlapping::new(in_out_slice, src.clone()).map_err(error::erase::<IndexError>)?;
let input = in_out.input();
let input_len = input.len();
let mut auth = gcm::Context::new(gcm_key, aad, input_len)?;
let remainder_len = input_len % BLOCK_LEN;
let whole_len = input_len - remainder_len;
let in_prefix_len = src.start;
{
let mut chunk_len = CHUNK_BLOCKS * BLOCK_LEN;
let mut output = 0;
let mut input = in_prefix_len;
loop {
if whole_len - output < chunk_len {
chunk_len = whole_len - output;
}
let ciphertext = &in_out_slice[input..][..chunk_len];
let (ciphertext, leftover) = slice::as_chunks(ciphertext);
debug_assert_eq!(leftover.len(), 0);
if ciphertext.is_empty() {
break;
}
auth.update_blocks(ciphertext);
let chunk = Overlapping::new(
&mut in_out_slice[output..][..(chunk_len + in_prefix_len)],
in_prefix_len..,
)
.map_err(error::erase::<IndexError>)?;
aes_key.ctr32_encrypt_within(chunk, &mut ctr);
output += chunk_len;
input += chunk_len;
}
}
let in_out = Overlapping::new(&mut in_out_slice[whole_len..], src)
.unwrap_or_else(|IndexError { .. }| unreachable!());
let in_out = OverlappingPartialBlock::new(in_out)
.unwrap_or_else(|InputTooLongError { .. }| unreachable!());
open_finish(aes_key, auth, in_out, ctr, tag_iv)
}
fn open_finish<A: aes::EncryptBlock, G: gcm::UpdateBlock>(
aes_key: &A,
mut auth: gcm::Context<G>,
remainder: OverlappingPartialBlock<'_>,
ctr: Counter,
tag_iv: aes::Iv,
) -> Result<Tag, error::Unspecified> {
if remainder.len() > 0 {
let mut input = ZERO_BLOCK;
overwrite_at_start(&mut input, remainder.input());
auth.update_block(input);
remainder.overwrite_at_start(aes_key.encrypt_iv_xor_block(ctr.into(), input));
}
Ok(finish(aes_key, auth, tag_iv))
}
fn finish<A: aes::EncryptBlock, G: gcm::UpdateBlock>(
aes_key: &A,
gcm_ctx: gcm::Context<G>,
tag_iv: aes::Iv,
) -> Tag {
// Finalize the tag and return it.
gcm_ctx.pre_finish(|pre_tag| Tag(aes_key.encrypt_iv_xor_block(tag_iv, pre_tag)))
}
pub(super) const MAX_IN_OUT_LEN: usize = super::max_input_len(BLOCK_LEN, 2);
// [NIST SP800-38D] Section 5.2.1.1. Note that [RFC 5116 Section 5.1] and
// [RFC 5116 Section 5.2] have an off-by-one error in `P_MAX`.
//
// [NIST SP800-38D]:
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
// [RFC 5116 Section 5.1]: https://tools.ietf.org/html/rfc5116#section-5.1
// [RFC 5116 Section 5.2]: https://tools.ietf.org/html/rfc5116#section-5.2
const _MAX_INPUT_LEN_BOUNDED_BY_NIST: () =
assert!(MAX_IN_OUT_LEN == usize_from_u64_saturated(((1u64 << 39) - 256) / 8));
#[derive(Copy, Clone)]
pub(super) struct Combo<Aes, Gcm> {
pub(super) aes_key: Aes,
pub(super) gcm_key: Gcm,
}