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
// Derived from JMulticard: see LICENSE.jmulticard.md.
//! Session with a DNIe 3.0/4.0, opened as `DnieFactory.getDnie` and `Dnie3` do, minus the reset:
//! classify the ATR, read the IDESP.
use std::collections::BTreeMap;
use crate::{
Atr, DigestAlgorithm, Error, KeyReference, Pin, StatusWord, Transport,
card_authenticator::CardAuthenticator,
certificates,
channel::{CommandChannel, PlainChannel},
cwa14890,
files::{self, Location},
key_sets::{ComponentRoots, KeyGeneration},
pin::PinGuard,
pkcs15, signature,
};
const IDESP: &[u8] = &[0x3F, 0x00, 0x00, 0x06];
const FILE_NOT_FOUND: StatusWord = StatusWord(0x6A82);
/// Session with a DNIe 3.0/4.0 over any [`Transport`].
///
/// [`Error::CardRemoved`] reaches the caller unchanged from every operation, and no PIN is sent
/// after it. The session does not recover: open a new transport and a new session.
pub struct Session<T: Transport> {
transport: T,
atr: Atr,
idesp: Option<String>,
pin_guard: PinGuard,
/// The CDF, the PrKDF and the DER of each label, each read on first request and then kept.
cdf: Option<Vec<pkcs15::Entry>>,
prkdf: Option<Vec<pkcs15::Entry>>,
ders: BTreeMap<String, Vec<u8>>,
}
impl<T: Transport> Session<T> {
/// Accepts the card only if its current ATR is a DNIe 3.0/4.0 and reads its IDESP, without
/// resetting it. A card without an IDESP, or with an empty one, takes the second generation.
///
/// # Errors
///
/// Those of [`Transport::transaction`], [`Transport::atr`], [`Error::NotDnie`],
/// [`Error::LegacyDnie`] and [`Error::BurnedDnie`], and any failure reading the IDESP but its
/// absence. A card reset by another application since `connect` fails with
/// [`Error::CardReset`]: reconnect and open again.
pub fn open(transport: T) -> Result<Self, Error> {
Self::open_with(transport, ComponentRoots::embedded())
}
/// [`Session::open`] trusting only `root` as the component root, for tests against an emulated
/// card.
///
/// # Errors
///
/// Those of [`Session::open`].
#[cfg(feature = "emulator")]
pub fn open_trusting(transport: T, root: rsa::RsaPublicKey) -> Result<Self, Error> {
Self::open_with(transport, ComponentRoots::only(root))
}
#[cfg(test)]
pub(crate) fn open_with_roots(transport: T, roots: ComponentRoots) -> Result<Self, Error> {
Self::open_with(transport, roots)
}
fn open_with(mut transport: T, roots: ComponentRoots) -> Result<Self, Error> {
let atr = transport.atr()?;
atr.check()?;
let idesp = operation(&mut transport, read_idesp)?;
Ok(Self {
transport,
atr,
pin_guard: PinGuard::new(CardAuthenticator::from_idesp(idesp.as_deref(), roots)),
idesp,
cdf: None,
prkdf: None,
ders: BTreeMap::new(),
})
}
/// Lists the PKCS#15 labels of the holder's certificates that have a private key, as
/// `getAliases`, without a PIN and without reading any certificate file. The session keeps the
/// CDF and the PrKDF from their first read; a failed read keeps nothing of that file.
///
/// # Errors
///
/// Those of [`Session::open`], [`Error::Status`] if a directory cannot be read and
/// [`Error::MalformedPkcs15`] if it cannot be decoded, a certificate has no UTF-8 label or its
/// key has no file in its path.
pub fn labels(&mut self) -> Result<Vec<String>, Error> {
Ok(self.keyed()?.into_iter().map(|(label, _)| label).collect())
}
/// The private key of the certificate labelled `label`, as `getPrivateKey`. `None` if no
/// certificate has that label or it has no key; with duplicates the last one wins.
///
/// # Errors
///
/// Those of [`Session::labels`].
pub fn private_key(&mut self, label: &str) -> Result<Option<KeyReference>, Error> {
Ok(self
.keyed()?
.into_iter()
.rev()
.find_map(|(keyed, key)| (keyed == label).then_some(key)))
}
pub(crate) fn keyed(&mut self) -> Result<Vec<(String, KeyReference)>, Error> {
let cdf = cached(&mut self.cdf, &mut self.transport, certificates::cdf)?;
let prkdf = cached(&mut self.prkdf, &mut self.transport, certificates::prkdf)?;
certificates::keyed(cdf, prkdf)
}
/// Fetches the DER of the CDF certificate labelled `label`, with or without a private key,
/// reading only its file, once per session. `None` if no certificate has that label; with
/// duplicates the last one in the CDF wins.
///
/// # Errors
///
/// Those of [`Session::open`], [`Error::Status`] if the CDF or the certificate file cannot be
/// read, [`Error::MalformedPkcs15`] if the CDF cannot be decoded or the certificate has no
/// file in its path and [`Error::MalformedCertificate`] if its bytes are not an X.509
/// certificate.
pub fn certificate(&mut self, label: &str) -> Result<Option<Vec<u8>>, Error> {
if let Some(der) = self.ders.get(label) {
return Ok(Some(der.clone()));
}
let cdf = cached(&mut self.cdf, &mut self.transport, certificates::cdf)?;
let Some(entry) = cdf.iter().rev().find(|entry| entry.label == label) else {
return Ok(None);
};
let der = operation(&mut self.transport, |card| certificates::read(card, entry))?;
self.ders.insert(label.to_owned(), der.clone());
Ok(Some(der))
}
/// Reads how many PIN attempts are left through the PIN channel, without sending a PIN.
///
/// # Errors
///
/// Those of [`Session::open`], [`Error::PinBlocked`], [`Error::SecureChannel`] if the card
/// refuses a step of the mutual authentication up to `EXTERNAL AUTHENTICATE` or fails it,
/// [`Error::Status`] if the card refuses `INTERNAL AUTHENTICATE`, `GET CHALLENGE` or
/// `GET CHIP INFO` or gives no retry count, and [`Error::CardReset`] or [`Error::Transport`]
/// if either strikes during the authentication.
pub fn pin_retries_left(&mut self) -> Result<u8, Error> {
self.pin_guard.read_retries(&mut self.transport)
}
/// Signs a SHA-256/384/512 digest with `key` after verifying `pin`, and returns the PKCS#1
/// v1.5 signature; the retries must still be those last shown, by [`Session::pin_retries_left`] or
/// by the [`Error::WrongPin`] of the previous attempt.
///
/// # Errors
///
/// [`Error::DigestLength`], then [`Error::InvalidPinFormat`], before touching the card, those
/// of [`Session::pin_retries_left`], [`Error::PinRetriesChanged`] if the retries moved between the
/// two phases, [`Error::WrongPin`] after the single attempt and [`Error::Status`] if the card
/// refuses the signature. The channel errors are those of [`Session::pin_retries_left`].
pub fn sign(
&mut self,
digest: &[u8],
algorithm: DigestAlgorithm,
key: &KeyReference,
pin: Pin,
) -> Result<Vec<u8>, Error> {
let digest_info = signature::digest_info(algorithm, digest)?;
self.pin_guard
.verified(&mut self.transport, pin, |channel| {
signature::sign(channel, key, digest_info)
})
}
/// Verifies `pin` on the card without signing, under the same policy as [`Session::sign`]; a
/// later `sign` verifies the PIN again.
///
/// # Errors
///
/// [`Error::InvalidPinFormat`] before touching the card, those of [`Session::pin_retries_left`],
/// [`Error::PinRetriesChanged`] if the retries moved between the two phases and
/// [`Error::WrongPin`] after the single attempt.
pub fn verify_pin(&mut self, pin: Pin) -> Result<(), Error> {
self.pin_guard
.verified(&mut self.transport, pin, |_| Ok(()))
}
/// The ATR [`Session::open`] classified, without touching the card.
#[must_use]
pub fn atr(&self) -> &Atr {
&self.atr
}
/// The IDESP [`Session::open`] read, as `getIdesp`, without touching the card; `None` for a
/// card without one.
#[must_use]
pub fn idesp(&self) -> Option<&str> {
self.idesp.as_deref()
}
/// The kind of card, as `getCardName`. `Session::open` accepts no other, and a 3.0 and a 4.0
/// run the same card OS, so they are not told apart.
#[must_use]
pub fn card_name(&self) -> &'static str {
"DNIe 3.0/4.0"
}
/// The chip serial, as `getSerialNumber`, from one `GET CHIP INFO` in its own transaction.
///
/// # Errors
///
/// Those of [`Transport::transaction`] and [`Error::Status`] if the card refuses.
pub fn serial_number(&mut self) -> Result<Vec<u8>, Error> {
operation(&mut self.transport, |card| {
// A channel a PIN operation left open would answer the CLA 90 command 69 87.
files::leave_any_channel(card)?;
cwa14890::chip_serial(card)
})
}
/// The terminal key generation the card's support number selects.
#[must_use]
pub fn key_generation(&self) -> KeyGeneration {
self.pin_guard.key_generation()
}
/// Ends the session and hands back the transport.
pub fn into_transport(self) -> T {
self.transport
}
}
/// Runs `body` in one transaction; like `Dnie3`, each operation opens its own channel.
fn operation<R>(
transport: &mut impl Transport,
body: impl FnOnce(&mut dyn CommandChannel) -> Result<R, Error>,
) -> Result<R, Error> {
transport.transaction(|card| body(&mut PlainChannel::new(card)))
}
/// The value in `slot`, read in its own operation if the slot is empty.
fn cached<'a, R>(
slot: &'a mut Option<R>,
transport: &mut impl Transport,
read: impl FnOnce(&mut dyn CommandChannel) -> Result<R, Error>,
) -> Result<&'a R, Error> {
let value = match slot.take() {
Some(value) => value,
None => operation(transport, read)?,
};
Ok(slot.insert(value))
}
/// The IDESP as stored, or `None` if the card has no IDESP file.
fn read_idesp(card: &mut dyn CommandChannel) -> Result<Option<String>, Error> {
let location = Location::new(IDESP).expect("the IDESP path is valid");
let idesp = match files::read(card, &location) {
Ok(idesp) => idesp,
Err(Error::Status(FILE_NOT_FOUND)) => return Ok(None),
Err(error) => return Err(error),
};
Ok(Some(String::from_utf8_lossy(&idesp).into_owned()))
}
#[cfg(test)]
pub(crate) mod tests;