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
use std::convert::{TryFrom, TryInto};
use crate::errors::LedgerError;
const MAX_DATA_SIZE: usize = 255;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct APDUData(Vec<u8>);
impl std::ops::Deref for APDUData {
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl APDUData {
pub fn new(buf: &[u8]) -> Self {
let length = std::cmp::min(buf.len(), MAX_DATA_SIZE);
APDUData(buf[..length].to_vec())
}
pub fn resize(&mut self, new_size: usize, fill_with: u8) {
self.0
.resize(std::cmp::min(new_size, MAX_DATA_SIZE), fill_with)
}
pub fn data(self) -> Vec<u8> {
self.0
}
}
impl From<&[u8]> for APDUData {
fn from(buf: &[u8]) -> Self {
Self::new(buf)
}
}
impl From<Vec<u8>> for APDUData {
fn from(mut v: Vec<u8>) -> Self {
v.resize(std::cmp::min(v.len(), MAX_DATA_SIZE), 0);
Self(v)
}
}
impl AsRef<[u8]> for APDUData {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0[..]
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct APDUCommand {
pub ins: u8,
pub p1: u8,
pub p2: u8,
pub data: APDUData,
pub response_len: Option<u8>,
}
impl std::fmt::Display for APDUCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("APDUCommand")
.field("ins", &self.ins)
.field("p1", &self.p1)
.field("p2", &self.p2)
.field("data", &hex::encode(&*self.data))
.field("response_len", &self.response_len)
.finish()
}
}
impl APDUCommand {
pub fn serialized_length(&self) -> usize {
let mut length = 4;
if !self.data.is_empty() {
length += 1;
length += self.data.len();
}
length += self.response_len.is_some() as usize;
length
}
pub fn write_to<W: std::io::Write>(&self, w: &mut W) -> Result<usize, std::io::Error> {
w.write_all(&[0xE0, self.ins, self.p1, self.p2])?;
if !self.data.is_empty() {
w.write_all(&[self.data.len() as u8])?;
w.write_all(self.data.as_ref())?;
}
if let Some(response_len) = self.response_len {
w.write_all(&[response_len])?;
}
Ok(self.serialized_length())
}
pub fn serialize(&self) -> Vec<u8> {
let mut v = Vec::with_capacity(self.serialized_length());
self.write_to(&mut v).unwrap();
v
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct APDUAnswer {
response: Vec<u8>,
}
impl std::ops::Deref for APDUAnswer {
type Target = Vec<u8>;
fn deref(&self) -> &Self::Target {
&self.response
}
}
impl std::fmt::Display for APDUAnswer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"APDUAnswer: {{\n\tResponse: {:?} \n\tData: {:?}\n}}",
self.response_status(),
self.data()
)
}
}
impl APDUAnswer {
pub fn from_answer(response: Vec<u8>) -> Result<APDUAnswer, LedgerError> {
if response.len() < 2 {
Err(LedgerError::ResponseTooShort(response.to_vec()))
} else {
Ok(Self { response })
}
}
pub fn is_success(&self) -> bool {
match self.response_status() {
Some(opcode) => opcode.is_success(),
None => false,
}
}
pub fn retcode(&self) -> u16 {
let mut buf = [0u8; 2];
buf.copy_from_slice(&self.response[self.len() - 2..]);
u16::from_be_bytes(buf)
}
pub fn response_status(&self) -> Option<APDUResponseCodes> {
self.retcode().try_into().ok()
}
pub fn data(&self) -> Option<&[u8]> {
if self.is_success() {
Some(&self.response[..self.len() - 2])
} else {
None
}
}
}
#[repr(u16)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum APDUResponseCodes {
NoError = 0x9000,
ExecutionError = 0x6400,
WrongLength = 0x6700,
UnlockDeviceError = 0x6804,
EmptyBuffer = 0x6982,
OutputBufferTooSmall = 0x6983,
DataInvalid = 0x6984,
ConditionsNotSatisfied = 0x6985,
CommandNotAllowed = 0x6986,
BadKeyHandle = 0x6A80,
InvalidP1P2 = 0x6B00,
InsNotSupported = 0x6D00,
ClaNotSupported = 0x6E00,
Unknown = 0x6F00,
SignVerifyError = 0x6F01,
}
impl std::fmt::Display for APDUResponseCodes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Code {:x} ({})", *self as u16, self.description())
}
}
impl APDUResponseCodes {
pub fn is_success(self) -> bool {
self == APDUResponseCodes::NoError
}
pub fn description(self) -> &'static str {
match self {
APDUResponseCodes::NoError => "[APDU_CODE_NOERROR]",
APDUResponseCodes::ExecutionError => {
"[APDU_CODE_EXECUTION_ERROR] No information given (NV-Ram not changed)"
}
APDUResponseCodes::WrongLength => "[APDU_CODE_WRONG_LENGTH] Wrong length",
APDUResponseCodes::UnlockDeviceError => {
"[APDU_CODE_UNLOCK_DEVICE_ERROR] Device is locked"
}
APDUResponseCodes::EmptyBuffer => "[APDU_CODE_EMPTY_BUFFER]",
APDUResponseCodes::OutputBufferTooSmall => "[APDU_CODE_OUTPUT_BUFFER_TOO_SMALL]",
APDUResponseCodes::DataInvalid => {
"[APDU_CODE_DATA_INVALID] data reversibly blocked (invalidated)"
}
APDUResponseCodes::ConditionsNotSatisfied => {
"[APDU_CODE_CONDITIONS_NOT_SATISFIED] Conditions of use not satisfied"
}
APDUResponseCodes::CommandNotAllowed => {
"[APDU_CODE_COMMAND_NOT_ALLOWED] Command not allowed (no current EF)"
}
APDUResponseCodes::BadKeyHandle => {
"[APDU_CODE_BAD_KEY_HANDLE] The parameters in the data field are incorrect"
}
APDUResponseCodes::InvalidP1P2 => "[APDU_CODE_INVALIDP1P2] Wrong parameter(s) P1-P2",
APDUResponseCodes::InsNotSupported => {
"[APDU_CODE_INS_NOT_SUPPORTED] Instruction code not supported or invalid"
}
APDUResponseCodes::ClaNotSupported => {
"[APDU_CODE_CLA_NOT_SUPPORTED] Class not supported"
}
APDUResponseCodes::Unknown => "[APDU_CODE_UNKNOWN]",
APDUResponseCodes::SignVerifyError => "[APDU_CODE_SIGN_VERIFY_ERROR]",
}
}
}
impl TryFrom<u16> for APDUResponseCodes {
type Error = LedgerError;
fn try_from(code: u16) -> Result<Self, Self::Error> {
match code {
0x9000 => Ok(APDUResponseCodes::NoError),
0x6400 => Ok(APDUResponseCodes::ExecutionError),
0x6700 => Ok(APDUResponseCodes::WrongLength),
0x6804 => Ok(APDUResponseCodes::UnlockDeviceError),
0x6982 => Ok(APDUResponseCodes::EmptyBuffer),
0x6983 => Ok(APDUResponseCodes::OutputBufferTooSmall),
0x6984 => Ok(APDUResponseCodes::DataInvalid),
0x6985 => Ok(APDUResponseCodes::ConditionsNotSatisfied),
0x6986 => Ok(APDUResponseCodes::CommandNotAllowed),
0x6A80 => Ok(APDUResponseCodes::BadKeyHandle),
0x6B00 => Ok(APDUResponseCodes::InvalidP1P2),
0x6D00 => Ok(APDUResponseCodes::InsNotSupported),
0x6E00 => Ok(APDUResponseCodes::ClaNotSupported),
0x6F00 => Ok(APDUResponseCodes::Unknown),
0x6F01 => Ok(APDUResponseCodes::SignVerifyError),
_ => Err(LedgerError::UnknownAPDUCode(code)),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn serialize() {
let data: &[u8] = &[0, 0, 0, 1, 0, 0, 0, 1];
let command = APDUCommand {
ins: 0x01,
p1: 0x00,
p2: 0x00,
data: data.into(),
response_len: None,
};
let serialized_command = command.serialize();
let expected = vec![224, 1, 0, 0, 8, 0, 0, 0, 1, 0, 0, 0, 1];
assert_eq!(serialized_command, expected);
let command = APDUCommand {
ins: 0x01,
p1: 0x00,
p2: 0x00,
data: data.into(),
response_len: Some(13),
};
let serialized_command = command.serialize();
let expected = vec![224, 1, 0, 0, 8, 0, 0, 0, 1, 0, 0, 0, 1, 13];
assert_eq!(serialized_command, expected)
}
}