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
/*******************************************************************************
*   (c) 2022 Zondax AG
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
********************************************************************************/
//! Support library for Ledger Nano S/X apps developed by Zondax
//!
//! Contains common commands

#![deny(warnings, trivial_casts)]
#![deny(unused_import_braces, unused_qualifications)]
#![deny(missing_docs)]

mod errors;
use std::str;

use async_trait::async_trait;
pub use errors::*;
use ledger_transport::{APDUAnswer, APDUCommand, APDUErrorCode, Exchange};
use serde::{Deserialize, Serialize};

const INS_GET_VERSION: u8 = 0x00;
const CLA_APP_INFO: u8 = 0xb0;
const INS_APP_INFO: u8 = 0x01;
const CLA_DEVICE_INFO: u8 = 0xe0;
const INS_DEVICE_INFO: u8 = 0x01;
const USER_MESSAGE_CHUNK_SIZE: usize = 250;

/// Chunk payload type
pub enum ChunkPayloadType {
    /// First chunk
    Init = 0x00,
    /// Append chunk
    Add = 0x01,
    /// Last chunk
    Last = 0x02,
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
/// App Version
pub struct Version {
    /// Application Mode
    #[serde(rename(serialize = "testMode"))]
    pub mode: u8,
    /// Version Major
    pub major: u16,
    /// Version Minor
    pub minor: u16,
    /// Version Patch
    pub patch: u16,
    /// Device is locked
    pub locked: bool,
    /// Target ID
    pub target_id: [u8; 4],
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
/// App Information
pub struct AppInfo {
    /// Name of the application
    #[serde(rename(serialize = "appName"))]
    pub app_name: String,
    /// App version
    #[serde(rename(serialize = "appVersion"))]
    pub app_version: String,
    /// Flag length
    #[serde(rename(serialize = "flagLen"))]
    pub flag_len: u8,
    /// Flag value
    #[serde(rename(serialize = "flagsValue"))]
    pub flags_value: u8,
    /// Flag Recovery
    #[serde(rename(serialize = "flagsRecovery"))]
    pub flag_recovery: bool,
    /// Flag Signed MCU code
    #[serde(rename(serialize = "flagsSignedMCUCode"))]
    pub flag_signed_mcu_code: bool,
    /// Flag Onboarded
    #[serde(rename(serialize = "flagsOnboarded"))]
    pub flag_onboarded: bool,
    /// Flag Pin Validated
    #[serde(rename(serialize = "flagsPINValidated"))]
    pub flag_pin_validated: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
/// App Device Info
pub struct DeviceInfo {
    /// Target ID
    #[serde(rename(serialize = "targetId"))]
    pub target_id: [u8; 4],
    /// Secure Element Version
    #[serde(rename(serialize = "seVersion"))]
    pub se_version: String,
    /// Device Flag
    pub flag: Vec<u8>,
    /// MCU Version
    #[serde(rename(serialize = "mcuVersion"))]
    pub mcu_version: String,
}

/// Defines what we can consider an "App"
pub trait App {
    /// App's APDU CLA
    const CLA: u8;
}

#[async_trait]
/// Common commands for any given APP
///
/// This trait is automatically implemented for any type that implements [App]
pub trait AppExt<E>: App
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    /// Retrieve the device info
    ///
    /// Works only in the dashboard
    async fn get_device_info(transport: &E) -> Result<DeviceInfo, LedgerAppError<E::Error>> {
        let command = APDUCommand { cla: CLA_DEVICE_INFO, ins: INS_DEVICE_INFO, p1: 0x00, p2: 0x00, data: Vec::new() };

        let response = transport.exchange(&command).await?;
        match response.error_code() {
            Ok(APDUErrorCode::NoError) => {},
            Ok(err) => return Err(LedgerAppError::Unknown(err as _)),
            Err(err) => return Err(LedgerAppError::Unknown(err)),
        }

        let response_data = response.data();

        let target_id_slice = &response_data[0 .. 4];
        let mut idx = 4;
        let se_version_len: usize = response_data[idx] as usize;
        idx += 1;
        let se_version_bytes = &response_data[idx .. idx + se_version_len];

        idx += se_version_len;

        let flags_len: usize = response_data[idx] as usize;
        idx += 1;
        let flag = &response_data[idx .. idx + flags_len];
        idx += flags_len;

        let mcu_version_len: usize = response_data[idx] as usize;
        idx += 1;
        let mut tmp = &response_data[idx .. idx + mcu_version_len];
        if tmp[mcu_version_len - 1] == 0 {
            tmp = &response_data[idx .. idx + mcu_version_len - 1];
        }

        let mut target_id = [Default::default(); 4];
        target_id.copy_from_slice(target_id_slice);

        let se_version = str::from_utf8(se_version_bytes).map_err(|_e| LedgerAppError::Utf8)?;
        let mcu_version = str::from_utf8(tmp).map_err(|_e| LedgerAppError::Utf8)?;

        let device_info = DeviceInfo {
            target_id,
            se_version: se_version.to_string(),
            flag: flag.to_vec(),
            mcu_version: mcu_version.to_string(),
        };

        Ok(device_info)
    }

