admin-app 0.5.0

Administrative Trussed app for SoloKeys Solo 2 security keys
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
use core::{
    fmt::{self, Display, Formatter, Write as _},
    str::FromStr,
};

use cbor_smol::{cbor_deserialize, cbor_serialize_to};
use heapless::{string::StringView, VecView};
use littlefs2_core::{path, Path};
use serde::{de::DeserializeOwned, Serialize};
use trussed::store::Filestore;
use trussed_core::{
    reset_signal::ResetSignalAllocation,
    try_syscall,
    types::{Location, Message},
    FilesystemClient,
};

const LOCATION: Location = Location::Internal;
const FILENAME: &Path = path!("config");

#[derive(Debug, Clone, Copy)]
pub enum ResetConfigResult {
    /// The config was changed as a result of the reset to default
    Changed,
    /// The config was at the default value
    Unchanged,
    /// The key does not correspond to any application that can be reset
    WrongKey,
}

impl ResetConfigResult {
    pub fn is_changed(&self) -> bool {
        matches!(self, Self::Changed)
    }
    pub fn is_unchanged(&self) -> bool {
        matches!(self, Self::Unchanged)
    }
    pub fn is_error(&self) -> bool {
        matches!(self, Self::WrongKey)
    }
}

pub trait Config: Default + PartialEq + DeserializeOwned + Serialize {
    fn field(&mut self, key: &str) -> Option<ConfigValueMut<'_>>;

    /// Client ID to factory-reset if the associated configuration option is changed
    ///
    /// # If the Request is for a `client_id`:
    ///
    /// - MUST return `Some` to indicate that the client can be factory reset by the admin app,
    ///   In that case, the path is the clientid that must be reset, and the allocation must point to a
    ///   signal that id checked by the application.
    /// - MUST return None otherwise.
    fn reset_client_id(
        &self,
        _key: &str,
    ) -> Option<(&'static Path, &'static ResetSignalAllocation)> {
        None
    }

    /// Reset the config of a client to its default value
    ///
    /// Returns `true` if the config has been changed as a result
    fn reset_client_config(&mut self, _key: &str) -> ResetConfigResult {
        ResetConfigResult::WrongKey
    }

    /// The migration version
    ///
    /// Return None if the configuration does not support storing the migration version
    fn migration_version(&self) -> Option<u32>;

    /// Set the migration version
    ///
    /// Return false if the configuration does not support storing the migration version
    fn set_migration_version(&mut self, _version: u32) -> bool;

    fn list_available_fields(&self) -> &'static [ConfigField];
}

// No need to rename, cbor-smol already packs enum using ids
//
// As the variants are serialized as their index, new variants may only be appended
#[derive(Serialize)]
#[non_exhaustive]
pub enum FieldType {
    Bool,
    U8,
    /// A UTF-8 string
    ///
    /// The maximum length is defined by the config struct holding the value, not by this type
    String,
}

#[derive(Serialize)]
pub struct ConfigField {
    #[serde(rename = "n")]
    pub name: &'static str,
    /// Changing the config field requires a touch
    #[serde(rename = "c")]
    pub requires_touch_confirmation: bool,
    /// Changing the config field requires a power cycle
    #[serde(rename = "r")]
    pub requires_reboot: bool,
    /// Changing the config field deletes data
    #[serde(rename = "d")]
    pub destructive: bool,
    /// The type of data stored in this field
    #[serde(rename = "t")]
    pub ty: FieldType,
}

impl Config for () {
    fn field(&mut self, _key: &str) -> Option<ConfigValueMut<'_>> {
        None
    }

    fn reset_client_config(&mut self, _key: &str) -> ResetConfigResult {
        ResetConfigResult::WrongKey
    }

    fn migration_version(&self) -> Option<u32> {
        None
    }

    fn set_migration_version(&mut self, _version: u32) -> bool {
        false
    }

    fn list_available_fields(&self) -> &'static [ConfigField] {
        &[]
    }
}

