sframe 2.0.0

pure rust implementation of SFrame (RFC 9605)
Documentation
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
use crate::{
    crypto::{
        aead::AeadEncrypt,
        buffer::{AadData, encryption::EncryptionBuffer},
        key_derivation::KeyDerivation,
    },
    error::{Result, SframeError},
    header::{Counter, SframeHeader},
    key::GenericEncryptionKey,
};

use super::{
    FrameBuffer, FrameCounter,
    encrypted_frame::{EncryptedFrame, EncryptedFrameView},
};
use std::convert::Infallible;

fn next_counter(frame_counter: &mut impl FrameCounter) -> Result<Counter> {
    frame_counter
        .try_next()
        .map_err(|err| SframeError::CounterCreationFailed(Box::new(err)))
}

/// A view on a buffer (as a continuous slice of memory), representing a media frame.
/// Can optionally have meta data (e.g. a header) associated to it, which is considered for authentication.
#[derive(Debug, PartialEq, Eq)]
pub struct MediaFrameView<'buf> {
    counter: Counter,
    meta_data: &'buf [u8],
    payload: &'buf [u8],
}

impl<'ibuf> MediaFrameView<'ibuf> {
    /// Creates a new view on a payload buffer and assigns it the next counter (CTR) value.
    /// Only available for a [`FrameCounter`] which cannot fail.
    pub fn new<C, P>(frame_counter: &mut C, payload: &'ibuf P) -> Self
    where
        C: FrameCounter<Error = Infallible>,
        P: AsRef<[u8]> + ?Sized,
    {
        Self::with_meta_data(frame_counter, payload, &[])
    }

    /// Creates a new view on a payload buffer, assigns it the next counter (CTR) value and associates it with the meta data.
    /// Only available for a [`FrameCounter`] which cannot fail.
    pub fn with_meta_data<C, P, M>(
        frame_counter: &mut C,
        payload: &'ibuf P,
        meta_data: &'ibuf M,
    ) -> Self
    where
        C: FrameCounter<Error = Infallible>,
        P: AsRef<[u8]> + ?Sized,
        M: AsRef<[u8]> + ?Sized,
    {
        let Ok(counter) = frame_counter.try_next();
        Self::with_meta_data_and_ctr(counter, payload, meta_data)
    }

    /// Creates a new view on a payload buffer and assigns it the next counter (CTR) value.
    /// Returns an [`SframeError::CounterCreationFailed`] wrapping the error of the
    /// [`FrameCounter`] if no counter value could be created.
    pub fn try_new<C, P>(frame_counter: &mut C, payload: &'ibuf P) -> Result<Self>
    where
        C: FrameCounter,
        P: AsRef<[u8]> + ?Sized,
    {
        Self::try_with_meta_data(frame_counter, payload, &[])
    }

    /// Creates a new view on a payload buffer, assigns it the next counter (CTR) value and associates it with the meta data.
    /// Returns an [`SframeError::CounterCreationFailed`] wrapping the error of the
    /// [`FrameCounter`] if no counter value could be created.
    pub fn try_with_meta_data<C, P, M>(
        frame_counter: &mut C,
        payload: &'ibuf P,
        meta_data: &'ibuf M,
    ) -> Result<Self>
    where
        C: FrameCounter,
        P: AsRef<[u8]> + ?Sized,
        M: AsRef<[u8]> + ?Sized,
    {
        let counter = next_counter(frame_counter)?;
        Ok(Self::with_meta_data_and_ctr(counter, payload, meta_data))
    }

    pub(super) fn with_meta_data_and_ctr<P, M>(
        counter: Counter,
        payload: &'ibuf P,
        meta_data: &'ibuf M,
    ) -> Self
    where
        P: AsRef<[u8]> + ?Sized,
        M: AsRef<[u8]> + ?Sized,
    {
        let payload = payload.as_ref();
        let meta_data = meta_data.as_ref();
        log::trace!(
            "Creating MediaFrame # {counter} with payload size {} using meta data of size {}",
            payload.len(),
            meta_data.len(),
        );
        Self {
            counter,
            meta_data,
            payload,
        }
    }

    /// Meta data associated with this media frame
    pub fn meta_data(&self) -> &'ibuf [u8] {
        self.meta_data
    }

    /// Payload of this media frame
    pub fn payload(&self) -> &'ibuf [u8] {
        self.payload
    }

