capsules_aes_gcm/
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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Western Digital 2023.

//! Implements an AES-GCM implementation using the underlying
//! AES-CTR implementation.
//!
//! This capsule requires an AES-CTR implementation to support
//! AES-GCM. The implementation relies on AES-CTR, AES-CBC, AES-ECB and
//! AES-CCM to ensure that when this capsule is used it exposes
//! all of supported AES operations in a single API.

use core::cell::Cell;
use ghash::universal_hash::NewUniversalHash;
use ghash::universal_hash::UniversalHash;
use ghash::GHash;
use ghash::Key;
use kernel::hil::symmetric_encryption;
use kernel::hil::symmetric_encryption::{
    AES128Ctr, AES128, AES128CBC, AES128CCM, AES128ECB, AES128_BLOCK_SIZE, AES128_KEY_SIZE,
};
use kernel::utilities::cells::{OptionalCell, TakeCell};
use kernel::ErrorCode;

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum GCMState {
    Idle,
    GenerateHashKey,
    CtrEncrypt,
}

pub struct Aes128Gcm<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>> {
    aes: &'a A,

    mac: OptionalCell<GHash>,

    crypt_buf: TakeCell<'static, [u8]>,

    client: OptionalCell<&'a dyn symmetric_encryption::Client<'a>>,
    ccm_client: OptionalCell<&'a dyn symmetric_encryption::CCMClient>,
    gcm_client: OptionalCell<&'a dyn symmetric_encryption::GCMClient>,

    state: Cell<GCMState>,
    encrypting: Cell<bool>,

    buf: TakeCell<'static, [u8]>,

