{- | Short-lived certificates and certificate-hash verification for
WebTransport. Browsers permit self-signed WebTransport certificates when a
SHA-256 certificate hash is supplied out of band, but require a validity
period of at most 14 days.
-}
module LibP2P.Transport.WebTransport.Certificate (
  newWebTransportCredential,
  verifyWebTransportCertificate,
) where

import Crypto.Error qualified as Crypto
import Crypto.Hash (Digest, SHA256, hash)
import Crypto.PubKey.Ed25519 qualified as Ed25519
import Crypto.Random (getRandomBytes)
import Data.ByteArray (convert)
import Data.ByteString (ByteString)
import Data.Hourglass (
  DateTime,
  Duration (..),
  Elapsed (..),
  Hours (..),
  Minutes (..),
  NanoSeconds (..),
  Seconds (..),
  timeAdd,
  timeConvert,
  timeGetElapsed,
 )
import Data.X509 (
  Certificate (..),
  CertificateChain (..),
  DistinguishedName (..),
  Extensions (..),
  PrivKey (..),
  PubKey (..),
  PubKeyALG (..),
  SignatureALG (..),
  SignedCertificate,
  encodeSignedObject,
  getSigned,
  objectToSignedExact,
  signedObject,
 )
import LibP2P.Core.Multihash qualified as Multihash
import Network.TLS (Credential)
import Time.System (timeCurrent)

certificateValidityHours :: Int
certificateValidityHours :: Int
certificateValidityHours = Int
13 Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
24

maximumValiditySeconds :: Integer
maximumValiditySeconds :: Integer
maximumValiditySeconds = Integer
14 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
24 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
60 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
60

certificateSignatureAlgorithm :: SignatureALG
certificateSignatureAlgorithm :: SignatureALG
certificateSignatureAlgorithm = PubKeyALG -> SignatureALG
SignatureALG_IntrinsicHash PubKeyALG
PubKeyALG_Ed25519

{- | Generate a browser-acceptable short-lived Ed25519 certificate and return
its SHA-256 multihash for use in a @/certhash@ multiaddr.
-}
newWebTransportCredential :: IO (Credential, ByteString)
newWebTransportCredential :: IO (Credential, ByteString)
newWebTransportCredential = do
  secret <- IO SecretKey
newTLSSecret
  now <- timeConvert <$> timeCurrent
  let publicKey = SecretKey -> PublicKey
Ed25519.toPublic SecretKey
secret
      certificate = DateTime -> PubKey -> Certificate
makeCertificate DateTime
now (PublicKey -> PubKey
PubKeyEd25519 PublicKey
publicKey)
      signCertificate ba
bytes =
        ( Signature -> a
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
convert (SecretKey -> PublicKey -> ba -> Signature
forall ba.
ByteArrayAccess ba =>
SecretKey -> PublicKey -> ba -> Signature
Ed25519.sign SecretKey
secret PublicKey
publicKey ba
bytes)
        , SignatureALG
certificateSignatureAlgorithm
        , ()
        )
      (signedCertificate, ()) = objectToSignedExact signCertificate certificate
      der = SignedExact Certificate -> ByteString
forall a.
(Show a, Eq a, ASN1Object a) =>
SignedExact a -> ByteString
encodeSignedObject SignedExact Certificate
signedCertificate
      credential = ([SignedExact Certificate] -> CertificateChain
CertificateChain [SignedExact Certificate
signedCertificate], SecretKey -> PrivKey
PrivKeyEd25519 SecretKey
secret)
  pure (credential, Multihash.encodeMultihash Multihash.SHA256 der)

newTLSSecret :: IO Ed25519.SecretKey
newTLSSecret :: IO SecretKey
newTLSSecret = do
  seed <- Int -> IO ByteString
forall byteArray. ByteArray byteArray => Int -> IO byteArray
forall (m :: * -> *) byteArray.
(MonadRandom m, ByteArray byteArray) =>
Int -> m byteArray
getRandomBytes Int
32 :: IO ByteString
  case Crypto.eitherCryptoError (Ed25519.secretKey seed) of
    Left CryptoError
err -> String -> IO SecretKey
forall a. String -> IO a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> IO SecretKey) -> String -> IO SecretKey
forall a b. (a -> b) -> a -> b
$ String
"newWebTransportCredential: " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> CryptoError -> String
forall a. Show a => a -> String
show CryptoError
err
    Right SecretKey
secret -> SecretKey -> IO SecretKey
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SecretKey
secret

makeCertificate :: DateTime -> PubKey -> Certificate
makeCertificate :: DateTime -> PubKey -> Certificate
makeCertificate DateTime
now PubKey
publicKey =
  Certificate
    { certVersion :: Int
certVersion = Int
2
    , certSerial :: Integer
certSerial = Integer
1
    , certSignatureAlg :: SignatureALG
certSignatureAlg = SignatureALG
certificateSignatureAlgorithm
    , certIssuerDN :: DistinguishedName
certIssuerDN = [(OID, ASN1CharacterString)] -> DistinguishedName
DistinguishedName []
    , certValidity :: (DateTime, DateTime)
certValidity =
        ( DateTime -> Duration -> DateTime
forall t ti. (Time t, TimeInterval ti) => t -> ti -> t
timeAdd DateTime
now (Int -> Duration
hoursDuration (-Int
1))
        , DateTime -> Duration -> DateTime
forall t ti. (Time t, TimeInterval ti) => t -> ti -> t
timeAdd DateTime
now (Int -> Duration
hoursDuration Int
certificateValidityHours)
        )
    , certSubjectDN :: DistinguishedName
certSubjectDN = [(OID, ASN1CharacterString)] -> DistinguishedName
DistinguishedName []
    , certPubKey :: PubKey
certPubKey = PubKey
publicKey
    , certExtensions :: Extensions
certExtensions = Maybe [ExtensionRaw] -> Extensions
Extensions Maybe [ExtensionRaw]
forall a. Maybe a
Nothing
    }

