generated from ali/HarmonyTemplate
提交 Haven Android 仓库源码 v5.87.79
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "sh.haven.core.fido"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":core:usb"))
|
||||
implementation(libs.jsch)
|
||||
implementation(libs.bouncycastle)
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.mockk)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest />
|
||||
@@ -0,0 +1,934 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/**
|
||||
* Minimal CBOR encoder/decoder for the CTAP2 commands Haven uses:
|
||||
* - authenticatorGetInfo (0x04) — capabilities, supported PIN protocols.
|
||||
* - authenticatorClientPIN (0x06) — keyAgreement and PIN/UV token retrieval.
|
||||
* - authenticatorGetAssertion (0x02) — the actual SSH signing operation.
|
||||
*
|
||||
* Implements the subset of CBOR (RFC 8949) needed by these commands:
|
||||
* unsigned ints, negative ints, byte strings, text strings, arrays, maps,
|
||||
* and booleans. Integer keys can be positive or negative (COSE_Key uses both).
|
||||
*/
|
||||
object Ctap2Cbor {
|
||||
|
||||
// CTAP2 command bytes
|
||||
const val CMD_MAKE_CREDENTIAL: Byte = 0x01
|
||||
const val CMD_GET_ASSERTION: Byte = 0x02
|
||||
const val CMD_GET_INFO: Byte = 0x04
|
||||
const val CMD_CLIENT_PIN: Byte = 0x06
|
||||
const val CMD_CREDENTIAL_MANAGEMENT: Byte = 0x0A
|
||||
|
||||
/**
|
||||
* `authenticatorCredentialManagementPreview` — the CTAP 2.1-PRE prototype
|
||||
* of 0x0A, carried as a vendor command. Keys that predate the standardised
|
||||
* version (YubiKey firmware < 5.5) answer only this one (#449).
|
||||
*/
|
||||
const val CMD_CREDENTIAL_MANAGEMENT_PREVIEW: Byte = 0x41
|
||||
|
||||
// COSE algorithm identifiers (used in MakeCredential pubKeyCredParams)
|
||||
const val COSE_ALG_EDDSA = -8 // Ed25519 -> sk-ssh-ed25519@openssh.com
|
||||
const val COSE_ALG_ES256 = -7 // ECDSA P-256 -> sk-ecdsa-sha2-nistp256@openssh.com
|
||||
|
||||
// CTAP2 status codes
|
||||
const val STATUS_OK: Byte = 0x00
|
||||
const val STATUS_PIN_INVALID: Byte = 0x31
|
||||
const val STATUS_PIN_BLOCKED: Byte = 0x32
|
||||
const val STATUS_PIN_AUTH_INVALID: Byte = 0x33
|
||||
const val STATUS_PIN_AUTH_BLOCKED: Byte = 0x34
|
||||
const val STATUS_PIN_NOT_SET: Byte = 0x35
|
||||
const val STATUS_PIN_REQUIRED: Byte = 0x36
|
||||
const val STATUS_PIN_POLICY_VIOLATION: Byte = 0x37
|
||||
const val STATUS_PIN_TOKEN_EXPIRED: Byte = 0x38
|
||||
const val STATUS_NO_CREDENTIALS: Byte = 0x2E
|
||||
const val STATUS_ACTION_TIMEOUT: Byte = 0x27
|
||||
|
||||
// clientPIN subcommand codes
|
||||
const val PIN_SUB_GET_KEY_AGREEMENT = 2
|
||||
const val PIN_SUB_SET_PIN = 3
|
||||
const val PIN_SUB_CHANGE_PIN = 4
|
||||
const val PIN_SUB_GET_PIN_TOKEN_LEGACY = 5
|
||||
const val PIN_SUB_GET_PIN_TOKEN_WITH_PERMS = 9
|
||||
|
||||
// PIN/UV permission bits (FIDO2 §6.5.5.7)
|
||||
const val PERMISSION_MAKE_CREDENTIAL = 0x01
|
||||
const val PERMISSION_GET_ASSERTION = 0x02
|
||||
const val PERMISSION_CREDENTIAL_MANAGEMENT = 0x04
|
||||
|
||||
// authenticatorData flag bits (WebAuthn §6.1)
|
||||
const val AUTHDATA_FLAG_USER_PRESENT = 0x01
|
||||
const val AUTHDATA_FLAG_USER_VERIFIED = 0x04
|
||||
const val AUTHDATA_FLAG_ATTESTED_CREDENTIAL_DATA = 0x40
|
||||
|
||||
// authenticatorCredentialManagement subcommands (CTAP 2.1 §6.8.2)
|
||||
const val CM_SUB_GET_CREDS_METADATA = 1
|
||||
const val CM_SUB_ENUMERATE_RPS_BEGIN = 2
|
||||
const val CM_SUB_ENUMERATE_RPS_GET_NEXT = 3
|
||||
const val CM_SUB_ENUMERATE_CREDS_BEGIN = 4
|
||||
const val CM_SUB_ENUMERATE_CREDS_GET_NEXT = 5
|
||||
|
||||
data class AssertionResponse(
|
||||
val authData: ByteArray,
|
||||
val signature: ByteArray,
|
||||
/**
|
||||
* The credential the authenticator actually used (response key 1's
|
||||
* `id`), present when the request's allowList had more than one entry —
|
||||
* which is how the either/or flow learns *which* of several configured
|
||||
* SK keys the user presented. Null for single-credential requests.
|
||||
*/
|
||||
val usedCredentialId: ByteArray? = null,
|
||||
)
|
||||
|
||||
/** Parsed authenticatorGetInfo response (only the fields Haven uses). */
|
||||
data class GetInfoResponse(
|
||||
val pinUvAuthProtocols: List<Int>,
|
||||
val clientPinSet: Boolean,
|
||||
/** Built-in user verification (biometric) is configured. */
|
||||
val uvBuiltIn: Boolean,
|
||||
/**
|
||||
* `pinUvAuthToken: true` in GetInfo options means the authenticator
|
||||
* implements CTAP 2.1 `getPinUvAuthTokenUsingPinWithPermissions`
|
||||
* (subCommand 0x09). Older CTAP 2.0 / 2.1-PRE keys (e.g. YubiKey 5
|
||||
* shipped before mid-2021) only support the legacy `getPinToken`
|
||||
* (subCommand 0x05); calling 0x09 on them returns INVALID_COMMAND.
|
||||
*/
|
||||
val pinUvAuthTokenSupported: Boolean,
|
||||
/**
|
||||
* `credMgmt: true` — the authenticator implements the STANDARDISED
|
||||
* CTAP 2.1 `authenticatorCredentialManagement` command (0x0A).
|
||||
*/
|
||||
val credMgmtSupported: Boolean,
|
||||
/**
|
||||
* `credentialMgmtPreview: true` — the authenticator only implements the
|
||||
* CTAP 2.1-PRE prototype of the same feature, under vendor command
|
||||
* 0x41. YubiKey firmware before 5.5 (e.g. 5.4.3) is in this group:
|
||||
* sending the standard 0x0A returns CTAP1_ERR_INVALID_COMMAND (0x01).
|
||||
*/
|
||||
val credMgmtPreviewSupported: Boolean,
|
||||
)
|
||||
|
||||
/** Authenticator's COSE_Key from clientPIN getKeyAgreement (P-256 only). */
|
||||
data class CoseEcdhPubKey(val x: ByteArray, val y: ByteArray)
|
||||
|
||||
// ---------- authenticatorGetAssertion ----------
|
||||
|
||||
/**
|
||||
* Encode authenticatorGetAssertion. When [pinUvAuthParam] is non-null,
|
||||
* the request also carries the PIN/UV auth proof under keys 6 and 7.
|
||||
*/
|
||||
fun encodeGetAssertionCommand(
|
||||
rpId: String,
|
||||
clientDataHash: ByteArray,
|
||||
credentialId: ByteArray,
|
||||
pinUvAuthParam: ByteArray? = null,
|
||||
pinUvAuthProtocol: Int? = null,
|
||||
up: Boolean = true,
|
||||
): ByteArray = encodeGetAssertionCommand(
|
||||
rpId, clientDataHash, listOf(credentialId), pinUvAuthParam, pinUvAuthProtocol, up,
|
||||
)
|
||||
|
||||
/**
|
||||
* Multi-credential variant: the allowList carries every [credentialIds]
|
||||
* entry, so whichever security key is presented signs with the credential
|
||||
* it actually holds — the basis of the either/or flow (#237). [up] = false
|
||||
* does a presence-free probe used only to detect *which* key is present
|
||||
* (the real signing assertion still uses up = true).
|
||||
*/
|
||||
fun encodeGetAssertionCommand(
|
||||
rpId: String,
|
||||
clientDataHash: ByteArray,
|
||||
credentialIds: List<ByteArray>,
|
||||
pinUvAuthParam: ByteArray? = null,
|
||||
pinUvAuthProtocol: Int? = null,
|
||||
up: Boolean = true,
|
||||
): ByteArray {
|
||||
require(credentialIds.isNotEmpty()) { "allowList must have at least one credential" }
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(CMD_GET_ASSERTION.toInt())
|
||||
|
||||
val mapEntries = if (pinUvAuthParam != null) 6 else 4
|
||||
encodeMapHeader(out, mapEntries)
|
||||
|
||||
// 1: rpId
|
||||
encodeUint(out, 1)
|
||||
encodeTextString(out, rpId)
|
||||
|
||||
// 2: clientDataHash
|
||||
encodeUint(out, 2)
|
||||
encodeByteString(out, clientDataHash)
|
||||
|
||||
// 3: allowList[{id, type}, …]
|
||||
encodeUint(out, 3)
|
||||
encodeArrayHeader(out, credentialIds.size)
|
||||
for (credentialId in credentialIds) {
|
||||
encodeMapHeader(out, 2)
|
||||
encodeTextString(out, "id")
|
||||
encodeByteString(out, credentialId)
|
||||
encodeTextString(out, "type")
|
||||
encodeTextString(out, "public-key")
|
||||
}
|
||||
|
||||
// 5: options {up}
|
||||
encodeUint(out, 5)
|
||||
encodeMapHeader(out, 1)
|
||||
encodeTextString(out, "up")
|
||||
encodeBoolean(out, up)
|
||||
|
||||
// 6, 7: pinUvAuthParam + protocol (only when UV path is in use)
|
||||
if (pinUvAuthParam != null) {
|
||||
requireNotNull(pinUvAuthProtocol) { "pinUvAuthProtocol required when pinUvAuthParam set" }
|
||||
encodeUint(out, 6)
|
||||
encodeByteString(out, pinUvAuthParam)
|
||||
encodeUint(out, 7)
|
||||
encodeUint(out, pinUvAuthProtocol)
|
||||
}
|
||||
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
fun decodeGetAssertionResponse(data: ByteArray): AssertionResponse {
|
||||
val buf = ByteBuffer.wrap(data)
|
||||
val mapSize = readMapHeader(buf)
|
||||
|
||||
var authData: ByteArray? = null
|
||||
var signature: ByteArray? = null
|
||||
var usedCredentialId: ByteArray? = null
|
||||
|
||||
for (i in 0 until mapSize) {
|
||||
val key = readSignedInt(buf)
|
||||
when (key) {
|
||||
1 -> usedCredentialId = readCredentialDescriptorId(buf)
|
||||
2 -> authData = readByteString(buf)
|
||||
3 -> signature = readByteString(buf)
|
||||
else -> skipValue(buf)
|
||||
}
|
||||
}
|
||||
|
||||
requireNotNull(authData) { "GetAssertion response missing authData (key 2)" }
|
||||
requireNotNull(signature) { "GetAssertion response missing signature (key 3)" }
|
||||
return AssertionResponse(authData, signature, usedCredentialId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a PublicKeyCredentialDescriptor map (`{id: bytes, type: tstr, …}`)
|
||||
* and return its `id`. Used to learn which credential a multi-credential
|
||||
* GetAssertion actually matched.
|
||||
*/
|
||||
private fun readCredentialDescriptorId(buf: ByteBuffer): ByteArray? {
|
||||
val size = readMapHeader(buf)
|
||||
var id: ByteArray? = null
|
||||
for (i in 0 until size) {
|
||||
if (readTextString(buf) == "id") id = readByteString(buf) else skipValue(buf)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// ---------- authenticatorMakeCredential ----------
|
||||
|
||||
/** A credential's COSE public key plus its handle, parsed from authData. */
|
||||
data class AttestedCredential(
|
||||
val aaguid: ByteArray,
|
||||
val credentialId: ByteArray,
|
||||
val publicKey: CosePublicKey,
|
||||
val flags: Byte,
|
||||
val signCount: Int,
|
||||
)
|
||||
|
||||
/** Parsed authenticatorMakeCredential response (only the fields Haven uses). */
|
||||
data class MakeCredentialResponse(
|
||||
val fmt: String?,
|
||||
val authData: ByteArray,
|
||||
)
|
||||
|
||||
/**
|
||||
* Encode authenticatorMakeCredential (0x01) for SSH-SK registration.
|
||||
*
|
||||
* Request map:
|
||||
* 1: clientDataHash, 2: rp{id,name}, 3: user{id,name,displayName},
|
||||
* 4: pubKeyCredParams [{alg,type}...], 7: options{rk} (when [residentKey]),
|
||||
* 8: pinUvAuthParam + 9: pinUvAuthProtocol (when [pinUvAuthParam] set).
|
||||
*
|
||||
* Providing [pinUvAuthParam] is how UV is conveyed; `options.uv` is left
|
||||
* unset per CTAP2. [algorithms] are COSE alg ids in preference order
|
||||
* (e.g. [COSE_ALG_EDDSA] for sk-ssh-ed25519).
|
||||
*/
|
||||
fun encodeMakeCredentialCommand(
|
||||
clientDataHash: ByteArray,
|
||||
rpId: String,
|
||||
rpName: String,
|
||||
userId: ByteArray,
|
||||
userName: String,
|
||||
userDisplayName: String,
|
||||
algorithms: List<Int>,
|
||||
residentKey: Boolean,
|
||||
pinUvAuthParam: ByteArray? = null,
|
||||
pinUvAuthProtocol: Int? = null,
|
||||
): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(CMD_MAKE_CREDENTIAL.toInt())
|
||||
|
||||
var entries = 4 // keys 1..4 always present
|
||||
if (residentKey) entries++ // 7: options
|
||||
if (pinUvAuthParam != null) entries += 2 // 8 + 9
|
||||
encodeMapHeader(out, entries)
|
||||
|
||||
// 1: clientDataHash
|
||||
encodeUint(out, 1); encodeByteString(out, clientDataHash)
|
||||
|
||||
// 2: rp { id, name }
|
||||
encodeUint(out, 2)
|
||||
encodeMapHeader(out, 2)
|
||||
encodeTextString(out, "id"); encodeTextString(out, rpId)
|
||||
encodeTextString(out, "name"); encodeTextString(out, rpName)
|
||||
|
||||
// 3: user { id, name, displayName }
|
||||
encodeUint(out, 3)
|
||||
encodeMapHeader(out, 3)
|
||||
encodeTextString(out, "id"); encodeByteString(out, userId)
|
||||
encodeTextString(out, "name"); encodeTextString(out, userName)
|
||||
encodeTextString(out, "displayName"); encodeTextString(out, userDisplayName)
|
||||
|
||||
// 4: pubKeyCredParams [ { alg, type } ]
|
||||
encodeUint(out, 4)
|
||||
encodeArrayHeader(out, algorithms.size)
|
||||
for (alg in algorithms) {
|
||||
encodeMapHeader(out, 2)
|
||||
encodeTextString(out, "alg"); encodeInt(out, alg)
|
||||
encodeTextString(out, "type"); encodeTextString(out, "public-key")
|
||||
}
|
||||
|
||||
// 7: options { rk: true }
|
||||
if (residentKey) {
|
||||
encodeUint(out, 7)
|
||||
encodeMapHeader(out, 1)
|
||||
encodeTextString(out, "rk"); encodeBoolean(out, true)
|
||||
}
|
||||
|
||||
// 8, 9: pinUvAuthParam + protocol
|
||||
if (pinUvAuthParam != null) {
|
||||
requireNotNull(pinUvAuthProtocol) { "pinUvAuthProtocol required when pinUvAuthParam set" }
|
||||
encodeUint(out, 8); encodeByteString(out, pinUvAuthParam)
|
||||
encodeUint(out, 9); encodeUint(out, pinUvAuthProtocol)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/** Decode an authenticatorMakeCredential response payload (status byte stripped). */
|
||||
fun decodeMakeCredentialResponse(data: ByteArray): MakeCredentialResponse {
|
||||
val buf = ByteBuffer.wrap(data)
|
||||
val mapSize = readMapHeader(buf)
|
||||
var fmt: String? = null
|
||||
var authData: ByteArray? = null
|
||||
for (i in 0 until mapSize) {
|
||||
val key = readSignedInt(buf)
|
||||
when (key) {
|
||||
1 -> fmt = readTextString(buf)
|
||||
2 -> authData = readByteString(buf)
|
||||
else -> skipValue(buf) // 3: attStmt (unused — no attestation verification)
|
||||
}
|
||||
}
|
||||
requireNotNull(authData) { "MakeCredential response missing authData (key 2)" }
|
||||
return MakeCredentialResponse(fmt, authData)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the attestedCredentialData out of a MakeCredential authData:
|
||||
* rpIdHash(32) | flags(1) | signCount(4) | aaguid(16) |
|
||||
* credIdLen(2, big-endian) | credentialId | credentialPublicKey(COSE).
|
||||
* Requires the AT (attested-credential-data) flag bit to be set.
|
||||
*/
|
||||
fun parseAttestedCredentialData(authData: ByteArray): AttestedCredential {
|
||||
require(authData.size >= 37 + 16 + 2) {
|
||||
"authData too short for attested credential: ${authData.size}"
|
||||
}
|
||||
val flags = authData[32]
|
||||
require(flags.toInt() and AUTHDATA_FLAG_ATTESTED_CREDENTIAL_DATA != 0) {
|
||||
"authData has no attested credential data (AT flag unset)"
|
||||
}
|
||||
val signCount = ((authData[33].toInt() and 0xFF) shl 24) or
|
||||
((authData[34].toInt() and 0xFF) shl 16) or
|
||||
((authData[35].toInt() and 0xFF) shl 8) or
|
||||
(authData[36].toInt() and 0xFF)
|
||||
val aaguid = authData.copyOfRange(37, 53)
|
||||
val credIdLen = ((authData[53].toInt() and 0xFF) shl 8) or (authData[54].toInt() and 0xFF)
|
||||
val credIdStart = 55
|
||||
val credIdEnd = credIdStart + credIdLen
|
||||
require(credIdEnd <= authData.size) { "credentialId length $credIdLen overruns authData" }
|
||||
val credentialId = authData.copyOfRange(credIdStart, credIdEnd)
|
||||
// The credential public key is the trailing COSE_Key CBOR map.
|
||||
val coseBuf = ByteBuffer.wrap(authData, credIdEnd, authData.size - credIdEnd)
|
||||
val publicKey = decodeCoseAuthenticatorPublicKey(coseBuf)
|
||||
return AttestedCredential(aaguid, credentialId, publicKey, flags, signCount)
|
||||
}
|
||||
|
||||
// ---------- authenticatorGetInfo ----------
|
||||
|
||||
/** GetInfo has no payload — just the command byte. */
|
||||
fun encodeGetInfoCommand(): ByteArray = byteArrayOf(CMD_GET_INFO)
|
||||
|
||||
fun decodeGetInfoResponse(data: ByteArray): GetInfoResponse {
|
||||
val buf = ByteBuffer.wrap(data)
|
||||
val mapSize = readMapHeader(buf)
|
||||
|
||||
var pinProtocols: List<Int> = emptyList()
|
||||
var clientPin = false
|
||||
var uv = false
|
||||
var pinUvAuthToken = false
|
||||
var credMgmt = false
|
||||
var credMgmtPreview = false
|
||||
|
||||
for (i in 0 until mapSize) {
|
||||
val key = readSignedInt(buf)
|
||||
when (key) {
|
||||
4 -> { // options: map<text, bool>
|
||||
val optSize = readMapHeader(buf)
|
||||
for (j in 0 until optSize) {
|
||||
val optKey = readTextString(buf)
|
||||
val optVal = readBoolean(buf)
|
||||
when (optKey) {
|
||||
"clientPin" -> clientPin = optVal
|
||||
"uv" -> uv = optVal
|
||||
"pinUvAuthToken" -> pinUvAuthToken = optVal
|
||||
"credMgmt" -> credMgmt = optVal
|
||||
"credentialMgmtPreview" -> credMgmtPreview = optVal
|
||||
}
|
||||
}
|
||||
}
|
||||
6 -> { // pinUvAuthProtocols: array of uint
|
||||
val n = readArrayHeader(buf)
|
||||
pinProtocols = (0 until n).map { readSignedInt(buf) }
|
||||
}
|
||||
else -> skipValue(buf)
|
||||
}
|
||||
}
|
||||
|
||||
return GetInfoResponse(
|
||||
pinUvAuthProtocols = pinProtocols,
|
||||
clientPinSet = clientPin,
|
||||
uvBuiltIn = uv,
|
||||
pinUvAuthTokenSupported = pinUvAuthToken,
|
||||
credMgmtSupported = credMgmt,
|
||||
credMgmtPreviewSupported = credMgmtPreview,
|
||||
)
|
||||
}
|
||||
|
||||
// ---------- authenticatorClientPIN ----------
|
||||
|
||||
/** clientPIN subcommand 2 (getKeyAgreement) — body { 1: protocol, 2: 2 }. */
|
||||
fun encodeClientPinGetKeyAgreement(protocol: Int): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(CMD_CLIENT_PIN.toInt())
|
||||
encodeMapHeader(out, 2)
|
||||
encodeUint(out, 1); encodeUint(out, protocol)
|
||||
encodeUint(out, 2); encodeUint(out, PIN_SUB_GET_KEY_AGREEMENT)
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* clientPIN subcommand 5 (getPinToken — legacy CTAP 2.0):
|
||||
* { 1: protocol, 2: 5, 3: platformKeyAgreement (COSE_Key), 6: pinHashEnc }
|
||||
*
|
||||
* Returned token is implicitly bound to GetAssertion + MakeCredential
|
||||
* permissions on every rpId — the per-permission/per-rpId scoping that
|
||||
* subCommand 9 introduced is unavailable here. Use this when GetInfo's
|
||||
* `options.pinUvAuthToken` is absent or false.
|
||||
*/
|
||||
fun encodeClientPinGetTokenLegacy(
|
||||
protocol: Int,
|
||||
platformKeyAgreement: CoseEcdhPubKey,
|
||||
pinHashEnc: ByteArray,
|
||||
): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(CMD_CLIENT_PIN.toInt())
|
||||
encodeMapHeader(out, 4)
|
||||
encodeUint(out, 1); encodeUint(out, protocol)
|
||||
encodeUint(out, 2); encodeUint(out, PIN_SUB_GET_PIN_TOKEN_LEGACY)
|
||||
encodeUint(out, 3); encodeCoseEcdhKey(out, platformKeyAgreement)
|
||||
encodeUint(out, 6); encodeByteString(out, pinHashEnc)
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* clientPIN subcommand 9 (getPinUvAuthTokenUsingPinWithPermissions):
|
||||
* { 1: protocol, 2: 9, 3: platformKeyAgreement (COSE_Key),
|
||||
* 6: pinHashEnc, 9: permissions, 10: rpId }
|
||||
*/
|
||||
fun encodeClientPinGetTokenWithPermissions(
|
||||
protocol: Int,
|
||||
platformKeyAgreement: CoseEcdhPubKey,
|
||||
pinHashEnc: ByteArray,
|
||||
permissions: Int,
|
||||
rpId: String?,
|
||||
): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(CMD_CLIENT_PIN.toInt())
|
||||
|
||||
val entries = if (rpId != null) 6 else 5
|
||||
encodeMapHeader(out, entries)
|
||||
|
||||
encodeUint(out, 1); encodeUint(out, protocol)
|
||||
encodeUint(out, 2); encodeUint(out, PIN_SUB_GET_PIN_TOKEN_WITH_PERMS)
|
||||
encodeUint(out, 3); encodeCoseEcdhKey(out, platformKeyAgreement)
|
||||
encodeUint(out, 6); encodeByteString(out, pinHashEnc)
|
||||
encodeUint(out, 9); encodeUint(out, permissions)
|
||||
if (rpId != null) {
|
||||
encodeUint(out, 10); encodeTextString(out, rpId)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* clientPIN subcommand 3 (setPIN — configure the first PIN on a key that
|
||||
* has none):
|
||||
* { 1: protocol, 2: 3, 3: platformKeyAgreement, 4: pinUvAuthParam,
|
||||
* 5: newPinEnc }
|
||||
* where `newPinEnc = encrypt(sharedSecret, pin-padded-to-64)` and
|
||||
* `pinUvAuthParam = authenticate(sharedSecret, newPinEnc)` — both keyed on
|
||||
* the ECDH shared secret, not a pinUvAuthToken (none exists yet).
|
||||
*/
|
||||
fun encodeClientPinSetPin(
|
||||
protocol: Int,
|
||||
platformKeyAgreement: CoseEcdhPubKey,
|
||||
pinUvAuthParam: ByteArray,
|
||||
newPinEnc: ByteArray,
|
||||
): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(CMD_CLIENT_PIN.toInt())
|
||||
encodeMapHeader(out, 5)
|
||||
encodeUint(out, 1); encodeUint(out, protocol)
|
||||
encodeUint(out, 2); encodeUint(out, PIN_SUB_SET_PIN)
|
||||
encodeUint(out, 3); encodeCoseEcdhKey(out, platformKeyAgreement)
|
||||
encodeUint(out, 4); encodeByteString(out, pinUvAuthParam)
|
||||
encodeUint(out, 5); encodeByteString(out, newPinEnc)
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode the COSE_Key from a getKeyAgreement response. The response map
|
||||
* has key 1 carrying the COSE_Key sub-map.
|
||||
*/
|
||||
fun decodeClientPinKeyAgreementResponse(data: ByteArray): CoseEcdhPubKey {
|
||||
val buf = ByteBuffer.wrap(data)
|
||||
val mapSize = readMapHeader(buf)
|
||||
var key: CoseEcdhPubKey? = null
|
||||
for (i in 0 until mapSize) {
|
||||
val k = readSignedInt(buf)
|
||||
if (k == 1) {
|
||||
key = decodeCoseEcdhKey(buf)
|
||||
} else {
|
||||
skipValue(buf)
|
||||
}
|
||||
}
|
||||
return requireNotNull(key) { "clientPIN keyAgreement response missing key 1" }
|
||||
}
|
||||
|
||||
/** Decode the encrypted pinUvAuthToken (response key 2) from a getToken reply. */
|
||||
fun decodeClientPinTokenResponse(data: ByteArray): ByteArray {
|
||||
val buf = ByteBuffer.wrap(data)
|
||||
val mapSize = readMapHeader(buf)
|
||||
var token: ByteArray? = null
|
||||
for (i in 0 until mapSize) {
|
||||
val k = readSignedInt(buf)
|
||||
if (k == 2) {
|
||||
token = readByteString(buf)
|
||||
} else {
|
||||
skipValue(buf)
|
||||
}
|
||||
}
|
||||
return requireNotNull(token) { "clientPIN token response missing key 2" }
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a COSE_Key in CTAP2 canonical form for an ECDH P-256 key:
|
||||
* { 1: 2 (EC2), 3: -25 (ECDH-ES+HKDF-256), -1: 1 (P-256), -2: x, -3: y }
|
||||
*/
|
||||
private fun encodeCoseEcdhKey(out: ByteArrayOutputStream, key: CoseEcdhPubKey) {
|
||||
encodeMapHeader(out, 5)
|
||||
encodeUint(out, 1); encodeUint(out, 2) // kty = EC2
|
||||
encodeUint(out, 3); encodeNint(out, -25) // alg = ECDH-ES+HKDF-256
|
||||
encodeNint(out, -1); encodeUint(out, 1) // crv = P-256
|
||||
encodeNint(out, -2); encodeByteString(out, key.x)
|
||||
encodeNint(out, -3); encodeByteString(out, key.y)
|
||||
}
|
||||
|
||||
/** Decode a COSE_Key from `buf` and return the (x, y) coordinates. */
|
||||
private fun decodeCoseEcdhKey(buf: ByteBuffer): CoseEcdhPubKey {
|
||||
val n = readMapHeader(buf)
|
||||
var x: ByteArray? = null
|
||||
var y: ByteArray? = null
|
||||
for (i in 0 until n) {
|
||||
val k = readSignedInt(buf)
|
||||
when (k) {
|
||||
-2 -> x = readByteString(buf)
|
||||
-3 -> y = readByteString(buf)
|
||||
else -> skipValue(buf) // kty, alg, crv — not needed once we know the shape
|
||||
}
|
||||
}
|
||||
requireNotNull(x) { "COSE_Key missing x (-2)" }
|
||||
requireNotNull(y) { "COSE_Key missing y (-3)" }
|
||||
return CoseEcdhPubKey(x, y)
|
||||
}
|
||||
|
||||
// ---------- authenticatorCredentialManagement (CTAP 2.1 §6.8) ----------
|
||||
|
||||
/**
|
||||
* COSE_Key shapes we care about for SSH-SK enumeration.
|
||||
* Ed25519 (OKP, alg = -8 EdDSA) carries the 32-byte public key at COSE
|
||||
* label -2 (`x`). ECDSA P-256 (EC2, alg = -7 ES256) carries `x` and `y`
|
||||
* at COSE labels -2 and -3.
|
||||
*/
|
||||
sealed class CosePublicKey {
|
||||
data class Ed25519(val rawKey: ByteArray) : CosePublicKey()
|
||||
data class EcdsaP256(val x: ByteArray, val y: ByteArray) : CosePublicKey()
|
||||
}
|
||||
|
||||
/** One row from authenticatorCredentialManagement.enumerateRPs. */
|
||||
data class RpEntity(
|
||||
val id: String,
|
||||
val rpIdHash: ByteArray,
|
||||
/** Only present on the Begin response; null on subsequent GetNext rows. */
|
||||
val totalRPs: Int? = null,
|
||||
)
|
||||
|
||||
/** One row from authenticatorCredentialManagement.enumerateCredentials. */
|
||||
data class CredentialEntry(
|
||||
val credentialId: ByteArray,
|
||||
val publicKey: CosePublicKey,
|
||||
val userId: ByteArray?,
|
||||
val userName: String?,
|
||||
val userDisplayName: String?,
|
||||
/** Only present on the Begin response; null on subsequent GetNext rows. */
|
||||
val totalCredentials: Int? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Encode authenticatorCredentialManagement (0x0A).
|
||||
* @param subCommand one of `CM_SUB_*`.
|
||||
* @param subCommandParams CBOR-encoded params map (without the major-5
|
||||
* wrapper byte — i.e. the bytes you'd get from encoding the params
|
||||
* as a fresh CBOR map). Required for ENUMERATE_CREDS_BEGIN; null for
|
||||
* GET_CREDS_METADATA, ENUMERATE_RPS_*, and the GET_NEXT subcommands.
|
||||
* @param pinUvAuthProtocol the PIN/UV protocol version (1 or 2).
|
||||
* Required for any subCommand that takes a token (1, 2, 4); the
|
||||
* GET_NEXT subcommands (3, 5) carry no auth.
|
||||
* @param pinUvAuthParam LEFT(16, HMAC-SHA-256(token, subCommand-byte ||
|
||||
* subCommandParams)). Required for the same subcommands as protocol.
|
||||
*/
|
||||
fun encodeCredentialManagementCommand(
|
||||
subCommand: Int,
|
||||
subCommandParams: ByteArray? = null,
|
||||
pinUvAuthProtocol: Int? = null,
|
||||
pinUvAuthParam: ByteArray? = null,
|
||||
/**
|
||||
* Send the CTAP 2.1-PRE prototype command 0x41 instead of the
|
||||
* standardised 0x0A. The body is identical; only the command byte
|
||||
* differs. Decided from GetInfo, never guessed (#449).
|
||||
*/
|
||||
preview: Boolean = false,
|
||||
): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(
|
||||
(if (preview) CMD_CREDENTIAL_MANAGEMENT_PREVIEW else CMD_CREDENTIAL_MANAGEMENT).toInt(),
|
||||
)
|
||||
|
||||
var entries = 1 // subCommand always
|
||||
if (subCommandParams != null) entries++
|
||||
if (pinUvAuthProtocol != null) entries++
|
||||
if (pinUvAuthParam != null) entries++
|
||||
encodeMapHeader(out, entries)
|
||||
|
||||
encodeUint(out, 1); encodeUint(out, subCommand)
|
||||
if (subCommandParams != null) {
|
||||
encodeUint(out, 2)
|
||||
// subCommandParams is already a valid CBOR map; write it as-is.
|
||||
out.write(subCommandParams)
|
||||
}
|
||||
if (pinUvAuthProtocol != null) {
|
||||
encodeUint(out, 3); encodeUint(out, pinUvAuthProtocol)
|
||||
}
|
||||
if (pinUvAuthParam != null) {
|
||||
encodeUint(out, 4); encodeByteString(out, pinUvAuthParam)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode the `subCommandParams` map for ENUMERATE_CREDS_BEGIN:
|
||||
* { 0x01 (rpIDHash): bstr }
|
||||
* Returned bytes are what should be hashed (alongside the subCommand
|
||||
* byte) for the pinUvAuthParam derivation, AND what should be passed
|
||||
* as the `subCommandParams` argument to
|
||||
* [encodeCredentialManagementCommand].
|
||||
*/
|
||||
fun encodeEnumerateCredentialsParams(rpIdHash: ByteArray): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
encodeMapHeader(out, 1)
|
||||
encodeUint(out, 1); encodeByteString(out, rpIdHash)
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
/** Decode an enumerateRPsBegin or enumerateRPsGetNextRP response. */
|
||||
fun decodeEnumerateRPsResponse(data: ByteArray): RpEntity {
|
||||
val buf = ByteBuffer.wrap(data)
|
||||
val mapSize = readMapHeader(buf)
|
||||
var rpId: String? = null
|
||||
var rpIdHash: ByteArray? = null
|
||||
var totalRPs: Int? = null
|
||||
for (i in 0 until mapSize) {
|
||||
val key = readSignedInt(buf)
|
||||
when (key) {
|
||||
3 -> { // rp: PublicKeyCredentialRpEntity { "id": text, ... }
|
||||
val n = readMapHeader(buf)
|
||||
for (j in 0 until n) {
|
||||
val sub = readTextString(buf)
|
||||
if (sub == "id") rpId = readTextString(buf) else skipValue(buf)
|
||||
}
|
||||
}
|
||||
4 -> rpIdHash = readByteString(buf)
|
||||
5 -> totalRPs = readSignedInt(buf)
|
||||
else -> skipValue(buf)
|
||||
}
|
||||
}
|
||||
requireNotNull(rpId) { "enumerateRPs response missing rp.id (key 3)" }
|
||||
requireNotNull(rpIdHash) { "enumerateRPs response missing rpIDHash (key 4)" }
|
||||
return RpEntity(id = rpId, rpIdHash = rpIdHash, totalRPs = totalRPs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode an enumerateCredentialsBegin or enumerateCredentialsGetNext
|
||||
* response. The publicKey field is parsed to [CosePublicKey] —
|
||||
* Ed25519 (OKP -8) or ECDSA P-256 (EC2 -7); other algorithms throw.
|
||||
*/
|
||||
fun decodeEnumerateCredentialsResponse(data: ByteArray): CredentialEntry {
|
||||
val buf = ByteBuffer.wrap(data)
|
||||
val mapSize = readMapHeader(buf)
|
||||
var userId: ByteArray? = null
|
||||
var userName: String? = null
|
||||
var userDisplay: String? = null
|
||||
var credentialId: ByteArray? = null
|
||||
var publicKey: CosePublicKey? = null
|
||||
var totalCreds: Int? = null
|
||||
for (i in 0 until mapSize) {
|
||||
val key = readSignedInt(buf)
|
||||
when (key) {
|
||||
6 -> { // user: PublicKeyCredentialUserEntity { id, name?, displayName? }
|
||||
val n = readMapHeader(buf)
|
||||
for (j in 0 until n) {
|
||||
val sub = readTextString(buf)
|
||||
when (sub) {
|
||||
"id" -> userId = readByteString(buf)
|
||||
"name" -> userName = readTextString(buf)
|
||||
"displayName" -> userDisplay = readTextString(buf)
|
||||
else -> skipValue(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
7 -> { // credentialID: PublicKeyCredentialDescriptor { id, type, transports? }
|
||||
val n = readMapHeader(buf)
|
||||
for (j in 0 until n) {
|
||||
val sub = readTextString(buf)
|
||||
if (sub == "id") credentialId = readByteString(buf) else skipValue(buf)
|
||||
}
|
||||
}
|
||||
8 -> publicKey = decodeCoseAuthenticatorPublicKey(buf)
|
||||
9 -> totalCreds = readSignedInt(buf)
|
||||
else -> skipValue(buf)
|
||||
}
|
||||
}
|
||||
requireNotNull(credentialId) { "enumerateCredentials response missing credentialID (key 7)" }
|
||||
requireNotNull(publicKey) { "enumerateCredentials response missing publicKey (key 8)" }
|
||||
return CredentialEntry(
|
||||
credentialId = credentialId,
|
||||
publicKey = publicKey,
|
||||
userId = userId,
|
||||
userName = userName,
|
||||
userDisplayName = userDisplay,
|
||||
totalCredentials = totalCreds,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a credential's COSE_Key into [CosePublicKey]. Handles the two
|
||||
* algorithms SSH-SK actually uses:
|
||||
* - Ed25519 (kty=1 OKP, alg=-8): -1 = crv (6 = Ed25519), -2 = x (raw key).
|
||||
* - ECDSA P-256 (kty=2 EC2, alg=-7): -1 = crv (1 = P-256), -2 = x, -3 = y.
|
||||
*/
|
||||
private fun decodeCoseAuthenticatorPublicKey(buf: ByteBuffer): CosePublicKey {
|
||||
val n = readMapHeader(buf)
|
||||
var kty: Int? = null
|
||||
var alg: Int? = null
|
||||
var x: ByteArray? = null
|
||||
var y: ByteArray? = null
|
||||
for (i in 0 until n) {
|
||||
val k = readSignedInt(buf)
|
||||
when (k) {
|
||||
1 -> kty = readSignedInt(buf)
|
||||
3 -> alg = readSignedInt(buf)
|
||||
-1 -> skipValue(buf) // crv — implied by alg
|
||||
-2 -> x = readByteString(buf)
|
||||
-3 -> y = readByteString(buf)
|
||||
else -> skipValue(buf)
|
||||
}
|
||||
}
|
||||
return when {
|
||||
kty == 1 && alg == -8 && x != null && x.size == 32 -> CosePublicKey.Ed25519(x)
|
||||
kty == 2 && alg == -7 && x != null && y != null && x.size == 32 && y.size == 32 ->
|
||||
CosePublicKey.EcdsaP256(x, y)
|
||||
else -> throw IllegalArgumentException(
|
||||
"Unsupported COSE_Key for SSH-SK: kty=$kty alg=$alg x=${x?.size} y=${y?.size}"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- CBOR encoding helpers ----------
|
||||
|
||||
private fun encodeUint(out: ByteArrayOutputStream, value: Int) {
|
||||
encodeMajor(out, 0, value)
|
||||
}
|
||||
|
||||
private fun encodeNint(out: ByteArrayOutputStream, value: Int) {
|
||||
require(value < 0) { "encodeNint requires negative value, got $value" }
|
||||
encodeMajor(out, 1, -1 - value)
|
||||
}
|
||||
|
||||
/** Encode a possibly-negative integer (e.g. a COSE alg id like -8). */
|
||||
private fun encodeInt(out: ByteArrayOutputStream, value: Int) {
|
||||
if (value < 0) encodeNint(out, value) else encodeUint(out, value)
|
||||
}
|
||||
|
||||
private fun encodeByteString(out: ByteArrayOutputStream, data: ByteArray) {
|
||||
encodeMajor(out, 2, data.size)
|
||||
out.write(data)
|
||||
}
|
||||
|
||||
private fun encodeTextString(out: ByteArrayOutputStream, text: String) {
|
||||
val bytes = text.toByteArray(Charsets.UTF_8)
|
||||
encodeMajor(out, 3, bytes.size)
|
||||
out.write(bytes)
|
||||
}
|
||||
|
||||
private fun encodeMapHeader(out: ByteArrayOutputStream, size: Int) {
|
||||
encodeMajor(out, 5, size)
|
||||
}
|
||||
|
||||
private fun encodeArrayHeader(out: ByteArrayOutputStream, size: Int) {
|
||||
encodeMajor(out, 4, size)
|
||||
}
|
||||
|
||||
private fun encodeBoolean(out: ByteArrayOutputStream, value: Boolean) {
|
||||
out.write(if (value) 0xF5 else 0xF4)
|
||||
}
|
||||
|
||||
private fun encodeMajor(out: ByteArrayOutputStream, majorType: Int, value: Int) {
|
||||
val mt = majorType shl 5
|
||||
when {
|
||||
value < 24 -> out.write(mt or value)
|
||||
value < 256 -> { out.write(mt or 24); out.write(value) }
|
||||
value < 65536 -> {
|
||||
out.write(mt or 25)
|
||||
out.write(value shr 8)
|
||||
out.write(value and 0xFF)
|
||||
}
|
||||
else -> {
|
||||
out.write(mt or 26)
|
||||
out.write(value shr 24)
|
||||
out.write((value shr 16) and 0xFF)
|
||||
out.write((value shr 8) and 0xFF)
|
||||
out.write(value and 0xFF)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- CBOR decoding helpers ----------
|
||||
|
||||
private fun readMapHeader(buf: ByteBuffer): Int {
|
||||
val initial = buf.get().toInt() and 0xFF
|
||||
val major = initial shr 5
|
||||
require(major == 5) { "Expected CBOR map, got major type $major" }
|
||||
return readAdditionalInfo(buf, initial and 0x1F)
|
||||
}
|
||||
|
||||
private fun readArrayHeader(buf: ByteBuffer): Int {
|
||||
val initial = buf.get().toInt() and 0xFF
|
||||
val major = initial shr 5
|
||||
require(major == 4) { "Expected CBOR array, got major type $major" }
|
||||
return readAdditionalInfo(buf, initial and 0x1F)
|
||||
}
|
||||
|
||||
/** Read an int that may be positive (major 0) or negative (major 1). */
|
||||
private fun readSignedInt(buf: ByteBuffer): Int {
|
||||
val initial = buf.get().toInt() and 0xFF
|
||||
val major = initial shr 5
|
||||
val info = readAdditionalInfo(buf, initial and 0x1F)
|
||||
return when (major) {
|
||||
0 -> info
|
||||
1 -> -1 - info
|
||||
else -> throw IllegalArgumentException("Expected CBOR int, got major type $major")
|
||||
}
|
||||
}
|
||||
|
||||
private fun readByteString(buf: ByteBuffer): ByteArray {
|
||||
val initial = buf.get().toInt() and 0xFF
|
||||
val major = initial shr 5
|
||||
require(major == 2) { "Expected CBOR byte string, got major type $major" }
|
||||
val len = readAdditionalInfo(buf, initial and 0x1F)
|
||||
val data = ByteArray(len)
|
||||
buf.get(data)
|
||||
return data
|
||||
}
|
||||
|
||||
private fun readTextString(buf: ByteBuffer): String {
|
||||
val initial = buf.get().toInt() and 0xFF
|
||||
val major = initial shr 5
|
||||
require(major == 3) { "Expected CBOR text string, got major type $major" }
|
||||
val len = readAdditionalInfo(buf, initial and 0x1F)
|
||||
val data = ByteArray(len)
|
||||
buf.get(data)
|
||||
return String(data, Charsets.UTF_8)
|
||||
}
|
||||
|
||||
private fun readBoolean(buf: ByteBuffer): Boolean {
|
||||
val b = buf.get().toInt() and 0xFF
|
||||
return when (b) {
|
||||
0xF5 -> true
|
||||
0xF4 -> false
|
||||
else -> throw IllegalArgumentException("Expected CBOR boolean, got 0x${"%02x".format(b)}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun readAdditionalInfo(buf: ByteBuffer, info: Int): Int = when {
|
||||
info < 24 -> info
|
||||
info == 24 -> buf.get().toInt() and 0xFF
|
||||
info == 25 -> ((buf.get().toInt() and 0xFF) shl 8) or (buf.get().toInt() and 0xFF)
|
||||
info == 26 -> ((buf.get().toInt() and 0xFF) shl 24) or
|
||||
((buf.get().toInt() and 0xFF) shl 16) or
|
||||
((buf.get().toInt() and 0xFF) shl 8) or
|
||||
(buf.get().toInt() and 0xFF)
|
||||
else -> throw IllegalArgumentException("Unsupported CBOR additional info: $info")
|
||||
}
|
||||
|
||||
private fun skipValue(buf: ByteBuffer) {
|
||||
val initial = buf.get().toInt() and 0xFF
|
||||
val major = initial shr 5
|
||||
val info = initial and 0x1F
|
||||
when (major) {
|
||||
0, 1 -> readAdditionalInfo(buf, info)
|
||||
2, 3 -> {
|
||||
val len = readAdditionalInfo(buf, info)
|
||||
buf.position(buf.position() + len)
|
||||
}
|
||||
4 -> {
|
||||
val count = readAdditionalInfo(buf, info)
|
||||
repeat(count) { skipValue(buf) }
|
||||
}
|
||||
5 -> {
|
||||
val count = readAdditionalInfo(buf, info)
|
||||
repeat(count) { skipValue(buf); skipValue(buf) }
|
||||
}
|
||||
7 -> {} // simple values (true/false/null) — already consumed
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import java.math.BigInteger
|
||||
import java.security.AlgorithmParameters
|
||||
import java.security.KeyFactory
|
||||
import java.security.KeyPair
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.security.interfaces.ECPrivateKey
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
import java.security.spec.ECParameterSpec
|
||||
import java.security.spec.ECPoint
|
||||
import java.security.spec.ECPublicKeySpec
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyAgreement
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
/**
|
||||
* CTAP2 PIN/UV Auth Protocol implementations (v1 and v2) per CTAP 2.1 §6.5.
|
||||
*
|
||||
* The protocol establishes a shared secret with the authenticator over ECDH
|
||||
* (P-256), then uses that secret to encrypt a PIN hash and authenticate
|
||||
* subsequent commands. Once the authenticator returns a `pinUvAuthToken`, the
|
||||
* platform can sign request payloads (e.g. clientDataHash) with HMAC-SHA-256
|
||||
* to prove user verification was performed.
|
||||
*
|
||||
* Protocol v2 uses HKDF-derived split keys (32-byte HMAC + 32-byte AES) with
|
||||
* a random IV; v1 uses raw SHA-256(Z) for both with a zero IV. v2 is preferred
|
||||
* when advertised by the authenticator (`pinUvAuthProtocols` in GetInfo).
|
||||
*/
|
||||
sealed class Ctap2PinProtocol(val version: Int) {
|
||||
|
||||
/**
|
||||
* Generate an ephemeral P-256 keypair. The public half is sent to the
|
||||
* authenticator as the platform's keyAgreement; the private half is used
|
||||
* with the authenticator's keyAgreement to derive the shared secret.
|
||||
*/
|
||||
fun generateEphemeralKeyPair(): KeyPair {
|
||||
val gen = KeyPairGenerator.getInstance("EC")
|
||||
gen.initialize(ECGenParameterSpec("secp256r1"))
|
||||
return gen.generateKeyPair()
|
||||
}
|
||||
|
||||
/** Compute the raw 32-byte ECDH shared X coordinate (Z in CTAP terms). */
|
||||
fun ecdh(privateKey: ECPrivateKey, peerPublic: ECPublicKey): ByteArray {
|
||||
val ka = KeyAgreement.getInstance("ECDH")
|
||||
ka.init(privateKey)
|
||||
ka.doPhase(peerPublic, true)
|
||||
return ka.generateSecret()
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the protocol's "shared secret" from the raw ECDH output Z.
|
||||
* v1: SHA-256(Z) — 32 bytes, used as both AES key and HMAC key.
|
||||
* v2: HKDF-SHA-256(salt=zeros, IKM=Z) → 32B HMAC || 32B AES — 64 bytes.
|
||||
*/
|
||||
abstract fun deriveSharedSecret(z: ByteArray): ByteArray
|
||||
|
||||
/**
|
||||
* Encrypt with the protocol's AES key. For v1 the IV is fixed zeros and
|
||||
* not prepended; for v2 a random IV is prepended to the ciphertext.
|
||||
* The plaintext must be a multiple of 16 bytes (AES block size).
|
||||
*/
|
||||
abstract fun encrypt(sharedSecret: ByteArray, plaintext: ByteArray): ByteArray
|
||||
|
||||
/** Reverse of [encrypt]. */
|
||||
abstract fun decrypt(sharedSecret: ByteArray, ciphertext: ByteArray): ByteArray
|
||||
|
||||
/**
|
||||
* Authenticate a message under the protocol's HMAC key. v1 truncates to
|
||||
* 16 bytes; v2 returns the full 32-byte HMAC-SHA-256.
|
||||
*/
|
||||
abstract fun authenticate(sharedSecret: ByteArray, message: ByteArray): ByteArray
|
||||
|
||||
/**
|
||||
* Decode an authenticator-supplied COSE_Key into a JCA ECPublicKey on
|
||||
* P-256. CTAP2 always sends EC2 / P-256 keyAgreements for PIN protocol.
|
||||
*/
|
||||
fun coseKeyToEcPublic(x: ByteArray, y: ByteArray): ECPublicKey {
|
||||
require(x.size == 32 && y.size == 32) {
|
||||
"P-256 coords must be 32 bytes (got x=${x.size}, y=${y.size})"
|
||||
}
|
||||
val params = ecP256Params()
|
||||
val point = ECPoint(BigInteger(1, x), BigInteger(1, y))
|
||||
val spec = ECPublicKeySpec(point, params)
|
||||
return KeyFactory.getInstance("EC").generatePublic(spec) as ECPublicKey
|
||||
}
|
||||
|
||||
/** Extract the 32-byte big-endian X and Y coordinates from a JCA ECPublicKey. */
|
||||
fun ecPublicToCoseCoords(pub: ECPublicKey): Pair<ByteArray, ByteArray> {
|
||||
val w = pub.w
|
||||
return padTo32(w.affineX.toByteArray()) to padTo32(w.affineY.toByteArray())
|
||||
}
|
||||
|
||||
object V1 : Ctap2PinProtocol(1) {
|
||||
private val zeroIv = ByteArray(16)
|
||||
|
||||
override fun deriveSharedSecret(z: ByteArray): ByteArray =
|
||||
MessageDigest.getInstance("SHA-256").digest(z)
|
||||
|
||||
override fun encrypt(sharedSecret: ByteArray, plaintext: ByteArray): ByteArray {
|
||||
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(sharedSecret, "AES"), IvParameterSpec(zeroIv))
|
||||
return cipher.doFinal(plaintext)
|
||||
}
|
||||
|
||||
override fun decrypt(sharedSecret: ByteArray, ciphertext: ByteArray): ByteArray {
|
||||
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(sharedSecret, "AES"), IvParameterSpec(zeroIv))
|
||||
return cipher.doFinal(ciphertext)
|
||||
}
|
||||
|
||||
override fun authenticate(sharedSecret: ByteArray, message: ByteArray): ByteArray {
|
||||
val mac = Mac.getInstance("HmacSHA256")
|
||||
mac.init(SecretKeySpec(sharedSecret, "HmacSHA256"))
|
||||
return mac.doFinal(message).copyOfRange(0, 16) // v1: truncated to 16 bytes
|
||||
}
|
||||
}
|
||||
|
||||
object V2 : Ctap2PinProtocol(2) {
|
||||
private val rng = SecureRandom()
|
||||
|
||||
override fun deriveSharedSecret(z: ByteArray): ByteArray {
|
||||
val prk = hmacSha256(ByteArray(32), z) // HKDF-Extract with zero salt
|
||||
val hmacKey = hkdfExpand(prk, "CTAP2 HMAC key".toByteArray(), 32)
|
||||
val aesKey = hkdfExpand(prk, "CTAP2 AES key".toByteArray(), 32)
|
||||
return hmacKey + aesKey
|
||||
}
|
||||
|
||||
override fun encrypt(sharedSecret: ByteArray, plaintext: ByteArray): ByteArray {
|
||||
val aesKey = sharedSecret.copyOfRange(32, 64)
|
||||
val iv = ByteArray(16).also { rng.nextBytes(it) }
|
||||
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(aesKey, "AES"), IvParameterSpec(iv))
|
||||
return iv + cipher.doFinal(plaintext)
|
||||
}
|
||||
|
||||
override fun decrypt(sharedSecret: ByteArray, ciphertext: ByteArray): ByteArray {
|
||||
require(ciphertext.size >= 16) { "v2 ciphertext too short for IV: ${ciphertext.size}" }
|
||||
val aesKey = sharedSecret.copyOfRange(32, 64)
|
||||
val iv = ciphertext.copyOfRange(0, 16)
|
||||
val ct = ciphertext.copyOfRange(16, ciphertext.size)
|
||||
val cipher = Cipher.getInstance("AES/CBC/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(aesKey, "AES"), IvParameterSpec(iv))
|
||||
return cipher.doFinal(ct)
|
||||
}
|
||||
|
||||
override fun authenticate(sharedSecret: ByteArray, message: ByteArray): ByteArray {
|
||||
val hmacKey = sharedSecret.copyOfRange(0, 32)
|
||||
return hmacSha256(hmacKey, message) // v2: full 32-byte tag
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Pick the strongest protocol that both we and the authenticator support.
|
||||
* Falls back to v1 when v2 is not advertised. Returns null if neither is
|
||||
* supported (in which case the authenticator does not require PIN at all).
|
||||
*/
|
||||
fun pick(authenticatorProtocols: List<Int>): Ctap2PinProtocol? = when {
|
||||
2 in authenticatorProtocols -> V2
|
||||
1 in authenticatorProtocols -> V1
|
||||
authenticatorProtocols.isEmpty() -> V2 // some keys omit the field but support v2
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Crypto helpers (private to the module) ---
|
||||
|
||||
internal fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray {
|
||||
val mac = Mac.getInstance("HmacSHA256")
|
||||
mac.init(SecretKeySpec(key, "HmacSHA256"))
|
||||
return mac.doFinal(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* HKDF-Expand per RFC 5869 with SHA-256. Concatenates `T(1) || T(2) || …`
|
||||
* where `T(i) = HMAC(PRK, T(i-1) || info || i)` until reaching `length`.
|
||||
*/
|
||||
internal fun hkdfExpand(prk: ByteArray, info: ByteArray, length: Int): ByteArray {
|
||||
require(length <= 255 * 32) { "HKDF length too large" }
|
||||
val out = ByteArray(length)
|
||||
var t = ByteArray(0)
|
||||
var pos = 0
|
||||
var i = 1
|
||||
while (pos < length) {
|
||||
val mac = Mac.getInstance("HmacSHA256")
|
||||
mac.init(SecretKeySpec(prk, "HmacSHA256"))
|
||||
mac.update(t)
|
||||
mac.update(info)
|
||||
mac.update(byteArrayOf(i.toByte()))
|
||||
t = mac.doFinal()
|
||||
val take = minOf(t.size, length - pos)
|
||||
t.copyInto(out, pos, 0, take)
|
||||
pos += take
|
||||
i++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Pad an unsigned big-endian integer byte array to exactly 32 bytes. */
|
||||
internal fun padTo32(bytes: ByteArray): ByteArray = when {
|
||||
bytes.size == 32 -> bytes
|
||||
bytes.size == 33 && bytes[0] == 0.toByte() -> bytes.copyOfRange(1, 33) // strip BigInteger sign byte
|
||||
bytes.size < 32 -> ByteArray(32 - bytes.size) + bytes
|
||||
else -> throw IllegalArgumentException("EC coord too large: ${bytes.size}")
|
||||
}
|
||||
|
||||
private fun ecP256Params(): ECParameterSpec {
|
||||
val params = AlgorithmParameters.getInstance("EC")
|
||||
params.init(ECGenParameterSpec("secp256r1"))
|
||||
return params.getParameterSpec(ECParameterSpec::class.java)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import android.hardware.usb.UsbDeviceConnection
|
||||
import android.hardware.usb.UsbEndpoint
|
||||
import android.util.Log
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
import kotlin.random.Random
|
||||
|
||||
private const val TAG = "CtapHid"
|
||||
|
||||
/** CTAPHID command IDs. */
|
||||
private const val CTAPHID_INIT: Byte = 0x06
|
||||
private const val CTAPHID_CBOR: Byte = 0x10
|
||||
private const val CTAPHID_KEEPALIVE: Byte = 0x3B.toByte()
|
||||
private const val CTAPHID_ERROR: Byte = 0x3F
|
||||
|
||||
/** CTAPHID keepalive status. */
|
||||
private const val STATUS_UPNEEDED: Byte = 0x02
|
||||
|
||||
/** HID report size for FIDO (always 64 bytes). */
|
||||
private const val REPORT_SIZE = 64
|
||||
private const val INIT_DATA_SIZE = 57 // 64 - 4(CID) - 1(CMD) - 2(LEN)
|
||||
private const val CONT_DATA_SIZE = 59 // 64 - 4(CID) - 1(SEQ)
|
||||
|
||||
/** Broadcast channel ID for CTAPHID_INIT. */
|
||||
private val BROADCAST_CID = byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte())
|
||||
|
||||
/** Timeout for USB transfers (30s for user presence). */
|
||||
private const val TRANSFER_TIMEOUT_MS = 30_000
|
||||
|
||||
/**
|
||||
* Max raw frames to drain while waiting for the CTAPHID_INIT reply. A busy or
|
||||
* contended key answers INIT with CTAPHID_KEEPALIVE, or the HID IN pipe still
|
||||
* holds stale frames from a prior aborted transaction — both common right after
|
||||
* a stalled SSH reconnect on a flaky link. Bounded so a never-replying key can't
|
||||
* wedge the caller.
|
||||
*/
|
||||
private const val MAX_INIT_READS = 16
|
||||
|
||||
/**
|
||||
* Read raw CTAPHID frames via [recv] until the CTAPHID_INIT reply arrives,
|
||||
* draining CTAPHID_KEEPALIVE ("busy") and any stray frames a busy/contended key
|
||||
* emits first. A single hard `require(cmd == INIT)` on the first frame turned a
|
||||
* transient "busy" (`got 0xbb` = KEEPALIVE) into a FIDO-auth failure → SSH
|
||||
* reconnect storm; draining fixes that. Throws on CTAPHID_ERROR or if no INIT
|
||||
* reply arrives within [maxReads] frames. Pure but for [recv] — unit-tested.
|
||||
*/
|
||||
internal fun drainToInitReply(
|
||||
maxReads: Int,
|
||||
recv: () -> Triple<ByteArray, Byte, ByteArray>,
|
||||
): Triple<ByteArray, Byte, ByteArray> {
|
||||
repeat(maxReads) {
|
||||
val frame = recv()
|
||||
when ((frame.second.toInt() and 0x7F).toByte()) {
|
||||
CTAPHID_INIT -> return frame
|
||||
CTAPHID_KEEPALIVE -> Log.d(TAG, "INIT: draining keepalive (key busy)")
|
||||
CTAPHID_ERROR -> {
|
||||
val code = if (frame.third.isNotEmpty()) frame.third[0].toInt() and 0xFF else -1
|
||||
throw IOException("CTAPHID error during INIT: 0x${"%02x".format(code)}")
|
||||
}
|
||||
else -> Log.w(TAG, "INIT: skipping unexpected 0x${"%02x".format(frame.second)}")
|
||||
}
|
||||
}
|
||||
throw IOException("No CTAPHID_INIT reply after $maxReads frames (key busy)")
|
||||
}
|
||||
|
||||
/**
|
||||
* CTAPHID protocol implementation over Android USB.
|
||||
* Handles HID packet framing, channel allocation, and keepalive.
|
||||
*/
|
||||
class CtapHidTransport(
|
||||
private val connection: UsbDeviceConnection,
|
||||
private val endpointIn: UsbEndpoint,
|
||||
private val endpointOut: UsbEndpoint,
|
||||
) : Closeable {
|
||||
|
||||
private var channelId: ByteArray = BROADCAST_CID
|
||||
|
||||
/**
|
||||
* Allocate a channel ID by sending CTAPHID_INIT on the broadcast channel.
|
||||
*/
|
||||
fun init() {
|
||||
val nonce = Random.nextBytes(8)
|
||||
sendRaw(BROADCAST_CID, CTAPHID_INIT, nonce)
|
||||
|
||||
// Drain keepalive/stale frames instead of failing on the first non-INIT
|
||||
// packet — a busy key (e.g. contended with the USB/IP export, or mid
|
||||
// reconnect on a flaky link) replies KEEPALIVE (0xbb) first.
|
||||
val (_, _, payload) = drainToInitReply(MAX_INIT_READS) { recvRaw() }
|
||||
require(payload.size >= 17) { "CTAPHID_INIT response too short: ${payload.size}" }
|
||||
|
||||
// Verify nonce matches
|
||||
for (i in 0 until 8) {
|
||||
require(payload[i] == nonce[i]) { "CTAPHID_INIT nonce mismatch at byte $i" }
|
||||
}
|
||||
|
||||
// Extract allocated channel ID (bytes 8-11)
|
||||
channelId = payload.sliceArray(8..11)
|
||||
Log.d(TAG, "Allocated channel: ${channelId.joinToString("") { "%02x".format(it) }}")
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a CTAP2 CBOR command and return the response payload.
|
||||
* Handles CTAPHID_KEEPALIVE packets during user presence wait.
|
||||
*
|
||||
* @param onKeepAlive called when the authenticator signals user touch needed
|
||||
*/
|
||||
fun sendCborCommand(data: ByteArray, onKeepAlive: (() -> Unit)? = null): ByteArray {
|
||||
sendRaw(channelId, CTAPHID_CBOR, data)
|
||||
|
||||
while (true) {
|
||||
val (cid, cmd, payload) = recvRaw()
|
||||
val cmdByte = (cmd.toInt() and 0x7F).toByte()
|
||||
|
||||
when (cmdByte) {
|
||||
CTAPHID_CBOR -> return payload
|
||||
CTAPHID_KEEPALIVE -> {
|
||||
if (payload.isNotEmpty() && payload[0] == STATUS_UPNEEDED) {
|
||||
Log.d(TAG, "Keepalive: user presence needed")
|
||||
onKeepAlive?.invoke()
|
||||
}
|
||||
// Continue waiting
|
||||
}
|
||||
CTAPHID_ERROR -> {
|
||||
val errCode = if (payload.isNotEmpty()) payload[0].toInt() and 0xFF else -1
|
||||
throw IOException("CTAPHID error: 0x${"%02x".format(errCode)}")
|
||||
}
|
||||
else -> {
|
||||
Log.w(TAG, "Unexpected CTAPHID command: 0x${"%02x".format(cmd)}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
connection.close()
|
||||
}
|
||||
|
||||
// --- HID packet framing ---
|
||||
|
||||
private fun sendRaw(cid: ByteArray, cmd: Byte, data: ByteArray) {
|
||||
val packets = mutableListOf<ByteArray>()
|
||||
|
||||
// Initialization packet
|
||||
val initPacket = ByteArray(REPORT_SIZE)
|
||||
cid.copyInto(initPacket, 0)
|
||||
initPacket[4] = (cmd.toInt() or 0x80).toByte() // Set bit 7 for init packet
|
||||
initPacket[5] = ((data.size shr 8) and 0xFF).toByte()
|
||||
initPacket[6] = (data.size and 0xFF).toByte()
|
||||
val initLen = minOf(data.size, INIT_DATA_SIZE)
|
||||
data.copyInto(initPacket, 7, 0, initLen)
|
||||
packets.add(initPacket)
|
||||
|
||||
// Continuation packets
|
||||
var offset = initLen
|
||||
var seq = 0
|
||||
while (offset < data.size) {
|
||||
val contPacket = ByteArray(REPORT_SIZE)
|
||||
cid.copyInto(contPacket, 0)
|
||||
contPacket[4] = (seq and 0x7F).toByte()
|
||||
val contLen = minOf(data.size - offset, CONT_DATA_SIZE)
|
||||
data.copyInto(contPacket, 5, offset, offset + contLen)
|
||||
packets.add(contPacket)
|
||||
offset += contLen
|
||||
seq++
|
||||
}
|
||||
|
||||
for (packet in packets) {
|
||||
val sent = connection.bulkTransfer(endpointOut, packet, packet.size, TRANSFER_TIMEOUT_MS)
|
||||
if (sent < 0) throw IOException("USB send failed")
|
||||
}
|
||||
}
|
||||
|
||||
private fun recvRaw(): Triple<ByteArray, Byte, ByteArray> {
|
||||
val buf = ByteArray(REPORT_SIZE)
|
||||
|
||||
// Read initialization packet
|
||||
val read = connection.bulkTransfer(endpointIn, buf, buf.size, TRANSFER_TIMEOUT_MS)
|
||||
if (read < 7) throw IOException("USB recv failed or too short: $read bytes")
|
||||
|
||||
val cid = buf.sliceArray(0..3)
|
||||
val cmd = buf[4]
|
||||
val totalLen = ((buf[5].toInt() and 0xFF) shl 8) or (buf[6].toInt() and 0xFF)
|
||||
val initLen = minOf(totalLen, INIT_DATA_SIZE)
|
||||
|
||||
val result = ByteArray(totalLen)
|
||||
buf.copyInto(result, 0, 7, 7 + initLen)
|
||||
|
||||
// Read continuation packets
|
||||
var offset = initLen
|
||||
while (offset < totalLen) {
|
||||
val contRead = connection.bulkTransfer(endpointIn, buf, buf.size, TRANSFER_TIMEOUT_MS)
|
||||
if (contRead < 5) throw IOException("USB cont recv failed: $contRead bytes")
|
||||
val contLen = minOf(totalLen - offset, CONT_DATA_SIZE)
|
||||
buf.copyInto(result, offset, 5, 5 + contLen)
|
||||
offset += contLen
|
||||
}
|
||||
|
||||
return Triple(cid, cmd, result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import android.nfc.tech.IsoDep
|
||||
import android.util.Log
|
||||
import java.io.Closeable
|
||||
import java.io.IOException
|
||||
|
||||
private const val TAG = "CtapNfc"
|
||||
|
||||
/** FIDO Alliance NFC applet AID: A0000006472F0001 */
|
||||
private val FIDO_AID = byteArrayOf(
|
||||
0xA0.toByte(), 0x00, 0x00, 0x06, 0x47, 0x2F, 0x00, 0x01,
|
||||
)
|
||||
|
||||
/** NFCCTAP command INS byte. */
|
||||
private const val INS_NFCCTAP_MSG: Byte = 0x10
|
||||
|
||||
/** ISO 7816-4 GET RESPONSE INS byte. */
|
||||
private const val INS_GET_RESPONSE: Byte = 0xC0.toByte()
|
||||
|
||||
/** ISO 7816-4 SELECT INS byte. */
|
||||
private const val INS_SELECT: Byte = 0xA4.toByte()
|
||||
|
||||
/** NFC timeout for user presence (30s). */
|
||||
private const val NFC_TIMEOUT_MS = 30_000
|
||||
|
||||
/**
|
||||
* CTAP2 over NFC ISO-DEP (ISO 7816-4 APDUs).
|
||||
* Implements FIDO NFC protocol: SELECT applet, then NFCCTAP_MSG commands.
|
||||
*/
|
||||
class CtapNfcTransport(
|
||||
private val isoDep: IsoDep,
|
||||
) : Closeable {
|
||||
|
||||
fun connect() {
|
||||
isoDep.timeout = NFC_TIMEOUT_MS
|
||||
isoDep.connect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the FIDO applet. Must be called before sendCborCommand.
|
||||
* @throws IOException if the applet is not present on this tag.
|
||||
*/
|
||||
fun select() {
|
||||
selectApplet { isoDep.transceive(it) }
|
||||
Log.d(TAG, "FIDO applet selected")
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a CTAP2 CBOR command and return the response payload.
|
||||
* Handles response chaining (SW=61xx).
|
||||
*/
|
||||
fun sendCborCommand(data: ByteArray): ByteArray {
|
||||
// NFCCTAP_MSG APDU: CLA=80 INS=10 P1=00 P2=00 Lc Data Le=00
|
||||
val apdu = if (data.size <= 255) {
|
||||
// Short APDU
|
||||
byteArrayOf(
|
||||
0x80.toByte(), INS_NFCCTAP_MSG, 0x00, 0x00,
|
||||
data.size.toByte(),
|
||||
) + data + byteArrayOf(0x00) // Le=00 (max response)
|
||||
} else {
|
||||
// Extended length APDU
|
||||
byteArrayOf(
|
||||
0x80.toByte(), INS_NFCCTAP_MSG, 0x00, 0x00,
|
||||
0x00, // Extended length marker
|
||||
((data.size shr 8) and 0xFF).toByte(),
|
||||
(data.size and 0xFF).toByte(),
|
||||
) + data + byteArrayOf(0x00, 0x00) // Le=0000
|
||||
}
|
||||
|
||||
var response = isoDep.transceive(apdu)
|
||||
val result = mutableListOf<Byte>()
|
||||
|
||||
while (true) {
|
||||
val sw = extractSw(response)
|
||||
// Copy data (everything except last 2 SW bytes)
|
||||
for (i in 0 until response.size - 2) {
|
||||
result.add(response[i])
|
||||
}
|
||||
|
||||
when {
|
||||
sw == 0x9000 -> break // Success, all data received
|
||||
(sw shr 8) == 0x61 -> {
|
||||
// More data available — send GET RESPONSE
|
||||
val remaining = sw and 0xFF
|
||||
val getResponse = byteArrayOf(
|
||||
0x00, INS_GET_RESPONSE, 0x00, 0x00,
|
||||
remaining.toByte(),
|
||||
)
|
||||
response = isoDep.transceive(getResponse)
|
||||
}
|
||||
else -> throw IOException("NFCCTAP error: SW=${"%04x".format(sw)}")
|
||||
}
|
||||
}
|
||||
|
||||
return result.toByteArray()
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
try {
|
||||
isoDep.close()
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
|
||||
private fun extractSw(response: ByteArray): Int = extractSwStatic(response)
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* SELECT the FIDO applet over an arbitrary APDU transport, draining
|
||||
* ISO 7816-4 "more data available" (SW=61xx) chaining via GET RESPONSE.
|
||||
*
|
||||
* A SELECT can answer 61xx instead of 9000: the applet returns its FCI
|
||||
* template in chunks and expects GET RESPONSE to drain them. Some keys
|
||||
* — e.g. Nitrokey 3A — do exactly this (#623); treating 61xx as fatal
|
||||
* broke FIDO2-over-NFC key import for them. Only a genuine error status
|
||||
* word is fatal; completion (9000) after draining is success.
|
||||
*
|
||||
* Parameterised on the transceive call so it is unit-testable without
|
||||
* an IsoDep (no Robolectric in this module).
|
||||
*
|
||||
* @throws IOException if the applet is not present (error SW).
|
||||
*/
|
||||
internal fun selectApplet(transceive: (ByteArray) -> ByteArray) {
|
||||
// SELECT APDU: CLA=00 INS=A4 P1=04 P2=00 Lc=08 Data=AID
|
||||
val apdu = byteArrayOf(
|
||||
0x00, INS_SELECT, 0x04, 0x00,
|
||||
FIDO_AID.size.toByte(),
|
||||
) + FIDO_AID
|
||||
var response = transceive(apdu)
|
||||
var sw = extractSwStatic(response)
|
||||
// Drain any "more data available" (SW=61xx) chained response data.
|
||||
while (sw shr 8 == 0x61) {
|
||||
val remaining = sw and 0xFF
|
||||
val getResponse = byteArrayOf(
|
||||
0x00, INS_GET_RESPONSE, 0x00, 0x00,
|
||||
remaining.toByte(),
|
||||
)
|
||||
response = transceive(getResponse)
|
||||
sw = extractSwStatic(response)
|
||||
}
|
||||
if (sw != 0x9000) {
|
||||
throw IOException("FIDO applet SELECT failed: SW=${"%04x".format(sw)}")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun extractSwStatic(response: ByteArray): Int {
|
||||
require(response.size >= 2) { "NFC response too short: ${response.size}" }
|
||||
return ((response[response.size - 2].toInt() and 0xFF) shl 8) or
|
||||
(response[response.size - 1].toInt() and 0xFF)
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,205 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import android.util.Log
|
||||
import com.jcraft.jsch.Identity
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
private const val TAG = "FidoIdentity"
|
||||
|
||||
/**
|
||||
* JSch Identity implementation for FIDO2 SK keys.
|
||||
*
|
||||
* When JSch calls getSignature(), this delegates to the FIDO2 authenticator
|
||||
* (USB/NFC security key) and assembles the SSH SK signature wire format.
|
||||
*
|
||||
* Wire format for SSH SK signatures:
|
||||
* string algorithm_name (e.g. "sk-ssh-ed25519@openssh.com")
|
||||
* string raw_signature
|
||||
* byte flags
|
||||
* uint32 counter
|
||||
*/
|
||||
class FidoIdentity(
|
||||
private val skKeyData: SkKeyData,
|
||||
private val authenticator: FidoAuthenticator,
|
||||
/** Profile key name shown in the touch prompt so the user presents the right key (#237). */
|
||||
private val keyLabel: String? = null,
|
||||
) : Identity {
|
||||
|
||||
override fun getAlgName(): String = skKeyData.algorithmName
|
||||
|
||||
override fun getName(): String = "haven-fido-${skKeyData.algorithmName}"
|
||||
|
||||
override fun getPublicKeyBlob(): ByteArray = skKeyData.publicKeyBlob
|
||||
|
||||
override fun isEncrypted(): Boolean = false
|
||||
|
||||
override fun setPassphrase(passphrase: ByteArray?): Boolean = true
|
||||
|
||||
override fun decrypt(): Boolean = true
|
||||
|
||||
override fun clear() {}
|
||||
|
||||
/**
|
||||
* Sign SSH authentication data using the FIDO2 hardware authenticator.
|
||||
*
|
||||
* This is called on JSch's I/O thread and will block until:
|
||||
* 1. A security key is connected (USB) or tapped (NFC)
|
||||
* 2. The user physically touches the security key
|
||||
*/
|
||||
override fun getSignature(data: ByteArray): ByteArray = getSignature(data, algName)
|
||||
|
||||
override fun getSignature(data: ByteArray, alg: String): ByteArray {
|
||||
// SSH SK key flags (drafts-miller-ssh-agent §3.1.4 / sk-api.h):
|
||||
// 0x01 = SSH_SK_USER_PRESENCE_REQUIRED — always set; CTAP2 up:true.
|
||||
// 0x04 = SSH_SK_USER_VERIFICATION_REQUIRED — `ssh-keygen -O verify-required`.
|
||||
// We must do CTAP2 PIN protocol before GetAssertion, otherwise
|
||||
// the authenticator filters this credential out of the allowList
|
||||
// and returns CTAP2_ERR_NO_CREDENTIALS (0x2E).
|
||||
val requireUv = (skKeyData.flags.toInt() and 0x04) != 0
|
||||
|
||||
Log.d(TAG, "getSignature called: alg=$alg, dataLen=${data.size}")
|
||||
Log.d(TAG, "Requesting FIDO2 assertion from security key...")
|
||||
Log.d(TAG, " rpId (application): ${skKeyData.application}")
|
||||
Log.d(TAG, " credentialId: ${skKeyData.credentialId.size} bytes")
|
||||
Log.d(TAG, " flags=0x${"%02x".format(skKeyData.flags)} requireUv=$requireUv")
|
||||
|
||||
// Block the JSch thread while waiting for FIDO2 hardware response.
|
||||
// This is intentional — JSch's auth is synchronous.
|
||||
val result = try {
|
||||
runBlocking {
|
||||
authenticator.getAssertion(
|
||||
rpId = skKeyData.application,
|
||||
message = data,
|
||||
credentialId = skKeyData.credentialId,
|
||||
requireUv = requireUv,
|
||||
keyLabel = keyLabel,
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "FIDO2 assertion failed: ${e.javaClass.simpleName}: ${e.message}")
|
||||
throw e
|
||||
}
|
||||
|
||||
Log.d(TAG, "FIDO2 assertion received: sig=${result.signature.size}b, " +
|
||||
"flags=0x${"%02x".format(result.flags)}, counter=${result.counter}")
|
||||
|
||||
// Assert the ceremony we promised actually ran. Shipping a signature
|
||||
// with the user-verified bit clear when the key is marked
|
||||
// verify-required turns into "Permission denied (publickey)" at the
|
||||
// server, which is indistinguishable from offering the wrong key
|
||||
// (#531).
|
||||
skAssertionUvMismatch(requireUv, result.flags)?.let { reason ->
|
||||
Log.e(TAG, reason)
|
||||
throw java.io.IOException(reason)
|
||||
}
|
||||
|
||||
// Assemble SSH SK signature wire format
|
||||
val sigBlob = assembleSshSkSignature(alg, result.signature, result.flags, result.counter)
|
||||
Log.d(TAG, "Assembled SSH SK signature: ${sigBlob.size} bytes")
|
||||
return sigBlob
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble the SSH SK signature wire format:
|
||||
* string algorithm_name
|
||||
* string raw_signature
|
||||
* byte flags
|
||||
* uint32 counter
|
||||
*/
|
||||
private fun assembleSshSkSignature(
|
||||
algName: String,
|
||||
rawSignature: ByteArray,
|
||||
flags: Byte,
|
||||
counter: Int,
|
||||
): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
|
||||
// string algorithm_name
|
||||
writeString(out, algName.toByteArray())
|
||||
|
||||
// string signature — but the two sk algorithms want different content
|
||||
// here (#531). sk-ssh-ed25519 takes the authenticator's raw 64-byte
|
||||
// signature as-is. sk-ecdsa-sha2-nistp256 must NOT: a CTAP2 ES256
|
||||
// assertion returns an ASN.1 DER SEQUENCE{r,s}, while the SSH field
|
||||
// wants the same inner encoding as plain ecdsa-sha2-nistp256 — the two
|
||||
// values as SSH mpints, concatenated (OpenSSH PROTOCOL.u2f). Passing
|
||||
// DER through is why every ECDSA sk auth failed server-side after a
|
||||
// successful touch while ed25519 sk worked.
|
||||
val sigField = if (algName.contains("ecdsa")) derEcdsaToSshBlob(rawSignature) else rawSignature
|
||||
writeString(out, sigField)
|
||||
|
||||
// byte flags
|
||||
out.write(flags.toInt() and 0xFF)
|
||||
|
||||
// uint32 counter
|
||||
val counterBuf = ByteBuffer.allocate(4)
|
||||
counterBuf.order(ByteOrder.BIG_ENDIAN)
|
||||
counterBuf.putInt(counter)
|
||||
out.write(counterBuf.array())
|
||||
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun writeString(out: ByteArrayOutputStream, data: ByteArray) {
|
||||
val lenBuf = ByteBuffer.allocate(4)
|
||||
lenBuf.order(ByteOrder.BIG_ENDIAN)
|
||||
lenBuf.putInt(data.size)
|
||||
out.write(lenBuf.array())
|
||||
out.write(data)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an ASN.1 DER ECDSA signature (SEQUENCE { INTEGER r, INTEGER s }) to
|
||||
* the SSH ECDSA signature blob: mpint r followed by mpint s, each as an SSH
|
||||
* string of the integer's minimal two's-complement bytes. Rejects anything
|
||||
* that is not exactly a two-integer sequence.
|
||||
*/
|
||||
internal fun derEcdsaToSshBlob(der: ByteArray): ByteArray {
|
||||
var pos = 0
|
||||
fun readByte(): Int {
|
||||
require(pos < der.size) { "truncated DER signature" }
|
||||
return der[pos++].toInt() and 0xFF
|
||||
}
|
||||
fun readLength(): Int {
|
||||
val first = readByte()
|
||||
if (first < 0x80) return first
|
||||
val numBytes = first and 0x7F
|
||||
require(numBytes in 1..2) { "unsupported DER length form" }
|
||||
var len = 0
|
||||
repeat(numBytes) { len = (len shl 8) or readByte() }
|
||||
return len
|
||||
}
|
||||
fun readInteger(): java.math.BigInteger {
|
||||
require(readByte() == 0x02) { "expected DER INTEGER" }
|
||||
val len = readLength()
|
||||
require(len > 0 && pos + len <= der.size) { "bad DER INTEGER length" }
|
||||
val bytes = der.copyOfRange(pos, pos + len)
|
||||
pos += len
|
||||
return java.math.BigInteger(bytes)
|
||||
}
|
||||
|
||||
require(readByte() == 0x30) { "expected DER SEQUENCE" }
|
||||
val seqLen = readLength()
|
||||
require(pos + seqLen == der.size) { "DER SEQUENCE length mismatch" }
|
||||
val r = readInteger()
|
||||
val s = readInteger()
|
||||
require(pos == der.size) { "trailing bytes after DER signature" }
|
||||
require(r.signum() > 0 && s.signum() > 0) { "non-positive ECDSA parameter" }
|
||||
|
||||
val out = ByteArrayOutputStream()
|
||||
for (v in listOf(r, s)) {
|
||||
// BigInteger.toByteArray() is minimal two's-complement with a leading
|
||||
// 0x00 when the top bit is set — exactly the mpint content encoding.
|
||||
val b = v.toByteArray()
|
||||
val lenBuf = ByteBuffer.allocate(4)
|
||||
lenBuf.order(ByteOrder.BIG_ENDIAN)
|
||||
lenBuf.putInt(b.size)
|
||||
out.write(lenBuf.array())
|
||||
out.write(b)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
/**
|
||||
* SSH SK signature flag bits (draft-miller-ssh-agent §3.1.4 / OpenSSH sk-api.h),
|
||||
* which are the same bits the authenticator sets in authenticatorData.
|
||||
*/
|
||||
object SkFlags {
|
||||
/** SSH_SK_USER_PRESENCE_REQUIRED — the key was touched. */
|
||||
const val USER_PRESENT: Int = 0x01
|
||||
|
||||
/** SSH_SK_USER_VERIFICATION_REQUIRED — a PIN or biometric was checked. */
|
||||
const val USER_VERIFIED: Int = 0x04
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that an assertion actually carried the user verification Haven asked
|
||||
* for, and describe the mismatch if it did not.
|
||||
*
|
||||
* A key marked "Require PIN at sign-in" makes Haven run the CTAP2 clientPIN
|
||||
* exchange and attach a `pinUvAuthParam` to the GetAssertion. The authenticator
|
||||
* is then supposed to set the user-verified bit in the assertion, and OpenSSH
|
||||
* copies that bit into the signature blob. A server configured with
|
||||
* `verify-required` checks it and rejects the key if it is clear.
|
||||
*
|
||||
* Without this check the failure is invisible from the phone: the key is
|
||||
* touched, a signature is produced, Haven sends it, and the only symptom is the
|
||||
* server answering "Permission denied (publickey)" — which reads as the wrong
|
||||
* key rather than a ceremony that did not happen (#531).
|
||||
*
|
||||
* @param requestedUv whether the stored SK flags asked for user verification
|
||||
* @param assertionFlags the flags byte the authenticator returned
|
||||
* @return null when the assertion is consistent with what was asked, otherwise
|
||||
* a sentence naming what is missing
|
||||
*/
|
||||
fun skAssertionUvMismatch(requestedUv: Boolean, assertionFlags: Byte): String? {
|
||||
if (!requestedUv) return null
|
||||
val flags = assertionFlags.toInt()
|
||||
if (flags and SkFlags.USER_VERIFIED != 0) return null
|
||||
return "This key is set to require a PIN at sign-in, but the security key " +
|
||||
"returned a signature without verifying you (flags=0x${"%02x".format(assertionFlags)}). " +
|
||||
"A server that enforces verify-required will reject it. Check that the " +
|
||||
"key has a PIN set, and that the credential was created with " +
|
||||
"verify-required if the server demands it."
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Parsed data from an OpenSSH SK private key file.
|
||||
* Contains the credential handle and public key — no actual private key material.
|
||||
*/
|
||||
data class SkKeyData(
|
||||
val algorithmName: String,
|
||||
val publicKeyBlob: ByteArray,
|
||||
val application: String,
|
||||
val credentialId: ByteArray,
|
||||
val flags: Byte,
|
||||
) {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
if (other !is SkKeyData) return false
|
||||
return algorithmName == other.algorithmName &&
|
||||
publicKeyBlob.contentEquals(other.publicKeyBlob) &&
|
||||
application == other.application &&
|
||||
credentialId.contentEquals(other.credentialId) &&
|
||||
flags == other.flags
|
||||
}
|
||||
|
||||
override fun hashCode(): Int = credentialId.contentHashCode()
|
||||
|
||||
companion object {
|
||||
private val MAGIC = "HAVEN_SK\u0000".toByteArray()
|
||||
|
||||
/** Serialize for storage in SshKey.privateKeyBytes. */
|
||||
fun serialize(data: SkKeyData): ByteArray {
|
||||
val buf = ByteBuffer.allocate(
|
||||
MAGIC.size +
|
||||
4 + data.algorithmName.toByteArray().size +
|
||||
4 + data.publicKeyBlob.size +
|
||||
4 + data.application.toByteArray().size +
|
||||
4 + data.credentialId.size +
|
||||
1
|
||||
)
|
||||
buf.order(ByteOrder.BIG_ENDIAN)
|
||||
buf.put(MAGIC)
|
||||
putString(buf, data.algorithmName.toByteArray())
|
||||
putBytes(buf, data.publicKeyBlob)
|
||||
putString(buf, data.application.toByteArray())
|
||||
putBytes(buf, data.credentialId)
|
||||
buf.put(data.flags)
|
||||
return buf.array().copyOf(buf.position())
|
||||
}
|
||||
|
||||
/** Deserialize from SshKey.privateKeyBytes. */
|
||||
fun deserialize(bytes: ByteArray): SkKeyData {
|
||||
val buf = ByteBuffer.wrap(bytes)
|
||||
buf.order(ByteOrder.BIG_ENDIAN)
|
||||
val magic = ByteArray(MAGIC.size)
|
||||
buf.get(magic)
|
||||
require(magic.contentEquals(MAGIC)) { "Not an SK key blob" }
|
||||
val algorithmName = String(readBytes(buf))
|
||||
val publicKeyBlob = readBytes(buf)
|
||||
val application = String(readBytes(buf))
|
||||
val credentialId = readBytes(buf)
|
||||
val flags = buf.get()
|
||||
return SkKeyData(algorithmName, publicKeyBlob, application, credentialId, flags)
|
||||
}
|
||||
|
||||
fun isSkKeyBlob(bytes: ByteArray): Boolean {
|
||||
if (bytes.size < MAGIC.size) return false
|
||||
return bytes.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)
|
||||
}
|
||||
|
||||
private fun putString(buf: ByteBuffer, data: ByteArray) = putBytes(buf, data)
|
||||
|
||||
private fun putBytes(buf: ByteBuffer, data: ByteArray) {
|
||||
buf.putInt(data.size)
|
||||
buf.put(data)
|
||||
}
|
||||
|
||||
private fun readBytes(buf: ByteBuffer): ByteArray {
|
||||
val len = buf.int
|
||||
val data = ByteArray(len)
|
||||
buf.get(data)
|
||||
return data
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import android.util.Log
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
|
||||
private const val TAG = "SkKeyParser"
|
||||
|
||||
/**
|
||||
* Parses OpenSSH private key files for sk-ssh-ed25519@openssh.com and
|
||||
* sk-ecdsa-sha2-nistp256@openssh.com key types.
|
||||
*
|
||||
* The OpenSSH key v1 format is:
|
||||
* "openssh-key-v1\0" || cipher || kdf || kdf_options || num_keys
|
||||
* || public_key_section || private_key_section
|
||||
*/
|
||||
object SkKeyParser {
|
||||
|
||||
private const val AUTH_MAGIC = "openssh-key-v1\u0000"
|
||||
|
||||
/** Quick check if file bytes look like an SK key. */
|
||||
fun isSkKeyFile(fileBytes: ByteArray): Boolean {
|
||||
val text = fileBytes.decodeToString()
|
||||
if (!text.contains("BEGIN OPENSSH PRIVATE KEY")) return false
|
||||
val b64 = extractBase64(text) ?: return false
|
||||
val raw = Base64.getDecoder().decode(b64)
|
||||
if (raw.size < AUTH_MAGIC.length + 20) return false
|
||||
val magic = String(raw, 0, AUTH_MAGIC.length)
|
||||
if (magic != AUTH_MAGIC) return false
|
||||
// Read far enough to get the key type from the public key section
|
||||
val buf = ByteBuffer.wrap(raw)
|
||||
buf.position(AUTH_MAGIC.length)
|
||||
try {
|
||||
readString(buf) // ciphername
|
||||
readString(buf) // kdfname
|
||||
readBytes(buf) // kdfoptions
|
||||
buf.int // number of keys
|
||||
val pubSection = readBytes(buf) // public key section
|
||||
val pubBuf = ByteBuffer.wrap(pubSection)
|
||||
val keyType = readString(pubBuf)
|
||||
return keyType.startsWith("sk-")
|
||||
} catch (_: Exception) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an OpenSSH SK private key file and extract the credential data.
|
||||
*
|
||||
* @throws IllegalArgumentException if the file is not a valid SK key
|
||||
*/
|
||||
fun parse(fileBytes: ByteArray): SkKeyData {
|
||||
val text = fileBytes.decodeToString()
|
||||
val b64 = extractBase64(text)
|
||||
?: throw IllegalArgumentException("Not an OpenSSH private key")
|
||||
val raw = Base64.getDecoder().decode(b64)
|
||||
|
||||
val buf = ByteBuffer.wrap(raw)
|
||||
buf.order(ByteOrder.BIG_ENDIAN)
|
||||
|
||||
// Verify magic
|
||||
val magic = ByteArray(AUTH_MAGIC.length)
|
||||
buf.get(magic)
|
||||
require(String(magic) == AUTH_MAGIC) { "Invalid OpenSSH key magic" }
|
||||
|
||||
val cipherName = readString(buf)
|
||||
val kdfName = readString(buf)
|
||||
val kdfOptions = readBytes(buf)
|
||||
val numKeys = buf.int
|
||||
|
||||
Log.d(TAG, "SK key: cipher=$cipherName, kdf=$kdfName, keys=$numKeys")
|
||||
|
||||
require(numKeys == 1) { "Expected 1 key, got $numKeys" }
|
||||
|
||||
if (cipherName != "none") {
|
||||
throw IllegalArgumentException(
|
||||
"Encrypted SK key files are not yet supported. " +
|
||||
"Re-export without a passphrase: ssh-keygen -p -N '' -f <keyfile>"
|
||||
)
|
||||
}
|
||||
|
||||
// Parse public key section
|
||||
val pubSection = readBytes(buf)
|
||||
val pubBuf = ByteBuffer.wrap(pubSection)
|
||||
val keyType = readString(pubBuf)
|
||||
Log.d(TAG, "SK key type: $keyType")
|
||||
|
||||
require(keyType.startsWith("sk-")) {
|
||||
"Expected sk- key type, got: $keyType"
|
||||
}
|
||||
|
||||
// The full public key section IS the public key blob (SSH wire format)
|
||||
val publicKeyBlob = pubSection
|
||||
|
||||
// Parse private key section
|
||||
val privSection = readBytes(buf)
|
||||
val privBuf = ByteBuffer.wrap(privSection)
|
||||
|
||||
// Check ints (both must match for unencrypted keys)
|
||||
val check1 = privBuf.int
|
||||
val check2 = privBuf.int
|
||||
require(check1 == check2) {
|
||||
"Check integers don't match (key may be encrypted)"
|
||||
}
|
||||
|
||||
// Read private key fields
|
||||
val privKeyType = readString(privBuf)
|
||||
require(privKeyType == keyType) { "Key type mismatch: $privKeyType vs $keyType" }
|
||||
|
||||
// Parse based on key type
|
||||
val (application, credentialId, flags) = when {
|
||||
keyType.contains("ed25519") -> parseEd25519Sk(privBuf)
|
||||
keyType.contains("ecdsa") -> parseEcdsaSk(privBuf)
|
||||
else -> throw IllegalArgumentException("Unknown SK key type: $keyType")
|
||||
}
|
||||
|
||||
Log.d(TAG, "SK key parsed: app=$application, credentialId=${credentialId.size} bytes, flags=$flags")
|
||||
|
||||
return SkKeyData(
|
||||
algorithmName = keyType,
|
||||
publicKeyBlob = publicKeyBlob,
|
||||
application = application,
|
||||
credentialId = credentialId,
|
||||
flags = flags,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the OpenSSH public key line (e.g. "sk-ssh-ed25519@openssh.com AAAA... comment")
|
||||
*/
|
||||
fun formatPublicKeyLine(data: SkKeyData): String {
|
||||
val b64 = Base64.getEncoder().encodeToString(data.publicKeyBlob)
|
||||
return "${data.algorithmName} $b64"
|
||||
}
|
||||
|
||||
fun fingerprintSha256(publicKeyBlob: ByteArray): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(publicKeyBlob)
|
||||
val b64 = Base64.getEncoder().withoutPadding().encodeToString(digest)
|
||||
return "SHA256:$b64"
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an [SkKeyData] from a CTAP `authenticatorCredentialManagement`
|
||||
* `enumerateCredentials*` row plus the RP id it belongs to. Used by the
|
||||
* "Discover from security key" import path so the user can add resident
|
||||
* SSH-SK keys without ever generating a local stub file.
|
||||
*
|
||||
* The synthesised [SkKeyData.publicKeyBlob] follows the same OpenSSH
|
||||
* SSH-wire format as a parsed stub file's blob — algorithm name +
|
||||
* algorithm-specific fields + application. Downstream code (export,
|
||||
* fingerprinting, host-side authorized_keys handling) treats both
|
||||
* paths identically.
|
||||
*
|
||||
* [flags] defaults to `0x01` (user-presence bit), matching the SSH
|
||||
* USER_PRESENCE_REQUIRED constant. Callers that know the credential
|
||||
* was registered with verify-required should OR in `0x04`
|
||||
* (user-verification) so [FidoAuthenticator.getAssertion] triggers
|
||||
* the PIN/UV exchange when the key is used.
|
||||
*/
|
||||
fun buildFromCtapCredential(
|
||||
credential: Ctap2Cbor.CredentialEntry,
|
||||
rpId: String,
|
||||
flags: Byte = 0x01,
|
||||
): SkKeyData {
|
||||
return when (val pk = credential.publicKey) {
|
||||
is Ctap2Cbor.CosePublicKey.Ed25519 -> SkKeyData(
|
||||
algorithmName = "sk-ssh-ed25519@openssh.com",
|
||||
publicKeyBlob = buildEd25519SshPublicKeyBlob(pk.rawKey, rpId),
|
||||
application = rpId,
|
||||
credentialId = credential.credentialId,
|
||||
flags = flags,
|
||||
)
|
||||
is Ctap2Cbor.CosePublicKey.EcdsaP256 -> SkKeyData(
|
||||
algorithmName = "sk-ecdsa-sha2-nistp256@openssh.com",
|
||||
publicKeyBlob = buildEcdsaSshPublicKeyBlob(pk.x, pk.y, rpId),
|
||||
application = rpId,
|
||||
credentialId = credential.credentialId,
|
||||
flags = flags,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SSH wire format for sk-ssh-ed25519@openssh.com public key:
|
||||
* string "sk-ssh-ed25519@openssh.com"
|
||||
* string 32-byte Ed25519 public key
|
||||
* string application (e.g. "ssh:")
|
||||
*/
|
||||
private fun buildEd25519SshPublicKeyBlob(rawKey: ByteArray, application: String): ByteArray {
|
||||
require(rawKey.size == 32) { "Ed25519 public key must be 32 bytes, got ${rawKey.size}" }
|
||||
val algorithm = "sk-ssh-ed25519@openssh.com".toByteArray()
|
||||
val app = application.toByteArray()
|
||||
val buf = ByteBuffer.allocate(4 + algorithm.size + 4 + rawKey.size + 4 + app.size)
|
||||
buf.order(ByteOrder.BIG_ENDIAN)
|
||||
buf.putInt(algorithm.size); buf.put(algorithm)
|
||||
buf.putInt(rawKey.size); buf.put(rawKey)
|
||||
buf.putInt(app.size); buf.put(app)
|
||||
return buf.array()
|
||||
}
|
||||
|
||||
/**
|
||||
* SSH wire format for sk-ecdsa-sha2-nistp256@openssh.com public key:
|
||||
* string "sk-ecdsa-sha2-nistp256@openssh.com"
|
||||
* string "nistp256"
|
||||
* string 65-byte uncompressed EC point (0x04 || X || Y)
|
||||
* string application
|
||||
*/
|
||||
private fun buildEcdsaSshPublicKeyBlob(x: ByteArray, y: ByteArray, application: String): ByteArray {
|
||||
require(x.size == 32 && y.size == 32) {
|
||||
"ECDSA P-256 coords must be 32 bytes each, got x=${x.size} y=${y.size}"
|
||||
}
|
||||
val algorithm = "sk-ecdsa-sha2-nistp256@openssh.com".toByteArray()
|
||||
val curve = "nistp256".toByteArray()
|
||||
val ecPoint = ByteArray(1 + 32 + 32).apply {
|
||||
this[0] = 0x04 // uncompressed
|
||||
System.arraycopy(x, 0, this, 1, 32)
|
||||
System.arraycopy(y, 0, this, 33, 32)
|
||||
}
|
||||
val app = application.toByteArray()
|
||||
val total = 4 + algorithm.size + 4 + curve.size + 4 + ecPoint.size + 4 + app.size
|
||||
val buf = ByteBuffer.allocate(total)
|
||||
buf.order(ByteOrder.BIG_ENDIAN)
|
||||
buf.putInt(algorithm.size); buf.put(algorithm)
|
||||
buf.putInt(curve.size); buf.put(curve)
|
||||
buf.putInt(ecPoint.size); buf.put(ecPoint)
|
||||
buf.putInt(app.size); buf.put(app)
|
||||
return buf.array()
|
||||
}
|
||||
|
||||
// Private section format for sk-ssh-ed25519@openssh.com:
|
||||
// string key_type ("sk-ssh-ed25519@openssh.com") — already consumed
|
||||
// string public_key (32 bytes)
|
||||
// string application
|
||||
// byte flags
|
||||
// string key_handle (credential ID)
|
||||
// string reserved (empty)
|
||||
// string comment
|
||||
private fun parseEd25519Sk(buf: ByteBuffer): Triple<String, ByteArray, Byte> {
|
||||
val pubKey = readBytes(buf) // 32-byte Ed25519 public key
|
||||
val application = readString(buf)
|
||||
val flags = buf.get()
|
||||
val keyHandle = readBytes(buf) // credential ID
|
||||
val reserved = readBytes(buf) // typically empty
|
||||
// comment follows but we don't need it
|
||||
Log.d(TAG, "Ed25519-SK: pubKey=${pubKey.size}b, app=$application, handle=${keyHandle.size}b")
|
||||
return Triple(application, keyHandle, flags)
|
||||
}
|
||||
|
||||
// Private section format for sk-ecdsa-sha2-nistp256@openssh.com:
|
||||
// string key_type — already consumed
|
||||
// string curve_name ("nistp256")
|
||||
// ec_point Q (public key point)
|
||||
// string application
|
||||
// byte flags
|
||||
// string key_handle (credential ID)
|
||||
// string reserved
|
||||
// string comment
|
||||
private fun parseEcdsaSk(buf: ByteBuffer): Triple<String, ByteArray, Byte> {
|
||||
val curveName = readString(buf)
|
||||
val ecPoint = readBytes(buf) // uncompressed EC point
|
||||
val application = readString(buf)
|
||||
val flags = buf.get()
|
||||
val keyHandle = readBytes(buf) // credential ID
|
||||
val reserved = readBytes(buf) // typically empty
|
||||
Log.d(TAG, "ECDSA-SK: curve=$curveName, point=${ecPoint.size}b, app=$application, handle=${keyHandle.size}b")
|
||||
return Triple(application, keyHandle, flags)
|
||||
}
|
||||
|
||||
private fun extractBase64(text: String): String? {
|
||||
val start = text.indexOf("-----BEGIN OPENSSH PRIVATE KEY-----")
|
||||
val end = text.indexOf("-----END OPENSSH PRIVATE KEY-----")
|
||||
if (start < 0 || end < 0) return null
|
||||
val body = text.substring(start + "-----BEGIN OPENSSH PRIVATE KEY-----".length, end)
|
||||
return body.replace(Regex("\\s+"), "")
|
||||
}
|
||||
|
||||
private fun readString(buf: ByteBuffer): String = String(readBytes(buf))
|
||||
|
||||
private fun readBytes(buf: ByteBuffer): ByteArray {
|
||||
val len = buf.int
|
||||
require(len >= 0 && len <= buf.remaining()) {
|
||||
"Invalid length: $len (remaining: ${buf.remaining()})"
|
||||
}
|
||||
val data = ByteArray(len)
|
||||
buf.get(data)
|
||||
return data
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* #449: after the PIN exchange succeeded, a YubiKey 5.4.3 rejected credential
|
||||
* enumeration with `CTAP2 error 0x01` (CTAP1_ERR_INVALID_COMMAND).
|
||||
*
|
||||
* Credential management exists in two forms: CTAP 2.1 standardised it as
|
||||
* command 0x0A, but it shipped first as the 2.1-PRE prototype 0x41, which is
|
||||
* all a YubiKey below firmware 5.5 answers. Haven only ever sent 0x0A.
|
||||
*/
|
||||
class CredentialManagementPreviewTest {
|
||||
|
||||
/** GetInfo options map: { 4: { "clientPin": true, <extra> } } as CBOR. */
|
||||
private fun getInfoWith(vararg options: Pair<String, Boolean>): ByteArray {
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
// map(1) { 4: map(n) { ... } }
|
||||
out.write(0xA1)
|
||||
out.write(0x04)
|
||||
out.write(0xA0 or options.size)
|
||||
options.forEach { (k, v) ->
|
||||
out.write(0x60 or k.length)
|
||||
out.write(k.toByteArray(Charsets.US_ASCII))
|
||||
out.write(if (v) 0xF5 else 0xF4)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a CTAP 2_1 key advertises credMgmt`() {
|
||||
val info = Ctap2Cbor.decodeGetInfoResponse(getInfoWith("credMgmt" to true))
|
||||
assertTrue(info.credMgmtSupported)
|
||||
assertFalse(info.credMgmtPreviewSupported)
|
||||
}
|
||||
|
||||
/** The #449 key: prototype only. */
|
||||
@Test
|
||||
fun `a pre-5_5 YubiKey advertises only credentialMgmtPreview`() {
|
||||
val info = Ctap2Cbor.decodeGetInfoResponse(getInfoWith("credentialMgmtPreview" to true))
|
||||
assertFalse(
|
||||
"sending 0x0A to this key returns CTAP1_ERR_INVALID_COMMAND",
|
||||
info.credMgmtSupported,
|
||||
)
|
||||
assertTrue(info.credMgmtPreviewSupported)
|
||||
}
|
||||
|
||||
/** A key with neither cannot enumerate at all, and must not be guessed at. */
|
||||
@Test
|
||||
fun `a key with neither option reports both false`() {
|
||||
val info = Ctap2Cbor.decodeGetInfoResponse(getInfoWith("clientPin" to true))
|
||||
assertFalse(info.credMgmtSupported)
|
||||
assertFalse(info.credMgmtPreviewSupported)
|
||||
}
|
||||
|
||||
/** The command byte is the whole fix — the bodies are identical. */
|
||||
@Test
|
||||
fun `preview changes only the command byte`() {
|
||||
val standard = Ctap2Cbor.encodeCredentialManagementCommand(
|
||||
subCommand = Ctap2Cbor.CM_SUB_ENUMERATE_RPS_BEGIN,
|
||||
preview = false,
|
||||
)
|
||||
val preview = Ctap2Cbor.encodeCredentialManagementCommand(
|
||||
subCommand = Ctap2Cbor.CM_SUB_ENUMERATE_RPS_BEGIN,
|
||||
preview = true,
|
||||
)
|
||||
assertEquals(0x0A.toByte(), standard[0])
|
||||
assertEquals(0x41.toByte(), preview[0])
|
||||
assertArrayEqualsMsg(
|
||||
"only the command byte may differ",
|
||||
standard.copyOfRange(1, standard.size),
|
||||
preview.copyOfRange(1, preview.size),
|
||||
)
|
||||
}
|
||||
|
||||
/** Default must stay the standard command, so nothing changes for modern keys. */
|
||||
@Test
|
||||
fun `default is the standardised command`() {
|
||||
val cmd = Ctap2Cbor.encodeCredentialManagementCommand(
|
||||
subCommand = Ctap2Cbor.CM_SUB_ENUMERATE_RPS_BEGIN,
|
||||
)
|
||||
assertEquals(0x0A.toByte(), cmd[0])
|
||||
}
|
||||
|
||||
private fun assertArrayEqualsMsg(msg: String, a: ByteArray, b: ByteArray) {
|
||||
assertEquals(msg, a.toList(), b.toList())
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Guards the CTAP2 GetAssertion status -> exception mapping that drives the
|
||||
* #237 wrong-key retry: a NO_CREDENTIALS answer (wrong key) must surface as the
|
||||
* typed [FidoNoMatchingCredentialException] so [FidoAuthenticator.getAssertion]
|
||||
* re-prompts for the correct key, while every other failure stays a plain
|
||||
* [IOException] (no retry). If this mapping regresses, the retry silently turns
|
||||
* back into the original "wrong tap aborts the whole publickey method" bug.
|
||||
*/
|
||||
class Ctap2AssertionStatusTest {
|
||||
|
||||
@Test
|
||||
fun `STATUS_OK maps to no error`() {
|
||||
assertNull(ctap2AssertionErrorForStatus(Ctap2Cbor.STATUS_OK))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `NO_CREDENTIALS maps to the typed no-matching-credential exception`() {
|
||||
val e = ctap2AssertionErrorForStatus(Ctap2Cbor.STATUS_NO_CREDENTIALS)
|
||||
assertTrue(
|
||||
"expected FidoNoMatchingCredentialException, got ${e?.javaClass?.simpleName}",
|
||||
e is FidoNoMatchingCredentialException,
|
||||
)
|
||||
// Must remain an IOException so post-exhaustion the SSH/identity catch
|
||||
// sites still handle it exactly as before.
|
||||
assertTrue(e is IOException)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ACTION_TIMEOUT maps to a plain IOException, not the retry-triggering type`() {
|
||||
val e = ctap2AssertionErrorForStatus(Ctap2Cbor.STATUS_ACTION_TIMEOUT)
|
||||
assertTrue(e is IOException)
|
||||
assertTrue(
|
||||
"a touch timeout must NOT trigger the wrong-key retry",
|
||||
e !is FidoNoMatchingCredentialException,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an unknown error status maps to a plain IOException, not a retry`() {
|
||||
val e = ctap2AssertionErrorForStatus(0x01)
|
||||
assertTrue(e is IOException)
|
||||
assertTrue(e !is FidoNoMatchingCredentialException)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class Ctap2CborTest {
|
||||
|
||||
@Test
|
||||
fun `getAssertion without pin auth retains v1 wire shape`() {
|
||||
val cmd = Ctap2Cbor.encodeGetAssertionCommand(
|
||||
rpId = "ssh:",
|
||||
clientDataHash = ByteArray(32) { it.toByte() },
|
||||
credentialId = ByteArray(48) { (it * 3).toByte() },
|
||||
)
|
||||
// Command byte (0x02) + map(4) is the same shape we shipped before
|
||||
// the PIN protocol. Spot-check the leading bytes.
|
||||
assertEquals(0x02.toByte(), cmd[0])
|
||||
assertEquals(0xA4.toByte(), cmd[1]) // CBOR map of size 4
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getAssertion with pin auth carries keys 6 and 7`() {
|
||||
val authParam = ByteArray(32) { 0x42 }
|
||||
val cmd = Ctap2Cbor.encodeGetAssertionCommand(
|
||||
rpId = "ssh:primary",
|
||||
clientDataHash = ByteArray(32),
|
||||
credentialId = ByteArray(48),
|
||||
pinUvAuthParam = authParam,
|
||||
pinUvAuthProtocol = 2,
|
||||
)
|
||||
assertEquals(0x02.toByte(), cmd[0])
|
||||
assertEquals(0xA6.toByte(), cmd[1]) // CBOR map of size 6
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getInfo decoder extracts pin protocols and clientPin flag`() {
|
||||
// Hand-crafted CBOR: { 4: { "clientPin": true, "uv": false }, 6: [1, 2] }
|
||||
// No pinUvAuthToken option — CTAP 2.0 shape (e.g. YubiKey 5 firmware 5.2.x)
|
||||
val data = byteArrayOf(
|
||||
0xA2.toByte(), // map(2)
|
||||
0x04, // key 4 (options)
|
||||
0xA2.toByte(), // map(2)
|
||||
0x69, 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x50, 0x69, 0x6E, // text(9) "clientPin"
|
||||
0xF5.toByte(), // true
|
||||
0x62, 0x75, 0x76, // text(2) "uv"
|
||||
0xF4.toByte(), // false
|
||||
0x06, // key 6 (pinUvAuthProtocols)
|
||||
0x82.toByte(), // array(2)
|
||||
0x01, 0x02, // [1, 2]
|
||||
)
|
||||
val info = Ctap2Cbor.decodeGetInfoResponse(data)
|
||||
assertEquals(listOf(1, 2), info.pinUvAuthProtocols)
|
||||
assertTrue(info.clientPinSet)
|
||||
assertFalse(info.uvBuiltIn)
|
||||
assertFalse(
|
||||
"pinUvAuthToken absent must decode as false (CTAP 2.0 / YubiKey 5 pre-5.4 path)",
|
||||
info.pinUvAuthTokenSupported,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getInfo decoder reads pinUvAuthToken option when present`() {
|
||||
// CTAP 2.1 shape: options { clientPin: true, pinUvAuthToken: true }, protocols [2, 1]
|
||||
val data = byteArrayOf(
|
||||
0xA2.toByte(), // map(2)
|
||||
0x04, // key 4 (options)
|
||||
0xA2.toByte(), // map(2)
|
||||
0x69, 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x50, 0x69, 0x6E, // text(9) "clientPin"
|
||||
0xF5.toByte(), // true
|
||||
0x6E, 0x70, 0x69, 0x6E, 0x55, 0x76, 0x41, 0x75,
|
||||
0x74, 0x68, 0x54, 0x6F, 0x6B, 0x65, 0x6E, // text(14) "pinUvAuthToken"
|
||||
0xF5.toByte(), // true
|
||||
0x06, // key 6 (pinUvAuthProtocols)
|
||||
0x82.toByte(), // array(2)
|
||||
0x02, 0x01, // [2, 1]
|
||||
)
|
||||
val info = Ctap2Cbor.decodeGetInfoResponse(data)
|
||||
assertTrue(info.pinUvAuthTokenSupported)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `legacy getPinToken encoder emits subCommand 5 with no permissions or rpId`() {
|
||||
// CTAP 2.0 path (#15, olmari's YubiKey returning INVALID_COMMAND on subCmd 9):
|
||||
// Request is { 1: protocol, 2: 5, 3: COSE_Key, 6: pinHashEnc } — map(4).
|
||||
val pair = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val (x, y) = Ctap2PinProtocol.V2.ecPublicToCoseCoords(
|
||||
pair.public as java.security.interfaces.ECPublicKey,
|
||||
)
|
||||
val cmd = Ctap2Cbor.encodeClientPinGetTokenLegacy(
|
||||
protocol = 2,
|
||||
platformKeyAgreement = Ctap2Cbor.CoseEcdhPubKey(x, y),
|
||||
pinHashEnc = ByteArray(32),
|
||||
)
|
||||
assertEquals(Ctap2Cbor.CMD_CLIENT_PIN, cmd[0])
|
||||
assertEquals(0xA4.toByte(), cmd[1]) // map(4) — protocol, sub, KA, pinHashEnc
|
||||
// Locate the subCommand value: bytes are { 0xA4, 0x01, 0x02, 0x02, <sub> ... }
|
||||
// i.e. map header, key 1, value 2 (protocol), key 2, value <sub>.
|
||||
assertEquals(
|
||||
"subCommand byte must be 5 (legacy getPinToken)",
|
||||
Ctap2Cbor.PIN_SUB_GET_PIN_TOKEN_LEGACY.toByte(), cmd[5],
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cose key encode-decode round-trip via clientPin keyAgreement`() {
|
||||
// Build a minimal getKeyAgreement-style response: map { 1: COSE_Key }
|
||||
// by piggybacking the encoder used in clientPinGetTokenWithPermissions.
|
||||
val pair = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val (x, y) = Ctap2PinProtocol.V2.ecPublicToCoseCoords(
|
||||
pair.public as java.security.interfaces.ECPublicKey,
|
||||
)
|
||||
val key = Ctap2Cbor.CoseEcdhPubKey(x, y)
|
||||
val cmd = Ctap2Cbor.encodeClientPinGetTokenWithPermissions(
|
||||
protocol = 2,
|
||||
platformKeyAgreement = key,
|
||||
pinHashEnc = ByteArray(32),
|
||||
permissions = Ctap2Cbor.PERMISSION_GET_ASSERTION,
|
||||
rpId = "ssh:",
|
||||
)
|
||||
// First byte is the CTAP command (clientPIN = 0x06)
|
||||
assertEquals(Ctap2Cbor.CMD_CLIENT_PIN, cmd[0])
|
||||
assertEquals(0xA6.toByte(), cmd[1]) // map(6) — protocol, sub, KA, pinHashEnc, perms, rpId
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `decode keyAgreement response extracts COSE coords`() {
|
||||
// Build a getKeyAgreement response: { 1: COSE_Key{ 1:2, 3:-25, -1:1, -2:x, -3:y } }
|
||||
val x = ByteArray(32) { (0xAA + it).toByte() }
|
||||
val y = ByteArray(32) { (0x55 + it).toByte() }
|
||||
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
out.write(0xA1) // map(1)
|
||||
out.write(0x01) // key 1
|
||||
// COSE_Key map(5): keys 1, 3, -1, -2, -3
|
||||
out.write(0xA5)
|
||||
out.write(0x01); out.write(0x02) // 1: 2
|
||||
out.write(0x03); out.write(0x38); out.write(24) // 3: -25 — major1 + ai24 + value24
|
||||
out.write(0x20); out.write(0x01) // -1: 1
|
||||
out.write(0x21); out.write(0x58); out.write(32); out.write(x)
|
||||
out.write(0x22); out.write(0x58); out.write(32); out.write(y)
|
||||
|
||||
val parsed = Ctap2Cbor.decodeClientPinKeyAgreementResponse(out.toByteArray())
|
||||
assertArrayEquals(x, parsed.x)
|
||||
assertArrayEquals(y, parsed.y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Guards the CBOR pieces behind the either/or SK auth (#237): a GetAssertion
|
||||
* whose allowList carries several credentials, and pulling the
|
||||
* authenticator-reported "which credential I used" out of the response so we
|
||||
* learn which of the configured keys the user presented.
|
||||
*/
|
||||
class Ctap2EitherOrTest {
|
||||
|
||||
private fun ByteArray.containsSub(sub: ByteArray): Boolean {
|
||||
if (sub.isEmpty() || sub.size > size) return false
|
||||
outer@ for (i in 0..size - sub.size) {
|
||||
for (j in sub.indices) if (this[i + j] != sub[j]) continue@outer
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** CBOR-encode a byte string (definite length). */
|
||||
private fun cborBytes(b: ByteArray): ByteArray =
|
||||
if (b.size < 24) byteArrayOf((0x40 or b.size).toByte()) + b
|
||||
else byteArrayOf(0x58.toByte(), b.size.toByte()) + b
|
||||
|
||||
private fun cborText(s: String): ByteArray {
|
||||
val t = s.toByteArray()
|
||||
return byteArrayOf((0x60 or t.size).toByte()) + t
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `multi-credential allowList carries every credential`() {
|
||||
val c1 = byteArrayOf(1, 2, 3, 4)
|
||||
val c2 = byteArrayOf(5, 6, 7, 8)
|
||||
val cmd = Ctap2Cbor.encodeGetAssertionCommand(
|
||||
rpId = "ssh:",
|
||||
clientDataHash = ByteArray(32),
|
||||
credentialIds = listOf(c1, c2),
|
||||
up = false,
|
||||
)
|
||||
// Each credential id appears as a 4-byte CBOR byte string (0x44 …).
|
||||
assertTrue("c1 in allowList", cmd.containsSub(byteArrayOf(0x44, 1, 2, 3, 4)))
|
||||
assertTrue("c2 in allowList", cmd.containsSub(byteArrayOf(0x44, 5, 6, 7, 8)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `single-credential overload still works and reports no used credential`() {
|
||||
// Build a minimal response WITHOUT a credential field (key 1 absent).
|
||||
val authData = ByteArray(37) { it.toByte() }
|
||||
val sig = byteArrayOf(9, 9, 9, 9)
|
||||
val resp = byteArrayOf(0xA2.toByte()) + // map(2)
|
||||
byteArrayOf(0x02) + cborBytes(authData) + // 2: authData
|
||||
byteArrayOf(0x03) + cborBytes(sig) // 3: signature
|
||||
val decoded = Ctap2Cbor.decodeGetAssertionResponse(resp)
|
||||
assertArrayEquals(authData, decoded.authData)
|
||||
assertNull(decoded.usedCredentialId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `decode extracts the used credential id from response key 1`() {
|
||||
val credId = byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte(), 0xDD.toByte())
|
||||
val authData = ByteArray(37) { it.toByte() }
|
||||
val sig = byteArrayOf(7, 7, 7, 7)
|
||||
val credMap = byteArrayOf(0xA2.toByte()) +
|
||||
cborText("id") + cborBytes(credId) +
|
||||
cborText("type") + cborText("public-key")
|
||||
val resp = byteArrayOf(0xA3.toByte()) + // map(3)
|
||||
byteArrayOf(0x01) + credMap + // 1: credential {id, type}
|
||||
byteArrayOf(0x02) + cborBytes(authData) + // 2: authData
|
||||
byteArrayOf(0x03) + cborBytes(sig) // 3: signature
|
||||
val decoded = Ctap2Cbor.decodeGetAssertionResponse(resp)
|
||||
assertArrayEquals(credId, decoded.usedCredentialId)
|
||||
assertArrayEquals(authData, decoded.authData)
|
||||
assertArrayEquals(sig, decoded.signature)
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* Covers the CTAP2 authenticatorMakeCredential request encoding, the setPIN
|
||||
* encoder, and the MakeCredential response / authData parsing added for
|
||||
* on-device SSH-SK key registration (multiple-YubiKey enrolment).
|
||||
*
|
||||
* The MakeCredential reply carries the new credential's handle + COSE public
|
||||
* key inside authenticatorData; getting the attestedCredentialData offsets
|
||||
* wrong would silently produce a corrupt SSH key, so the authData parse is the
|
||||
* load-bearing test here.
|
||||
*/
|
||||
class Ctap2MakeCredentialTest {
|
||||
|
||||
@Test
|
||||
fun `makeCredential resident without UV is a map of 5`() {
|
||||
val cmd = Ctap2Cbor.encodeMakeCredentialCommand(
|
||||
clientDataHash = ByteArray(32) { it.toByte() },
|
||||
rpId = "ssh:",
|
||||
rpName = "SSH",
|
||||
userId = ByteArray(32) { (it * 7).toByte() },
|
||||
userName = "haven",
|
||||
userDisplayName = "Haven SSH",
|
||||
algorithms = listOf(Ctap2Cbor.COSE_ALG_EDDSA),
|
||||
residentKey = true,
|
||||
)
|
||||
assertEquals(Ctap2Cbor.CMD_MAKE_CREDENTIAL, cmd[0])
|
||||
assertEquals(0xA5.toByte(), cmd[1]) // map(5): cdh, rp, user, params, options
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `makeCredential with UV carries pinUvAuthParam keys 8 and 9 (map of 7)`() {
|
||||
val cmd = Ctap2Cbor.encodeMakeCredentialCommand(
|
||||
clientDataHash = ByteArray(32),
|
||||
rpId = "ssh:",
|
||||
rpName = "SSH",
|
||||
userId = ByteArray(16),
|
||||
userName = "haven",
|
||||
userDisplayName = "Haven SSH",
|
||||
algorithms = listOf(Ctap2Cbor.COSE_ALG_EDDSA),
|
||||
residentKey = true,
|
||||
pinUvAuthParam = ByteArray(16) { 0x42 },
|
||||
pinUvAuthProtocol = 2,
|
||||
)
|
||||
assertEquals(Ctap2Cbor.CMD_MAKE_CREDENTIAL, cmd[0])
|
||||
assertEquals(0xA7.toByte(), cmd[1]) // map(7)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `setPIN encoder emits subCommand 3 with keyAgreement, authParam, newPinEnc`() {
|
||||
val pair = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val (x, y) = Ctap2PinProtocol.V2.ecPublicToCoseCoords(
|
||||
pair.public as java.security.interfaces.ECPublicKey,
|
||||
)
|
||||
val cmd = Ctap2Cbor.encodeClientPinSetPin(
|
||||
protocol = 2,
|
||||
platformKeyAgreement = Ctap2Cbor.CoseEcdhPubKey(x, y),
|
||||
pinUvAuthParam = ByteArray(32) { 0x11 },
|
||||
newPinEnc = ByteArray(64) { 0x22 },
|
||||
)
|
||||
assertEquals(Ctap2Cbor.CMD_CLIENT_PIN, cmd[0])
|
||||
assertEquals(0xA5.toByte(), cmd[1]) // map(5)
|
||||
// bytes: { 0xA5, 0x01, 0x02(protocol), 0x02, <sub> ... }
|
||||
assertEquals(
|
||||
"subCommand byte must be 3 (setPIN)",
|
||||
Ctap2Cbor.PIN_SUB_SET_PIN.toByte(), cmd[5],
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `decode makeCredential response extracts authData`() {
|
||||
val authData = ByteArray(80) { it.toByte() }
|
||||
val out = ByteArrayOutputStream().apply {
|
||||
write(0xA2) // map(2)
|
||||
write(0x01) // key 1 (fmt)
|
||||
write(0x64); write("none".toByteArray()) // text(4) "none"
|
||||
write(0x02) // key 2 (authData)
|
||||
write(0x58); write(authData.size); write(authData) // bstr(80)
|
||||
}
|
||||
val resp = Ctap2Cbor.decodeMakeCredentialResponse(out.toByteArray())
|
||||
assertEquals("none", resp.fmt)
|
||||
assertArrayEquals(authData, resp.authData)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `parse attestedCredentialData extracts handle and ed25519 pubkey`() {
|
||||
val edPub = ByteArray(32) { (0x30 + it).toByte() }
|
||||
val credId = ByteArray(16) { (0x90 + it).toByte() }
|
||||
val authData = ByteArrayOutputStream().apply {
|
||||
write(ByteArray(32) { 0x01 }) // rpIdHash
|
||||
write(0x41) // flags: AT(0x40) | UP(0x01)
|
||||
write(byteArrayOf(0, 0, 0, 5)) // signCount = 5
|
||||
write(ByteArray(16) { 0x02 }) // aaguid
|
||||
write(byteArrayOf(0x00, credId.size.toByte())) // credIdLen = 16, big-endian
|
||||
write(credId)
|
||||
// COSE Ed25519 key: map(4) { 1:1 (OKP), 3:-8 (EdDSA), -1:6 (crv), -2: bstr(32) }
|
||||
write(0xA4)
|
||||
write(0x01); write(0x01)
|
||||
write(0x03); write(0x27) // 3: -8
|
||||
write(0x20); write(0x06) // -1: 6
|
||||
write(0x21); write(0x58); write(0x20); write(edPub) // -2: bstr(32)
|
||||
}.toByteArray()
|
||||
|
||||
val cred = Ctap2Cbor.parseAttestedCredentialData(authData)
|
||||
assertArrayEquals(credId, cred.credentialId)
|
||||
assertEquals(5, cred.signCount)
|
||||
assertTrue(cred.publicKey is Ctap2Cbor.CosePublicKey.Ed25519)
|
||||
assertArrayEquals(edPub, (cred.publicKey as Ctap2Cbor.CosePublicKey.Ed25519).rawKey)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `parse attestedCredentialData rejects authData without the AT flag`() {
|
||||
val authData = ByteArray(60).apply { this[32] = 0x01 } // UP only, AT bit unset
|
||||
try {
|
||||
Ctap2Cbor.parseAttestedCredentialData(authData)
|
||||
fail("expected IllegalArgumentException for missing AT flag")
|
||||
} catch (e: IllegalArgumentException) {
|
||||
assertTrue(e.message!!.contains("AT flag"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Test
|
||||
import java.security.MessageDigest
|
||||
import java.security.interfaces.ECPublicKey
|
||||
|
||||
class Ctap2PinProtocolTest {
|
||||
|
||||
@Test
|
||||
fun `v2 ecdh round-trip yields equal shared secret on both sides`() {
|
||||
// Two parties each generate ephemeral P-256 keys and run ECDH with
|
||||
// the v2 KDF; both must arrive at the same 64-byte shared secret.
|
||||
val alice = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val bob = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
|
||||
val zAlice = Ctap2PinProtocol.V2.ecdh(
|
||||
alice.private as java.security.interfaces.ECPrivateKey,
|
||||
bob.public as ECPublicKey,
|
||||
)
|
||||
val zBob = Ctap2PinProtocol.V2.ecdh(
|
||||
bob.private as java.security.interfaces.ECPrivateKey,
|
||||
alice.public as ECPublicKey,
|
||||
)
|
||||
assertArrayEquals("ECDH symmetry", zAlice, zBob)
|
||||
|
||||
val ssAlice = Ctap2PinProtocol.V2.deriveSharedSecret(zAlice)
|
||||
val ssBob = Ctap2PinProtocol.V2.deriveSharedSecret(zBob)
|
||||
assertEquals(64, ssAlice.size)
|
||||
assertArrayEquals("v2 shared secret symmetry", ssAlice, ssBob)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `v2 encrypt-decrypt round-trips a 16-byte pin hash`() {
|
||||
val keyA = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val keyB = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val z = Ctap2PinProtocol.V2.ecdh(
|
||||
keyA.private as java.security.interfaces.ECPrivateKey,
|
||||
keyB.public as ECPublicKey,
|
||||
)
|
||||
val ss = Ctap2PinProtocol.V2.deriveSharedSecret(z)
|
||||
|
||||
val pinHash = MessageDigest.getInstance("SHA-256")
|
||||
.digest("hunter2".toByteArray()).copyOfRange(0, 16)
|
||||
|
||||
val ct = Ctap2PinProtocol.V2.encrypt(ss, pinHash)
|
||||
// v2 prepends a 16-byte IV
|
||||
assertEquals(32, ct.size)
|
||||
val pt = Ctap2PinProtocol.V2.decrypt(ss, ct)
|
||||
assertArrayEquals(pinHash, pt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `v2 encrypt produces fresh IV across calls`() {
|
||||
val keyA = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val keyB = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val z = Ctap2PinProtocol.V2.ecdh(
|
||||
keyA.private as java.security.interfaces.ECPrivateKey,
|
||||
keyB.public as ECPublicKey,
|
||||
)
|
||||
val ss = Ctap2PinProtocol.V2.deriveSharedSecret(z)
|
||||
|
||||
val pt = ByteArray(16)
|
||||
val ct1 = Ctap2PinProtocol.V2.encrypt(ss, pt)
|
||||
val ct2 = Ctap2PinProtocol.V2.encrypt(ss, pt)
|
||||
// Same plaintext + key, different random IVs → different ciphertext blobs
|
||||
assertNotEquals(ct1.toList(), ct2.toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `v2 hmac matches across both parties`() {
|
||||
val keyA = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val keyB = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val z = Ctap2PinProtocol.V2.ecdh(
|
||||
keyA.private as java.security.interfaces.ECPrivateKey,
|
||||
keyB.public as ECPublicKey,
|
||||
)
|
||||
val ss = Ctap2PinProtocol.V2.deriveSharedSecret(z)
|
||||
val msg = "clientDataHash".toByteArray()
|
||||
val a = Ctap2PinProtocol.V2.authenticate(ss, msg)
|
||||
val b = Ctap2PinProtocol.V2.authenticate(ss, msg)
|
||||
assertEquals(32, a.size)
|
||||
assertArrayEquals(a, b)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `v1 round-trip pin hash with zero-iv aes`() {
|
||||
val keyA = Ctap2PinProtocol.V1.generateEphemeralKeyPair()
|
||||
val keyB = Ctap2PinProtocol.V1.generateEphemeralKeyPair()
|
||||
val z = Ctap2PinProtocol.V1.ecdh(
|
||||
keyA.private as java.security.interfaces.ECPrivateKey,
|
||||
keyB.public as ECPublicKey,
|
||||
)
|
||||
val ss = Ctap2PinProtocol.V1.deriveSharedSecret(z)
|
||||
assertEquals(32, ss.size)
|
||||
|
||||
val pinHash = MessageDigest.getInstance("SHA-256")
|
||||
.digest("password".toByteArray()).copyOfRange(0, 16)
|
||||
val ct = Ctap2PinProtocol.V1.encrypt(ss, pinHash)
|
||||
// v1 has no IV prefix; one AES block
|
||||
assertEquals(16, ct.size)
|
||||
assertArrayEquals(pinHash, Ctap2PinProtocol.V1.decrypt(ss, ct))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `v1 hmac is truncated to 16 bytes`() {
|
||||
val ss = ByteArray(32) { it.toByte() }
|
||||
val tag = Ctap2PinProtocol.V1.authenticate(ss, ByteArray(32))
|
||||
assertEquals(16, tag.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `protocol pick prefers v2 when both supported`() {
|
||||
assertEquals(Ctap2PinProtocol.V2, Ctap2PinProtocol.pick(listOf(1, 2)))
|
||||
assertEquals(Ctap2PinProtocol.V2, Ctap2PinProtocol.pick(listOf(2)))
|
||||
assertEquals(Ctap2PinProtocol.V1, Ctap2PinProtocol.pick(listOf(1)))
|
||||
// Empty list — some keys omit the field but support v2
|
||||
assertEquals(Ctap2PinProtocol.V2, Ctap2PinProtocol.pick(emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cose key round-trip preserves coords`() {
|
||||
val pair = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val pub = pair.public as ECPublicKey
|
||||
val (x, y) = Ctap2PinProtocol.V2.ecPublicToCoseCoords(pub)
|
||||
assertEquals(32, x.size)
|
||||
assertEquals(32, y.size)
|
||||
|
||||
// Reconstruct from coords and confirm ECDH still works
|
||||
val reconstructed = Ctap2PinProtocol.V2.coseKeyToEcPublic(x, y)
|
||||
val other = Ctap2PinProtocol.V2.generateEphemeralKeyPair()
|
||||
val zViaOriginal = Ctap2PinProtocol.V2.ecdh(
|
||||
other.private as java.security.interfaces.ECPrivateKey,
|
||||
pub,
|
||||
)
|
||||
val zViaReconstructed = Ctap2PinProtocol.V2.ecdh(
|
||||
other.private as java.security.interfaces.ECPrivateKey,
|
||||
reconstructed,
|
||||
)
|
||||
assertArrayEquals(zViaOriginal, zViaReconstructed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Channel-INIT must drain CTAPHID_KEEPALIVE (and stray frames) instead of
|
||||
* failing on the first non-INIT packet — that hard failure on a busy key
|
||||
* (reply 0xbb) was the FIDO-auth-on-reconnect storm seen on a flaky link.
|
||||
*/
|
||||
class CtapHidInitDrainTest {
|
||||
|
||||
// Raw on-wire cmd bytes: init packets carry bit 7. INIT=0x06, KEEPALIVE=0x3B, ERROR=0x3F.
|
||||
private val INIT = 0x86.toByte()
|
||||
private val KEEPALIVE = 0xBB.toByte()
|
||||
private val ERROR = 0xBF.toByte()
|
||||
|
||||
private fun frame(cmd: Byte, payload: ByteArray = ByteArray(17)) =
|
||||
Triple(byteArrayOf(0, 0, 0, 0), cmd, payload)
|
||||
|
||||
private fun source(vararg frames: Triple<ByteArray, Byte, ByteArray>): () -> Triple<ByteArray, Byte, ByteArray> {
|
||||
val q = ArrayDeque(frames.toList())
|
||||
return { q.removeFirst() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `returns the init reply when it arrives first`() {
|
||||
val reply = ByteArray(17) { it.toByte() }
|
||||
val r = drainToInitReply(MAX_READS, source(frame(INIT, reply)))
|
||||
assertArrayEquals(reply, r.third)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `drains keepalives then returns the init reply`() {
|
||||
val reply = ByteArray(17) { 9 }
|
||||
val r = drainToInitReply(
|
||||
MAX_READS,
|
||||
source(frame(KEEPALIVE), frame(KEEPALIVE), frame(KEEPALIVE), frame(INIT, reply)),
|
||||
)
|
||||
assertEquals(INIT, r.second)
|
||||
assertArrayEquals(reply, r.third)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `skips a stray non-init frame then succeeds`() {
|
||||
val r = drainToInitReply(MAX_READS, source(frame(0x90.toByte()), frame(INIT)))
|
||||
assertEquals(INIT, r.second)
|
||||
}
|
||||
|
||||
@Test(expected = IOException::class)
|
||||
fun `throws on ctaphid error during init`() {
|
||||
drainToInitReply(MAX_READS, source(frame(ERROR, byteArrayOf(0x06))))
|
||||
}
|
||||
|
||||
@Test(expected = IOException::class)
|
||||
fun `throws after maxReads keepalives without an init reply`() {
|
||||
var n = 0
|
||||
drainToInitReply(4) { n++; frame(KEEPALIVE) }
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MAX_READS = 16
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* SELECT must drain ISO 7816-4 "more data available" (SW=61xx) via GET
|
||||
* RESPONSE instead of failing on it. The Nitrokey 3A answers SELECT with
|
||||
* SW=6106, which the old strict 9000-only check rejected as fatal (#623).
|
||||
*/
|
||||
class CtapNfcSelectChainingTest {
|
||||
|
||||
private fun sw(hi: Int, lo: Int) = byteArrayOf(hi.toByte(), lo.toByte())
|
||||
|
||||
@Test
|
||||
fun `select succeeds when the applet answers 9000 directly`() {
|
||||
var calls = 0
|
||||
CtapNfcTransport.selectApplet { apdu ->
|
||||
calls++
|
||||
assertEquals(0xA4.toByte(), apdu[1]) // INS_SELECT
|
||||
sw(0x90, 0x00)
|
||||
}
|
||||
assertEquals(1, calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `select drains 61xx chaining via GET RESPONSE instead of failing`() {
|
||||
val fci = ByteArray(6) { 0x61.toByte() }
|
||||
val calls = mutableListOf<ByteArray>()
|
||||
CtapNfcTransport.selectApplet { apdu ->
|
||||
calls.add(apdu)
|
||||
when (calls.size) {
|
||||
1 -> fci + sw(0x61, 0x06) // SELECT: 6 bytes more available
|
||||
2 -> {
|
||||
assertEquals(0xC0.toByte(), apdu[1]) // INS_GET_RESPONSE
|
||||
assertEquals(6.toByte(), apdu[4]) // Le = remaining
|
||||
sw(0x90, 0x00) // drain complete
|
||||
}
|
||||
else -> error("unexpected extra transceive")
|
||||
}
|
||||
}
|
||||
assertEquals(2, calls.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `select drains multi-chunk 61xx chaining`() {
|
||||
var calls = 0
|
||||
CtapNfcTransport.selectApplet { _ ->
|
||||
calls++
|
||||
when (calls) {
|
||||
1 -> ByteArray(3) + sw(0x61, 0x03)
|
||||
2 -> ByteArray(3) + sw(0x61, 0x03)
|
||||
3 -> sw(0x90, 0x00)
|
||||
else -> error("unexpected extra transceive")
|
||||
}
|
||||
}
|
||||
assertEquals(3, calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `select fails on a genuine error status word`() {
|
||||
// 6A82 = file not found: the applet is not on this tag.
|
||||
var threw = false
|
||||
try {
|
||||
CtapNfcTransport.selectApplet { sw(0x6A, 0x82) }
|
||||
} catch (e: IOException) {
|
||||
threw = true
|
||||
assertTrue(e.message!!.contains("6a82"))
|
||||
}
|
||||
assertTrue("error SW must still be fatal", threw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.math.BigInteger
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* sk-ecdsa signature encoding (#531): a CTAP2 ES256 assertion signature is DER,
|
||||
* but the SSH sk-ecdsa signature field wants mpint r || mpint s. These tests
|
||||
* pin the conversion, including the padding edge cases where DER and mpint
|
||||
* agree (both use minimal two's-complement) and the malformed-input rejects.
|
||||
*/
|
||||
class DerEcdsaToSshBlobTest {
|
||||
|
||||
private fun derInteger(v: BigInteger): ByteArray {
|
||||
val b = v.toByteArray()
|
||||
return byteArrayOf(0x02, b.size.toByte()) + b
|
||||
}
|
||||
|
||||
private fun derSequence(vararg parts: ByteArray): ByteArray {
|
||||
val body = parts.reduce { a, b -> a + b }
|
||||
require(body.size < 0x80)
|
||||
return byteArrayOf(0x30, body.size.toByte()) + body
|
||||
}
|
||||
|
||||
private fun sshString(b: ByteArray): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
out.write(byteArrayOf(0, 0, 0, b.size.toByte()))
|
||||
out.write(b)
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun expectedBlob(r: BigInteger, s: BigInteger): ByteArray =
|
||||
sshString(r.toByteArray()) + sshString(s.toByteArray())
|
||||
|
||||
@Test
|
||||
fun `small r and s round-trip`() {
|
||||
val r = BigInteger.valueOf(0x1234)
|
||||
val s = BigInteger.valueOf(0x56)
|
||||
val der = derSequence(derInteger(r), derInteger(s))
|
||||
assertArrayEquals(expectedBlob(r, s), derEcdsaToSshBlob(der))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `high-bit values keep their sign byte`() {
|
||||
// 32-byte values with the top bit set: DER and mpint both need the
|
||||
// leading 0x00, so the 33-byte form must survive the conversion.
|
||||
val r = BigInteger(1, ByteArray(32) { 0xFF.toByte() })
|
||||
val s = BigInteger(1, byteArrayOf(0x80.toByte()) + ByteArray(31) { 0x11 })
|
||||
val der = derSequence(derInteger(r), derInteger(s))
|
||||
val blob = derEcdsaToSshBlob(der)
|
||||
assertArrayEquals(expectedBlob(r, s), blob)
|
||||
// First mpint is 33 bytes: 0x00 pad + 32 value bytes.
|
||||
assertArrayEquals(byteArrayOf(0, 0, 0, 33), blob.copyOfRange(0, 4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `short s from a lucky signature stays short`() {
|
||||
// ECDSA s can be numerically small; DER encodes it minimally and the
|
||||
// mpint must too, not zero-padded back to 32 bytes.
|
||||
val r = BigInteger(1, byteArrayOf(0x7F) + ByteArray(31) { 0x22 })
|
||||
val s = BigInteger.valueOf(0x0A)
|
||||
val der = derSequence(derInteger(r), derInteger(s))
|
||||
assertArrayEquals(expectedBlob(r, s), derEcdsaToSshBlob(der))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `long-form sequence length parses`() {
|
||||
// A P-256 signature body maxes out at 70 bytes so short form always
|
||||
// suffices there, but larger curves (P-521) need the 0x81 length form;
|
||||
// accept it rather than bake in a P-256-only assumption.
|
||||
val r = BigInteger(1, ByteArray(32) { 0xF0.toByte() })
|
||||
val s = BigInteger(1, ByteArray(32) { 0x9A.toByte() })
|
||||
val body = derInteger(r) + derInteger(s)
|
||||
val der = byteArrayOf(0x30, 0x81.toByte(), body.size.toByte()) + body
|
||||
assertArrayEquals(expectedBlob(r, s), derEcdsaToSshBlob(der))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `raw ed25519-style signature is rejected, not passed through`() {
|
||||
val raw = ByteArray(64) { 0x42 }
|
||||
assertThrows(IllegalArgumentException::class.java) { derEcdsaToSshBlob(raw) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `trailing bytes are rejected`() {
|
||||
val r = BigInteger.valueOf(5)
|
||||
val der = derSequence(derInteger(r), derInteger(r)) + byteArrayOf(0x00)
|
||||
assertThrows(IllegalArgumentException::class.java) { derEcdsaToSshBlob(der) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import android.hardware.usb.UsbConstants
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbEndpoint
|
||||
import android.hardware.usb.UsbInterface
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* [findFidoCtapHidInterface] device-matching coverage.
|
||||
*
|
||||
* Regression for the reported bug: FIDO2 (incl. NFC) auth stopped working when
|
||||
* a USB audio dongle was plugged in, because the old "any HID interface" match
|
||||
* selected the dongle's volume-button HID as the security key. A CTAPHID
|
||||
* interface is HID-class with an interrupt IN+OUT pair; the audio dongle's
|
||||
* consumer-control HID is interrupt-IN only, so it must NOT match — letting the
|
||||
* flow fall through to the user's NFC key.
|
||||
*/
|
||||
class FidoDeviceMatchTest {
|
||||
|
||||
private fun endpoint(dir: Int, type: Int = UsbConstants.USB_ENDPOINT_XFER_INT): UsbEndpoint =
|
||||
mockk {
|
||||
every { direction } returns dir
|
||||
every { this@mockk.type } returns type
|
||||
}
|
||||
|
||||
private fun iface(cls: Int, eps: List<UsbEndpoint>): UsbInterface = mockk {
|
||||
every { interfaceClass } returns cls
|
||||
every { endpointCount } returns eps.size
|
||||
eps.forEachIndexed { i, ep -> every { getEndpoint(i) } returns ep }
|
||||
}
|
||||
|
||||
private fun device(ifaces: List<UsbInterface>): UsbDevice = mockk {
|
||||
every { interfaceCount } returns ifaces.size
|
||||
ifaces.forEachIndexed { i, f -> every { getInterface(i) } returns f }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `FIDO key — HID with interrupt IN+OUT — matches`() {
|
||||
val dev = device(
|
||||
listOf(
|
||||
iface(
|
||||
UsbConstants.USB_CLASS_HID,
|
||||
listOf(
|
||||
endpoint(UsbConstants.USB_DIR_IN),
|
||||
endpoint(UsbConstants.USB_DIR_OUT),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
assertNotNull(findFidoCtapHidInterface(dev))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `USB audio dongle — HID consumer-control, interrupt IN only — does not match`() {
|
||||
// Composite audio device: an Audio-class interface plus a HID interface
|
||||
// with a single interrupt-IN endpoint (the inline volume/play buttons).
|
||||
val dev = device(
|
||||
listOf(
|
||||
iface(UsbConstants.USB_CLASS_AUDIO, listOf(endpoint(UsbConstants.USB_DIR_IN))),
|
||||
iface(UsbConstants.USB_CLASS_HID, listOf(endpoint(UsbConstants.USB_DIR_IN))),
|
||||
),
|
||||
)
|
||||
assertNull(findFidoCtapHidInterface(dev))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `composite OTP+FIDO key — keyboard HID IN-only plus CTAPHID IN+OUT — matches via CTAPHID`() {
|
||||
// The OTP keyboard HID has interrupt-IN only (no OUT); the CTAPHID
|
||||
// interface has the IN+OUT pair. Must match (via the CTAPHID interface).
|
||||
val dev = device(
|
||||
listOf(
|
||||
iface(UsbConstants.USB_CLASS_HID, listOf(endpoint(UsbConstants.USB_DIR_IN))),
|
||||
iface(
|
||||
UsbConstants.USB_CLASS_HID,
|
||||
listOf(
|
||||
endpoint(UsbConstants.USB_DIR_IN),
|
||||
endpoint(UsbConstants.USB_DIR_OUT),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
assertNotNull(findFidoCtapHidInterface(dev))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `HID with bulk IN+OUT (not interrupt) — does not match`() {
|
||||
// CTAPHID uses interrupt endpoints; a HID interface whose IN+OUT pair is
|
||||
// bulk is not a CTAPHID interface.
|
||||
val dev = device(
|
||||
listOf(
|
||||
iface(
|
||||
UsbConstants.USB_CLASS_HID,
|
||||
listOf(
|
||||
endpoint(UsbConstants.USB_DIR_IN, UsbConstants.USB_ENDPOINT_XFER_BULK),
|
||||
endpoint(UsbConstants.USB_DIR_OUT, UsbConstants.USB_ENDPOINT_XFER_BULK),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
assertNull(findFidoCtapHidInterface(dev))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no HID interface at all — does not match`() {
|
||||
val dev = device(listOf(iface(UsbConstants.USB_CLASS_AUDIO, listOf(endpoint(UsbConstants.USB_DIR_IN)))))
|
||||
assertNull(findFidoCtapHidInterface(dev))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* #449: importing a resident key over NFC surfaced Android's own wording for a
|
||||
* lifted tag — "Permission Denial: Tag ( ID: 27 77 A3 97 01 A3 77 ) is out of
|
||||
* date" — which reads like a permissions bug in Haven rather than "the key left
|
||||
* the field".
|
||||
*/
|
||||
class FidoFailureMessageTest {
|
||||
|
||||
/** The exact text from the #449 logcat. */
|
||||
private val tagLost = SecurityException(
|
||||
"Permission Denial: Tag ( ID: 27 77 A3 97 01 A3 77 ) is out of date",
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `a lifted NFC tag is explained in the user's terms`() {
|
||||
val msg = fidoFailureMessage(tagLost)
|
||||
assertNotNull("the #449 error must be recognised", msg)
|
||||
assertTrue(
|
||||
"should say what to do, not quote Android internals: $msg",
|
||||
msg!!.contains("Hold it flat"),
|
||||
)
|
||||
assertTrue("should not leak the raw wording", !msg.contains("Permission Denial"))
|
||||
}
|
||||
|
||||
/**
|
||||
* The other wording for the same physical event, seen on-device while
|
||||
* verifying the fix: the field breaks mid-transceive rather than the handle
|
||||
* going stale. TagLostException carries this message.
|
||||
*/
|
||||
@Test
|
||||
fun `a tag lost mid-exchange gets the same explanation`() {
|
||||
val msg = fidoFailureMessage(java.io.IOException("Tag was lost."))
|
||||
assertNotNull("TagLostException's wording must be recognised too", msg)
|
||||
assertTrue(msg!!.contains("Hold it flat"))
|
||||
}
|
||||
|
||||
/** Anything else falls through so the caller keeps the raw detail. */
|
||||
@Test
|
||||
fun `unrelated failures are not rewritten`() {
|
||||
assertNull(fidoFailureMessage(java.io.IOException("CTAP error 0x31")))
|
||||
assertNull(fidoFailureMessage(SecurityException("USB permission denied")))
|
||||
}
|
||||
|
||||
/** A null message must not blow up the mapper. */
|
||||
@Test
|
||||
fun `a message-less exception is handled`() {
|
||||
assertNull(fidoFailureMessage(SecurityException()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package sh.haven.core.fido
|
||||
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* #531. A reporter's `sk-ecdsa-sha2-nistp256@openssh.com` key was touched, a
|
||||
* signature was produced, and the server answered "publickey,password" — the
|
||||
* same thing it says for a key it has never heard of. The one fact that would
|
||||
* have separated the two, whether the assertion carried the user-verified bit,
|
||||
* was only ever in logcat.
|
||||
*/
|
||||
class SkAssertionCheckTest {
|
||||
|
||||
private val touchOnly: Byte = 0x01
|
||||
private val touchAndPin: Byte = 0x05
|
||||
|
||||
@Test
|
||||
fun `asking for verification and not getting it is reported`() {
|
||||
val msg = skAssertionUvMismatch(requestedUv = true, assertionFlags = touchOnly)
|
||||
assertNotNull("a UV-less assertion for a verify-required key must be caught", msg)
|
||||
assertTrue("should name the flags it saw: $msg", msg!!.contains("0x01"))
|
||||
assertTrue("should say the server will reject it: $msg", msg.contains("verify-required"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `asking for verification and getting it passes`() {
|
||||
assertNull(skAssertionUvMismatch(requestedUv = true, assertionFlags = touchAndPin))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a touch-only key is not held to a bit it never asked for`() {
|
||||
assertNull(skAssertionUvMismatch(requestedUv = false, assertionFlags = touchOnly))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a touch-only key that verifies anyway is not an error`() {
|
||||
assertNull(skAssertionUvMismatch(requestedUv = false, assertionFlags = touchAndPin))
|
||||
}
|
||||
|
||||
/**
|
||||
* Some authenticators set attested-credential-data (0x40) or extension-data
|
||||
* (0x80) alongside the presence bits, which makes the byte negative in
|
||||
* Kotlin. The check must look at the bit, not the sign.
|
||||
*/
|
||||
@Test
|
||||
fun `high bits set alongside user verification still count as verified`() {
|
||||
assertNull(
|
||||
skAssertionUvMismatch(requestedUv = true, assertionFlags = 0x85.toByte()),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `high bits set without user verification are still a mismatch`() {
|
||||
assertNotNull(
|
||||
skAssertionUvMismatch(requestedUv = true, assertionFlags = 0x81.toByte()),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user