    /// Frame count for the Sframe scheme associated to this media frame
    pub fn counter(&self) -> Counter {
        self.counter
    }

    /// Encrypts the media frame with the sframe key according to [RFC 9605 4.4.3](https://www.rfc-editor.org/rfc/rfc9605.html#name-encryption). Dynamically allocates memory for the resulting [`EncryptedFrame`].
    /// The associated meta data is not encrypted but considered for the authentication tag.
    /// Returns an [`crate::error::SframeError`] when encryption fails.
    pub fn encrypt<A, D>(&self, key: &GenericEncryptionKey<A, D>) -> Result<EncryptedFrame>
    where
        A: AeadEncrypt<Secret = D::Secret>,
        D: KeyDerivation,
    {
        let mut buffer = Vec::new();
        let view = self.encrypt_into(key, &mut buffer)?;

        let header = *view.header();
        let meta_len = view.meta_data().len();

        let encrypted_frame = EncryptedFrame::from_buffer(buffer, header, meta_len);

        Ok(encrypted_frame)
    }

    /// Encrypts the media frame with the sframe key according to [RFC 9605 4.4.3](https://www.rfc-editor.org/rfc/rfc9605.html#name-encryption) and stores the result, an [`EncryptedFrameView`], into the provided buffer.
    /// The associated meta data is not encrypted but considered for the authentication tag.
    /// Returns an [`crate::error::SframeError`] when encryption fails.
    pub fn encrypt_into<'obuf, A, D>(
        &self,
        key: &GenericEncryptionKey<A, D>,
        buffer: &'obuf mut impl FrameBuffer,
    ) -> Result<EncryptedFrameView<'obuf>>
    where
        A: AeadEncrypt<Secret = D::Secret>,
        D: KeyDerivation,
    {
        let key_id = key.key_id();
        log::trace!(
            "Encrypting MediaFrame # {} using KeyId {key_id} and CipherSuite {}",
            self.counter,
            key.cipher_suite()
        );

        let header = SframeHeader::new(key_id, self.counter);
        log::trace!("MediaFrame # {} using header {}", self.counter, header);

        let aad = Aad {
            meta_data: self.meta_data,
            header: &header,
        };
        let mut crypto_buffer =
            EncryptionBuffer::try_allocate(buffer, key.cipher_suite(), &aad, self.payload)?;

        log::trace!("MediaFrame # {} trying to encrypt", self.counter);
        key.encrypt(&mut crypto_buffer, self.counter)?;

        let meta_len = self.meta_data().len();
        let buffer: &mut [u8] = crypto_buffer.into();
        let encrypted =
            EncryptedFrameView::with_header(header, &buffer[meta_len..], &buffer[..meta_len]);

        Ok(encrypted)
    }
}

struct Aad<'a> {
    meta_data: &'a [u8],
    header: &'a SframeHeader,
}

impl AadData for Aad<'_> {
    fn len(&self) -> usize {
        self.meta_data.len() + self.header.len()
    }

    fn serialize(&self, buffer: &mut [u8]) -> Result<()> {
        let (meta_data, header) = buffer.split_at_mut(self.meta_data.len());
        meta_data.copy_from_slice(self.meta_data);
        self.header.serialize(header)?;
        Ok(())
    }
}

/// A an abstraction of a media frame owning an internal buffer.
/// Can optionally have meta data (e.g. a header) associated to it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MediaFrame {
    counter: Counter,
    buffer: Vec<u8>,
    meta_len: usize,
}

impl MediaFrame {
    /// Creates a new media frame by copying the data of a payload buffer and assigning it the next counter (CTR) value.
    /// Only available for a [`FrameCounter`] which cannot fail.
    pub fn new<C, P>(frame_counter: &mut C, payload: P) -> Self
    where
        C: FrameCounter<Error = Infallible>,
        P: AsRef<[u8]>,
    {
        Self::with_meta_data(frame_counter, payload, [])
    }

    /// Creates a new media frame and assigns it the next counter (CTR) value.
    /// Payload and meta data are copied into an internal buffer.
    /// Only available for a [`FrameCounter`] which cannot fail.
    pub fn with_meta_data<C, P, M>(frame_counter: &mut C, payload: P, meta_data: M) -> Self
    where
        C: FrameCounter<Error = Infallible>,
        P: AsRef<[u8]>,
        M: AsRef<[u8]>,
    {
        let Ok(counter) = frame_counter.try_next();
        Self::with_meta_data_and_ctr(counter, payload, meta_data)
    }