    pos: Cell<(usize, usize, usize)>,
    key: Cell<[u8; AES128_KEY_SIZE]>,
    iv: Cell<[u8; AES128_KEY_SIZE]>,
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>> Aes128Gcm<'a, A> {
    pub fn new(aes: &'a A, crypt_buf: &'static mut [u8]) -> Aes128Gcm<'a, A> {
        Aes128Gcm {
            aes,

            mac: OptionalCell::empty(),

            crypt_buf: TakeCell::new(crypt_buf),

            client: OptionalCell::empty(),
            ccm_client: OptionalCell::empty(),
            gcm_client: OptionalCell::empty(),

            state: Cell::new(GCMState::Idle),
            encrypting: Cell::new(false),

            buf: TakeCell::empty(),
            pos: Cell::new((0, 0, 0)),
            key: Cell::new(Default::default()),
            iv: Cell::new(Default::default()),
        }
    }

    fn start_ctr_encrypt(&self) -> Result<(), ErrorCode> {
        self.aes.set_mode_aes128ctr(self.encrypting.get())?;

        let res = AES128::set_key(self.aes, &self.key.get());
        if res != Ok(()) {
            return res;
        }

        self.aes.set_iv(&self.iv.get()).unwrap();

        self.aes.start_message();
        let crypt_buf = self.crypt_buf.take().unwrap();
        let (_aad_offset, message_offset, message_len) = self.pos.get();

        match AES128::crypt(
            self.aes,
            None,
            crypt_buf,
            message_offset,
            message_offset + message_len + AES128_BLOCK_SIZE,
        ) {
            None => {
                self.state.set(GCMState::CtrEncrypt);
                Ok(())
            }
            Some((res, _, crypt_buf)) => {
                self.crypt_buf.replace(crypt_buf);
                res
            }
        }
    }

    fn crypt_r(
        &self,
        buf: &'static mut [u8],
        aad_offset: usize,
        message_offset: usize,
        message_len: usize,
        encrypting: bool,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        if self.state.get() != GCMState::Idle {
            return Err((ErrorCode::BUSY, buf));
        }

        self.encrypting.set(encrypting);

        self.aes.set_mode_aes128ctr(self.encrypting.get()).unwrap();
        AES128::set_key(self.aes, &self.key.get()).unwrap();
        self.aes.set_iv(&[0; AES128_BLOCK_SIZE]).unwrap();

        self.aes.start_message();
        let crypt_buf = self.crypt_buf.take().unwrap();

        for i in 0..AES128_BLOCK_SIZE {
            crypt_buf[i] = 0;
        }

        match AES128::crypt(self.aes, None, crypt_buf, 0, AES128_BLOCK_SIZE) {
            None => {
                self.state.set(GCMState::GenerateHashKey);
            }
            Some((_res, _, crypt_buf)) => {
                self.crypt_buf.replace(crypt_buf);
            }
        }

        self.buf.replace(buf);
        self.pos.set((aad_offset, message_offset, message_len));
        Ok(())
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>>
    symmetric_encryption::CCMClient for Aes128Gcm<'a, A>
{
    fn crypt_done(&self, buf: &'static mut [u8], res: Result<(), ErrorCode>, tag_is_valid: bool) {
        self.ccm_client.map(move |client| {
            client.crypt_done(buf, res, tag_is_valid);
        });
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>>
    symmetric_encryption::AES128GCM<'a> for Aes128Gcm<'a, A>
{
    fn set_client(&self, client: &'a dyn symmetric_encryption::GCMClient) {
        self.gcm_client.set(client);
    }

    fn set_key(&self, key: &[u8]) -> Result<(), ErrorCode> {
        if key.len() < AES128_KEY_SIZE {
            Err(ErrorCode::INVAL)
        } else {
            let mut new_key = [0u8; AES128_KEY_SIZE];
            new_key.copy_from_slice(key);
            self.key.set(new_key);
            Ok(())
        }
    }

    fn set_iv(&self, nonce: &[u8]) -> Result<(), ErrorCode> {
        let mut new_nonce = [0u8; AES128_KEY_SIZE];
        let len = nonce.len().min(12);

        new_nonce[0..len].copy_from_slice(&nonce[0..len]);
        new_nonce[12..16].copy_from_slice(&[0, 0, 0, 1]);

        self.iv.set(new_nonce);
        Ok(())
    }

    fn crypt(
        &self,
        buf: &'static mut [u8],
        aad_offset: usize,
        message_offset: usize,
        message_len: usize,
        encrypting: bool,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        if self.state.get() != GCMState::Idle {
            return Err((ErrorCode::BUSY, buf));
        }

        let _ = self
            .crypt_r(buf, aad_offset, message_offset, message_len, encrypting)
            .map_err(|(ecode, _)| {
                self.buf.take().map(|buf| {
                    self.gcm_client.map(move |client| {
                        client.crypt_done(buf, Err(ecode), false);
                    });
                });
            });

        Ok(())
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>>
    symmetric_encryption::AES128<'a> for Aes128Gcm<'a, A>
{
    fn enable(&self) {
        self.aes.enable();
    }

    fn disable(&self) {
        self.aes.disable();
    }

    fn set_client(&'a self, client: &'a dyn symmetric_encryption::Client<'a>) {
        self.client.set(client);
    }

    fn set_key(&self, key: &[u8]) -> Result<(), ErrorCode> {
        AES128::set_key(self.aes, key)
    }

    fn set_iv(&self, iv: &[u8]) -> Result<(), ErrorCode> {
        self.aes.set_iv(iv)
    }

    fn start_message(&self) {
        self.aes.start_message()
    }

    fn crypt(
        &self,
        source: Option<&'static mut [u8]>,
        dest: &'static mut [u8],
        start_index: usize,
        stop_index: usize,
    ) -> Option<(
        Result<(), ErrorCode>,
        Option<&'static mut [u8]>,
        &'static mut [u8],
    )> {
        AES128::crypt(self.aes, source, dest, start_index, stop_index)
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a> + AES128CCM<'a>>
    symmetric_encryption::AES128CCM<'a> for Aes128Gcm<'a, A>
{
    fn set_client(&'a self, client: &'a dyn symmetric_encryption::CCMClient) {
        self.ccm_client.set(client);
    }

    fn set_key(&self, key: &[u8]) -> Result<(), ErrorCode> {
        AES128CCM::set_key(self.aes, key)
    }

    fn set_nonce(&self, nonce: &[u8]) -> Result<(), ErrorCode> {
        self.aes.set_nonce(nonce)
    }

    fn crypt(
        &self,
        buf: &'static mut [u8],
        a_off: usize,
        m_off: usize,
        m_len: usize,
        mic_len: usize,
        confidential: bool,
        encrypting: bool,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        AES128CCM::crypt(
            self.aes,
            buf,
            a_off,
            m_off,
            m_len,
            mic_len,
            confidential,
            encrypting,
        )
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>> AES128Ctr
    for Aes128Gcm<'a, A>
{
    fn set_mode_aes128ctr(&self, encrypting: bool) -> Result<(), ErrorCode> {
        self.aes.set_mode_aes128ctr(encrypting)
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>> AES128ECB
    for Aes128Gcm<'a, A>
{
    fn set_mode_aes128ecb(&self, encrypting: bool) -> Result<(), ErrorCode> {
        self.aes.set_mode_aes128ecb(encrypting)
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>> AES128CBC
    for Aes128Gcm<'a, A>
{
    fn set_mode_aes128cbc(&self, encrypting: bool) -> Result<(), ErrorCode> {
        self.aes.set_mode_aes128cbc(encrypting)
    }
}

impl<'a, A: AES128<'a> + AES128Ctr + AES128CBC + AES128ECB + AES128CCM<'a>>
    symmetric_encryption::Client<'a> for Aes128Gcm<'a, A>
{
    fn crypt_done(&self, _: Option<&'static mut [u8]>, crypt_buf: &'static mut [u8]) {
        match self.state.get() {
            GCMState::Idle => unreachable!(),
            GCMState::GenerateHashKey => {
                let (aad_offset, message_offset, message_len) = self.pos.get();

                let mut mac = GHash::new(Key::from_slice(&crypt_buf[0..AES128_BLOCK_SIZE]));
                let buf = self.buf.take().unwrap();

                if self.encrypting.get() {
                    mac.update_padded(&buf[aad_offset..message_offset]);

                    crypt_buf[AES128_BLOCK_SIZE..(AES128_BLOCK_SIZE + message_len)]
                        .copy_from_slice(&buf[message_offset..(message_offset + message_len)]);
                    for i in 0..AES128_BLOCK_SIZE {
                        crypt_buf[i] = 0;
                    }

                    self.mac.replace(mac);
                } else {
                    let copy_offset = (message_offset / AES128_BLOCK_SIZE) * AES128_BLOCK_SIZE;
                    mac.update_padded(&buf[aad_offset..message_offset]);
                    mac.update_padded(&buf[message_offset..(message_offset + message_len)]);

                    let associated_data_bits = ((message_offset - aad_offset) as u64) * 8;
                    let buffer_bits = (message_len as u64) * 8;

                    let mut block = ghash::Block::default();
                    block[..8].copy_from_slice(&associated_data_bits.to_be_bytes());
                    block[8..].copy_from_slice(&buffer_bits.to_be_bytes());
                    mac.update(&block);

                    let mut tag = mac.finalize().into_bytes();

                    for i in 0..AES128_BLOCK_SIZE {
                        tag[i] ^= crypt_buf[copy_offset + i];
                    }

                    buf[0..AES128_BLOCK_SIZE].copy_from_slice(&tag);
                }
                self.crypt_buf.replace(crypt_buf);
                self.buf.replace(buf);

                self.start_ctr_encrypt().unwrap();
            }
            GCMState::CtrEncrypt => {
                let buf = self.buf.take().unwrap();
                let (aad_offset, message_offset, message_len) = self.pos.get();
                let tag_offset = (message_offset / AES128_BLOCK_SIZE) * AES128_BLOCK_SIZE;
                let copy_offset = (message_offset / AES128_BLOCK_SIZE).max(1) * AES128_BLOCK_SIZE;

                if self.encrypting.get() {
                    // Check the mac
                    let mut mac = self.mac.take().unwrap();
                    mac.update_padded(
                        &crypt_buf[(message_offset + AES128_BLOCK_SIZE)
                            ..(message_offset + message_len + AES128_BLOCK_SIZE)],
                    );

                    buf[0..message_len]
                        .copy_from_slice(&crypt_buf[copy_offset..(copy_offset + message_len)]);

                    let associated_data_bits = ((message_offset - aad_offset) as u64) * 8;
                    let buffer_bits = (message_len as u64) * 8;

                    let mut block = ghash::Block::default();
                    block[..8].copy_from_slice(&associated_data_bits.to_be_bytes());
                    block[8..].copy_from_slice(&buffer_bits.to_be_bytes());
                    mac.update(&block);

                    let mut tag = mac.finalize().into_bytes();

                    for i in 0..AES128_BLOCK_SIZE {
                        tag[i] ^= crypt_buf[tag_offset + i];
                    }

                    buf[(message_offset + message_len)
                        ..(message_offset + message_len + AES128_BLOCK_SIZE)]
                        .copy_from_slice(&tag);
                } else {
                    buf[0..message_len]
                        .copy_from_slice(&crypt_buf[copy_offset..(copy_offset + message_len)]);
                }

                self.aes.disable();
                self.crypt_buf.replace(crypt_buf);
                self.state.set(GCMState::Idle);
                self.gcm_client.map(move |client| {
                    client.crypt_done(buf, Ok(()), true);
                });
            }
        }
    }
}