webauthn-client-0.1.0.0: src/WebAuthn/Client.hs
{-# LANGUAGE OverloadedStrings #-}
-- | A software WebAuthn authenticator: the client half of a passkey ceremony,
-- as a library.
--
-- WebAuthn's client side is normally the browser plus a hardware or platform
-- authenticator. All the RP actually verifies, though, is an ES256 signature by
-- the public key it enrolled for the credential, over
-- @authData || SHA-256(clientDataJSON)@. This module performs that same
-- operation with a P-256 keypair held by the caller, which makes passkey-gated
-- APIs usable from a headless program.
--
-- The wire formats follow the WebAuthn Level 2 specification and, in
-- particular, the attestation format @none@: this authenticator makes no
-- attestation claims. Relying parties that require attestation, or that demand
-- an AAGUID with a known model, will not accept it — by design.
--
-- == Security
--
-- The private key is the credential. Anyone who can read the stored
-- 'Credential' can sign in exactly as the caller can. Persist it with
-- 'saveCredentialFile' (which sets mode @0600@) or with equivalent care.
module WebAuthn.Client
( -- * Credentials
Credential (..)
, loadCredentialFile
, saveCredentialFile
-- * Ceremony options
, RegistrationOptions (..)
, AuthenticationOptions (..)
, parseRegistrationOptions
, parseAuthenticationOptions
-- * Ceremonies
, createRegistration
, createAssertion
, registrationResponse
, assertionResponse
, assertionParts
-- * Encoding helpers
, b64url
, unb64url
, sha256Raw
) where
import Control.Exception (SomeException, try)
import Crypto.Hash (Digest, SHA256 (..), hash)
import Crypto.PubKey.ECC.ECDSA
( PrivateKey (..), PublicKey (..), Signature (..), sign )
import Crypto.PubKey.ECC.Generate (generate)
import Crypto.PubKey.ECC.Types
( CurveName (SEC_p256r1), Point (..), getCurveByName )
import Crypto.Random (getRandomBytes)
import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), object, withObject, (.:), (.=))
import Data.Aeson qualified as A
import Data.Aeson.Key qualified as Key
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Bits (shiftR, (.&.))
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Base64.URL qualified as B64Url
import Data.ByteString.Char8 qualified as BC
import Data.ByteString.Lazy qualified as BL
import Data.Char (isDigit)
import Data.Text (Text)
import Data.Text qualified as T
import Data.Text.Encoding qualified as TE
import System.Directory (createDirectoryIfMissing, doesFileExist)
import System.FilePath (takeDirectory)
import System.Posix.Files (setFileMode)
-- | An enrolled software credential. The private key is a P-256 scalar; the
-- sign counter is incremented for every assertion.
data Credential = Credential
{ credentialId :: !ByteString
-- ^ The raw WebAuthn credential id (random, 32 bytes for new credentials).
, privateKey :: !Integer
-- ^ The P-256 private scalar.
, rpId :: !Text
-- ^ The relying-party id the credential was created for.
, origin :: !Text
-- ^ The origin used in @clientDataJSON@ during registration.
, signCount :: !Int
-- ^ The last sign counter signed. Assertions use a greater value.
} deriving stock (Eq, Show)
instance ToJSON Credential where
toJSON cred = object
[ "credential_id" .= b64url (credentialId cred)
, "private_key" .= privateKey cred
, "rp_id" .= rpId cred
, "origin" .= origin cred
, "sign_count" .= signCount cred
]
instance FromJSON Credential where
parseJSON = withObject "Credential" $ \o -> do
rawId <- o .: "credential_id"
cid <- either (fail . T.unpack) pure (unb64url rawId)
Credential cid
<$> o .: "private_key"
<*> o .: "rp_id"
<*> o .: "origin"
<*> o .: "sign_count"
-- | Read a credential written by 'saveCredentialFile'. @Right Nothing@ means
-- the file does not exist; @Left@ means it exists but could not be read.
loadCredentialFile :: FilePath -> IO (Either Text (Maybe Credential))
loadCredentialFile path = do
exists <- doesFileExist path
if not exists
then pure (Right Nothing)
else do
raw <- BL.readFile path
pure $ case A.eitherDecode raw of
Left err -> Left ("could not parse the credential at " <> T.pack path
<> ": " <> T.pack err)
Right cred -> Right (Just cred)
-- | Write a credential owner-only (mode @0600@).
saveCredentialFile :: FilePath -> Credential -> IO (Either Text ())
saveCredentialFile path cred = do
let write = do
createDirectoryIfMissing True (takeDirectory path)
BL.writeFile path (A.encode cred)
setFileMode path 0o600
result <- try write
pure $ case result of
Left (e :: SomeException) ->
Left ("could not write the credential at " <> T.pack path <> ": "
<> T.pack (show e))
Right () -> Right ()
-- | The fields of a @PublicKeyCredentialCreationOptions@ that a software
-- authenticator needs.
data RegistrationOptions = RegistrationOptions
{ roChallenge :: !Text
, roRpId :: !Text
} deriving stock (Eq, Show)
-- | The fields of a @PublicKeyCredentialRequestOptions@ that a software
-- authenticator needs.
data AuthenticationOptions = AuthenticationOptions
{ aoChallenge :: !Text
, aoRpId :: !Text
} deriving stock (Eq, Show)
parseRegistrationOptions :: Value -> Either Text RegistrationOptions
parseRegistrationOptions value =
RegistrationOptions
<$> stringField value "challenge"
<*> nestedStringField value "rp" "id"
parseAuthenticationOptions :: Value -> Either Text AuthenticationOptions
parseAuthenticationOptions value =
AuthenticationOptions
<$> stringField value "challenge"
<*> stringField value "rpId"
-- | Generate a keypair and a credential id, and build the
-- @navigator.credentials.create()@ response for @challenge@.
createRegistration
:: Text -- ^ origin
-> Text -- ^ relying-party id
-> Text -- ^ challenge
-> IO (Credential, Value)
createRegistration originText rpId' challenge = do
(pub, priv) <- generate (getCurveByName SEC_p256r1)
credId <- getRandomBytes 32
let PrivateKey _ d = priv
cred = Credential
{ credentialId = credId
, privateKey = d
, rpId = rpId'
, origin = originText
, signCount = 0
}
pure (cred, registrationResponse originText rpId' challenge credId (public_q pub))
-- | Build the @navigator.credentials.get()@ response for @challenge@, using and
-- incrementing the credential's sign counter.
createAssertion :: Credential -> Text -> IO (Credential, Value)
createAssertion cred challenge = do
let counter = signCount cred + 1
cred' = cred { signCount = counter }
priv = PrivateKey (getCurveByName SEC_p256r1) (privateKey cred)
(clientData, authData, sig) <-
assertionParts (origin cred) (rpId cred) challenge counter priv
pure (cred', object
[ "clientDataJSON" .= b64url clientData
, "authenticatorData" .= b64url authData
, "signature" .= b64url (encodeDerSig sig)
, "rawId" .= b64url (credentialId cred)
])
-- | The three authenticated pieces of an assertion, so a test or a verifier can
-- check the signature without re-parsing the DER.
assertionParts
:: Text -> Text -> Text -> Int -> PrivateKey
-> IO (ByteString, ByteString, Signature)
assertionParts originText rpId' challenge counter priv = do
let clientData = clientDataJSON "webauthn.get" challenge originText
authData = sha256Raw (TE.encodeUtf8 rpId')
<> BS.singleton 0x05 -- UP | UV
<> beN 4 (fromIntegral counter)
sig <- sign priv SHA256 (authData <> sha256Raw clientData)
pure (clientData, authData, sig)
-- | The @clientDataJSON@ for a ceremony.
clientDataJSON :: Text -> Text -> Text -> ByteString
clientDataJSON typ challenge originText = BL.toStrict (A.encode (object
[ "type" .= typ
, "challenge" .= challenge
, "origin" .= originText
, "crossOrigin" .= False
]))
-- | A @navigator.credentials.create()@ response with attestation format
-- @none@.
registrationResponse :: Text -> Text -> Text -> ByteString -> Point -> Value
registrationResponse originText rpId' challenge credId point =
object
[ "clientDataJSON" .= b64url clientData
, "attestationObject" .= b64url attestation
, "rawId" .= b64url credId
]
where
clientData = clientDataJSON "webauthn.create" challenge originText
attestation = cborMap 3
<> cborText "fmt" <> cborText "none"
<> cborText "attStmt" <> cborMap 0
<> cborText "authData" <> cborBytes authData
authData = sha256Raw (TE.encodeUtf8 rpId')
<> BS.singleton 0x45 -- UP | UV | AT
<> beN 4 0 -- sign counter
<> BS.replicate 16 0 -- AAGUID
<> beN 2 (toInteger (BS.length credId)) <> credId
<> coseKey
(xc, yc) = BS.splitAt 32 (pointBytes point)
coseKey = cborMap 5
<> cborInt 1 <> cborInt 2 -- kty: EC2
<> cborInt 3 <> cborInt (-7) -- alg: ES256
<> cborInt (-1) <> cborInt 1 -- crv: P-256
<> cborInt (-2) <> cborBytes xc
<> cborInt (-3) <> cborBytes yc
-- | A @navigator.credentials.get()@ response.
assertionResponse
:: Text -> Text -> Text -> ByteString -> PrivateKey -> Int
-> IO Value
assertionResponse originText rpId' challenge credId priv counter = do
(clientData, authData, sig) <-
assertionParts originText rpId' challenge counter priv
pure $ object
[ "clientDataJSON" .= b64url clientData
, "authenticatorData" .= b64url authData
, "signature" .= b64url (encodeDerSig sig)
, "rawId" .= b64url credId
]
-- ---------------------------------------------------------------------------
-- JSON field access
-- ---------------------------------------------------------------------------
stringField :: Value -> Text -> Either Text Text
stringField (Object o) key = case KeyMap.lookup (Key.fromText key) o of
Just (String s) -> Right s
_ -> Left ("missing or non-string field \"" <> key <> "\"")
stringField _ _ = Left "expected a JSON object"
nestedStringField :: Value -> Text -> Text -> Either Text Text
nestedStringField (Object o) outer inner = case KeyMap.lookup (Key.fromText outer) o of
Just value -> stringField value inner
Nothing -> Left ("missing field \"" <> outer <> "\"")
nestedStringField _ _ _ = Left "expected a JSON object"
-- ---------------------------------------------------------------------------
-- WebAuthn byte construction
-- ---------------------------------------------------------------------------
sha256Raw :: ByteString -> ByteString
sha256Raw bs = hexToBytes (BC.pack (show (hash bs :: Digest SHA256)))
-- | crypton-1.x's 'Digest' is not a memory 'ByteArrayAccess', so its 'Show'
-- (lowercase hex) is the stable way to get at the raw bytes.
hexToBytes :: ByteString -> ByteString
hexToBytes = BS.pack . pairs . BC.unpack
where
pairs (a : b : rest) = fromIntegral (digit a * 16 + digit b) : pairs rest
pairs _ = []
digit c
| isDigit c = fromEnum c - fromEnum '0'
| c >= 'a' && c <= 'f' = fromEnum c - fromEnum 'a' + 10
| c >= 'A' && c <= 'F' = fromEnum c - fromEnum 'A' + 10
| otherwise = 0
cborHeader :: Int -> Int -> ByteString
cborHeader major n
| n < 24 = BS.singleton (fromIntegral (major * 32 + n))
| n < 256 = BS.pack [fromIntegral (major * 32 + 24), fromIntegral n]
| otherwise = BS.pack [ fromIntegral (major * 32 + 25)
, fromIntegral (n `div` 256), fromIntegral (n `mod` 256) ]
cborBytes :: ByteString -> ByteString
cborBytes b = cborHeader 2 (BS.length b) <> b
cborText :: ByteString -> ByteString
cborText t = cborHeader 3 (BS.length t) <> t
cborMap :: Int -> ByteString
cborMap = cborHeader 5
cborInt :: Int -> ByteString
cborInt n
| n >= 0 = cborHeader 0 n
| otherwise = cborHeader 1 (negate n - 1)
pointBytes :: Point -> ByteString
pointBytes (Point x y) = be32 x <> be32 y
pointBytes PointO = BS.replicate 64 0
beN :: Int -> Integer -> ByteString
beN width n =
BS.pack [fromIntegral ((n `shiftR` (8 * i)) .&. 0xff) | i <- [width - 1, width - 2 .. 0]]
be32 :: Integer -> ByteString
be32 = beN 32
-- | DER-encode an ECDSA signature as @SEQUENCE { r INTEGER, s INTEGER }@.
encodeDerSig :: Signature -> ByteString
encodeDerSig (Signature r s) =
let body = encInt r <> encInt s
in BS.singleton 0x30 <> encLen (BS.length body) <> body
where
encInt n =
let raw = unsigned n
padded = case BS.uncons raw of
Just (b, _) | b >= 0x80 -> BS.cons 0x00 raw
_ -> raw
in BS.singleton 0x02 <> encLen (BS.length padded) <> padded
unsigned n
| n < 256 = BS.singleton (fromIntegral n)
| otherwise = unsigned (n `div` 256) <> BS.singleton (fromIntegral (n `mod` 256))
encLen n
| n < 0x80 = BS.singleton (fromIntegral n)
| otherwise =
let b = unsigned (toInteger n)
in BS.singleton (0x80 + fromIntegral (BS.length b)) <> b
b64url :: ByteString -> Text
b64url = TE.decodeUtf8 . B64Url.encodeUnpadded
unb64url :: Text -> Either Text ByteString
unb64url = either (Left . T.pack) Right . B64Url.decodeUnpadded . TE.encodeUtf8