use std::collections::HashMap;
use std::fmt;
use sha2::Digest;
use thiserror::Error;
use zeroize::Zeroizing;
use crate::__internal::padding::Hash;
use crate::__internal::tlv::{
TlvError, parse_tlv_dict, parse_tlv_list, tlv_append, tlv_encode, tlv_unpack,
};
use crate::core::Version;
use crate::core::{bytes2int, int2bytes, patch_version};
use crate::keys::{
EcCurve, EcPublicKey, Ed25519PublicKey, PrivateKey, PublicKey, RsaKeySize, RsaPublicKey,
X25519PublicKey,
};
use crate::keys::{
OID_BRAINPOOL_P256R1, OID_BRAINPOOL_P384R1, OID_BRAINPOOL_P512R1, OID_SECP256K1, OID_SECP256R1,
OID_SECP384R1, OID_SECP521R1,
};
use crate::smartcard::{Aid, SmartCardConnection, SmartCardError, SmartCardProtocol, Sw};
use x509_cert::spki::ObjectIdentifier;
pub const DEFAULT_USER_PIN: &str = "123456";
pub const DEFAULT_ADMIN_PIN: &str = "12345678";
const INVALID_PIN: &[u8] = &[0; 8];
const INS_VERIFY: u8 = 0x20;
const INS_CHANGE_PIN: u8 = 0x24;
const INS_RESET_RETRY_COUNTER: u8 = 0x2C;
const INS_PSO: u8 = 0x2A;
const INS_ACTIVATE: u8 = 0x44;
const INS_GENERATE_ASYM: u8 = 0x47;
const INS_GET_CHALLENGE: u8 = 0x84;
const INS_INTERNAL_AUTHENTICATE: u8 = 0x88;
const INS_SELECT_DATA: u8 = 0xA5;
const INS_GET_DATA: u8 = 0xCA;
const INS_PUT_DATA: u8 = 0xDA;
const INS_PUT_DATA_ODD: u8 = 0xDB;
const INS_TERMINATE: u8 = 0xE6;
const INS_GET_VERSION: u8 = 0xF1;
const INS_SET_PIN_RETRIES: u8 = 0xF2;
const INS_GET_ATTESTATION: u8 = 0xFB;
const TAG_DISCRETIONARY: u32 = 0x73;
const TAG_EXTENDED_CAPABILITIES: u32 = 0xC0;
const TAG_FINGERPRINTS: u32 = 0xC5;
const TAG_CA_FINGERPRINTS: u32 = 0xC6;
const TAG_GENERATION_TIMES: u32 = 0xCD;
const TAG_SIGNATURE_COUNTER: u32 = 0x93;
const TAG_KEY_INFORMATION: u32 = 0xDE;
const TAG_PUBLIC_KEY: u32 = 0x7F49;
const BUTTON_FLAG: u8 = 0x20;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenPgpError {
#[error("Not supported: {0}")]
NotSupported(String),
#[error("Invalid data: {0}")]
InvalidData(String),
#[error("Invalid PIN, {0} attempts remaining")]
InvalidPin(u32),
#[error("PIN blocked")]
PinBlocked,
#[error("Connection error: {0}")]
Connection(SmartCardError),
}
impl From<SmartCardError> for OpenPgpError {
fn from(e: SmartCardError) -> Self {
match e {
SmartCardError::NotSupported(msg) => OpenPgpError::NotSupported(msg),
SmartCardError::InvalidData(msg) => OpenPgpError::InvalidData(msg),
other => OpenPgpError::Connection(other),
}
}
}
impl From<TlvError> for OpenPgpError {
fn from(e: TlvError) -> Self {
OpenPgpError::InvalidData(e.to_string())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum Uif {
Off = 0x00,
On = 0x01,
Fixed = 0x02,
Cached = 0x03,
CachedFixed = 0x04,
}
impl Uif {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0x00 => Some(Self::Off),
0x01 => Some(Self::On),
0x02 => Some(Self::Fixed),
0x03 => Some(Self::Cached),
0x04 => Some(Self::CachedFixed),
_ => None,
}
}
pub fn parse(encoded: &[u8]) -> Option<Self> {
encoded.first().and_then(|&v| Self::from_u8(v))
}
pub fn is_fixed(self) -> bool {
matches!(self, Uif::Fixed | Uif::CachedFixed)
}
pub fn is_cached(self) -> bool {
matches!(self, Uif::Cached | Uif::CachedFixed)
}
pub fn to_bytes(self) -> [u8; 2] {
[self as u8, BUTTON_FLAG]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum PinPolicy {
Always = 0x00,
Once = 0x01,
}
impl PinPolicy {
pub fn from_u8(v: u8) -> Self {
match v {
0x01 => Self::Once,
_ => Self::Always,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Pw {
User = 0x81,
Reset = 0x82,
Admin = 0x83,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u16)]
pub enum Do {
PrivateUse1 = 0x0101,
PrivateUse2 = 0x0102,
PrivateUse3 = 0x0103,
PrivateUse4 = 0x0104,
Aid = 0x4F,
Name = 0x5B,
LoginData = 0x5E,
Language = 0xEF2D,
Sex = 0x5F35,
Url = 0x5F50,
HistoricalBytes = 0x5F52,
ExtendedLengthInfo = 0x7F66,
GeneralFeatureManagement = 0x7F74,
CardholderRelatedData = 0x65,
ApplicationRelatedData = 0x6E,
AlgorithmAttributesSig = 0xC1,
AlgorithmAttributesDec = 0xC2,
AlgorithmAttributesAut = 0xC3,
AlgorithmAttributesAtt = 0xDA,
PwStatusBytes = 0xC4,
FingerprintSig = 0xC7,
FingerprintDec = 0xC8,
FingerprintAut = 0xC9,
FingerprintAtt = 0xDB,
CaFingerprint1 = 0xCA,
CaFingerprint2 = 0xCB,
CaFingerprint3 = 0xCC,
CaFingerprint4 = 0xDC,
GenerationTimeSig = 0xCE,
GenerationTimeDec = 0xCF,
GenerationTimeAut = 0xD0,
GenerationTimeAtt = 0xDD,
ResettingCode = 0xD3,
UifSig = 0xD6,
UifDec = 0xD7,
UifAut = 0xD8,
UifAtt = 0xD9,
SecuritySupportTemplate = 0x7A,
CardholderCertificate = 0x7F21,
Kdf = 0xF9,
AlgorithmInformation = 0xFA,
AttCertificate = 0xFC,
KeyInformation = 0xDE,
}
impl Do {
pub fn p1(self) -> u8 {
((self as u16) >> 8) as u8
}
pub fn p2(self) -> u8 {
(self as u16) as u8
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum KeyRef {
Sig = 0x01,
Dec = 0x02,
Aut = 0x03,
Att = 0x81,
}
impl KeyRef {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0x01 => Some(Self::Sig),
0x02 => Some(Self::Dec),
0x03 => Some(Self::Aut),
0x81 => Some(Self::Att),
_ => None,
}
}
pub const ALL: &[KeyRef] = &[KeyRef::Sig, KeyRef::Dec, KeyRef::Aut, KeyRef::Att];
pub fn algorithm_attributes_do(self) -> Do {
match self {
Self::Sig => Do::AlgorithmAttributesSig,
Self::Dec => Do::AlgorithmAttributesDec,
Self::Aut => Do::AlgorithmAttributesAut,
Self::Att => Do::AlgorithmAttributesAtt,
}
}
pub fn uif_do(self) -> Do {
match self {
Self::Sig => Do::UifSig,
Self::Dec => Do::UifDec,
Self::Aut => Do::UifAut,
Self::Att => Do::UifAtt,
}
}
pub fn generation_time_do(self) -> Do {
match self {
Self::Sig => Do::GenerationTimeSig,
Self::Dec => Do::GenerationTimeDec,
Self::Aut => Do::GenerationTimeAut,
Self::Att => Do::GenerationTimeAtt,
}
}
pub fn fingerprint_do(self) -> Do {
match self {
Self::Sig => Do::FingerprintSig,
Self::Dec => Do::FingerprintDec,
Self::Aut => Do::FingerprintAut,
Self::Att => Do::FingerprintAtt,
}
}
pub fn crt(self) -> Vec<u8> {
match self {
Self::Sig => tlv_encode(0xB6, &[]),
Self::Dec => tlv_encode(0xB8, &[]),
Self::Aut => tlv_encode(0xA4, &[]),
Self::Att => {
let inner = tlv_encode(0x84, &[0x81]);
tlv_encode(0xB6, &inner)
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum KeyStatus {
None = 0,
Generated = 1,
Imported = 2,
}
impl KeyStatus {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0 => Some(Self::None),
1 => Some(Self::Generated),
2 => Some(Self::Imported),
_ => Option::None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum RsaImportFormat {
Standard = 0,
StandardWMod = 1,
Crt = 2,
CrtWMod = 3,
}
impl RsaImportFormat {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0 => Some(Self::Standard),
1 => Some(Self::StandardWMod),
2 => Some(Self::Crt),
3 => Some(Self::CrtWMod),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum EcImportFormat {
Standard = 0,
StandardWPubkey = 0xFF,
}
impl EcImportFormat {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0x00 => Some(Self::Standard),
0xFF => Some(Self::StandardWPubkey),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum HashAlgorithm {
Sha256 = 0x08,
Sha512 = 0x0A,
}
impl HashAlgorithm {
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0x08 => Some(Self::Sha256),
0x0A => Some(Self::Sha512),
_ => None,
}
}
}
pub mod extended_capability_flags {
pub const KDF: u8 = 1 << 0;
pub const PSO_DEC_ENC_AES: u8 = 1 << 1;
pub const ALGORITHM_ATTRIBUTES_CHANGEABLE: u8 = 1 << 2;
pub const PRIVATE_USE: u8 = 1 << 3;
pub const PW_STATUS_CHANGEABLE: u8 = 1 << 4;
pub const KEY_IMPORT: u8 = 1 << 5;
pub const GET_CHALLENGE: u8 = 1 << 6;
pub const SECURE_MESSAGING: u8 = 1 << 7;
}
const OID_X25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.3029.1.5.1");
const OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.11591.15.1");
const EC_ALG_ECDH: u8 = 0x12;
const EC_ALG_ECDSA: u8 = 0x13;
const EC_ALG_EDDSA: u8 = 0x16;
const RSA_ALG_ID: u8 = 0x01;
#[derive(Clone)]
pub struct OpenPgpPin(crate::__internal::SecretValue<Vec<u8>>);
impl OpenPgpPin {
pub fn new(pin: &str) -> Self {
Self(crate::__internal::SecretValue::new(pin.as_bytes().to_vec()))
}
#[allow(dead_code)]
pub(crate) fn as_bytes(&self) -> &[u8] {
self.0.expose_secret()
}
pub(crate) fn as_str(&self) -> &str {
std::str::from_utf8(self.0.expose_secret()).expect("OpenPgpPin is always valid UTF-8")
}
}
impl fmt::Debug for OpenPgpPin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("OpenPgpPin([REDACTED])")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum AlgorithmAttributes {
Rsa(RsaAttributes),
Ec(EcAttributes),
}
impl AlgorithmAttributes {
pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
if encoded.is_empty() {
return Err(OpenPgpError::InvalidData(
"Empty algorithm attributes".into(),
));
}
let algorithm_id = encoded[0];
match algorithm_id {
RSA_ALG_ID => Ok(Self::Rsa(RsaAttributes::parse_data(&encoded[1..])?)),
EC_ALG_ECDH | EC_ALG_ECDSA | EC_ALG_EDDSA => Ok(Self::Ec(EcAttributes::parse_data(
algorithm_id,
&encoded[1..],
)?)),
_ => Err(OpenPgpError::InvalidData(format!(
"Unsupported algorithm ID: 0x{algorithm_id:02X}"
))),
}
}
pub fn to_bytes(&self) -> Vec<u8> {
match self {
Self::Rsa(a) => a.to_bytes(),
Self::Ec(a) => a.to_bytes(),
}
}
pub fn algorithm_id(&self) -> u8 {
match self {
Self::Rsa(_) => RSA_ALG_ID,
Self::Ec(a) => a.algorithm_id,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RsaAttributes {
pub n_len: u16,
pub e_len: u16,
pub import_format: RsaImportFormat,
}
impl RsaAttributes {
pub fn create(n_len: RsaKeySize, import_format: RsaImportFormat) -> Self {
Self {
n_len: n_len as u16,
e_len: 17,
import_format,
}
}
fn parse_data(data: &[u8]) -> Result<Self, OpenPgpError> {
if data.len() < 5 {
return Err(OpenPgpError::InvalidData("RSA attributes too short".into()));
}
let n_len = u16::from_be_bytes([data[0], data[1]]);
let e_len = u16::from_be_bytes([data[2], data[3]]);
let import_format = RsaImportFormat::from_u8(data[4]).ok_or_else(|| {
OpenPgpError::InvalidData(format!("Unknown RSA import format: {}", data[4]))
})?;
Ok(Self {
n_len,
e_len,
import_format,
})
}
fn to_bytes(&self) -> Vec<u8> {
let mut buf = vec![RSA_ALG_ID];
buf.extend_from_slice(&self.n_len.to_be_bytes());
buf.extend_from_slice(&self.e_len.to_be_bytes());
buf.push(self.import_format as u8);
buf
}
}
#[non_exhaustive]
pub enum OpenPgpCurve {
P256,
P384,
P521,
Secp256k1,
BrainpoolP256r1,
BrainpoolP384r1,
BrainpoolP512r1,
Ed25519,
X25519,
}
impl OpenPgpCurve {
fn oid(&self) -> ObjectIdentifier {
match self {
Self::P256 => OID_SECP256R1,
Self::P384 => OID_SECP384R1,
Self::P521 => OID_SECP521R1,
Self::Secp256k1 => OID_SECP256K1,
Self::BrainpoolP256r1 => OID_BRAINPOOL_P256R1,
Self::BrainpoolP384r1 => OID_BRAINPOOL_P384R1,
Self::BrainpoolP512r1 => OID_BRAINPOOL_P512R1,
Self::Ed25519 => OID_ED25519,
Self::X25519 => OID_X25519,
}
}
pub fn from_oid(oid_str: &str) -> Result<Self, OpenPgpError> {
let oid = ObjectIdentifier::new(oid_str)
.map_err(|_| OpenPgpError::InvalidData(format!("Invalid OID string: {}", oid_str)))?;
match oid {
OID_SECP256R1 => Ok(Self::P256),
OID_SECP384R1 => Ok(Self::P384),
OID_SECP521R1 => Ok(Self::P521),
OID_SECP256K1 => Ok(Self::Secp256k1),
OID_BRAINPOOL_P256R1 => Ok(Self::BrainpoolP256r1),
OID_BRAINPOOL_P384R1 => Ok(Self::BrainpoolP384r1),
OID_BRAINPOOL_P512R1 => Ok(Self::BrainpoolP512r1),
OID_ED25519 => Ok(Self::Ed25519),
OID_X25519 => Ok(Self::X25519),
_ => Err(OpenPgpError::InvalidData(format!(
"Unsupported OID: {}",
oid_str
))),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EcAttributes {
pub algorithm_id: u8,
pub oid: Vec<u8>,
pub import_format: EcImportFormat,
}
impl EcAttributes {
pub fn create(key_ref: KeyRef, curve: &OpenPgpCurve) -> Result<Self, OpenPgpError> {
let oid = curve.oid();
let algorithm_id = if oid == OID_ED25519 {
EC_ALG_EDDSA
} else if key_ref == KeyRef::Dec {
EC_ALG_ECDH
} else {
EC_ALG_ECDSA
};
Ok(Self {
algorithm_id,
oid: oid.as_bytes().to_vec(),
import_format: EcImportFormat::Standard,
})
}
fn parse_data(algorithm_id: u8, data: &[u8]) -> Result<Self, OpenPgpError> {
if data.is_empty() {
return Err(OpenPgpError::InvalidData("EC attributes too short".into()));
}
let (oid, import_format) = if *data.last().unwrap() == 0xFF {
(&data[..data.len() - 1], EcImportFormat::StandardWPubkey)
} else {
(data, EcImportFormat::Standard)
};
Ok(Self {
algorithm_id,
oid: oid.to_vec(),
import_format,
})
}
fn to_bytes(&self) -> Vec<u8> {
let mut buf = vec![self.algorithm_id];
buf.extend_from_slice(&self.oid);
if self.import_format == EcImportFormat::StandardWPubkey {
buf.push(0xFF);
}
buf
}
pub fn oid_str(&self) -> Result<String, OpenPgpError> {
ObjectIdentifier::from_bytes(&self.oid)
.map(|o| o.to_string())
.map_err(|e| OpenPgpError::InvalidData(format!("Invalid curve OID: {e}")))
}
fn oid(&self) -> Result<ObjectIdentifier, OpenPgpError> {
ObjectIdentifier::from_bytes(&self.oid)
.map_err(|e| OpenPgpError::InvalidData(format!("Invalid curve OID: {e}")))
}
}
fn bcd(value: u8) -> u8 {
10 * (value >> 4) + (value & 0x0F)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenPgpAid {
pub raw: Vec<u8>,
}
impl OpenPgpAid {
pub fn parse(data: &[u8]) -> Self {
Self { raw: data.to_vec() }
}
pub fn version(&self) -> (u8, u8) {
(
bcd(*self.raw.get(6).unwrap_or(&0)),
bcd(*self.raw.get(7).unwrap_or(&0)),
)
}
pub fn manufacturer(&self) -> u16 {
if self.raw.len() >= 10 {
u16::from_be_bytes([self.raw[8], self.raw[9]])
} else {
0
}
}
pub fn serial(&self) -> i64 {
if self.raw.len() >= 14 {
let bytes = &self.raw[10..14];
let hex_str = format!(
"{:02X}{:02X}{:02X}{:02X}",
bytes[0], bytes[1], bytes[2], bytes[3]
);
if let Ok(val) = hex_str.parse::<i64>() {
val
} else {
-(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as i64)
}
} else {
0
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PwStatus {
pub pin_policy_user: PinPolicy,
pub max_len_user: u8,
pub max_len_reset: u8,
pub max_len_admin: u8,
pub attempts_user: u8,
pub attempts_reset: u8,
pub attempts_admin: u8,
}
impl PwStatus {
pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
if encoded.len() < 7 {
return Err(OpenPgpError::InvalidData("PwStatus too short".into()));
}
Ok(Self {
pin_policy_user: PinPolicy::from_u8(encoded[0]),
max_len_user: encoded[1],
max_len_reset: encoded[2],
max_len_admin: encoded[3],
attempts_user: encoded[4],
attempts_reset: encoded[5],
attempts_admin: encoded[6],
})
}
pub fn get_max_len(&self, pw: Pw) -> u8 {
match pw {
Pw::User => self.max_len_user,
Pw::Reset => self.max_len_reset,
Pw::Admin => self.max_len_admin,
}
}
pub fn get_attempts(&self, pw: Pw) -> u8 {
match pw {
Pw::User => self.attempts_user,
Pw::Reset => self.attempts_reset,
Pw::Admin => self.attempts_admin,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtendedCapabilities {
pub flags: u8,
pub sm_algorithm: u8,
pub challenge_max_length: u16,
pub certificate_max_length: u16,
pub special_do_max_length: u16,
pub pin_block_2_format: bool,
pub mse_command: bool,
}
impl ExtendedCapabilities {
pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
if encoded.len() < 10 {
return Err(OpenPgpError::InvalidData(
"ExtendedCapabilities too short".into(),
));
}
Ok(Self {
flags: encoded[0],
sm_algorithm: encoded[1],
challenge_max_length: u16::from_be_bytes([encoded[2], encoded[3]]),
certificate_max_length: u16::from_be_bytes([encoded[4], encoded[5]]),
special_do_max_length: u16::from_be_bytes([encoded[6], encoded[7]]),
pin_block_2_format: encoded[8] == 1,
mse_command: encoded[9] == 1,
})
}
pub fn has_flag(&self, flag: u8) -> bool {
self.flags & flag != 0
}
}
pub type Fingerprints = HashMap<KeyRef, Vec<u8>>;
pub type GenerationTimes = HashMap<KeyRef, u32>;
pub type KeyInformation = HashMap<KeyRef, KeyStatus>;
fn parse_fingerprints(encoded: &[u8]) -> Fingerprints {
let mut map = HashMap::new();
for (i, key) in KeyRef::ALL.iter().enumerate() {
let start = i * 20;
if start + 20 <= encoded.len() {
map.insert(*key, encoded[start..start + 20].to_vec());
}
}
map
}
fn parse_timestamps(encoded: &[u8]) -> GenerationTimes {
let mut map = HashMap::new();
for (i, key) in KeyRef::ALL.iter().enumerate() {
let start = i * 4;
if start + 4 <= encoded.len() {
let ts = u32::from_be_bytes([
encoded[start],
encoded[start + 1],
encoded[start + 2],
encoded[start + 3],
]);
map.insert(*key, ts);
}
}
map
}
fn parse_key_information(encoded: &[u8]) -> KeyInformation {
let mut map = HashMap::new();
let mut i = 0;
while i + 1 < encoded.len() {
if let (Some(key), Some(status)) = (
KeyRef::from_u8(encoded[i]),
KeyStatus::from_u8(encoded[i + 1]),
) {
map.insert(key, status);
}
i += 2;
}
map
}
#[derive(Debug, Clone)]
pub struct DiscretionaryDataObjects {
pub extended_capabilities: ExtendedCapabilities,
pub attributes_sig: AlgorithmAttributes,
pub attributes_dec: AlgorithmAttributes,
pub attributes_aut: AlgorithmAttributes,
pub attributes_att: Option<AlgorithmAttributes>,
pub pw_status: PwStatus,
pub fingerprints: Fingerprints,
pub ca_fingerprints: Fingerprints,
pub generation_times: GenerationTimes,
pub key_information: KeyInformation,
pub uif_sig: Option<Uif>,
pub uif_dec: Option<Uif>,
pub uif_aut: Option<Uif>,
pub uif_att: Option<Uif>,
}
impl DiscretionaryDataObjects {
pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
let data = parse_tlv_dict(encoded)?;
Ok(Self {
extended_capabilities: ExtendedCapabilities::parse(
data.get(&TAG_EXTENDED_CAPABILITIES).ok_or_else(|| {
OpenPgpError::InvalidData("Missing extended capabilities".into())
})?,
)?,
attributes_sig: AlgorithmAttributes::parse(
data.get(&(Do::AlgorithmAttributesSig as u32))
.ok_or_else(|| {
OpenPgpError::InvalidData("Missing SIG algorithm attributes".into())
})?,
)?,
attributes_dec: AlgorithmAttributes::parse(
data.get(&(Do::AlgorithmAttributesDec as u32))
.ok_or_else(|| {
OpenPgpError::InvalidData("Missing DEC algorithm attributes".into())
})?,
)?,
attributes_aut: AlgorithmAttributes::parse(
data.get(&(Do::AlgorithmAttributesAut as u32))
.ok_or_else(|| {
OpenPgpError::InvalidData("Missing AUT algorithm attributes".into())
})?,
)?,
attributes_att: data
.get(&(Do::AlgorithmAttributesAtt as u32))
.map(|v| AlgorithmAttributes::parse(v))
.transpose()?,
pw_status: PwStatus::parse(
data.get(&(Do::PwStatusBytes as u32))
.ok_or_else(|| OpenPgpError::InvalidData("Missing PW status bytes".into()))?,
)?,
fingerprints: parse_fingerprints(
data.get(&TAG_FINGERPRINTS)
.map(|v| v.as_slice())
.unwrap_or(&[]),
),
ca_fingerprints: parse_fingerprints(
data.get(&TAG_CA_FINGERPRINTS)
.map(|v| v.as_slice())
.unwrap_or(&[]),
),
generation_times: parse_timestamps(
data.get(&TAG_GENERATION_TIMES)
.map(|v| v.as_slice())
.unwrap_or(&[]),
),
key_information: parse_key_information(
data.get(&TAG_KEY_INFORMATION)
.map(|v| v.as_slice())
.unwrap_or(&[]),
),
uif_sig: data.get(&(Do::UifSig as u32)).and_then(|v| Uif::parse(v)),
uif_dec: data.get(&(Do::UifDec as u32)).and_then(|v| Uif::parse(v)),
uif_aut: data.get(&(Do::UifAut as u32)).and_then(|v| Uif::parse(v)),
uif_att: data.get(&(Do::UifAtt as u32)).and_then(|v| Uif::parse(v)),
})
}
pub fn get_algorithm_attributes(&self, key_ref: KeyRef) -> Option<&AlgorithmAttributes> {
match key_ref {
KeyRef::Sig => Some(&self.attributes_sig),
KeyRef::Dec => Some(&self.attributes_dec),
KeyRef::Aut => Some(&self.attributes_aut),
KeyRef::Att => self.attributes_att.as_ref(),
}
}
pub fn get_uif(&self, key_ref: KeyRef) -> Option<Uif> {
match key_ref {
KeyRef::Sig => self.uif_sig,
KeyRef::Dec => self.uif_dec,
KeyRef::Aut => self.uif_aut,
KeyRef::Att => self.uif_att,
}
}
}
#[derive(Debug, Clone)]
pub struct ApplicationRelatedData {
pub aid: OpenPgpAid,
pub historical: Vec<u8>,
pub discretionary: DiscretionaryDataObjects,
}
impl ApplicationRelatedData {
pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
let outer = tlv_unpack(Do::ApplicationRelatedData as u32, encoded)?;
let data = parse_tlv_dict(&outer)?;
let aid_bytes = data
.get(&(Do::Aid as u32))
.ok_or_else(|| OpenPgpError::InvalidData("Missing AID".into()))?;
let historical = data
.get(&(Do::HistoricalBytes as u32))
.cloned()
.unwrap_or_default();
let disc_data = data
.get(&TAG_DISCRETIONARY)
.filter(|v| !v.is_empty())
.map(|v| v.as_slice())
.unwrap_or(&outer);
let discretionary = DiscretionaryDataObjects::parse(disc_data)?;
Ok(Self {
aid: OpenPgpAid::parse(aid_bytes),
historical,
discretionary,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Kdf {
None,
IterSaltedS2k {
hash_algorithm: HashAlgorithm,
iteration_count: u32,
salt_user: Vec<u8>,
salt_reset: Option<Vec<u8>>,
salt_admin: Option<Vec<u8>>,
initial_hash_user: Option<Vec<u8>>,
initial_hash_admin: Option<Vec<u8>>,
},
}
impl Kdf {
pub fn parse(encoded: &[u8]) -> Result<Self, OpenPgpError> {
let data = parse_tlv_dict(encoded)?;
let algorithm = data.get(&0x81).map(|v| bytes2int(v) as u8).unwrap_or(0);
if algorithm == 3 {
let hash_algorithm =
HashAlgorithm::from_u8(data.get(&0x82).map(|v| bytes2int(v) as u8).unwrap_or(0x08))
.unwrap_or(HashAlgorithm::Sha256);
let iteration_count = data.get(&0x83).map(|v| bytes2int(v) as u32).unwrap_or(0);
Ok(Kdf::IterSaltedS2k {
hash_algorithm,
iteration_count,
salt_user: data.get(&0x84).cloned().unwrap_or_default(),
salt_reset: data.get(&0x85).cloned(),
salt_admin: data.get(&0x86).cloned(),
initial_hash_user: data.get(&0x87).cloned(),
initial_hash_admin: data.get(&0x88).cloned(),
})
} else {
Ok(Kdf::None)
}
}
pub fn to_bytes(&self) -> Vec<u8> {
match self {
Kdf::None => tlv_encode(0x81, &[0x00]),
Kdf::IterSaltedS2k {
hash_algorithm,
iteration_count,
salt_user,
salt_reset,
salt_admin,
initial_hash_user,
initial_hash_admin,
} => {
let mut buf = Vec::new();
buf.extend_from_slice(&tlv_encode(0x81, &[0x03]));
buf.extend_from_slice(&tlv_encode(0x82, &[*hash_algorithm as u8]));
buf.extend_from_slice(&tlv_encode(0x83, &iteration_count.to_be_bytes()));
buf.extend_from_slice(&tlv_encode(0x84, salt_user));
if let Some(sr) = salt_reset {
buf.extend_from_slice(&tlv_encode(0x85, sr));
}
if let Some(sa) = salt_admin {
buf.extend_from_slice(&tlv_encode(0x86, sa));
}
if let Some(ih) = initial_hash_user {
buf.extend_from_slice(&tlv_encode(0x87, ih));
}
if let Some(ia) = initial_hash_admin {
buf.extend_from_slice(&tlv_encode(0x88, ia));
}
buf
}
}
}
pub fn create_iter_salted_s2k(
hash_algorithm: HashAlgorithm,
iteration_count: u32,
) -> Result<Self, OpenPgpError> {
let mut salt_user = [0u8; 8];
let mut salt_reset = [0u8; 8];
let mut salt_admin = [0u8; 8];
getrandom::fill(&mut salt_user)
.map_err(|e| OpenPgpError::InvalidData(format!("RNG error: {e}")))?;
getrandom::fill(&mut salt_reset)
.map_err(|e| OpenPgpError::InvalidData(format!("RNG error: {e}")))?;
getrandom::fill(&mut salt_admin)
.map_err(|e| OpenPgpError::InvalidData(format!("RNG error: {e}")))?;
let initial_hash_user = std::mem::take(&mut *kdf_s2k_hash(
hash_algorithm,
iteration_count,
&salt_user,
DEFAULT_USER_PIN,
));
let initial_hash_admin = std::mem::take(&mut *kdf_s2k_hash(
hash_algorithm,
iteration_count,
&salt_admin,
DEFAULT_ADMIN_PIN,
));
Ok(Kdf::IterSaltedS2k {
hash_algorithm,
iteration_count,
salt_user: salt_user.to_vec(),
salt_reset: Some(salt_reset.to_vec()),
salt_admin: Some(salt_admin.to_vec()),
initial_hash_user: Some(initial_hash_user),
initial_hash_admin: Some(initial_hash_admin),
})
}
fn process(&self, pw: Pw, pin: &str) -> Zeroizing<Vec<u8>> {
match self {
Kdf::None => Zeroizing::new(pin.as_bytes().to_vec()),
Kdf::IterSaltedS2k {
hash_algorithm,
iteration_count,
salt_user,
salt_reset,
salt_admin,
..
} => {
let salt = match pw {
Pw::User => salt_user.as_slice(),
Pw::Reset => salt_reset.as_deref().unwrap_or(salt_user.as_slice()),
Pw::Admin => salt_admin.as_deref().unwrap_or(salt_user.as_slice()),
};
kdf_s2k_hash(*hash_algorithm, *iteration_count, salt, pin)
}
}
}
}
fn kdf_s2k_hash(
hash_algorithm: HashAlgorithm,
iteration_count: u32,
salt: &[u8],
pin: &str,
) -> Zeroizing<Vec<u8>> {
let data = Zeroizing::new([salt, pin.as_bytes()].concat());
let count = (iteration_count as usize).max(data.len());
let (full_rounds, trailing) = if data.is_empty() {
(0, 0)
} else {
(count / data.len(), count % data.len())
};
match hash_algorithm {
HashAlgorithm::Sha256 => {
let mut digest = sha2::Sha256::new();
for _ in 0..full_rounds {
digest.update(data.as_slice());
}
if trailing > 0 {
digest.update(&data[..trailing]);
}
Zeroizing::new(digest.finalize().to_vec())
}
HashAlgorithm::Sha512 => {
let mut digest = sha2::Sha512::new();
for _ in 0..full_rounds {
digest.update(data.as_slice());
}
if trailing > 0 {
digest.update(&data[..trailing]);
}
Zeroizing::new(digest.finalize().to_vec())
}
}
}
fn algorithm_attributes_for_key(
key_ref: KeyRef,
private_key: &PrivateKey,
) -> Result<AlgorithmAttributes, OpenPgpError> {
match private_key {
PrivateKey::Rsa(rsa) => {
match rsa.key_size {
RsaKeySize::Rsa2048 | RsaKeySize::Rsa3072 | RsaKeySize::Rsa4096 => {}
_ => {
return Err(OpenPgpError::InvalidData(format!(
"Unsupported RSA key size for OpenPGP: {:?}",
rsa.key_size
)));
}
};
let import_format = if !rsa.dp.expose_secret().is_empty() && !rsa.n.is_empty() {
RsaImportFormat::CrtWMod
} else if !rsa.dp.expose_secret().is_empty() {
RsaImportFormat::Crt
} else if !rsa.n.is_empty() {
RsaImportFormat::StandardWMod
} else {
RsaImportFormat::Standard
};
Ok(AlgorithmAttributes::Rsa(RsaAttributes::create(
rsa.key_size,
import_format,
)))
}
PrivateKey::Ec(ec) => {
let curve = match ec.curve {
EcCurve::P256 => OpenPgpCurve::P256,
EcCurve::P384 => OpenPgpCurve::P384,
EcCurve::P521 => OpenPgpCurve::P521,
EcCurve::Secp256k1 => OpenPgpCurve::Secp256k1,
EcCurve::BrainpoolP256r1 => OpenPgpCurve::BrainpoolP256r1,
EcCurve::BrainpoolP384r1 => OpenPgpCurve::BrainpoolP384r1,
EcCurve::BrainpoolP512r1 => OpenPgpCurve::BrainpoolP512r1,
};
Ok(AlgorithmAttributes::Ec(EcAttributes::create(
key_ref, &curve,
)?))
}
PrivateKey::Ed25519(_) => Ok(AlgorithmAttributes::Ec(EcAttributes::create(
key_ref,
&OpenPgpCurve::Ed25519,
)?)),
PrivateKey::X25519(_) => Ok(AlgorithmAttributes::Ec(EcAttributes::create(
key_ref,
&OpenPgpCurve::X25519,
)?)),
_ => Err(OpenPgpError::NotSupported(
"Key type not supported for OpenPGP import".into(),
)),
}
}
fn build_private_key_template(
key_ref: KeyRef,
private_key: &PrivateKey,
) -> Result<Zeroizing<Vec<u8>>, OpenPgpError> {
let mut temp = Zeroizing::new(Vec::new());
let component_tlvs: Vec<(u32, &[u8])> = match private_key {
PrivateKey::Rsa(rsa) => {
let mut v = vec![
(0x91, rsa.e.as_slice()),
(0x92, rsa.p.expose_secret().as_slice()),
(0x93, rsa.q.expose_secret().as_slice()),
];
if !rsa.qinv.expose_secret().is_empty() {
v.push((0x94, rsa.qinv.expose_secret().as_slice()));
}
if !rsa.dp.expose_secret().is_empty() {
v.push((0x95, rsa.dp.expose_secret().as_slice()));
}
if !rsa.dq.expose_secret().is_empty() {
v.push((0x96, rsa.dq.expose_secret().as_slice()));
}
if !rsa.n.is_empty() {
v.push((0x97, rsa.n.as_slice()));
}
v
}
PrivateKey::Ec(ec) => {
let mut v = vec![(0x92, ec.scalar.expose_secret().as_slice())];
if let Some(pk) = &ec.public_key {
v.push((0x99, pk.as_slice()));
}
v
}
PrivateKey::Ed25519(k) => {
vec![(0x92, k.secret.expose_secret().as_slice())]
}
PrivateKey::X25519(k) => {
temp.extend(k.secret.expose_secret());
temp.reverse();
vec![(0x92, temp.as_slice())]
}
_ => {
return Err(OpenPgpError::NotSupported(
"Key type not supported for OpenPGP import".into(),
));
}
};
let mut headers = Vec::new();
let mut values = Zeroizing::new(Vec::new());
for (tag, value) in &component_tlvs {
let encoded = Zeroizing::new(tlv_encode(*tag, value));
let header_len = encoded.len() - value.len();
headers.extend_from_slice(&encoded[..header_len]);
values.extend_from_slice(value);
}
let mut inner = Zeroizing::new(key_ref.crt());
tlv_append(&mut inner, 0x7F48, &headers);
tlv_append(&mut inner, 0x5F48, &values);
Ok(Zeroizing::new(tlv_encode(0x4D, &inner)))
}
fn parse_rsa_public_key(pk_data: &[u8]) -> Result<PublicKey, OpenPgpError> {
let tlvs = parse_tlv_list(pk_data)?;
let n = crate::__internal::tlv::tlv_get(&tlvs, 0x81)
.ok_or_else(|| OpenPgpError::InvalidData("Missing RSA modulus (tag 0x81)".into()))?;
let e = crate::__internal::tlv::tlv_get(&tlvs, 0x82)
.ok_or_else(|| OpenPgpError::InvalidData("Missing RSA exponent (tag 0x82)".into()))?;
let n = if !n.is_empty() && n[0] == 0 {
n[1..].to_vec()
} else {
n.to_vec()
};
let key_size = RsaKeySize::from_bit_len(n.len() * 8).ok_or_else(|| {
OpenPgpError::InvalidData(format!("Unsupported RSA key size: {} bits", n.len() * 8))
})?;
let public_key = RsaPublicKey::new(n, e.to_vec())
.map_err(|e| OpenPgpError::InvalidData(format!("Invalid RSA public key: {e}")))?;
if public_key.key_size != key_size {
return Err(OpenPgpError::InvalidData(
"RSA public key size mismatch".into(),
));
}
Ok(PublicKey::Rsa(public_key))
}
fn parse_ec_public_key(pk_data: &[u8], oid: &ObjectIdentifier) -> Result<PublicKey, OpenPgpError> {
let point = tlv_unpack(0x86, pk_data)?;
if *oid == OID_ED25519 {
Ok(PublicKey::Ed25519(Ed25519PublicKey::new(point).map_err(
|e| OpenPgpError::InvalidData(format!("Invalid Ed25519 public key: {e}")),
)?))
} else if *oid == OID_X25519 {
Ok(PublicKey::X25519(X25519PublicKey::new(point).map_err(
|e| OpenPgpError::InvalidData(format!("Invalid X25519 public key: {e}")),
)?))
} else {
let curve = EcCurve::from_oid(oid)
.ok_or_else(|| OpenPgpError::InvalidData("Unsupported EC curve".into()))?;
Ok(PublicKey::Ec(EcPublicKey::new(curve, point).map_err(
|e| OpenPgpError::InvalidData(format!("Invalid EC public key: {e}")),
)?))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignHashAlgorithm {
Sha1,
Sha256,
Sha384,
Sha512,
Prehashed(PrehashAlgorithm),
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PrehashAlgorithm {
Sha1,
Sha256,
Sha384,
Sha512,
}
fn pad_message(
attributes: &AlgorithmAttributes,
message: &[u8],
hash_algorithm: SignHashAlgorithm,
) -> Result<Vec<u8>, OpenPgpError> {
if attributes.algorithm_id() == EC_ALG_EDDSA {
return Ok(message.to_vec());
}
let hash = match hash_algorithm {
SignHashAlgorithm::Sha1 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha1) => {
Some(Hash::Sha1)
}
SignHashAlgorithm::Sha256 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha256) => {
Some(Hash::Sha256)
}
SignHashAlgorithm::Sha384 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha384) => {
Some(Hash::Sha384)
}
SignHashAlgorithm::Sha512 | SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha512) => {
Some(Hash::Sha512)
}
SignHashAlgorithm::None => None,
};
let hashed = match (hash_algorithm, hash) {
(SignHashAlgorithm::Prehashed(_), Some(hash)) => {
if message.len() != hash.output_len() {
return Err(OpenPgpError::InvalidData(format!(
"Prehashed input must contain exactly {} bytes.",
hash.output_len()
)));
}
message.to_vec()
}
(_, None) => message.to_vec(),
(_, Some(hash)) => hash.digest(message).to_vec(),
};
match attributes {
AlgorithmAttributes::Ec(_) => Ok(hashed),
AlgorithmAttributes::Rsa(_) => hash
.ok_or_else(|| OpenPgpError::InvalidData("Hash algorithm required for RSA".into()))?
.digest_info(&hashed)
.map_err(|e| OpenPgpError::InvalidData(e.to_string())),
}
}
pub struct OpenPgpSession<C: SmartCardConnection> {
protocol: SmartCardProtocol<C>,
version: Version,
app_data: ApplicationRelatedData,
}
impl<C: SmartCardConnection> OpenPgpSession<C> {
pub fn new(connection: C) -> Result<Self, (OpenPgpError, C)> {
let mut protocol = SmartCardProtocol::new(connection);
match protocol.select(Aid::OPENPGP) {
Ok(_) => {}
Err(SmartCardError::Apdu { sw, .. }) if sw == 0x6285 || sw == 0x6985 => {
if let Err(e) = protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[]) {
return Err((e.into(), protocol.into_connection()));
}
if let Err(e) = protocol.select(Aid::OPENPGP) {
return Err((e.into(), protocol.into_connection()));
}
}
Err(e) => return Err((e.into(), protocol.into_connection())),
}
Self::init(protocol)
}
pub fn new_with_scp(
connection: C,
scp_key_params: &crate::smartcard::ScpKeyParams,
) -> Result<Self, (OpenPgpError, C)> {
let mut protocol = SmartCardProtocol::new(connection);
match protocol.select(Aid::OPENPGP) {
Ok(_) => {}
Err(SmartCardError::Apdu { sw, .. }) if sw == 0x6285 || sw == 0x6985 => {
if let Err(e) = protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[]) {
return Err((e.into(), protocol.into_connection()));
}
if let Err(e) = protocol.select(Aid::OPENPGP) {
return Err((e.into(), protocol.into_connection()));
}
}
Err(e) => return Err((e.into(), protocol.into_connection())),
}
if let Err(e) = protocol.init_scp(scp_key_params) {
return Err((e.into(), protocol.into_connection()));
}
Self::init(protocol)
}
fn init(mut protocol: SmartCardProtocol<C>) -> Result<Self, (OpenPgpError, C)> {
log::debug!("Opening OpenPgpSession");
let version = match protocol.send_apdu(0, INS_GET_VERSION, 0, 0, &[]) {
Ok(bcd_bytes) => Version(
bcd(*bcd_bytes.first().unwrap_or(&0)),
bcd(*bcd_bytes.get(1).unwrap_or(&0)),
bcd(*bcd_bytes.get(2).unwrap_or(&0)),
),
Err(SmartCardError::Apdu { sw: 0x6985, .. }) => Version(1, 0, 0),
Err(e) => return Err((e.into(), protocol.into_connection())),
};
let version = patch_version(version);
protocol.configure(version);
let app_data_raw = match protocol.send_apdu(
0,
INS_GET_DATA,
Do::ApplicationRelatedData.p1(),
Do::ApplicationRelatedData.p2(),
&[],
) {
Ok(v) => v,
Err(e) => return Err((e.into(), protocol.into_connection())),
};
let app_data = match ApplicationRelatedData::parse(&app_data_raw) {
Ok(v) => v,
Err(e) => return Err((e, protocol.into_connection())),
};
Ok(Self {
protocol,
version,
app_data,
})
}
pub fn aid(&self) -> &OpenPgpAid {
&self.app_data.aid
}
pub fn version(&self) -> Version {
self.version
}
pub fn extended_capabilities(&self) -> &ExtendedCapabilities {
&self.app_data.discretionary.extended_capabilities
}
pub fn protocol(&self) -> &SmartCardProtocol<C> {
&self.protocol
}
pub fn protocol_mut(&mut self) -> &mut SmartCardProtocol<C> {
&mut self.protocol
}
pub fn into_connection(self) -> C {
self.protocol.into_connection()
}
pub fn get_data(&mut self, data_object: Do) -> Result<Vec<u8>, OpenPgpError> {
Ok(self
.protocol
.send_apdu(0, INS_GET_DATA, data_object.p1(), data_object.p2(), &[])?)
}
pub fn put_data(&mut self, data_object: Do, data: &[u8]) -> Result<(), OpenPgpError> {
self.protocol
.send_apdu(0, INS_PUT_DATA, data_object.p1(), data_object.p2(), data)?;
Ok(())
}
pub fn get_pin_status(&mut self) -> Result<PwStatus, OpenPgpError> {
let data = self.get_data(Do::PwStatusBytes)?;
PwStatus::parse(&data)
}
pub fn get_signature_counter(&mut self) -> Result<u32, OpenPgpError> {
let data = self.get_data(Do::SecuritySupportTemplate)?;
let inner = tlv_unpack(Do::SecuritySupportTemplate as u32, &data)?;
let dict = parse_tlv_dict(&inner)?;
let counter_bytes = dict
.get(&TAG_SIGNATURE_COUNTER)
.ok_or_else(|| OpenPgpError::InvalidData("Missing signature counter".into()))?;
Ok(bytes2int(counter_bytes) as u32)
}
pub fn get_application_related_data(&mut self) -> Result<ApplicationRelatedData, OpenPgpError> {
let data = self.get_data(Do::ApplicationRelatedData)?;
let mut app_data = ApplicationRelatedData::parse(&data)?;
if app_data.aid.version() < (3, 0) {
app_data.discretionary.uif_sig = self.get_uif(KeyRef::Sig).ok();
app_data.discretionary.uif_dec = self.get_uif(KeyRef::Dec).ok();
app_data.discretionary.uif_aut = self.get_uif(KeyRef::Aut).ok();
}
Ok(app_data)
}
pub fn get_key_information(&mut self) -> Result<KeyInformation, OpenPgpError> {
Ok(self
.get_application_related_data()?
.discretionary
.key_information)
}
pub fn get_generation_times(&mut self) -> Result<GenerationTimes, OpenPgpError> {
Ok(self
.get_application_related_data()?
.discretionary
.generation_times)
}
pub fn get_fingerprints(&mut self) -> Result<Fingerprints, OpenPgpError> {
Ok(self
.get_application_related_data()?
.discretionary
.fingerprints)
}
fn process_pin(
&self,
kdf: &Kdf,
pw: Pw,
pin: &str,
) -> Result<Zeroizing<Vec<u8>>, OpenPgpError> {
if matches!(kdf, Kdf::None) {
let pin_len = pin.len();
let min_len: usize = if matches!(pw, Pw::User) { 6 } else { 8 };
let max_len = self.app_data.discretionary.pw_status.get_max_len(pw) as usize;
if pin_len < min_len || pin_len > max_len {
return Err(OpenPgpError::InvalidData(format!(
"PIN length must be in the range {min_len}-{max_len}"
)));
}
}
Ok(kdf.process(pw, pin))
}
fn verify_inner(&mut self, pw: Pw, pin: &OpenPgpPin, mode: u8) -> Result<(), OpenPgpError> {
let kdf = self.get_kdf()?;
let pin_enc = self.process_pin(&kdf, pw, pin.as_str())?;
match self
.protocol
.send_apdu(0, INS_VERIFY, 0, pw as u8 + mode, &pin_enc)
{
Ok(_) => Ok(()),
Err(SmartCardError::Apdu { sw, .. })
if sw == 0x6982 || (sw >> 8 == 0x63 && self.version < Version(4, 0, 0)) =>
{
let attempts = self.get_pin_status()?.get_attempts(pw) as u32;
Err(OpenPgpError::InvalidPin(attempts))
}
Err(SmartCardError::Apdu { sw: 0x6983, .. }) => Err(OpenPgpError::PinBlocked),
Err(e) => Err(e.into()),
}
}
pub fn verify_pin(&mut self, pin: &OpenPgpPin, extended: bool) -> Result<(), OpenPgpError> {
log::debug!("Verifying OpenPGP PIN");
let mode = if extended { 1 } else { 0 };
self.verify_inner(Pw::User, pin, mode)
}
pub fn verify_admin(&mut self, admin_pin: &OpenPgpPin) -> Result<(), OpenPgpError> {
log::debug!("Verifying OpenPGP admin PIN");
self.verify_inner(Pw::Admin, admin_pin, 0)
}
pub fn unverify_pin(&mut self, pw: Pw) -> Result<(), OpenPgpError> {
log::debug!("Clearing PIN verification");
require_version(self.version, Version(5, 6, 0), "unverify_pin")?;
self.protocol
.send_apdu(0, INS_VERIFY, 0xFF, pw as u8, &[])?;
Ok(())
}
fn change_inner(
&mut self,
pw: Pw,
pin: &OpenPgpPin,
new_pin: &OpenPgpPin,
) -> Result<(), OpenPgpError> {
let kdf = self.get_kdf()?;
let mut data = Zeroizing::new(self.process_pin(&kdf, pw, pin.as_str())?.to_vec());
data.extend_from_slice(&self.process_pin(&kdf, pw, new_pin.as_str())?);
match self
.protocol
.send_apdu(0, INS_CHANGE_PIN, 0, pw as u8, &data)
{
Ok(_) => Ok(()),
Err(SmartCardError::Apdu { sw, .. })
if sw == 0x6982 || (sw == 0x6985 && self.version < Version(4, 0, 0)) =>
{
let attempts = self.get_pin_status()?.get_attempts(pw) as u32;
Err(OpenPgpError::InvalidPin(attempts))
}
Err(SmartCardError::Apdu { sw: 0x6983, .. }) => Err(OpenPgpError::PinBlocked),
Err(e) => Err(e.into()),
}
}
pub fn change_pin(
&mut self,
pin: &OpenPgpPin,
new_pin: &OpenPgpPin,
) -> Result<(), OpenPgpError> {
log::debug!("Changing OpenPGP PIN");
self.change_inner(Pw::User, pin, new_pin)?;
log::info!("OpenPGP PIN changed");
Ok(())
}
pub fn change_admin(
&mut self,
admin_pin: &OpenPgpPin,
new_admin_pin: &OpenPgpPin,
) -> Result<(), OpenPgpError> {
log::debug!("Changing OpenPGP admin PIN");
self.change_inner(Pw::Admin, admin_pin, new_admin_pin)?;
log::info!("OpenPGP admin PIN changed");
Ok(())
}
pub fn set_reset_code(&mut self, reset_code: &OpenPgpPin) -> Result<(), OpenPgpError> {
log::debug!("Setting OpenPGP reset code");
let kdf = self.get_kdf()?;
let data = self.process_pin(&kdf, Pw::Reset, reset_code.as_str())?;
self.put_data(Do::ResettingCode, &data)?;
log::info!("OpenPGP reset code set");
Ok(())
}
pub fn reset_pin(
&mut self,
new_pin: &OpenPgpPin,
reset_code: Option<&OpenPgpPin>,
) -> Result<(), OpenPgpError> {
log::debug!("Resetting OpenPGP PIN");
let kdf = self.get_kdf()?;
let new_pin_data = self.process_pin(&kdf, Pw::User, new_pin.as_str())?;
let (p1, data): (u8, Zeroizing<Vec<u8>>) = if let Some(code) = reset_code {
let mut d = Zeroizing::new(self.process_pin(&kdf, Pw::Reset, code.as_str())?.to_vec());
d.extend_from_slice(&new_pin_data);
(0, d)
} else {
(2, new_pin_data)
};
match self
.protocol
.send_apdu(0, INS_RESET_RETRY_COUNTER, p1, Pw::User as u8, &data)
{
Ok(_) => {
log::info!("OpenPGP PIN reset");
Ok(())
}
Err(SmartCardError::Apdu { sw, .. }) if sw == 0x6982 && reset_code.is_some() => {
let attempts = self.get_pin_status()?.attempts_reset as u32;
Err(OpenPgpError::InvalidPin(attempts))
}
Err(SmartCardError::Apdu { sw, .. })
if (sw == 0x6983 || sw == 0x6A80) && reset_code.is_some() =>
{
Err(OpenPgpError::PinBlocked)
}
Err(e) => Err(e.into()),
}
}
pub fn set_signature_pin_policy(&mut self, pin_policy: PinPolicy) -> Result<(), OpenPgpError> {
log::debug!("Setting signature PIN policy");
self.put_data(Do::PwStatusBytes, &[pin_policy as u8])?;
log::info!("Signature PIN policy set");
Ok(())
}
pub fn set_pin_attempts(
&mut self,
user_attempts: u8,
reset_attempts: u8,
admin_attempts: u8,
) -> Result<(), OpenPgpError> {
log::debug!("Setting OpenPGP PIN attempts");
if self.version.0 == 1 {
require_version(self.version, Version(1, 0, 7), "set_pin_attempts")?;
} else {
require_version(self.version, Version(4, 3, 1), "set_pin_attempts")?;
}
self.protocol.send_apdu(
0,
INS_SET_PIN_RETRIES,
0,
0,
&[user_attempts, reset_attempts, admin_attempts],
)?;
log::info!("OpenPGP PIN attempts set");
Ok(())
}
pub fn get_kdf(&mut self) -> Result<Kdf, OpenPgpError> {
if !self
.app_data
.discretionary
.extended_capabilities
.has_flag(extended_capability_flags::KDF)
{
return Ok(Kdf::None);
}
let data = self.get_data(Do::Kdf)?;
Kdf::parse(&data)
}
pub fn set_kdf(&mut self, kdf: &Kdf) -> Result<(), OpenPgpError> {
log::debug!("Setting OpenPGP KDF");
if !self
.app_data
.discretionary
.extended_capabilities
.has_flag(extended_capability_flags::KDF)
{
return Err(OpenPgpError::NotSupported("KDF is not supported".into()));
}
self.put_data(Do::Kdf, &kdf.to_bytes())?;
log::info!("OpenPGP KDF configured");
Ok(())
}
pub fn reset(&mut self) -> Result<(), OpenPgpError> {
log::debug!("Resetting OpenPGP application");
require_version(self.version, Version(1, 0, 6), "reset")?;
let status = self.get_pin_status()?;
for pw in [Pw::User, Pw::Admin] {
let attempts = status.get_attempts(pw);
for _ in 0..attempts {
let _ = self
.protocol
.send_apdu(0, INS_VERIFY, 0, pw as u8, INVALID_PIN);
}
}
self.protocol.send_apdu(0, INS_TERMINATE, 0, 0, &[])?;
self.protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[])?;
log::info!("OpenPGP application reset");
Ok(())
}
pub fn get_algorithm_attributes(
&mut self,
key_ref: KeyRef,
) -> Result<AlgorithmAttributes, OpenPgpError> {
let data = self.get_application_related_data()?;
data.discretionary
.get_algorithm_attributes(key_ref)
.cloned()
.ok_or_else(|| {
OpenPgpError::InvalidData(format!("No algorithm attributes for key {:?}", key_ref))
})
}
pub fn get_algorithm_information(
&mut self,
) -> Result<HashMap<KeyRef, Vec<AlgorithmAttributes>>, OpenPgpError> {
if !self
.app_data
.discretionary
.extended_capabilities
.has_flag(extended_capability_flags::ALGORITHM_ATTRIBUTES_CHANGEABLE)
{
return Err(OpenPgpError::NotSupported(
"Writing Algorithm Attributes is not supported".into(),
));
}
if self.version < Version(5, 2, 0) && self.version.0 > 0 {
let fmt = if 0 < self.version.0 && self.version.0 < 4 {
RsaImportFormat::CrtWMod
} else {
RsaImportFormat::Standard
};
let mut sizes = vec![RsaKeySize::Rsa2048];
if self.version.0 >= 4 && (self.version.0, self.version.1) != (4, 4) {
sizes.push(RsaKeySize::Rsa3072);
sizes.push(RsaKeySize::Rsa4096);
}
let attrs: Vec<AlgorithmAttributes> = sizes
.iter()
.map(|&s| AlgorithmAttributes::Rsa(RsaAttributes::create(s, fmt)))
.collect();
let mut map = HashMap::new();
map.insert(KeyRef::Sig, attrs.clone());
map.insert(KeyRef::Dec, attrs.clone());
map.insert(KeyRef::Aut, attrs);
return Ok(map);
}
let buf = self.get_data(Do::AlgorithmInformation)?;
let inner = match tlv_unpack(Do::AlgorithmInformation as u32, &buf) {
Ok(v) => v,
Err(_) => {
let mut padded = buf.clone();
padded.extend_from_slice(&[0, 0]);
let v = tlv_unpack(Do::AlgorithmInformation as u32, &padded)?;
if v.len() >= 2 {
v[..v.len() - 2].to_vec()
} else {
v
}
}
};
let entries = parse_tlv_list(&inner)?;
let slot_map: HashMap<u32, KeyRef> = [
(Do::AlgorithmAttributesSig as u32, KeyRef::Sig),
(Do::AlgorithmAttributesDec as u32, KeyRef::Dec),
(Do::AlgorithmAttributesAut as u32, KeyRef::Aut),
(Do::AlgorithmAttributesAtt as u32, KeyRef::Att),
]
.into();
let mut result: HashMap<KeyRef, Vec<AlgorithmAttributes>> = HashMap::new();
for (tag, value) in &entries {
if let Some(&key) = slot_map.get(tag)
&& let Ok(attrs) = AlgorithmAttributes::parse(value)
{
result.entry(key).or_default().push(attrs);
}
}
Ok(result)
}
pub fn set_algorithm_attributes(
&mut self,
key_ref: KeyRef,
attributes: &AlgorithmAttributes,
) -> Result<(), OpenPgpError> {
log::debug!("Setting algorithm attributes for {:?}", key_ref);
self.put_data(key_ref.algorithm_attributes_do(), &attributes.to_bytes())?;
log::info!("Algorithm attributes set for {:?}", key_ref);
Ok(())
}
pub fn get_uif(&mut self, key_ref: KeyRef) -> Result<Uif, OpenPgpError> {
if self.version >= Version(4, 2, 0) {
let data = self.get_data(key_ref.uif_do())?;
Uif::parse(&data).ok_or_else(|| OpenPgpError::InvalidData("Invalid UIF value".into()))
} else {
Ok(Uif::Off)
}
}
pub fn set_uif(&mut self, key_ref: KeyRef, uif: Uif) -> Result<(), OpenPgpError> {
log::debug!("Setting UIF for {:?}", key_ref);
require_version(self.version, Version(4, 2, 0), "set_uif")?;
if key_ref == KeyRef::Att {
require_version(self.version, Version(5, 2, 1), "set_uif for ATT key")?;
}
if uif.is_cached() {
require_version(self.version, Version(5, 2, 1), "cached UIF")?;
}
let current = self.get_uif(key_ref)?;
if current.is_fixed() {
return Err(OpenPgpError::InvalidData(
"Cannot change UIF when set to FIXED".into(),
));
}
self.put_data(key_ref.uif_do(), &uif.to_bytes())?;
log::info!("UIF configured for {:?}", key_ref);
Ok(())
}
pub fn set_generation_time(
&mut self,
key_ref: KeyRef,
timestamp: u32,
) -> Result<(), OpenPgpError> {
self.put_data(key_ref.generation_time_do(), ×tamp.to_be_bytes())
}
pub fn set_fingerprint(
&mut self,
key_ref: KeyRef,
fingerprint: &[u8],
) -> Result<(), OpenPgpError> {
self.put_data(key_ref.fingerprint_do(), fingerprint)
}
pub fn generate_rsa_key(
&mut self,
key_ref: KeyRef,
key_size: RsaKeySize,
) -> Result<PublicKey, OpenPgpError> {
log::debug!("Generating RSA key for {:?}", key_ref);
if self.version >= Version(4, 2, 0) && self.version < Version(4, 3, 5) {
return Err(OpenPgpError::NotSupported(
"RSA key generation not supported on this YubiKey".into(),
));
}
if self
.app_data
.discretionary
.extended_capabilities
.has_flag(extended_capability_flags::ALGORITHM_ATTRIBUTES_CHANGEABLE)
{
let import_format = if 0 < self.version.0 && self.version.0 < 4 {
RsaImportFormat::CrtWMod
} else {
RsaImportFormat::Standard
};
let attributes =
AlgorithmAttributes::Rsa(RsaAttributes::create(key_size, import_format));
self.set_algorithm_attributes(key_ref, &attributes)?;
} else if key_size != RsaKeySize::Rsa2048 {
return Err(OpenPgpError::NotSupported(
"Algorithm attributes not supported".into(),
));
}
let crt = key_ref.crt();
let resp = self
.protocol
.send_apdu(0, INS_GENERATE_ASYM, 0x80, 0x00, &crt)?;
let pk_data = tlv_unpack(TAG_PUBLIC_KEY, &resp)?;
log::info!("RSA key generated");
parse_rsa_public_key(&pk_data)
}
pub fn generate_ec_key(
&mut self,
key_ref: KeyRef,
curve: OpenPgpCurve,
) -> Result<PublicKey, OpenPgpError> {
log::debug!("Generating EC key for {:?}", key_ref);
require_version(self.version, Version(5, 2, 0), "generate_ec_key")?;
let attributes = AlgorithmAttributes::Ec(EcAttributes::create(key_ref, &curve)?);
self.set_algorithm_attributes(key_ref, &attributes)?;
let crt = key_ref.crt();
let resp = self
.protocol
.send_apdu(0, INS_GENERATE_ASYM, 0x80, 0x00, &crt)?;
let pk_data = tlv_unpack(TAG_PUBLIC_KEY, &resp)?;
log::info!("EC key generated");
parse_ec_public_key(&pk_data, &curve.oid())
}
pub fn get_public_key(&mut self, key_ref: KeyRef) -> Result<PublicKey, OpenPgpError> {
let attributes = self.get_algorithm_attributes(key_ref)?;
let crt = key_ref.crt();
let resp = self
.protocol
.send_apdu(0, INS_GENERATE_ASYM, 0x81, 0x00, &crt)?;
let pk_data = tlv_unpack(TAG_PUBLIC_KEY, &resp)?;
match &attributes {
AlgorithmAttributes::Rsa(_) => parse_rsa_public_key(&pk_data),
AlgorithmAttributes::Ec(ec) => {
let oid = ec.oid()?;
parse_ec_public_key(&pk_data, &oid)
}
}
}
pub fn put_key(
&mut self,
key_ref: KeyRef,
private_key: &PrivateKey,
) -> Result<(), OpenPgpError> {
log::debug!("Importing key for {:?}", key_ref);
let attributes = algorithm_attributes_for_key(key_ref, private_key)?;
self.set_algorithm_attributes(key_ref, &attributes)?;
let template = build_private_key_template(key_ref, private_key)?;
self.protocol
.send_apdu(0, INS_PUT_DATA_ODD, 0x3F, 0xFF, &template)?;
log::info!("Key imported");
Ok(())
}
pub fn delete_key(&mut self, key_ref: KeyRef) -> Result<(), OpenPgpError> {
log::debug!("Deleting key for {:?}", key_ref);
if 0 < self.version.0 && self.version.0 < 4 {
return Err(OpenPgpError::NotSupported(
"delete_key on NEO requires full key import".into(),
));
}
self.put_data(
key_ref.algorithm_attributes_do(),
&AlgorithmAttributes::Rsa(RsaAttributes::create(
RsaKeySize::Rsa4096,
RsaImportFormat::Standard,
))
.to_bytes(),
)?;
self.set_algorithm_attributes(
key_ref,
&AlgorithmAttributes::Rsa(RsaAttributes::create(
RsaKeySize::Rsa2048,
RsaImportFormat::Standard,
)),
)?;
log::info!("Key deleted for {:?}", key_ref);
Ok(())
}
pub fn sign(
&mut self,
message: &[u8],
hash_algorithm: SignHashAlgorithm,
) -> Result<Vec<u8>, OpenPgpError> {
log::debug!("Signing with {:?}", KeyRef::Sig);
let attributes = self.get_algorithm_attributes(KeyRef::Sig)?;
let padded = pad_message(&attributes, message, hash_algorithm)?;
let response = self.protocol.send_apdu(0, INS_PSO, 0x9E, 0x9A, &padded)?;
Ok(response)
}
pub fn decrypt(&mut self, value: &[u8]) -> Result<Vec<u8>, OpenPgpError> {
log::debug!("Decrypting with key");
let attributes = self.get_algorithm_attributes(KeyRef::Dec)?;
let data = match &attributes {
AlgorithmAttributes::Rsa(_) => {
let mut d = vec![0x00];
d.extend_from_slice(value);
d
}
AlgorithmAttributes::Ec(_) => {
let inner = tlv_encode(0x86, value);
let mid = tlv_encode(0x7F49, &inner);
tlv_encode(0xA6, &mid)
}
};
let response = self.protocol.send_apdu(0, INS_PSO, 0x80, 0x86, &data)?;
Ok(response)
}
pub fn authenticate(
&mut self,
message: &[u8],
hash_algorithm: SignHashAlgorithm,
) -> Result<Vec<u8>, OpenPgpError> {
log::debug!("Authenticating with {:?}", KeyRef::Aut);
let attributes = self.get_algorithm_attributes(KeyRef::Aut)?;
let padded = pad_message(&attributes, message, hash_algorithm)?;
let response =
self.protocol
.send_apdu(0, INS_INTERNAL_AUTHENTICATE, 0x00, 0x00, &padded)?;
Ok(response)
}
fn select_certificate(&mut self, key_ref: KeyRef) -> Result<(), OpenPgpError> {
if self.version >= Version(5, 2, 0) {
let do_bytes = int2bytes(Do::CardholderCertificate as u64);
let inner = tlv_encode(0x5C, &do_bytes);
let mut outer = tlv_encode(0x60, &inner);
if self.version <= Version(5, 4, 3) {
let mut patched = vec![0x06];
patched.extend_from_slice(&outer);
outer = patched;
}
let index = 3u8.saturating_sub(key_ref as u8);
self.protocol
.send_apdu(0, INS_SELECT_DATA, index, 0x04, &outer)?;
} else if key_ref != KeyRef::Aut {
return Err(OpenPgpError::NotSupported(
"Certificate slot selection requires v5.2.0+".into(),
));
}
Ok(())
}
pub fn get_certificate(&mut self, key_ref: KeyRef) -> Result<Vec<u8>, OpenPgpError> {
if key_ref == KeyRef::Att {
require_version(self.version, Version(5, 2, 0), "ATT certificate")?;
let data = self.get_data(Do::AttCertificate)?;
if data.is_empty() {
return Err(OpenPgpError::InvalidData("No certificate found".into()));
}
return Ok(data);
}
self.select_certificate(key_ref)?;
let data = self.get_data(Do::CardholderCertificate)?;
if data.is_empty() {
return Err(OpenPgpError::InvalidData("No certificate found".into()));
}
Ok(data)
}
pub fn put_certificate(
&mut self,
key_ref: KeyRef,
cert_der: &[u8],
) -> Result<(), OpenPgpError> {
log::debug!("Importing certificate for {:?}", key_ref);
if key_ref == KeyRef::Att {
require_version(self.version, Version(5, 2, 0), "ATT certificate")?;
self.put_data(Do::AttCertificate, cert_der)?;
log::info!("Certificate imported");
return Ok(());
}
self.select_certificate(key_ref)?;
self.put_data(Do::CardholderCertificate, cert_der)?;
log::info!("Certificate imported");
Ok(())
}
pub fn delete_certificate(&mut self, key_ref: KeyRef) -> Result<(), OpenPgpError> {
log::debug!("Deleting certificate for {:?}", key_ref);
if key_ref == KeyRef::Att {
require_version(self.version, Version(5, 2, 0), "ATT certificate")?;
self.put_data(Do::AttCertificate, &[])?;
log::info!("Certificate deleted");
return Ok(());
}
self.select_certificate(key_ref)?;
self.put_data(Do::CardholderCertificate, &[])?;
log::info!("Certificate deleted");
Ok(())
}
pub fn attest_key(&mut self, key_ref: KeyRef) -> Result<Vec<u8>, OpenPgpError> {
log::debug!("Attesting key for {:?}", key_ref);
require_version(self.version, Version(5, 2, 0), "attest_key")?;
self.protocol
.send_apdu(0x80, INS_GET_ATTESTATION, key_ref as u8, 0, &[])?;
self.get_certificate(key_ref)
}
pub fn get_challenge(&mut self, length: u16) -> Result<Vec<u8>, OpenPgpError> {
let ec = &self.app_data.discretionary.extended_capabilities;
if !ec.has_flag(extended_capability_flags::GET_CHALLENGE) {
return Err(OpenPgpError::NotSupported(
"GET_CHALLENGE is not supported".into(),
));
}
if length == 0 || length > ec.challenge_max_length {
return Err(OpenPgpError::InvalidData(
"Unsupported challenge length".into(),
));
}
let resp = self
.protocol
.send_apdu_with_le(0, INS_GET_CHALLENGE, 0, 0, &[], length)?;
Ok(resp)
}
}
pub fn safe_reset<C: SmartCardConnection>(connection: C) -> Result<(), SmartCardError> {
let mut protocol = SmartCardProtocol::new(connection);
protocol.select(Aid::OPENPGP)?;
for pw in [Pw::User, Pw::Admin] {
loop {
match protocol.send_apdu(0, INS_VERIFY, 0, pw as u8, INVALID_PIN) {
Err(SmartCardError::Apdu { sw, .. })
if sw == Sw::SecurityConditionNotSatisfied as u16 =>
{
continue;
}
_ => break,
}
}
}
protocol.send_apdu(0, INS_TERMINATE, 0, 0, &[])?;
protocol.send_apdu(0, INS_ACTIVATE, 0, 0, &[])?;
Ok(())
}
fn require_version(current: Version, required: Version, feature: &str) -> Result<(), OpenPgpError> {
crate::core::require_version(current, required, feature).map_err(OpenPgpError::NotSupported)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::__internal::tlv::tlv_parse;
#[test]
fn test_uif_properties() {
assert!(!Uif::Off.is_fixed());
assert!(!Uif::Off.is_cached());
assert!(!Uif::On.is_fixed());
assert!(Uif::Fixed.is_fixed());
assert!(Uif::Cached.is_cached());
assert!(Uif::CachedFixed.is_fixed());
assert!(Uif::CachedFixed.is_cached());
}
#[test]
fn test_uif_to_bytes() {
assert_eq!(Uif::Off.to_bytes(), [0x00, 0x20]);
assert_eq!(Uif::On.to_bytes(), [0x01, 0x20]);
assert_eq!(Uif::Fixed.to_bytes(), [0x02, 0x20]);
}
#[test]
fn test_uif_parse() {
assert_eq!(Uif::parse(&[0x00, 0x20]), Some(Uif::Off));
assert_eq!(Uif::parse(&[0x03, 0x20]), Some(Uif::Cached));
assert_eq!(Uif::parse(&[]), None);
}
#[test]
fn test_do_p1_p2() {
assert_eq!(Do::ApplicationRelatedData.p1(), 0x00);
assert_eq!(Do::ApplicationRelatedData.p2(), 0x6E);
assert_eq!(Do::PrivateUse1.p1(), 0x01);
assert_eq!(Do::PrivateUse1.p2(), 0x01);
assert_eq!(Do::Language.p1(), 0xEF);
assert_eq!(Do::Language.p2(), 0x2D);
}
#[test]
fn test_key_ref_crt() {
let sig_crt = KeyRef::Sig.crt();
assert_eq!(sig_crt, vec![0xB6, 0x00]);
let att_crt = KeyRef::Att.crt();
assert_eq!(att_crt, vec![0xB6, 0x03, 0x84, 0x01, 0x81]);
}
#[test]
fn test_rsa_attributes_roundtrip() {
let attrs = RsaAttributes::create(RsaKeySize::Rsa2048, RsaImportFormat::Standard);
let bytes = attrs.to_bytes();
assert_eq!(bytes, vec![0x01, 0x08, 0x00, 0x00, 0x11, 0x00]);
let parsed = AlgorithmAttributes::parse(&bytes).unwrap();
match parsed {
AlgorithmAttributes::Rsa(r) => {
assert_eq!(r.n_len, 2048);
assert_eq!(r.e_len, 17);
assert_eq!(r.import_format, RsaImportFormat::Standard);
}
_ => panic!("Expected RSA"),
}
}
#[test]
fn test_ec_attributes_roundtrip() {
let attrs = EcAttributes::create(KeyRef::Sig, &OpenPgpCurve::Ed25519).unwrap();
assert_eq!(attrs.algorithm_id, EC_ALG_EDDSA);
let bytes = attrs.to_bytes();
let parsed = AlgorithmAttributes::parse(&bytes).unwrap();
match parsed {
AlgorithmAttributes::Ec(e) => {
assert_eq!(e.algorithm_id, EC_ALG_EDDSA);
assert_eq!(e.import_format, EcImportFormat::Standard);
assert_eq!(e.oid().unwrap(), OID_ED25519);
}
_ => panic!("Expected EC"),
}
}
#[test]
fn test_ec_attributes_ecdh_for_dec() {
let attrs = EcAttributes::create(KeyRef::Dec, &OpenPgpCurve::P256).unwrap();
assert_eq!(attrs.algorithm_id, EC_ALG_ECDH);
}
#[test]
fn test_ec_attributes_ecdsa_for_sig() {
let attrs = EcAttributes::create(KeyRef::Sig, &OpenPgpCurve::P256).unwrap();
assert_eq!(attrs.algorithm_id, EC_ALG_ECDSA);
}
#[test]
fn test_pw_status_parse() {
let data = [0x01, 127, 127, 127, 3, 0, 3];
let status = PwStatus::parse(&data).unwrap();
assert_eq!(status.pin_policy_user, PinPolicy::Once);
assert_eq!(status.max_len_user, 127);
assert_eq!(status.attempts_user, 3);
assert_eq!(status.attempts_admin, 3);
}
#[test]
fn test_extended_capabilities_parse() {
let data = [0xFF, 0x01, 0x00, 0x80, 0x04, 0x00, 0x04, 0x00, 0x01, 0x01];
let ec = ExtendedCapabilities::parse(&data).unwrap();
assert!(ec.has_flag(extended_capability_flags::KDF));
assert!(ec.has_flag(extended_capability_flags::SECURE_MESSAGING));
assert_eq!(ec.challenge_max_length, 128);
assert_eq!(ec.certificate_max_length, 1024);
assert!(ec.pin_block_2_format);
assert!(ec.mse_command);
}
#[test]
fn test_openpgp_aid_parse() {
let mut raw = vec![0xD2, 0x76, 0x00, 0x01, 0x24, 0x01];
raw.push(0x03); raw.push(0x04); raw.push(0x00); raw.push(0x06); raw.extend_from_slice(&[0x12, 0x34, 0x56, 0x78]); raw.extend_from_slice(&[0x00, 0x00]);
let aid = OpenPgpAid::parse(&raw);
assert_eq!(aid.version(), (3, 4));
assert_eq!(aid.manufacturer(), 6);
assert_eq!(aid.serial(), 12345678);
}
#[test]
fn test_kdf_none_roundtrip() {
let kdf = Kdf::None;
let bytes = kdf.to_bytes();
assert_eq!(bytes, vec![0x81, 0x01, 0x00]);
let parsed = Kdf::parse(&bytes).unwrap();
assert_eq!(parsed, Kdf::None);
}
#[test]
fn test_kdf_none_process() {
let kdf = Kdf::None;
assert_eq!(kdf.process(Pw::User, "123456").as_slice(), b"123456");
}
#[test]
fn test_kdf_s2k_hash_minimum_and_repetition() {
for algorithm in [HashAlgorithm::Sha256, HashAlgorithm::Sha512] {
for pin in ["123456", "12345678", "12345\u{e9}"] {
let data = [b"12345678".as_slice(), pin.as_bytes()].concat();
for count in [0, 1, 7, 8, 9, 13, 14, 15, 16, 27, 28, 29, 1024] {
let mut input = data.clone();
while input.len() < count as usize {
let remaining = count as usize - input.len();
input.extend_from_slice(&data[..remaining.min(data.len())]);
}
let expected = match algorithm {
HashAlgorithm::Sha256 => sha2::Sha256::digest(&input).to_vec(),
HashAlgorithm::Sha512 => sha2::Sha512::digest(&input).to_vec(),
};
assert_eq!(
kdf_s2k_hash(algorithm, count, b"12345678", pin).as_slice(),
expected,
"{algorithm:?}, count={count}, pin={pin:?}"
);
}
}
}
}
#[test]
fn test_kdf_initial_hashes_include_full_default_pins() {
for algorithm in [HashAlgorithm::Sha256, HashAlgorithm::Sha512] {
let kdf = Kdf::create_iter_salted_s2k(algorithm, 8).unwrap();
let Kdf::IterSaltedS2k {
salt_user,
salt_admin: Some(salt_admin),
initial_hash_user: Some(initial_user),
initial_hash_admin: Some(initial_admin),
..
} = &kdf
else {
panic!("Missing initial KDF hashes");
};
for (pw, salt, pin, initial) in [
(Pw::User, salt_user, DEFAULT_USER_PIN, initial_user),
(Pw::Admin, salt_admin, DEFAULT_ADMIN_PIN, initial_admin),
] {
let input = [salt.as_slice(), pin.as_bytes()].concat();
let expected = match algorithm {
HashAlgorithm::Sha256 => sha2::Sha256::digest(&input).to_vec(),
HashAlgorithm::Sha512 => sha2::Sha512::digest(&input).to_vec(),
};
assert_eq!(*initial, expected);
assert_eq!(kdf.process(pw, pin).as_slice(), expected);
}
}
}
#[test]
fn test_kdf_iter_salted_s2k_roundtrip() {
let kdf = Kdf::IterSaltedS2k {
hash_algorithm: HashAlgorithm::Sha256,
iteration_count: 0x780000,
salt_user: vec![1, 2, 3, 4, 5, 6, 7, 8],
salt_reset: Some(vec![9, 10, 11, 12, 13, 14, 15, 16]),
salt_admin: Some(vec![17, 18, 19, 20, 21, 22, 23, 24]),
initial_hash_user: None,
initial_hash_admin: None,
};
let bytes = kdf.to_bytes();
let parsed = Kdf::parse(&bytes).unwrap();
assert_eq!(parsed, kdf);
}
#[test]
fn test_parse_fingerprints() {
let mut data = vec![0u8; 80]; data[0] = 0xAA; data[20] = 0xBB; let fps = parse_fingerprints(&data);
assert_eq!(fps[&KeyRef::Sig][0], 0xAA);
assert_eq!(fps[&KeyRef::Dec][0], 0xBB);
assert_eq!(fps.len(), 4);
}
#[test]
fn test_parse_timestamps() {
let data = [
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, ];
let ts = parse_timestamps(&data);
assert_eq!(ts[&KeyRef::Sig], 1);
assert_eq!(ts[&KeyRef::Dec], 2);
assert_eq!(ts[&KeyRef::Aut], 3);
assert_eq!(ts[&KeyRef::Att], 4);
}
#[test]
fn test_parse_key_information() {
let data = [0x01, 0x01, 0x02, 0x02, 0x03, 0x00];
let ki = parse_key_information(&data);
assert_eq!(ki[&KeyRef::Sig], KeyStatus::Generated);
assert_eq!(ki[&KeyRef::Dec], KeyStatus::Imported);
assert_eq!(ki[&KeyRef::Aut], KeyStatus::None);
}
#[test]
fn test_build_private_key_template_ec() {
use crate::keys::{EcCurve, EcPrivateKey};
let key =
PrivateKey::Ec(EcPrivateKey::new(EcCurve::P256, vec![0x01, 0x02, 0x03], None).unwrap());
let template = build_private_key_template(KeyRef::Sig, &key).unwrap();
assert_eq!(template[0], 0x4D);
}
#[test]
fn test_build_private_key_template_rsa() {
use crate::keys::{RsaKeySize, RsaPrivateKey};
let key = PrivateKey::Rsa(
RsaPrivateKey::new(
RsaKeySize::Rsa2048,
vec![0xFF; 256],
vec![0x01, 0x00, 0x01],
vec![0xAA; 128],
vec![0xBB; 128],
vec![0xDD; 128],
vec![0xEE; 128],
vec![0xCC; 128],
)
.unwrap(),
);
let template = build_private_key_template(KeyRef::Sig, &key).unwrap();
assert_eq!(template[0], 0x4D);
}
#[test]
fn test_build_private_key_template_rsa_crt() {
use crate::keys::{RsaKeySize, RsaPrivateKey};
let key = PrivateKey::Rsa(
RsaPrivateKey::new(
RsaKeySize::Rsa2048,
vec![0xFF; 256],
vec![0x01, 0x00, 0x01],
vec![0xAA; 128],
vec![0xBB; 128],
vec![0xDD; 128],
vec![0xEE; 128],
vec![0xCC; 128],
)
.unwrap(),
);
let template = build_private_key_template(KeyRef::Sig, &key).unwrap();
assert_eq!(template[0], 0x4D);
let (tag, val_off, val_len, _) = tlv_parse(&template, 0).unwrap();
assert_eq!(tag, 0x4D);
let inner = &template[val_off..val_off + val_len];
assert!(inner.starts_with(&[0xB6, 0x00]));
}
#[test]
fn test_pad_message_eddsa_no_hash() {
let attrs = AlgorithmAttributes::Ec(EcAttributes {
algorithm_id: EC_ALG_EDDSA,
oid: OpenPgpCurve::Ed25519.oid().as_bytes().to_vec(),
import_format: EcImportFormat::Standard,
});
let msg = b"hello world";
let padded = pad_message(&attrs, msg, SignHashAlgorithm::None).unwrap();
assert_eq!(padded, msg);
}
#[test]
fn test_pad_message_rsa_sha256() {
let attrs = AlgorithmAttributes::Rsa(RsaAttributes::create(
RsaKeySize::Rsa2048,
RsaImportFormat::Standard,
));
let msg = b"test message";
let padded = pad_message(&attrs, msg, SignHashAlgorithm::Sha256).unwrap();
assert_eq!(padded.len(), 19 + 32);
assert!(padded.starts_with(&[
0x30, 0x31, 0x30, 0x0D, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
0x01, 0x05, 0x00, 0x04, 0x20
]));
let prehashed = pad_message(
&attrs,
&padded[19..],
SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha256),
)
.unwrap();
assert_eq!(prehashed, padded);
let sha1 = pad_message(&attrs, msg, SignHashAlgorithm::Sha1).unwrap();
assert_eq!(sha1.len(), 15 + 20);
assert!(pad_message(&attrs, msg, SignHashAlgorithm::None).is_err());
}
#[test]
fn test_pad_message_ec_sha256() {
let attrs = AlgorithmAttributes::Ec(EcAttributes {
algorithm_id: EC_ALG_ECDSA,
oid: OpenPgpCurve::Ed25519.oid().as_bytes().to_vec(), import_format: EcImportFormat::Standard,
});
let msg = b"test message";
let padded = pad_message(&attrs, msg, SignHashAlgorithm::Sha256).unwrap();
assert_eq!(padded.len(), 32);
}
#[test]
fn test_pad_message_prehashed_digest_lengths() {
let attributes = [
AlgorithmAttributes::Rsa(RsaAttributes::create(
RsaKeySize::Rsa2048,
RsaImportFormat::Standard,
)),
AlgorithmAttributes::Ec(
EcAttributes::create(KeyRef::Sig, &OpenPgpCurve::P256).unwrap(),
),
];
for attributes in attributes {
for (algorithm, length) in [
(PrehashAlgorithm::Sha1, 20),
(PrehashAlgorithm::Sha256, 32),
(PrehashAlgorithm::Sha384, 48),
(PrehashAlgorithm::Sha512, 64),
] {
for size in [0, length - 1, length, length + 1] {
let digest = vec![0x11; size];
let result = pad_message(
&attributes,
&digest,
SignHashAlgorithm::Prehashed(algorithm),
);
if size == length {
let padded = result.unwrap();
assert!(padded.ends_with(&digest));
if matches!(attributes, AlgorithmAttributes::Ec(_)) {
assert_eq!(padded, digest);
}
} else {
assert!(matches!(
result,
Err(OpenPgpError::InvalidData(message))
if message == format!(
"Prehashed input must contain exactly {length} bytes."
)
));
}
}
}
}
}
#[test]
fn test_pad_message_preserves_raw_ec_and_eddsa_input() {
let message = b"not a digest";
for curve in [OpenPgpCurve::P256, OpenPgpCurve::Ed25519] {
let attributes =
AlgorithmAttributes::Ec(EcAttributes::create(KeyRef::Sig, &curve).unwrap());
assert_eq!(
pad_message(&attributes, message, SignHashAlgorithm::None).unwrap(),
message
);
if matches!(curve, OpenPgpCurve::Ed25519) {
assert_eq!(
pad_message(
&attributes,
message,
SignHashAlgorithm::Prehashed(PrehashAlgorithm::Sha256)
)
.unwrap(),
message
);
}
}
}
#[test]
fn test_require_version_ok() {
assert!(require_version(Version(5, 3, 0), Version(5, 2, 0), "test").is_ok());
}
#[test]
fn test_require_version_fail() {
let err = require_version(Version(4, 1, 0), Version(5, 2, 0), "test").unwrap_err();
match err {
OpenPgpError::NotSupported(msg) => assert!(msg.contains("test")),
_ => panic!("Expected NotSupported"),
}
}
#[test]
fn test_bytes2int() {
assert_eq!(bytes2int(&[]), 0);
assert_eq!(bytes2int(&[0x01]), 1);
assert_eq!(bytes2int(&[0x01, 0x00]), 256);
assert_eq!(bytes2int(&[0xFF, 0xFF]), 65535);
}
#[test]
fn test_key_ref_all() {
assert_eq!(KeyRef::ALL.len(), 4);
assert_eq!(KeyRef::ALL[0], KeyRef::Sig);
assert_eq!(KeyRef::ALL[3], KeyRef::Att);
}
#[test]
fn test_pin_policy_from_u8() {
assert_eq!(PinPolicy::from_u8(0x00), PinPolicy::Always);
assert_eq!(PinPolicy::from_u8(0x01), PinPolicy::Once);
assert_eq!(PinPolicy::from_u8(0xFF), PinPolicy::Always); }
#[test]
fn test_key_ref_associated_dos() {
assert_eq!(
KeyRef::Sig.algorithm_attributes_do() as u16,
Do::AlgorithmAttributesSig as u16
);
assert_eq!(KeyRef::Dec.uif_do() as u16, Do::UifDec as u16);
assert_eq!(
KeyRef::Aut.generation_time_do() as u16,
Do::GenerationTimeAut as u16
);
assert_eq!(
KeyRef::Att.fingerprint_do() as u16,
Do::FingerprintAtt as u16
);
}
}