hoursDuration :: Int -> Duration
hoursDuration :: Int -> Duration
hoursDuration Int
hours =
  Hours -> Minutes -> Seconds -> NanoSeconds -> Duration
Duration (Int64 -> Hours
Hours (Int -> Int64
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
hours)) (Int64 -> Minutes
Minutes Int64
0) (Int64 -> Seconds
Seconds Int64
0) (Int64 -> NanoSeconds
NanoSeconds Int64
0)

{- | Verify a one-certificate WebTransport chain against any advertised
SHA-256 multihash and enforce the browser certificate constraints.
-}
verifyWebTransportCertificate ::
  [ByteString] -> CertificateChain -> IO (Either String ())
verifyWebTransportCertificate :: [ByteString] -> CertificateChain -> IO (Either String ())
verifyWebTransportCertificate [ByteString]
expected CertificateChain
chain = do
  now <- Elapsed -> DateTime
forall t1 t2. (Timeable t1, Time t2) => t1 -> t2
timeConvert (Elapsed -> DateTime) -> IO Elapsed -> IO DateTime
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO Elapsed
timeCurrent
  pure $ verifyAt now expected chain

verifyAt :: DateTime -> [ByteString] -> CertificateChain -> Either String ()
verifyAt :: DateTime -> [ByteString] -> CertificateChain -> Either String ()
verifyAt DateTime
now [ByteString]
expected (CertificateChain [SignedExact Certificate
signedCertificate]) = do
  digests <- (ByteString -> Either String ByteString)
-> [ByteString] -> Either String [ByteString]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM ByteString -> Either String ByteString
decodeSHA256 [ByteString]
expected
  let actual = SignedExact Certificate -> ByteString
certificateDigest SignedExact Certificate
signedCertificate
      certificate = Signed Certificate -> Certificate
forall a. (Show a, Eq a, ASN1Object a) => Signed a -> a
signedObject (SignedExact Certificate -> Signed Certificate
forall a. (Show a, Eq a, ASN1Object a) => SignedExact a -> Signed a
getSigned SignedExact Certificate
signedCertificate)
  require (actual `elem` digests) "WebTransport certificate hash mismatch"
  verifyValidity now certificate
  verifyKeyType (certPubKey certificate)
verifyAt DateTime
_ [ByteString]
_ CertificateChain
_ = String -> Either String ()
forall a b. a -> Either a b
Left String
"WebTransport TLS chain must contain exactly one certificate"

decodeSHA256 :: ByteString -> Either String ByteString
decodeSHA256 :: ByteString -> Either String ByteString
decodeSHA256 ByteString
multihash = do
  (algorithm, digest) <- ByteString -> Either String (HashFunction, ByteString)
Multihash.validateMultihash ByteString
multihash
  require (algorithm == Multihash.SHA256) "WebTransport certhash must use SHA-256"
  pure digest

certificateDigest :: SignedCertificate -> ByteString
certificateDigest :: SignedExact Certificate -> ByteString
certificateDigest SignedExact Certificate
certificate =
  Digest SHA256 -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
convert (ByteString -> Digest SHA256
forall ba a.
(ByteArrayAccess ba, HashAlgorithm a) =>
ba -> Digest a
hash (SignedExact Certificate -> ByteString
forall a.
(Show a, Eq a, ASN1Object a) =>
SignedExact a -> ByteString
encodeSignedObject SignedExact Certificate
certificate) :: Digest SHA256)

verifyValidity :: DateTime -> Certificate -> Either String ()
verifyValidity :: DateTime -> Certificate -> Either String ()
verifyValidity DateTime
now Certificate
certificate = do
  let (DateTime
notBefore, DateTime
notAfter) = Certificate -> (DateTime, DateTime)
certValidity Certificate
certificate
      Elapsed (Seconds Int64
validitySeconds) =
        DateTime -> Elapsed
forall t. Timeable t => t -> Elapsed
timeGetElapsed DateTime
notAfter Elapsed -> Elapsed -> Elapsed
forall a. Num a => a -> a -> a
- DateTime -> Elapsed
forall t. Timeable t => t -> Elapsed
timeGetElapsed DateTime
notBefore
  Bool -> String -> Either String ()
require (DateTime
now DateTime -> DateTime -> Bool
forall a. Ord a => a -> a -> Bool
>= DateTime
notBefore) String
"WebTransport certificate is not yet valid"
  Bool -> String -> Either String ()
require (DateTime
now DateTime -> DateTime -> Bool
forall a. Ord a => a -> a -> Bool
<= DateTime
notAfter) String
"WebTransport certificate has expired"
  Bool -> String -> Either String ()
require
    (Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger Int64
validitySeconds Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
maximumValiditySeconds)
    String
"WebTransport certificate is valid for longer than 14 days"

verifyKeyType :: PubKey -> Either String ()
verifyKeyType :: PubKey -> Either String ()
verifyKeyType PubKeyRSA{} = String -> Either String ()
forall a b. a -> Either a b
Left String
"WebTransport certificate must not use RSA"
verifyKeyType PubKey
_ = () -> Either String ()
forall a b. b -> Either a b
Right ()

require :: Bool -> String -> Either String ()
require :: Bool -> String -> Either String ()
require Bool
True String
_ = () -> Either String ()
forall a b. b -> Either a b
Right ()
require Bool
False String
message = String -> Either String ()
forall a b. a -> Either a b
Left String
message