liboscore 0.2.7

Rust wrapper around the libOSCORE implementation of OSCORE (RFC8613), a security layer for CoAP
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
//! Wrapper around the `liboscore` C library, which implements the [OSCORE
//! RFC](https://datatracker.ietf.org/doc/html/rfc8613), and thus symmetric encryption for the
//! [CoAP protocol](https://datatracker.ietf.org/doc/html/rfc7252).
//!
//! To ensure proper setup and teardown of data structures that include references, several
//! functions in this library take callbacks in which the accessed data is used; for example, an
//! encrypted message is passed to [`protect_request()`] along with a callback, and the plaintext
//! is then passed back to the caller in that callback closure inside `protect_request()`. While
//! nothing in this library is a potentially-blocking operation (and thus worht async'ifying),
//! there might be asynchronous code in callbacks: Therefore, asynchronous versions of the
//! functions are provided that take asynchronous callbacks. They are functionally identical.
//! Future versions of this crate might consider other idioms rather than callbacks (e.g.
//! destructors) to avoid going through callbacks altogether.
#![no_std]
// We need these linked in
extern crate liboscore_cryptobackend;
extern crate liboscore_msgbackend;

use core::mem::MaybeUninit;

mod platform;

// FIXME: pub only for tests?
pub mod raw;

mod impl_message;
pub use impl_message::ProtectedMessage;

mod oscore_option;
pub use oscore_option::OscoreOption;

mod algorithms;
pub use algorithms::{AeadAlg, AlgorithmNotSupported, HkdfAlg};

mod primitive;
pub use primitive::{DeriveError, PrimitiveContext, PrimitiveImmutables};

#[track_caller]
#[inline]
fn poll_once_expect_immediate<R>(future: impl core::future::Future<Output = R>) -> R {
    let future = core::pin::pin!(future);
    let mut context = core::task::Context::from_waker(core::task::Waker::noop());
    match future.poll(&mut context) {
        core::task::Poll::Ready(r) => r,
        core::task::Poll::Pending => unreachable!("The function's only await point is in the callback, and the provided callback has none."),
    }
}

#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum PrepareError {
    /// The security context can not provide protection for this message
    SecurityContextUnavailable,
}