#[derive(Debug, Serialize)]
#[non_exhaustive]
pub enum ConfigValueMut<'a> {
    Bool(&'a mut bool),
    U8(&'a mut u8),
    /// A string of any capacity, obtained from a `heapless::String<N>` with `as_mut_view`
    String(&'a mut StringView),
}

impl<'a> ConfigValueMut<'a> {
    fn set(&mut self, value: &str) -> Result<(), ConfigError> {
        fn set_value<T: FromStr>(target: &mut T, s: &str) -> Result<(), ConfigError> {
            *target = s.parse().map_err(|_| ConfigError::InvalidValue)?;
            Ok(())
        }

        match self {
            Self::Bool(r) => set_value(*r, value),
            Self::U8(r) => set_value(*r, value),
            Self::String(r) => {
                // Check the capacity before clearing so that a rejected value leaves the stored
                // one intact
                if value.len() > r.capacity() {
                    return Err(ConfigError::DataTooLong);
                }
                r.clear();
                r.push_str(value).map_err(|_| ConfigError::DataTooLong)
            }
        }
    }
}

impl<'a> Display for ConfigValueMut<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bool(value) => write!(f, "{value}"),
            Self::U8(value) => write!(f, "{value}"),
            Self::String(value) => f.write_str(value),
        }
    }
}