    /// Creates a new media frame by copying the data of a payload buffer and assigning it the next counter (CTR) value.
    /// Returns an [`SframeError::CounterCreationFailed`] wrapping the error of the
    /// [`FrameCounter`] if no counter value could be created.
    pub fn try_new<C, P>(frame_counter: &mut C, payload: P) -> Result<Self>
    where
        C: FrameCounter,
        P: AsRef<[u8]>,
    {
        Self::try_with_meta_data(frame_counter, payload, [])
    }

    /// Creates a new media frame and assigns it the next counter (CTR) value.
    /// Payload and meta data are copied into an internal buffer.
    /// Returns an [`SframeError::CounterCreationFailed`] wrapping the error of the
    /// [`FrameCounter`] if no counter value could be created.
    pub fn try_with_meta_data<C, P, M>(
        frame_counter: &mut C,
        payload: P,
        meta_data: M,
    ) -> Result<Self>
    where
        C: FrameCounter,
        P: AsRef<[u8]>,
        M: AsRef<[u8]>,
    {
        let counter = next_counter(frame_counter)?;
        Ok(Self::with_meta_data_and_ctr(counter, payload, meta_data))
    }

    pub(super) fn with_meta_data_and_ctr<P, M>(counter: Counter, payload: P, meta_data: M) -> Self
    where
        P: AsRef<[u8]>,
        M: AsRef<[u8]>,
    {
        let payload = payload.as_ref();
        let meta_data = meta_data.as_ref();
        let meta_len = meta_data.len();
        let payload_len = payload.len();
        log::trace!(
            "Creating MediaFrame # {counter} with payload of size {payload_len} using meta data of size {meta_len}"
        );

        let mut buffer = Vec::with_capacity(payload_len + meta_len);
        buffer.extend(meta_data);
        buffer.extend(payload);

        Self {
            counter,
            buffer,
            meta_len,
        }
    }

    pub(super) fn with_buffer(counter: Counter, buffer: Vec<u8>, meta_len: usize) -> Self {
        Self {
            counter,
            buffer,
            meta_len,
        }
    }

    /// Meta data associated with this media frame
    pub fn meta_data(&self) -> &[u8] {
        &self.buffer[..self.meta_len]
    }

    /// Payload of this media frame
    pub fn payload(&self) -> &[u8] {
        &self.buffer[self.meta_len..]
    }

    /// Frame count for the Sframe scheme associated to this media frame
    pub fn counter(&self) -> Counter {
        self.counter
    }

    /// Encrypts the media frame with the sframe key according to [RFC 9605 4.4.3](https://www.rfc-editor.org/rfc/rfc9605.html#name-encryption).
    /// Dynamically allocates memory for the resulting [`EncryptedFrame`].
    /// The associated meta data is not encrypted but considered for the authentication tag.
    /// Returns an [`crate::error::SframeError`] when encryption fails
    pub fn encrypt<A, D>(&self, key: &GenericEncryptionKey<A, D>) -> Result<EncryptedFrame>
    where
        A: AeadEncrypt<Secret = D::Secret>,
        D: KeyDerivation,
    {
        let view =
            MediaFrameView::with_meta_data_and_ctr(self.counter, self.payload(), self.meta_data());
        view.encrypt(key)
    }

    /// Encrypts the media frame with the sframe key according to [RFC 9605 4.4.3](https://www.rfc-editor.org/rfc/rfc9605.html#name-encryption)
    /// and stores the result into the provided buffer. An [`EncryptedFrameView`] on the buffer is returned on success.
    /// The associated meta data is not encrypted but considered for the authentication tag.
    /// Returns an [`crate::error::SframeError`] when encryption fails.
    pub fn encrypt_into<'obuf, A, D>(
        &self,
        key: &GenericEncryptionKey<A, D>,
        buffer: &'obuf mut impl FrameBuffer,
    ) -> Result<EncryptedFrameView<'obuf>>
    where
        A: AeadEncrypt<Secret = D::Secret>,
        D: KeyDerivation,
    {
        let view =
            MediaFrameView::with_meta_data_and_ctr(self.counter, self.payload(), self.meta_data());
        view.encrypt_into(key, buffer)
    }
}

