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
//! The bootloader interface
//!
//! Construct a `Bootloader` from a VID/PID pair (optionally a UUID to disambiguate),
//! then call its methods.

use core::fmt;

use anyhow::anyhow;
use enum_iterator::all;
use hidapi::HidApi;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub mod command;
pub use command::{Command, KeystoreOperation, Response};
pub mod error;
pub mod property;
pub use property::{GetProperties, Properties, Property};
pub mod protocol;
pub mod provision;
use protocol::Protocol;

pub trait UuidSelectable: Sized {
    /// Returns the UUID associated with the thing, if it has a UUID.
    ///
    /// Note: This may modify the thing as it might need to communicate with it.
    fn try_uuid(&mut self) -> anyhow::Result<Uuid>;

    /// Returns all of the available things.
    fn list() -> Vec<Self>;

    /// Returns the thing with the given UUID.
    ///
    /// Default implementation; replace for better error messages.
    fn having(uuid: Uuid) -> anyhow::Result<Self> {
        let mut candidates: Vec<Self> = Self::list()
            .into_iter()
            // The Err variant is preventing a simple `Ok(uuid) == entry.try_uuid()`,
            // as there is no Eq on anyhow::Error.
            .filter_map(|mut entry| {
                if let Ok(entry_uuid) = entry.try_uuid() {
                    if entry_uuid == uuid {
                        Some(entry)
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .collect();
        match candidates.len() {
            0 => Err(anyhow!("No candidate has UUID {:X}", uuid.simple())),
            1 => Ok(candidates.remove(0)),
            n => Err(anyhow!(
                "Multiple ({}) candidates have UUID {:X}",
                n,
                uuid.simple()
            )),
        }
    }
}

pub struct Bootloader {
    pub protocol: Protocol,
    // move around; also "new" should scan the device_list iterator
    // to pull out all the info
    pub vid: u16,
    pub pid: u16,
    pub uuid: u128,
}

impl fmt::Debug for Bootloader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Bootloader")
            .field("vid", &hexstr!(&self.vid.to_be_bytes()))
            .field("pid", &hexstr!(&self.pid.to_be_bytes()))
            .field("uuid", &hexstr!(&self.uuid.to_be_bytes()))
            .finish()
    }
}

impl fmt::Display for Bootloader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

/// Bootloader commands return a "status". The non-zero statii can be split
/// as `100*group + code`. We map these groups into enum variants, containing
/// the code interpreted as an error the area.
///
/// TODO: To implement StdError via thiserror::Error, we need to
/// add error messages to all the error variants.
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum Error {
    Generic(error::GenericError),
    FlashDriver(error::FlashDriverError),
    PropertyStore(error::PropertyStoreError),
    CrcChecker(error::CrcCheckerError),
    SbLoader(error::SbLoaderError),
    Unknown(u32),
}

pub type Result<T> = std::result::Result<T, Error>;

impl UuidSelectable for Bootloader {
    fn try_uuid(&mut self) -> anyhow::Result<Uuid> {
        Ok(self.uuid())
    }

    fn having(uuid: Uuid) -> anyhow::Result<Self> {
        let mut candidates: Vec<Self> = Self::list()
            .into_iter()
            .filter(|bootloader| bootloader.uuid() == uuid)
            .collect();
        match candidates.len() {
            0 => Err(anyhow!("No usable bootloader has UUID {:X}", uuid.simple())),
            1 => Ok(candidates.remove(0)),
            n => Err(anyhow!(
                "Multiple ({}) bootloaders have UUID {:X}",
                n,
                uuid.simple()
            )),
        }
    }

    /// Returns a vector of all HID devices that appear to be ROM bootloaders
    fn list() -> Vec<Self> {
        let api = HidApi::new().unwrap();
        api.device_list()
            .filter_map(|device_info| {
                let vid = device_info.vendor_id();
                let pid = device_info.product_id();

                // TODO: Check if these checks are globally valid.
                // Perhaps drop them completely?
                // The intent is to avoid sending the UUID query to completely unrelated devices.
                if device_info.manufacturer_string() != Some("NXP SEMICONDUCTOR INC.") {
                    return None;
                }
                if device_info.product_string() != Some("USB COMPOSITE DEVICE") {
                    return None;
                }
                device_info
                    .open_device(&api)
                    .ok()
                    .map(|device| (device, vid, pid))
            })
            .filter_map(|(device, vid, pid)| {
                let protocol = Protocol::new(device);
                GetProperties {
                    protocol: &protocol,
                }
                .device_uuid()
                .ok()
                .map(|uuid| Self {
                    protocol,
                    vid,
                    pid,
                    uuid,
                })
            })
            .collect()
    }
}

impl Bootloader {
    fn uuid(&self) -> Uuid {
        Uuid::from_u128(self.uuid)
    }

    /// Select a unique ROM bootloader with the given VID and PID.
    pub fn try_new(vid: Option<u16>, pid: Option<u16>) -> anyhow::Result<Self> {
        Self::try_find(vid, pid, None)
    }

    /// Attempt to find a unique ROM bootloader with the given VID, PID and UUID.
    pub fn try_find(
        vid: Option<u16>,
        pid: Option<u16>,
        uuid: Option<Uuid>,
    ) -> anyhow::Result<Self> {
        let mut bootloaders = Self::find(vid, pid, uuid);
        if bootloaders.len() > 1 {
            Err(anyhow!("Muliple matching bootloaders found"))
        } else {
            bootloaders
                .pop()
                .ok_or_else(|| anyhow!("No matching bootloader found"))
        }
    }

    /// Finds all ROM bootloader with the given VID, PID and UUID.
    pub fn find(vid: Option<u16>, pid: Option<u16>, uuid: Option<Uuid>) -> Vec<Self> {
        Self::list()
            .into_iter()
            .filter(|bootloader| vid.map_or(true, |vid| vid == bootloader.vid))
            .filter(|bootloader| pid.map_or(true, |pid| pid == bootloader.pid))
            .filter(|bootloader| uuid.map_or(true, |uuid| uuid.as_u128() == bootloader.uuid))
            .collect()
    }

    pub fn info(&self) {
        for property in all::<Property>() {
            // println!("\n{:?}", property);
            self.property(property).ok();
        }
    }

    pub fn reboot(&self) {
        info!("calling Command::Reset");
        self.protocol.call(&Command::Reset).expect("success");
    }

    pub fn enroll_puf(&self) {
        // first time i ran this:
        // 03000C00 A0000002 00000000 15000000 00000000 00000000 00000000 00000000 00000000 00000030 FF5F0030 00000020 FF5F0020 00000000 00000000
        // second time i ran this:
        // 03000C00 A0000002 00000000 15000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
        self.protocol
            .call(&Command::Keystore(KeystoreOperation::Enroll))
            .expect("success");
        info!("PUF enrolled");
    }

    /// The reason for this wrapper is that the device aborts early if more than 512 bytes are
    /// requested. Unclear why it does this...
    ///
    /// This is a traffic trace (requesting all of PFR in one go), removing the "surplus junk"
    ///
    /// --> 01002000 03000002 00DE0900 000E0000 00000000 00000000 00000000 00000000 00000000
    /// <-- 03000C00 A3010002 00000000 000E0000
    /// <-- 04003800 00000000 02000000 02000000 02000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 02000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    /// <-- 04003800 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 ECE6A668 2922E9CC F462A95F DF81E180 E1528642 7C520098
    /// <-- 04000000
    /// <-- 03000C00 A0000002 65000000 03000000
    ///
    /// The error is 101 = 100 + 1 = (supposedly) a flash driver "alignment" error (?!)
    ///
    /// The interesting thing is that at the point where the device aborts, there are 8 bytes
    /// remaining, which it otherwise produces in a final
    ///
    /// <-- 04000800 2C80BA51 B067AF3C
    /// <-- 03000C00 A0000002 00000000 03000000
    ///
    /// TODO: should we just enter our desired length anyway, and handle such situations?
    /// As in retry at the new index, with the reduced length? Instead of using a fixed 512B chunking?
    ///
    /// TODO: Need to expect errors such as: `Response status = 139 (0x8b) kStatus_FLASH_NmpaUpdateNotAllowed`
    /// This happens with `read-memory $((0x0009_FC70)) 16`, which would be the UUID
    ///
    /// TODO: Need to expect errors such as: `Response status = 10200 (0x27d8) kStatusMemoryRangeInvalid`
    /// This happens with `read-memory $((0x5000_0FFC)) 1`, which would be the DIEID (for chip rev)
    pub fn read_memory(&self, address: usize, length: usize) -> Vec<u8> {
        let mut data = Vec::new();
        let mut remaining = length;
        let mut address = address;
        while remaining > 0 {
            let length = core::cmp::min(remaining, 512);
            data.extend_from_slice(&self.read_memory_at_most_512(address, length));
            remaining -= length;
            address += length;
        }
        data
    }

    pub fn read_memory_at_most_512(&self, address: usize, length: usize) -> Vec<u8> {
        let response = self
            .protocol
            .call(&Command::ReadMemory { address, length })
            .expect("success");
        if let Response::ReadMemory(data) = response {
            data
        } else {
            todo!();
        }
    }

    pub fn receive_sb_file<'a>(&self, data: &[u8], progress: Option<&'a dyn Fn(usize)>) {
        let _response = self
            .protocol
            .call_progress(
                &Command::ReceiveSbFile {
                    data: data.to_vec(),
                },
                progress,
            )
            .expect("success");
    }

    pub fn erase_flash(&self, address: usize, length: usize) {
        let _response = self
            .protocol
            .call(&Command::EraseFlash { address, length })
            .expect("success");
    }

    pub fn write_memory(&self, address: usize, data: Vec<u8>) {
        let _response = self
            .protocol
            .call(&Command::WriteMemory { address, data })
            .expect("success");
    }

    fn property(&self, property: property::Property) -> Result<Vec<u32>> {
        self.protocol.property(property)
    }

    pub fn properties(&self) -> property::GetProperties<'_> {
        GetProperties {
            protocol: &self.protocol,
        }
    }

    pub fn all_properties(&self) -> Properties {
        self.properties().all()
    }

    pub fn run_command(
        &self,
        cmd: Command,
    ) -> std::result::Result<command::Response, protocol::Error> {
        self.protocol.call(&cmd)
    }
}

#[cfg(all(feature = "with-device", test))]
fn all_properties() {
    // let (vid, pid) = (0x1fc9, 0x0021);
    let (vid, pid) = (0x1209, 0xb000);
    let bootloader = Bootloader::try_new(Some(vid), Some(pid)).unwrap();
    insta::assert_debug_snapshot!(bootloader.all_properties());
}