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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
// SPDX-FileCopyrightText: 2021-2022 Heiko Schaefer <heiko@schaefer.name>
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Client library for
//! [OpenPGP card](https://en.wikipedia.org/wiki/OpenPGP_card)
//! devices (such as Gnuk, YubiKey, or Java smartcards running an OpenPGP
//! card application).
//!
//! This library aims to offer
//! - access to all features in the OpenPGP
//! [card specification](https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.4.1.pdf),
//! - without relying on a particular
//! [OpenPGP implementation](https://www.openpgp.org/software/developer/).
//!
//! This library can't directly access cards by itself. Instead, users
//! need to supply a backend that implements the [`CardBackend`]
//! / [`CardTransaction`] traits. The companion crate
//! [openpgp-card-pcsc](https://crates.io/crates/openpgp-card-pcsc)
//! offers a backend that uses [PC/SC](https://en.wikipedia.org/wiki/PC/SC) to
//! communicate with Smart Cards.
//!
//! The [openpgp-card-sequoia](https://crates.io/crates/openpgp-card-sequoia)
//! crate offers a higher level wrapper based on the [Sequoia PGP](https://sequoia-pgp.org/)
//! implementation.
//!
//! See the [architecture diagram](https://gitlab.com/openpgp-card/openpgp-card#architecture) for
//! a visualization.
extern crate core;
pub mod algorithm;
pub(crate) mod apdu;
pub mod card_do;
pub mod crypto_data;
mod errors;
pub(crate) mod keys;
mod oid;
mod openpgp;
mod tlv;
use std::convert::TryInto;
use crate::apdu::commands;
use crate::card_do::ApplicationRelatedData;
pub use crate::errors::{Error, SmartcardError, StatusBytes};
pub use crate::openpgp::{OpenPgp, OpenPgpTransaction};
use crate::tlv::{tag::Tag, value::Value, Tlv};
/// The CardBackend trait defines a connection with an OpenPGP card via a
/// backend implementation (e.g. via the pcsc backend in the crate
/// [openpgp-card-pcsc](https://crates.io/crates/openpgp-card-pcsc)),
/// A CardBackend is only used to get access to a `CardTransaction` object.
#[blanket::blanket(derive(Box))]
pub trait CardBackend {
fn transaction(&mut self) -> Result<Box<dyn CardTransaction + Send + Sync + '_>, Error>;
}
/// The CardTransaction trait defines communication with an OpenPGP card via a
/// backend implementation (e.g. the pcsc backend in the crate
/// [openpgp-card-pcsc](https://crates.io/crates/openpgp-card-pcsc)),
/// after opening a transaction from a CardBackend.
#[blanket::blanket(derive(Box))]
pub trait CardTransaction {
/// Transmit the command data in `cmd` to the card.
///
/// `buf_size` is a hint to the backend (the backend may ignore it)
/// indicating the expected maximum response size.
fn transmit(&mut self, cmd: &[u8], buf_size: usize) -> Result<Vec<u8>, Error>;
/// Set the card capabilities in the CardTransaction.
///
/// Setting these capabilities is typically part of a bootstrapping
/// process (this fn is typically called from [CardTransaction::initialize].
/// When implementing CardTransaction, you probably want to call
/// [CardTransaction::initialize] during setup).
///
/// The information about the card's capabilities is typically
/// requested from the card using the same CardTransaction instance,
/// before the card's capabilities have been initialized.
fn init_card_caps(&mut self, caps: CardCaps);
/// Request the card's capabilities
///
/// (apdu serialization makes use of this information, e.g. to
/// determine if extended length can be used)
fn card_caps(&self) -> Option<&CardCaps>;
/// If a CardTransaction implementation introduces an additional,
/// backend-specific limit for maximum number of bytes per command,
/// this fn can indicate that limit by returning `Some(max_cmd_len)`.
fn max_cmd_len(&self) -> Option<usize> {
None
}
/// Does the reader support FEATURE_VERIFY_PIN_DIRECT?
fn feature_pinpad_verify(&self) -> bool;
/// Does the reader support FEATURE_MODIFY_PIN_DIRECT?
fn feature_pinpad_modify(&self) -> bool;
/// Verify the PIN `id` via the reader pinpad
fn pinpad_verify(&mut self, pin: PinType) -> Result<Vec<u8>, Error>;
/// Modify the PIN `id` via the reader pinpad
fn pinpad_modify(&mut self, pin: PinType) -> Result<Vec<u8>, Error>;
/// Select the OpenPGP card application
fn select(&mut self) -> Result<Vec<u8>, Error> {
log::info!("CardTransaction: select");
let select_openpgp = commands::select_openpgp();
apdu::send_command(self, select_openpgp, false)?.try_into()
}
/// Activate file
fn activate_file(&mut self) -> Result<Vec<u8>, Error> {
log::info!("CardTransaction: activate_file");
let activate_file = commands::activate_file();
apdu::send_command(self, activate_file, false)?.try_into()
}
/// Get the "application related data" from the card.
///
/// (This data should probably be cached in a higher layer. Some parts of
/// it are needed regularly, and it does not usually change during
/// normal use of a card.)
fn application_related_data(&mut self) -> Result<ApplicationRelatedData, Error> {
let ad = commands::application_related_data();
let resp = apdu::send_command(self, ad, true)?;
let value = Value::from(resp.data()?, true)?;
log::trace!(" ARD value: {:x?}", value);
Ok(ApplicationRelatedData(Tlv::new(
Tags::ApplicationRelatedData,
value,
)))
}
/// Get a CardApp based on a CardTransaction.
///
/// It is expected that SELECT has already been performed on the card
/// beforehand.
///
/// This fn initializes the CardCaps by requesting
/// application_related_data from the card, and setting the
/// capabilities accordingly.
fn initialize(&mut self) -> Result<(), Error> {
let ard = self.application_related_data()?;
// Determine chaining/extended length support from card
// metadata and cache this information in the CardTransaction
// implementation (as a CardCaps)
let mut ext_support = false;
let mut chaining_support = false;
if let Ok(hist) = ard.historical_bytes() {
if let Some(cc) = hist.card_capabilities() {
chaining_support = cc.command_chaining();
ext_support = cc.extended_lc_le();
}
}
let ext_cap = ard.extended_capabilities()?;
// Get max command/response byte sizes from card
let (max_cmd_bytes, max_rsp_bytes) =
if let Ok(Some(eli)) = ard.extended_length_information() {
// In card 3.x, max lengths come from ExtendedLengthInfo
(eli.max_command_bytes(), eli.max_response_bytes())
} else if let (Some(cmd), Some(rsp)) = (ext_cap.max_cmd_len(), ext_cap.max_resp_len()) {
// In card 2.x, max lengths come from ExtendedCapabilities
(cmd, rsp)
} else {
// Fallback: use 255 if we have no information from the card
(255, 255)
};
let pw_status = ard.pw_status_bytes()?;
let pw1_max = pw_status.pw1_max_len();
let pw3_max = pw_status.pw3_max_len();
let caps = CardCaps {
ext_support,
chaining_support,
max_cmd_bytes,
max_rsp_bytes,
pw1_max_len: pw1_max,
pw3_max_len: pw3_max,
};
log::trace!("init_card_caps to: {:x?}", caps);
self.init_card_caps(caps);
Ok(())
}
}
/// Information about the capabilities of a card.
///
/// CardCaps is used to signal capabilities (chaining, extended length support, max
/// command/response sizes, max PIN lengths) of the current card to backends.
///
/// CardCaps is not intended for users of this library.
///
/// (The information is gathered from the "Card Capabilities", "Extended length information" and
/// "PWStatus" DOs)
#[derive(Clone, Copy, Debug)]
pub struct CardCaps {
/// Does the card support extended Lc and Le fields?
ext_support: bool,
/// Command chaining support?
chaining_support: bool,
/// Maximum number of bytes in a command APDU
max_cmd_bytes: u16,
/// Maximum number of bytes in a response APDU
max_rsp_bytes: u16,
/// Maximum length of PW1
pw1_max_len: u8,
/// Maximum length of PW3
pw3_max_len: u8,
}
impl CardCaps {
pub fn ext_support(&self) -> bool {
self.ext_support
}
pub fn max_rsp_bytes(&self) -> u16 {
self.max_rsp_bytes
}
pub fn pw1_max_len(&self) -> u8 {
self.pw1_max_len
}
pub fn pw3_max_len(&self) -> u8 {
self.pw3_max_len
}
}
/// Tags, as specified and used in the OpenPGP card 3.4.1 spec.
/// All tags in OpenPGP card are either 1 or 2 bytes long.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
#[allow(dead_code)]
pub(crate) enum Tags {
// BER identifiers
OctetString,
Null,
ObjectIdentifier,
Sequence,
// GET DATA
PrivateUse1,
PrivateUse2,
PrivateUse3,
PrivateUse4,
ApplicationIdentifier,
LoginData,
Url,
HistoricalBytes,
CardholderRelatedData,
Name,
LanguagePref,
Sex,
ApplicationRelatedData,
ExtendedLengthInformation,
GeneralFeatureManagement,
DiscretionaryDataObjects,
ExtendedCapabilities,
AlgorithmAttributesSignature,
AlgorithmAttributesDecryption,
AlgorithmAttributesAuthentication,
PWStatusBytes,
Fingerprints,
CaFingerprints,
GenerationTimes,
KeyInformation,
UifSig,
UifDec,
UifAuth,
UifAttestation,
SecuritySupportTemplate,
DigitalSignatureCounter,
CardholderCertificate,
AlgorithmAttributesAttestation,
FingerprintAttestation,
CaFingerprintAttestation,
GenerationTimeAttestation,
KdfDo,
AlgorithmInformation,
CertificateSecureMessaging,
AttestationCertificate,
// PUT DATA (additional Tags that don't get used for GET DATA)
FingerprintSignature,
FingerprintDecryption,
FingerprintAuthentication,
CaFingerprint1,
CaFingerprint2,
CaFingerprint3,
GenerationTimeSignature,
GenerationTimeDecryption,
GenerationTimeAuthentication,
// FIXME: +D1, D2
ResettingCode,
PsoEncDecKey,
// OTHER
// 4.4.3.12 Private Key Template
ExtendedHeaderList,
CardholderPrivateKeyTemplate,
ConcatenatedKeyData,
CrtKeySignature,
CrtKeyConfidentiality,
CrtKeyAuthentication,
PrivateKeyDataRsaPublicExponent,
PrivateKeyDataRsaPrime1,
PrivateKeyDataRsaPrime2,
PrivateKeyDataRsaPq,
PrivateKeyDataRsaDp1,
PrivateKeyDataRsaDq1,
PrivateKeyDataRsaModulus,
PrivateKeyDataEccPrivateKey,
PrivateKeyDataEccPublicKey,
// 7.2.14 GENERATE ASYMMETRIC KEY PAIR
PublicKey,
PublicKeyDataRsaModulus,
PublicKeyDataRsaExponent,
PublicKeyDataEccPoint,
// 7.2.11 PSO: DECIPHER
Cipher,
ExternalPublicKey,
// 7.2.5 SELECT DATA
GeneralReference,
TagList,
}
impl From<Tags> for Vec<u8> {
fn from(t: Tags) -> Self {
ShortTag::from(t).into()
}
}
impl From<Tags> for Tag {
fn from(t: Tags) -> Self {
ShortTag::from(t).into()
}
}
impl From<Tags> for ShortTag {
fn from(t: Tags) -> Self {
match t {
// BER identifiers https://en.wikipedia.org/wiki/X.690#BER_encoding
Tags::OctetString => [0x04].into(),
Tags::Null => [0x05].into(),
Tags::ObjectIdentifier => [0x06].into(),
Tags::Sequence => [0x30].into(),
// GET DATA
Tags::PrivateUse1 => [0x01, 0x01].into(),
Tags::PrivateUse2 => [0x01, 0x02].into(),
Tags::PrivateUse3 => [0x01, 0x03].into(),
Tags::PrivateUse4 => [0x01, 0x04].into(),
Tags::ApplicationIdentifier => [0x4f].into(),
Tags::LoginData => [0x5e].into(),
Tags::Url => [0x5f, 0x50].into(),
Tags::HistoricalBytes => [0x5f, 0x52].into(),
Tags::CardholderRelatedData => [0x65].into(),
Tags::Name => [0x5b].into(),
Tags::LanguagePref => [0x5f, 0x2d].into(),
Tags::Sex => [0x5f, 0x35].into(),
Tags::ApplicationRelatedData => [0x6e].into(),
Tags::ExtendedLengthInformation => [0x7f, 0x66].into(),
Tags::GeneralFeatureManagement => [0x7f, 0x74].into(),
Tags::DiscretionaryDataObjects => [0x73].into(),
Tags::ExtendedCapabilities => [0xc0].into(),
Tags::AlgorithmAttributesSignature => [0xc1].into(),
Tags::AlgorithmAttributesDecryption => [0xc2].into(),
Tags::AlgorithmAttributesAuthentication => [0xc3].into(),
Tags::PWStatusBytes => [0xc4].into(),
Tags::Fingerprints => [0xc5].into(),
Tags::CaFingerprints => [0xc6].into(),
Tags::GenerationTimes => [0xcd].into(),
Tags::KeyInformation => [0xde].into(),
Tags::UifSig => [0xd6].into(),
Tags::UifDec => [0xd7].into(),
Tags::UifAuth => [0xd8].into(),
Tags::UifAttestation => [0xd9].into(),
Tags::SecuritySupportTemplate => [0x7a].into(),
Tags::DigitalSignatureCounter => [0x93].into(),
Tags::CardholderCertificate => [0x7f, 0x21].into(),
Tags::AlgorithmAttributesAttestation => [0xda].into(),
Tags::FingerprintAttestation => [0xdb].into(),
Tags::CaFingerprintAttestation => [0xdc].into(),
Tags::GenerationTimeAttestation => [0xdd].into(),
Tags::KdfDo => [0xf9].into(),
Tags::AlgorithmInformation => [0xfa].into(),
Tags::CertificateSecureMessaging => [0xfb].into(),
Tags::AttestationCertificate => [0xfc].into(),
// PUT DATA
Tags::FingerprintSignature => [0xc7].into(),
Tags::FingerprintDecryption => [0xc8].into(),
Tags::FingerprintAuthentication => [0xc9].into(),
Tags::CaFingerprint1 => [0xca].into(),
Tags::CaFingerprint2 => [0xcb].into(),
Tags::CaFingerprint3 => [0xcc].into(),
Tags::GenerationTimeSignature => [0xce].into(),
Tags::GenerationTimeDecryption => [0xcf].into(),
Tags::GenerationTimeAuthentication => [0xd0].into(),
Tags::ResettingCode => [0xd3].into(),
Tags::PsoEncDecKey => [0xd5].into(),
// OTHER
// 4.4.3.12 Private Key Template
Tags::ExtendedHeaderList => [0x4d].into(),
Tags::CardholderPrivateKeyTemplate => [0x7f, 0x48].into(),
Tags::ConcatenatedKeyData => [0x5f, 0x48].into(),
Tags::CrtKeySignature => [0xb6].into(),
Tags::CrtKeyConfidentiality => [0xb8].into(),
Tags::CrtKeyAuthentication => [0xa4].into(),
Tags::PrivateKeyDataRsaPublicExponent => [0x91].into(),
Tags::PrivateKeyDataRsaPrime1 => [0x92].into(), // Note: value reused!
Tags::PrivateKeyDataRsaPrime2 => [0x93].into(),
Tags::PrivateKeyDataRsaPq => [0x94].into(),
Tags::PrivateKeyDataRsaDp1 => [0x95].into(),
Tags::PrivateKeyDataRsaDq1 => [0x96].into(),
Tags::PrivateKeyDataRsaModulus => [0x97].into(),
Tags::PrivateKeyDataEccPrivateKey => [0x92].into(), // Note: value reused!
Tags::PrivateKeyDataEccPublicKey => [0x99].into(),
// 7.2.14 GENERATE ASYMMETRIC KEY PAIR
Tags::PublicKey => [0x7f, 0x49].into(),
Tags::PublicKeyDataRsaModulus => [0x81].into(),
Tags::PublicKeyDataRsaExponent => [0x82].into(),
Tags::PublicKeyDataEccPoint => [0x86].into(),
// 7.2.11 PSO: DECIPHER
Tags::Cipher => [0xa6].into(),
Tags::ExternalPublicKey => [0x86].into(),
// 7.2.5 SELECT DATA
Tags::GeneralReference => [0x60].into(),
Tags::TagList => [0x5c].into(),
}
}
}
/// A ShortTag is a Tlv tag that is guaranteed to be either 1 or 2 bytes long.
///
/// This covers any tag that can be used in the OpenPGP card context (the spec doesn't describe how
/// longer tags might be used.)
///
/// (The type tlv::Tag will usually/always contain 1 or 2 byte long tags, in this library.
/// But its length is not guaranteed by the type system)
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum ShortTag {
One(u8),
Two(u8, u8),
}
impl From<ShortTag> for Tag {
fn from(n: ShortTag) -> Self {
match n {
ShortTag::One(t0) => [t0].into(),
ShortTag::Two(t0, t1) => [t0, t1].into(),
}
}
}
impl From<[u8; 1]> for ShortTag {
fn from(v: [u8; 1]) -> Self {
ShortTag::One(v[0])
}
}
impl From<[u8; 2]> for ShortTag {
fn from(v: [u8; 2]) -> Self {
ShortTag::Two(v[0], v[1])
}
}
impl From<ShortTag> for Vec<u8> {
fn from(t: ShortTag) -> Self {
match t {
ShortTag::One(t0) => vec![t0],
ShortTag::Two(t0, t1) => vec![t0, t1],
}
}
}
/// Specify a PIN to *verify* (distinguishes between `Sign`, `User` and `Admin`).
///
/// (Note that for PIN *management*, in particular changing a PIN, "signing and user" are
/// not distinguished. They always share the same PIN value `PW1`)
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PinType {
/// Verify PW1 in mode P2=81 (for the PSO:CDS operation)
Sign,
/// Verify PW1 in mode P2=82 (for all other User operations)
User,
/// Verify PW3 (for Admin operations)
Admin,
}
impl PinType {
pub fn id(&self) -> u8 {
match self {
PinType::Sign => 0x81,
PinType::User => 0x82,
PinType::Admin => 0x83,
}
}
}
/// Identify a Key slot on an OpenPGP card
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum KeyType {
Signing,
Decryption,
Authentication,
Attestation,
}
impl KeyType {
/// Get C1/C2/C3/DA values for this KeyTypes, to use as Tag
fn algorithm_tag(&self) -> ShortTag {
match self {
Self::Signing => Tags::AlgorithmAttributesSignature,
Self::Decryption => Tags::AlgorithmAttributesDecryption,
Self::Authentication => Tags::AlgorithmAttributesAuthentication,
Self::Attestation => Tags::AlgorithmAttributesAttestation,
}
.into()
}
/// Get C7/C8/C9/DB values for this KeyTypes, to use as Tag.
///
/// (NOTE: these Tags are only used for "PUT DO", but GETting
/// fingerprint information from the card uses the combined Tag C5)
fn fingerprint_put_tag(&self) -> ShortTag {
match self {
Self::Signing => Tags::FingerprintSignature,
Self::Decryption => Tags::FingerprintDecryption,
Self::Authentication => Tags::FingerprintAuthentication,
Self::Attestation => Tags::FingerprintAttestation,
}
.into()
}
/// Get CE/CF/D0/DD values for this KeyTypes, to use as Tag.
///
/// (NOTE: these Tags are only used for "PUT DO", but GETting
/// timestamp information from the card uses the combined Tag CD)
fn timestamp_put_tag(&self) -> ShortTag {
match self {
Self::Signing => Tags::GenerationTimeSignature,
Self::Decryption => Tags::GenerationTimeDecryption,
Self::Authentication => Tags::GenerationTimeAuthentication,
Self::Attestation => Tags::GenerationTimeAttestation,
}
.into()
}
}
/// A KeySet binds together a triple of information about each Key on a card
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct KeySet<T> {
signature: Option<T>,
decryption: Option<T>,
authentication: Option<T>,
}
impl<T> From<(Option<T>, Option<T>, Option<T>)> for KeySet<T> {
fn from(tuple: (Option<T>, Option<T>, Option<T>)) -> Self {
Self {
signature: tuple.0,
decryption: tuple.1,
authentication: tuple.2,
}
}
}
impl<T> KeySet<T> {
pub fn signature(&self) -> Option<&T> {
self.signature.as_ref()
}
pub fn decryption(&self) -> Option<&T> {
self.decryption.as_ref()
}
pub fn authentication(&self) -> Option<&T> {
self.authentication.as_ref()
}
}