impl AsRef<[u8]> for MediaFrame {
    fn as_ref(&self) -> &[u8] {
        self.buffer.as_slice()
    }
}

#[cfg(all(test, crypto_backend))]
mod test {
    use crate::{
        CipherSuite,
        frame::{
            FrameCounter,
            media_frame::{MediaFrame, MediaFrameView},
        },
        header::Counter,
        key::EncryptionKey,
        util::test::assert_bytes_eq,
    };
    use pretty_assertions::assert_eq;
    use std::convert::Infallible;

    const COUNTER: u64 = 42;
    const PAYLOAD: &[u8] = &[6, 6, 6, 6, 6, 6];
    const KEY_ID: u64 = 666;
    const META_DATA: &[u8] = b"META";

    /// A counter which cannot fail, so that the infallible API can be used
    struct InfallibleCounter;
    impl FrameCounter for InfallibleCounter {
        type Error = Infallible;
        fn try_next(&mut self) -> Result<Counter, Self::Error> {
            Ok(COUNTER)
        }
    }

    #[derive(Debug, thiserror::Error)]
    #[error("no counter left")]
    struct NoCounter;

    /// A counter which always fails, to observe how its error is propagated
    struct FailingCounter;
    impl FrameCounter for FailingCounter {
        type Error = NoCounter;
        fn try_next(&mut self) -> Result<Counter, Self::Error> {
            Err(NoCounter)
        }
    }

    #[test]
    fn create_media_frame_view_with_an_infallible_counter() {
        let frame_view = MediaFrameView::new(&mut InfallibleCounter, &PAYLOAD);

        assert_eq!(frame_view.counter(), COUNTER);
    }

    #[test]
    fn create_media_frame_with_an_infallible_counter() {
        let frame = MediaFrame::new(&mut InfallibleCounter, PAYLOAD);

        assert_eq!(frame.counter(), COUNTER);
    }

    #[test]
    fn propagate_the_counter_error_creating_a_media_frame_view() {
        let error = MediaFrameView::try_new(&mut FailingCounter, &PAYLOAD).unwrap_err();

        assert!(error.source_as::<NoCounter>().is_some());
    }

    #[test]
    fn propagate_the_counter_error_creating_a_media_frame() {
        let error = MediaFrame::try_new(&mut FailingCounter, PAYLOAD).unwrap_err();

        assert!(error.source_as::<NoCounter>().is_some());
    }

    #[test]
    fn create_media_frame_with_meta_data() {
        let frame_view = MediaFrameView::with_meta_data_and_ctr(COUNTER, &PAYLOAD, &META_DATA);

        assert_eq!(frame_view.payload(), PAYLOAD);
        assert_eq!(frame_view.counter(), COUNTER);
        assert_eq!(frame_view.meta_data(), META_DATA);
    }

    #[test]
    fn encrypt_media_frame_view() {
        let key =
            EncryptionKey::derive_from(CipherSuite::AesGcm256Sha512, KEY_ID, "SECRET").unwrap();
        let mut encrypt_buffer = Vec::new();

        let media_frame = MediaFrameView::with_meta_data_and_ctr(COUNTER, &PAYLOAD, META_DATA);
        let encrypted_frame = media_frame.encrypt_into(&key, &mut encrypt_buffer).unwrap();

        assert_eq!(encrypted_frame.header().key_id(), KEY_ID);
        assert_eq!(encrypted_frame.header().counter(), COUNTER);
        assert_bytes_eq(encrypted_frame.meta_data(), META_DATA);
        assert!(!encrypted_frame.cipher_text().is_empty());
    }

    #[test]
    fn encrypt_media_frame() {
        let key =
            EncryptionKey::derive_from(CipherSuite::AesGcm256Sha512, KEY_ID, "SECRET").unwrap();

        let media_frame = MediaFrame::with_meta_data_and_ctr(COUNTER, PAYLOAD, META_DATA);
        let encrypted_frame = media_frame.encrypt(&key).unwrap();

        assert_eq!(encrypted_frame.header().key_id(), KEY_ID);
        assert_eq!(encrypted_frame.header().counter(), COUNTER);
        assert_bytes_eq(encrypted_frame.meta_data(), META_DATA);
        assert!(!encrypted_frame.cipher_text().is_empty());
    }
}