macro_rules! enum_u8 {
    (
        $(#[$outer:meta])*
        $vis:vis enum $name:ident {
            $($(#[$attr:meta])* $var:ident = $num:expr),+
            $(,)*
        }
    ) => {
        $(#[$outer])*
        #[repr(u8)]
        $vis enum $name {
            $(
                $(#[$attr])*
                $var = $num,
            )*
        }

        impl $name {
            const fn from_repr(val: u8) -> Option<$name> {
                match val {
                    $(
                       $num => Some($name::$var),
                    )*
                    _ => None,
                }
            }
        }
    }
}

enum_u8!(
    #[derive(Debug)]
    pub enum ConfigError {
        ReadFailed = 1,
        WriteFailed = 2,
        DeserializationFailed = 3,
        SerializationFailed = 4,
        InvalidKey = 5,
        InvalidValue = 6,
        DataTooLong = 7,
        NotConfirmed = 8,
    }
);
const _: () = assert!(
    ConfigError::from_repr(0).is_none(),
    "ConfigError may not have a variant with discriminant zero as zero indicates success.",
);

impl From<ConfigError> for u8 {
    fn from(error: ConfigError) -> u8 {
        error as _
    }
}

pub fn get<C: Config>(
    config: &mut C,
    key: &str,
    response: &mut VecView<u8>,
) -> Result<(), ConfigError> {
    let field = config.field(key).ok_or(ConfigError::InvalidKey)?;
    write!(response, "{field}").map_err(|_| ConfigError::DataTooLong)
}

pub fn set<C: Config>(config: &mut C, key: &str, value: &str) -> Result<(), ConfigError> {
    config
        .field(key)
        .ok_or(ConfigError::InvalidKey)?
        .set(value)?;
    Ok(())
}

pub fn load<F: Filestore, C: Config>(store: &mut F) -> Result<C, ConfigError> {
    let Some(data) = load_if_exists(store, LOCATION, FILENAME)? else {
        return Ok(Default::default());
    };
    cbor_deserialize(&data).map_err(|_| ConfigError::DeserializationFailed)
}

pub fn save_filestore<F: Filestore, C: Config>(
    store: &mut F,
    config: &C,
) -> Result<(), ConfigError> {
    if config == &C::default() {
        if store.exists(FILENAME, LOCATION) {
            store
                .remove_file(FILENAME, LOCATION)
                .map_err(|_| ConfigError::WriteFailed)?;
        }
    } else {
        let mut data = Message::new();
        cbor_serialize_to(config, &mut data).map_err(|_| ConfigError::SerializationFailed)?;
        store
            .write(FILENAME, LOCATION, &data)
            .map_err(|_| ConfigError::SerializationFailed)?;
    }
    Ok(())
}

pub fn save<T: FilesystemClient, C: Config>(client: &mut T, config: &C) -> Result<(), ConfigError> {
    if config == &Default::default() {
        if exists(client, LOCATION, FILENAME)? {
            try_syscall!(client.remove_file(LOCATION, FILENAME.into()))
                .map_err(|_| ConfigError::WriteFailed)?;
        }
    } else {
        let mut data = Message::new();
        cbor_serialize_to(config, &mut data).map_err(|_| ConfigError::SerializationFailed)?;
        try_syscall!(client.write_file(LOCATION, FILENAME.into(), data, None))
            .map_err(|_| ConfigError::WriteFailed)?;
    }
    Ok(())
}

fn exists<T: FilesystemClient>(
    client: &mut T,
    location: Location,
    path: &Path,
) -> Result<bool, ConfigError> {
    try_syscall!(client.entry_metadata(location, path.into()))
        .map(|r| r.metadata.is_some())
        .map_err(|_| ConfigError::ReadFailed)
}

fn load_if_exists<F: Filestore>(
    store: &mut F,
    location: Location,
    path: &Path,
) -> Result<Option<Message>, ConfigError> {
    store.read(path, location).map(Some).or_else(|_| {
        if store.exists(path, location) {
            Err(ConfigError::ReadFailed)
        } else {
            Ok(None)
        }
    })
}

#[cfg(test)]
mod tests {
    use hex_literal::hex;

    use super::*;

    #[test]
    fn config_field() {
        let fields = &[ConfigField {
            name: "test_name",
            requires_touch_confirmation: true,
            requires_reboot: false,
            destructive: true,
            ty: FieldType::Bool,
        }];
        let mut bytes: heapless::Vec<u8, 100> = Default::default();
        cbor_smol::cbor_serialize_to(fields, &mut bytes).unwrap();
        assert_eq!(
            &bytes,
            &hex!("81A5616E69746573745F6E616D656163F56172F46164F5617400")
        );
    }

    // The field types are parsed as integers by the hosts, so their values may never change
    #[test]
    fn field_type_ids() {
        for (ty, id) in [
            (FieldType::Bool, hex!("00").as_slice()),
            (FieldType::U8, hex!("01").as_slice()),
            (FieldType::String, hex!("02").as_slice()),
        ] {
            let mut bytes: heapless::Vec<u8, 8> = Default::default();
            cbor_smol::cbor_serialize_to(&ty, &mut bytes).unwrap();
            assert_eq!(bytes.as_slice(), id);
        }
    }

    #[derive(Default, PartialEq, serde::Deserialize, serde::Serialize)]
    struct TestConfig {
        label: heapless::String<8>,
    }

    impl Config for TestConfig {
        fn field(&mut self, key: &str) -> Option<ConfigValueMut<'_>> {
            match key {
                "label" => Some(ConfigValueMut::String(self.label.as_mut_view())),
                _ => None,
            }
        }

        fn migration_version(&self) -> Option<u32> {
            None
        }

        fn set_migration_version(&mut self, _version: u32) -> bool {
            false
        }

        fn list_available_fields(&self) -> &'static [ConfigField] {
            &[]
        }
    }

    fn get_field(config: &mut TestConfig, key: &str) -> Result<heapless::String<32>, ConfigError> {
        let mut response: heapless::Vec<u8, 32> = Default::default();
        get(config, key, response.as_mut_view())?;
        Ok(core::str::from_utf8(&response).unwrap().try_into().unwrap())
    }

    #[test]
    fn string_field() {
        let mut config = TestConfig::default();
        assert_eq!(get_field(&mut config, "label").unwrap(), "");

        set(&mut config, "label", "Backup").unwrap();
        assert_eq!(config.label, "Backup");
        assert_eq!(get_field(&mut config, "label").unwrap(), "Backup");

        set(&mut config, "label", "12345678").unwrap();
        assert_eq!(config.label, "12345678");
        set(&mut config, "label", "").unwrap();
        assert_eq!(config.label, "");
    }

    #[test]
    fn string_field_too_long() {
        let mut config = TestConfig::default();
        set(&mut config, "label", "old").unwrap();

        let error = set(&mut config, "label", "123456789").unwrap_err();
        assert!(matches!(error, ConfigError::DataTooLong), "{error:?}");
        // A rejected value must not destroy the stored one
        assert_eq!(config.label, "old");
    }

    // The firmware stores arbitrary UTF-8, clients sanitize the value before displaying it
    #[test]
    fn string_field_arbitrary_utf8() {
        let mut config = TestConfig::default();

        for value in ["a\nb", "\x1b[2J", "\u{202e}", "\u{2028}", "Χ’Χ‘Χ¨"] {
            set(&mut config, "label", value).unwrap_or_else(|e| panic!("{value:?}: {e:?}"));
            assert_eq!(config.label, value);
        }
    }

    // Values are bounded by their length in bytes, not in characters
    #[test]
    fn string_field_multibyte() {
        let mut config = TestConfig::default();

        // The capacity is 8 bytes: two 4-byte characters fit, three 3-byte ones do not
        set(&mut config, "label", "πŸ”‘πŸ”‘").unwrap();
        assert_eq!(config.label, "πŸ”‘πŸ”‘");
        assert_eq!(config.label.len(), 8);

        let error = set(&mut config, "label", "δΈ­δΈ­δΈ­").unwrap_err();
        assert!(matches!(error, ConfigError::DataTooLong), "{error:?}");
        assert_eq!(config.label, "πŸ”‘πŸ”‘");
    }
}