    /// Retrieve the app info
    ///
    /// Works only in app (TOOD: dashboard support)
    async fn get_app_info(transport: &E) -> Result<AppInfo, LedgerAppError<E::Error>> {
        let command = APDUCommand { cla: CLA_APP_INFO, ins: INS_APP_INFO, p1: 0x00, p2: 0x00, data: Vec::new() };

        let response = transport.exchange(&command).await?;
        match response.error_code() {
            Ok(APDUErrorCode::NoError) => {},
            Ok(err) => return Err(LedgerAppError::AppSpecific(err as _, err.description())),
            Err(err) => return Err(LedgerAppError::Unknown(err as _)),
        }

        let response_data = response.data();

        if response_data[0] != 1 {
            return Err(LedgerAppError::InvalidFormatID);
        }

        let app_name_len: usize = response_data[1] as usize;
        let app_name_bytes = &response_data[2 .. app_name_len];

        let mut idx = 2 + app_name_len;
        let app_version_len: usize = response_data[idx] as usize;
        idx += 1;
        let app_version_bytes = &response_data[idx .. idx + app_version_len];

        idx += app_version_len;

        let app_flags_len = response_data[idx];
        idx += 1;
        let flags_value = response_data[idx];

        let app_name = str::from_utf8(app_name_bytes).map_err(|_e| LedgerAppError::Utf8)?;
        let app_version = str::from_utf8(app_version_bytes).map_err(|_e| LedgerAppError::Utf8)?;

        let app_info = AppInfo {
            app_name: app_name.to_string(),
            app_version: app_version.to_string(),
            flag_len: app_flags_len,
            flags_value,
            flag_recovery: (flags_value & 1) != 0,
            flag_signed_mcu_code: (flags_value & 2) != 0,
            flag_onboarded: (flags_value & 4) != 0,
            flag_pin_validated: (flags_value & 128) != 0,
        };

        Ok(app_info)
    }

    /// Retrieve the app version
    async fn get_version(transport: &E) -> Result<Version, LedgerAppError<E::Error>> {
        let command = APDUCommand { cla: Self::CLA, ins: INS_GET_VERSION, p1: 0x00, p2: 0x00, data: Vec::new() };

        let response = transport.exchange(&command).await?;
        match response.error_code() {
            Ok(APDUErrorCode::NoError) => {},
            Ok(err) => return Err(LedgerAppError::Unknown(err as _)),
            Err(err) => return Err(LedgerAppError::Unknown(err)),
        }

        let response_data = response.data();

        let version = match response_data.len() {
            // single byte version numbers
            4 => Version {
                mode: response_data[0],
                major: response_data[1] as u16,
                minor: response_data[2] as u16,
                patch: response_data[3] as u16,
                locked: false,
                target_id: [0, 0, 0, 0],
            },
            // double byte version numbers
            7 => Version {
                mode: response_data[0],
                major: response_data[1] as u16 * 256 + response_data[2] as u16,
                minor: response_data[3] as u16 * 256 + response_data[4] as u16,
                patch: response_data[5] as u16 * 256 + response_data[6] as u16,
                locked: false,
                target_id: [0, 0, 0, 0],
            },
            // double byte version numbers + lock + target id
            9 => Version {
                mode: response_data[0],
                major: response_data[1] as u16,
                minor: response_data[2] as u16,
                patch: response_data[3] as u16,
                locked: response_data[4] != 0,
                target_id: [response_data[5], response_data[6], response_data[7], response_data[8]],
            },
            // double byte version numbers + lock + target id
            12 => Version {
                mode: response_data[0],
                major: response_data[1] as u16 * 256 + response_data[2] as u16,
                minor: response_data[3] as u16 * 256 + response_data[4] as u16,
                patch: response_data[5] as u16 * 256 + response_data[6] as u16,
                locked: response_data[7] != 0,
                target_id: [response_data[8], response_data[9], response_data[10], response_data[11]],
            },
            _ => return Err(LedgerAppError::InvalidVersion),
        };
        Ok(version)
    }

    /// Stream a long request in chunks
    async fn send_chunks<I: std::ops::Deref<Target = [u8]> + Send + Sync>(
        transport: &E,
        command: APDUCommand<I>,
        message: &[u8],
    ) -> Result<APDUAnswer<E::AnswerType>, LedgerAppError<E::Error>> {
        let chunks = message.chunks(USER_MESSAGE_CHUNK_SIZE);
        match chunks.len() {
            0 => return Err(LedgerAppError::InvalidEmptyMessage),
            n if n > 255 => return Err(LedgerAppError::InvalidMessageSize),
            _ => (),
        }

        if command.p1 != ChunkPayloadType::Init as u8 {
            return Err(LedgerAppError::InvalidChunkPayloadType);
        }

        let mut response = transport.exchange(&command).await?;
        match response.error_code() {
            Ok(APDUErrorCode::NoError) => {},
            Ok(err) => return Err(LedgerAppError::AppSpecific(err as _, err.description())),
            Err(err) => return Err(LedgerAppError::Unknown(err as _)),
        }

        // Send message chunks
        let last_chunk_index = chunks.len() - 1;
        for (packet_idx, chunk) in chunks.enumerate() {
            let mut p1 = ChunkPayloadType::Add as u8;
            if packet_idx == last_chunk_index {
                p1 = ChunkPayloadType::Last as u8
            }

            let command = APDUCommand { cla: command.cla, ins: command.ins, p1, p2: 0, data: chunk.to_vec() };

            response = transport.exchange(&command).await?;
            match response.error_code() {
                Ok(APDUErrorCode::NoError) => {},
                Ok(err) => return Err(LedgerAppError::AppSpecific(err as _, err.description())),
                Err(err) => return Err(LedgerAppError::Unknown(err as _)),
            }
        }

        Ok(response)
    }
}

impl<T, E> AppExt<E> for T
where
    T: App,
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
}