Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/openssh-compatibility-status.md

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions src/ssh/security_key/internal/ctap2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ impl CosePublicKey {

const PIN_SUB_GET_KEY_AGREEMENT: i64 = 0x02;
const PIN_SUB_GET_PIN_TOKEN: i64 = 0x05;
const PIN_SUB_GET_UV_TOKEN_WITH_PERMISSIONS: i64 = 0x06;
const PIN_SUB_GET_PIN_TOKEN_WITH_PERMISSIONS: i64 = 0x09;
/// `pinUvAuthToken` permission bit for `getAssertion`.
pub const PERMISSION_GET_ASSERTION: i64 = 0x02;
Expand Down Expand Up @@ -350,6 +351,30 @@ pub fn encode_client_pin_get_token(
out
}

/// `getPinUvAuthTokenUsingUvWithPermissions` (0x06). Unlike the PIN
/// variants, this request deliberately carries no `pinHashEnc`: the
/// authenticator performs user verification through its built-in method.
#[must_use]
pub fn encode_client_pin_get_uv_token(
protocol: u64,
platform_key: &CosePublicKey,
permissions: (i64, &str),
) -> Vec<u8> {
let (bits, rp_id) = permissions;
let mut out = vec![CMD_CLIENT_PIN];
out.extend(cbor::encode(&Value::Map(vec![
(Value::Int(1), Value::Int(protocol as i64)),
(
Value::Int(2),
Value::Int(PIN_SUB_GET_UV_TOKEN_WITH_PERMISSIONS),
),
(Value::Int(3), platform_key.to_value()),
(Value::Int(9), Value::Int(bits)),
(Value::Int(10), Value::from(rp_id)),
])));
out
}

/// The still-encrypted `pinUvAuthToken`.
pub fn parse_pin_token(response: &[u8]) -> Result<Zeroizing<Vec<u8>>, CtapError> {
let map = cbor::decode(response_body(response)?)?;
Expand Down
11 changes: 11 additions & 0 deletions src/ssh/security_key/internal/ctap2_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,17 @@ fn client_pin_requests_select_the_subcommand_and_carry_permissions() {
decoded.get_int(6).unwrap().as_bytes(),
Some(&[0x9c; 32][..])
);

let uv = encode_client_pin_get_uv_token(2, &platform, (PERMISSION_GET_ASSERTION, "ssh:"));
assert_eq!(&uv[..6], &[0x06, 0xa5, 0x01, 0x02, 0x02, 0x06]);
let decoded = cbor::decode(&uv[1..]).unwrap();
assert_eq!(
CosePublicKey::from_value(decoded.get_int(3).unwrap()).unwrap(),
platform
);
assert_eq!(decoded.get_int(6), None, "UV token request has no PIN hash");
assert_eq!(decoded.get_int(9).and_then(Value::as_int), Some(0x02));
assert_eq!(decoded.get_int(10).and_then(Value::as_text), Some("ssh:"));
}

#[test]
Expand Down
63 changes: 52 additions & 11 deletions src/ssh/security_key/internal/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use zeroize::Zeroizing;

use super::ctap2::{self, AuthenticatorInfo, GetAssertionRequest, PERMISSION_GET_ASSERTION};
use super::ctaphid::{CMD_CBOR, CMD_MSG, CtapHidChannel, HidBackend, HidDeviceInfo, remaining};
use super::pin_protocol::{PinProtocol, PlatformKeyAgreement, authenticate_with};
use super::pin_protocol::{PinProtocol, PlatformKeyAgreement, SharedSecret, authenticate_with};
use super::u2f;
use super::{CtapError, UserPresence};

Expand Down Expand Up @@ -182,14 +182,21 @@ impl Authenticator {
let param = Zeroizing::new(authenticate_with(protocol, &token, client_data_hash));
Some((param, protocol))
}
None if request.uv == Some(true) && info.supports_permissions() => {
let (token, protocol) = self.uv_token(info, request.rp_id, deadline, rng)?;
let param = Zeroizing::new(authenticate_with(protocol, &token, client_data_hash));
Some((param, protocol))
}
None => None,
};
let encoded = ctap2::encode_get_assertion(&GetAssertionRequest {
rp_id: request.rp_id,
client_data_hash,
credential_id: request.credential_id,
up: request.up,
uv: request.uv,
// A PIN/UV token proves verification; CTAP 2.1 requires the
// assertion's `uv` option to be omitted in this path.
uv: if pin_auth.is_some() { None } else { request.uv },
pin_auth: pin_auth
.as_ref()
.map(|(param, protocol)| (&param[..], protocol.number())),
Expand All @@ -215,15 +222,7 @@ impl Authenticator {
deadline: Instant,
rng: &mut R,
) -> Result<(Zeroizing<Vec<u8>>, PinProtocol), CtapError> {
let protocol = PinProtocol::select(&info.pin_protocols);
let platform = PlatformKeyAgreement::generate(rng);
let reply = self.channel.transact(
CMD_CBOR,
&ctap2::encode_client_pin_key_agreement(protocol.number()),
Some(remaining(deadline)?),
)?;
let peer = ctap2::parse_key_agreement(&reply)?;
let secret = platform.shared_secret(protocol, &peer)?;
let (platform, secret, protocol) = self.key_agreement(info, deadline, rng)?;
let pin_hash_enc = secret.encrypt_pin_hash(pin, rng)?;
let permissions = info
.supports_permissions()
Expand All @@ -242,6 +241,48 @@ impl Authenticator {
Ok((token, protocol))
}

/// CTAP 2.1 `getPinUvAuthTokenUsingUvWithPermissions`: let the
/// authenticator perform built-in verification and issue a token without
/// a PIN or `pinHashEnc`.
fn uv_token<R: rand::CryptoRng + ?Sized>(
&mut self,
info: &AuthenticatorInfo,
rp_id: &str,
deadline: Instant,
rng: &mut R,
) -> Result<(Zeroizing<Vec<u8>>, PinProtocol), CtapError> {
let (platform, secret, protocol) = self.key_agreement(info, deadline, rng)?;
let reply = self.channel.transact(
CMD_CBOR,
&ctap2::encode_client_pin_get_uv_token(
protocol.number(),
platform.public_key(),
(PERMISSION_GET_ASSERTION, rp_id),
),
Some(remaining(deadline)?),
)?;
let token = secret.decrypt(&ctap2::parse_pin_token(&reply)?)?;
Ok((token, protocol))
}

fn key_agreement<R: rand::CryptoRng + ?Sized>(
&mut self,
info: &AuthenticatorInfo,
deadline: Instant,
rng: &mut R,
) -> Result<(PlatformKeyAgreement, SharedSecret, PinProtocol), CtapError> {
let protocol = PinProtocol::select(&info.pin_protocols);
let platform = PlatformKeyAgreement::generate(rng);
let reply = self.channel.transact(
CMD_CBOR,
&ctap2::encode_client_pin_key_agreement(protocol.number()),
Some(remaining(deadline)?),
)?;
let peer = ctap2::parse_key_agreement(&reply)?;
let secret = platform.shared_secret(protocol, &peer)?;
Ok((platform, secret, protocol))
}

/// `u2f_authenticate`: look the key handle up with a check-only request,
/// then sign with user presence enforced, retrying while the device
/// reports that the user has not touched it yet.
Expand Down
3 changes: 3 additions & 0 deletions src/ssh/security_key/internal/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ pub struct MockAuthenticator {
pub u2f_presence_retries: usize,
/// Answer every getAssertion with this status instead of signing.
pub forced_status: Option<u8>,
/// Answer `getPinUvAuthTokenUsingUvWithPermissions` with this status.
pub uv_token_status: Option<u8>,
pub requests: Vec<Request>,
pub cancels: usize,
cid: [u8; 4],
Expand All @@ -189,6 +191,7 @@ impl MockAuthenticator {
stall: None,
u2f_presence_retries: 0,
forced_status: None,
uv_token_status: None,
requests: Vec::new(),
cancels: 0,
cid: [0x0b, 0x55, 0x47, 0x01],
Expand Down
24 changes: 19 additions & 5 deletions src/ssh/security_key/internal/mock_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ impl MockAuthenticator {
.get_int(9)
.and_then(Value::as_int)
.and_then(|bits| Some((bits, map.get_int(10)?.as_text()?.to_string())));
let has_permissions = permissions.is_some();
self.requests.push(Request::ClientPin {
subcommand,
protocol: protocol_number,
Expand All @@ -185,17 +186,30 @@ impl MockAuthenticator {
self.agreement = Some(agreement);
Some(reply)
}
0x05 | 0x09 => {
0x05 | 0x06 | 0x09 => {
let platform = CosePublicKey::from_value(map.get_int(3)?).ok()?;
let secret: SharedSecret = self
.agreement
.as_ref()?
.shared_secret(protocol, &platform)
.ok()?;
let pin_hash = secret.decrypt(map.get_int(6)?.as_bytes()?).ok()?;
let expected = Sha256::digest(config.pin.as_deref()?.as_bytes());
if pin_hash[..] != expected[..16] {
return Some(vec![status::PIN_INVALID]);
if subcommand == 0x06 {
if let Some(status) = self.uv_token_status {
return Some(vec![status]);
}
if config.options.get("uv") != Some(&true)
|| config.options.get("pinUvAuthToken") != Some(&true)
|| !has_permissions
|| map.get_int(6).is_some()
{
return Some(vec![status::INVALID_OPTION]);
}
} else {
let pin_hash = secret.decrypt(map.get_int(6)?.as_bytes()?).ok()?;
let expected = Sha256::digest(config.pin.as_deref()?.as_bytes());
if pin_hash[..] != expected[..16] {
return Some(vec![status::PIN_INVALID]);
}
}
let token = secret
.encrypt(&self.pin_token, &mut rand::rng())
Expand Down
4 changes: 4 additions & 0 deletions src/ssh/security_key/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,10 @@ mod tests;
#[path = "selection_tests.rs"]
mod selection_tests;

#[cfg(test)]
#[path = "uv_token_tests.rs"]
mod uv_token_tests;

#[cfg(test)]
#[path = "robustness_tests.rs"]
mod robustness_tests;
1 change: 1 addition & 0 deletions src/ssh/security_key/internal/selection_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ fn verify_required_without_a_pin_needs_one_unless_the_device_verifies_itself() {
"nothing is sent before the PIN is known"
);

// CTAP 2.0 keeps the direct `options.uv = true` path.
let mut biometric = Fido2Config::plain();
biometric.options.insert("uv".to_string(), true);
let (provider, devices) = provider_with(vec![(
Expand Down
116 changes: 116 additions & 0 deletions src/ssh/security_key/internal/uv_token_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! CTAP 2.1 built-in user verification token flows.

use super::mock::{CredentialKey, Fido2Config, Request};
use super::tests::{APPLICATION, fido2, provider_with, public_key, request, verify};
use super::*;
use crate::ssh::security_key::encode_signature;

fn biometric(protocol: u64) -> Fido2Config {
let mut config = Fido2Config::with_pin("123456");
config.options.insert("uv".to_string(), true);
config.pin_protocols = vec![protocol];
config
}

#[test]
fn a_built_in_sensor_obtains_a_uv_token_without_a_pin() {
for protocol in [1_u64, 2] {
let (provider, devices) = provider_with(vec![(
"/dev/hidraw1",
fido2(
biometric(protocol),
Some(CredentialKey::ed25519(protocol as u8)),
),
)]);
let response = provider
.sign(&request(SkAlgorithm::Ed25519, 0x05), None)
.unwrap();
assert_eq!(response.flags, 0x05);
verify(
&public_key(&devices[0].lock().unwrap()),
&encode_signature(SkAlgorithm::Ed25519, &response).unwrap(),
);
let device = devices[0].lock().unwrap();
assert!(device.requests.contains(&Request::ClientPin {
subcommand: 0x06,
protocol: protocol as i64,
permissions: Some((0x02, APPLICATION.to_string())),
}));
assert!(matches!(
device.assertion_requests()[0],
Request::GetAssertion {
uv: None,
pin_auth: Some((param, actual_protocol)),
..
} if *actual_protocol == protocol as i64
&& param.len() == if protocol == 1 { 16 } else { 32 }
));
}
}

#[test]
fn a_refused_uv_token_prompts_for_a_pin_then_retries_with_subcommand_0x09() {
for protocol in [1_u64, 2] {
let mut authenticator = fido2(
biometric(protocol),
Some(CredentialKey::ed25519(protocol as u8)),
);
authenticator.uv_token_status = Some(ctap2::status::PIN_REQUIRED);
let (provider, devices) = provider_with(vec![("/dev/hidraw1", authenticator)]);

assert_eq!(
provider
.sign(&request(SkAlgorithm::Ed25519, 0x05), None)
.unwrap_err(),
SecurityKeyError::PinRequired
);
provider
.sign(&request(SkAlgorithm::Ed25519, 0x05), Some("123456"))
.unwrap();

let device = devices[0].lock().unwrap();
let client_pin = device
.requests
.iter()
.filter_map(|request| match request {
Request::ClientPin {
subcommand,
protocol,
..
} => Some((*subcommand, *protocol)),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(
client_pin,
[
(0x02, protocol as i64),
(0x06, protocol as i64),
(0x02, protocol as i64),
(0x09, protocol as i64),
]
);
assert!(matches!(
device.assertion_requests()[0],
Request::GetAssertion {
uv: None,
pin_auth: Some((_, actual_protocol)),
..
} if *actual_protocol == protocol as i64
));
}
}
Loading