impl PrepareError {
    /// Construct a Rust error type out of the C type
    ///
    /// This returns a result to be easily usable with the `?` operator.
    fn new(input: raw::oscore_prepare_result) -> Result<(), Self> {
        match input {
            raw::oscore_prepare_result_OSCORE_PREPARE_OK => Ok(()),
            raw::oscore_prepare_result_OSCORE_PREPARE_SECCTX_UNAVAILABLE => {
                Err(PrepareError::SecurityContextUnavailable)
            }
            _ => unreachable!(),
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum FinishError {
    Size,
    Crypto,
}

impl FinishError {
    /// Construct a Rust error type out of the C type
    ///
    /// This returns a result to be easily usable with the `?` operator.
    fn new(input: raw::oscore_finish_result) -> Result<(), Self> {
        match input {
            raw::oscore_finish_result_OSCORE_FINISH_OK => Ok(()),
            raw::oscore_finish_result_OSCORE_FINISH_ERROR_SIZE => Err(FinishError::Size),
            raw::oscore_finish_result_OSCORE_FINISH_ERROR_CRYPTO => Err(FinishError::Crypto),
            _ => unreachable!(),
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum ProtectError {
    Prepare(PrepareError),
    Finish(FinishError),
}

impl From<PrepareError> for ProtectError {
    fn from(e: PrepareError) -> Self {
        ProtectError::Prepare(e)
    }
}

impl From<FinishError> for ProtectError {
    fn from(e: FinishError) -> Self {
        ProtectError::Finish(e)
    }
}

#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum UnprotectRequestError {
    Duplicate,
    Invalid,
}

impl UnprotectRequestError {
    /// Construct a Rust error type out of the C type
    ///
    /// This returns a result to be easily usable with the `?` operator.
    fn new(input: raw::oscore_unprotect_request_result) -> Result<(), Self> {
        match input {
            raw::oscore_unprotect_request_result_OSCORE_UNPROTECT_REQUEST_OK => Ok(()),
            raw::oscore_unprotect_request_result_OSCORE_UNPROTECT_REQUEST_DUPLICATE => {
                Err(UnprotectRequestError::Duplicate)
            }
            raw::oscore_unprotect_request_result_OSCORE_UNPROTECT_REQUEST_INVALID => {
                Err(UnprotectRequestError::Invalid)
            }
            _ => unreachable!(),
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Copy, Clone)]
pub enum UnprotectResponseError {
    Invalid,
}

impl UnprotectResponseError {
    /// Construct a Rust error type out of the C type
    ///
    /// This returns a result to be easily usable with the `?` operator.
    fn new(input: raw::oscore_unprotect_response_result) -> Result<(), Self> {
        match input {
            raw::oscore_unprotect_response_result_OSCORE_UNPROTECT_RESPONSE_OK => Ok(()),
            raw::oscore_unprotect_response_result_OSCORE_UNPROTECT_RESPONSE_INVALID => {
                Err(UnprotectResponseError::Invalid)
            }
            _ => unreachable!(),
        }
    }
}

/// Protects an OSCORE request.
///
/// The message into which the ciphertext is to be written is passed in as `request`; the actual
/// writing happens while there is a protected message configured during a callback.
///
/// Along with any output of the callback, this produces a request identity that will be needed
/// later to unprotect the response.
///
/// For sync callbacks, see [`protect_request`].
// FIXME we should carry the context around, but that'd require it to have a shared portion that we
// can then clone and combine with the oscore_requestid_t.
pub async fn async_protect_request<R>(
    request: impl liboscore_msgbackend::WithMsgNative,
    ctx: &mut PrimitiveContext,
    writer: impl AsyncFnOnce(&mut ProtectedMessage) -> R,
) -> Result<(raw::oscore_requestid_t, R), ProtectError> {
    request
        .async_with_msg_native(async |msg| {
            let mut plaintext = MaybeUninit::uninit();
            let mut request_data = MaybeUninit::uninit();
            // Safety: Everything that needs to be initialized is
            let prepare_ok = unsafe {
                raw::oscore_prepare_request(
                    msg,
                    plaintext.as_mut_ptr(),
                    ctx.as_mut(),
                    request_data.as_mut_ptr(),
                )
            };
            PrepareError::new(prepare_ok)?;
            // Safety: Initialized after successful return
            let plaintext = unsafe { plaintext.assume_init() };
            let request_data = unsafe { request_data.assume_init() };

            let mut plaintext = crate::ProtectedMessage::new(plaintext);
            let user_carry = writer(&mut plaintext).await;
            plaintext.flush();
            let mut plaintext = plaintext.into_inner();

            let mut returned_msg = MaybeUninit::uninit();
            // Safety: Everything that needs to be initialized is
            let finish_ok =
                unsafe { raw::oscore_encrypt_message(&mut plaintext, returned_msg.as_mut_ptr()) };
            FinishError::new(finish_ok)?;
            // We're discarding the native message that's in returned_msg. If it were owned (which
            // would be a valid choice for with_inmemory_write), the closure might be required to
            // return it, but it currently isn't.

            Ok((request_data, user_carry))
        })
        .await
}

/// Synchronous version of [`async_protect_request`], see there.
pub fn protect_request<R>(
    request: impl liboscore_msgbackend::WithMsgNative,
    ctx: &mut PrimitiveContext,
    writer: impl FnOnce(&mut ProtectedMessage) -> R,
) -> Result<(raw::oscore_requestid_t, R), ProtectError> {
    poll_once_expect_immediate(async_protect_request(request, ctx, async |m| writer(m)))
}

/// Unprotects an OSCORE request.
///
/// The message from which the ciphertext is read in as `request` (and taken mutably because it is
/// decrypted in-place, rendering it nonsensical to any other CoAP processing); the actual
/// processing of the plaintext happens while there is a protected message configured during a
/// callback.
///
/// Along with the output of the callback, this produces a request identity that will be needed to
/// later protect the response(s).
///
/// For sync callbacks, see [`unprotect_request`].
pub async fn async_unprotect_request<R>(
    request: impl liboscore_msgbackend::WithMsgNative,
    oscoreoption: OscoreOption<'_>, // Here's where we need to cheat a bit: We both take the message
    // writably, *and* we take data out of that message through
    // another pointer. This is legal because we don't alter any
    // option values, or more precisely, we don't alter the OSCORE
    // option's value, but yet it's slightly uncomfortable (and
    // users may need to resort to unsafe to call this).
    ctx: &mut PrimitiveContext,
    reader: impl AsyncFnOnce(&ProtectedMessage) -> R,
) -> Result<(raw::oscore_requestid_t, R), UnprotectRequestError> {
    request
        .async_with_msg_native(async |nativemsg| {
            let mut plaintext = MaybeUninit::uninit();
            let mut request_data = MaybeUninit::uninit();
            let decrypt_ok = unsafe {
                raw::oscore_unprotect_request(
                    nativemsg,
                    plaintext.as_mut_ptr(),
                    &oscoreoption.into_inner(),
                    ctx.as_mut(),
                    request_data.as_mut_ptr(),
                )
            };
            // We could introduce extra handling of Invalid if our handlers had a notion of being (even
            // security-wise) idempotent, or if we supported B.1 recovery here.
            UnprotectRequestError::new(decrypt_ok)?;

            let plaintext = unsafe { plaintext.assume_init() };
            let request_data = unsafe { request_data.assume_init() };

            let plaintext = ProtectedMessage::new(plaintext);

            let user_data = reader(&plaintext).await;

            unsafe { raw::oscore_release_unprotected(&mut plaintext.into_inner()) };

            Ok((request_data, user_data))
        })
        .await
}

/// Synchronous version of [`async_unprotect_request`], see there.
pub fn unprotect_request<R>(
    request: impl liboscore_msgbackend::WithMsgNative,
    oscoreoption: OscoreOption<'_>,
    ctx: &mut PrimitiveContext,
    reader: impl FnOnce(&ProtectedMessage) -> R,
) -> Result<(raw::oscore_requestid_t, R), UnprotectRequestError> {
    poll_once_expect_immediate(async_unprotect_request(
        request,
        oscoreoption,
        ctx,
        async |m| reader(m),
    ))
}

/// Protects an OSCORE response.
///
/// The message into which the ciphertext is to be written is passed in as `response`; the actual
/// writing happens while there is a protected message configured during a callback.
///
/// The `correlation` data (to be carried over from the corresponding request operation) is not
/// consumed, but altered: if at all, only the first response can use the nonce of the request.
/// Later uses will create larger responses that include an own nonce.
pub async fn async_protect_response<R>(
    response: impl liboscore_msgbackend::WithMsgNative,
    ctx: &mut PrimitiveContext,
    correlation: &mut raw::oscore_requestid_t,
    writer: impl AsyncFnOnce(&mut ProtectedMessage) -> R,
) -> Result<R, ProtectError> {
    response
        .async_with_msg_native(async |nativemsg| {
            let mut plaintext = MaybeUninit::uninit();
            // Safety: Everything that needs to be initialized is
            let prepare_ok = unsafe {
                raw::oscore_prepare_response(
                    nativemsg,
                    plaintext.as_mut_ptr(),
                    ctx.as_mut(),
                    correlation,
                )
            };
            PrepareError::new(prepare_ok)?;
            // Safety: Initialized after successful return
            let plaintext = unsafe { plaintext.assume_init() };

            let mut plaintext = crate::ProtectedMessage::new(plaintext);
            let user_data = writer(&mut plaintext).await;
            plaintext.flush();
            let mut plaintext = plaintext.into_inner();

            let mut returned_msg = MaybeUninit::uninit();
            // Safety: Everything that needs to be initialized is
            let finish_ok =
                unsafe { raw::oscore_encrypt_message(&mut plaintext, returned_msg.as_mut_ptr()) };
            FinishError::new(finish_ok)?;
            // We're discarding the native message that's in returned_msg. If it were owned (which
            // would be a valid choice for with_inmemory_write), the closure might be required to
            // return it, but it currently isn't.

            Ok(user_data)
        })
        .await
}

/// Synchronous version of [`async_protect_response`], see there.
pub fn protect_response<R>(
    response: impl liboscore_msgbackend::WithMsgNative,
    ctx: &mut PrimitiveContext,
    correlation: &mut raw::oscore_requestid_t,
    writer: impl FnOnce(&mut ProtectedMessage) -> R,
) -> Result<R, ProtectError> {
    poll_once_expect_immediate(async_protect_response(
        response,
        ctx,
        correlation,
        async |m| writer(m),
    ))
}

/// Unprotects an OSCORE response.
///
/// The message from which the ciphertext is read in as `response` (and taken mutably because it is
/// decrypted in-place, rendering it nonsensical to any other CoAP processing); the actual
/// processing of the plaintext happens while there is a protected message configured during a
/// callback.
///
/// The `correlation` data is to be carried over from the corresponding request operation.
//
// A narrower set of requirements than &MutableWritableMessage, like
// "ReadableMessageWithMutablePayload", would suffice, but none such trait is useful outside of
// here ... though, for CBOR decoding, maybe, where we memmove around indefinite length strings
// into place?
pub async fn async_unprotect_response<R>(
    response: impl liboscore_msgbackend::WithMsgNative,
    ctx: &mut PrimitiveContext,
    oscoreoption: OscoreOption<'_>,
    correlation: &mut raw::oscore_requestid_t,
    reader: impl AsyncFnOnce(&ProtectedMessage) -> R,
) -> Result<R, UnprotectResponseError> {
    response
        .async_with_msg_native(async |nativemsg| {
            let mut plaintext = MaybeUninit::uninit();
            let decrypt_ok = unsafe {
                raw::oscore_unprotect_response(
                    nativemsg,
                    plaintext.as_mut_ptr(),
                    &oscoreoption.into_inner(),
                    ctx.as_mut(),
                    correlation,
                )
            };
            UnprotectResponseError::new(decrypt_ok)?;

            let plaintext = unsafe { plaintext.assume_init() };

            let plaintext = ProtectedMessage::new(plaintext);

            let user_data = reader(&plaintext).await;

            unsafe { raw::oscore_release_unprotected(&mut plaintext.into_inner()) };

            Ok(user_data)
        })
        .await
}

/// Synchronous version of [`async_unprotect_response`], see there.
pub fn unprotect_response<R>(
    response: impl liboscore_msgbackend::WithMsgNative,
    ctx: &mut PrimitiveContext,
    oscoreoption: OscoreOption<'_>,
    correlation: &mut raw::oscore_requestid_t,
    reader: impl FnOnce(&ProtectedMessage) -> R,
) -> Result<R, UnprotectResponseError> {
    poll_once_expect_immediate(async_unprotect_response(
        response,
        ctx,
        oscoreoption,
        correlation,
        async |m| reader(m),
    ))
}