module Network.TLS.Handshake.Certificate (
    certificateRejected,
    badCertificate,
    rejectOnException,
    verifyLeafKeyUsage,
    verifyLeafKeyUsagePurpose,
    verifyLeafKeySize,
    extractCAname,
) where

import qualified Control.Exception as E
import Control.Monad (unless)
import Control.Monad.State.Strict
import qualified Crypto.PubKey.RSA as RSA
import Data.ASN1.Types (asn1CharacterToString)
import Data.ByteArray.Encoding (Base (Base64), convertToBase)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8
import Data.List (intercalate, isInfixOf)
import Data.X509 (
    ExtExtendedKeyUsage (..),
    ExtKeyUsage (..),
    ExtKeyUsageFlag,
    ExtKeyUsagePurpose (..),
    PubKey (PubKeyRSA),
    encodeSignedObject,
    extensionGet,
    getDistinguishedElements,
 )

import Network.TLS.Context.Internal
import Network.TLS.Parameters
import Network.TLS.Struct
import Network.TLS.X509

-- | On certificate reject, throw an exception with the proper protocol alert
-- error.  The message carries the reasons of the validation and the subject
-- and issuer of the leaf; the whole chain goes to 'debugError' in PEM.
certificateRejected
    :: MonadIO m
    => Context -> [FailedReason] -> CertificateChain -> CertificateRejectReason -> m a
certificateRejected :: forall (m :: * -> *) a.
MonadIO m =>
Context
-> [FailedReason]
-> CertificateChain
-> CertificateRejectReason
-> m a
certificateRejected Context
ctx [FailedReason]
reasons CertificateChain
cc CertificateRejectReason
reason = do
    let ~String
pem = CertificateChain -> String
chainPEM CertificateChain
cc
    IO () -> m ()
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ DebugParams -> String -> IO ()
debugError (Context -> DebugParams
ctxDebug Context
ctx) (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
msg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
details String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
pem
    TLSError -> m a
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore (TLSError -> m a) -> TLSError -> m a
forall a b. (a -> b) -> a -> b
$ String -> AlertDescription -> TLSError
Error_Protocol (String
msg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
details) AlertDescription
alert
  where
    (String
msg, AlertDescription
alert) = case CertificateRejectReason
reason of
        CertificateRejectReason
CertificateRejectRevoked -> (String
"certificate is revoked", AlertDescription
CertificateRevoked)
        CertificateRejectReason
CertificateRejectExpired -> (String
"certificate has expired", AlertDescription
CertificateExpired)
        CertificateRejectReason
CertificateRejectUnknownCA -> (String
"certificate has unknown CA", AlertDescription
UnknownCa)
        CertificateRejectReason
CertificateRejectAbsent -> (String
"certificate is missing", AlertDescription
CertificateRequired)
        CertificateRejectOther String
s -> (String
"certificate rejected: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
s, AlertDescription
CertificateUnknown)
    -- wrapCertificateChecks may have put the reasons in the message already
    details :: String
details =
        (String -> String) -> [String] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (String
"; " String -> String -> String
forall a. [a] -> [a] -> [a]
++) ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$
            [String
rs | Bool -> Bool
not ([FailedReason] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [FailedReason]
reasons), Bool -> Bool
not (String
rs String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isInfixOf` String
msg)] [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ CertificateChain -> [String]
leafSummary CertificateChain
cc
    rs :: String
rs = [FailedReason] -> String
forall a. Show a => a -> String
show [FailedReason]
reasons

-- | The subject and issuer of the leaf certificate.
leafSummary :: CertificateChain -> [String]
leafSummary :: CertificateChain -> [String]
leafSummary (CertificateChain []) = []
leafSummary (CertificateChain (SignedExact Certificate
signed : [SignedExact Certificate]
_)) =
    [ String
"subject: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ DistinguishedName -> String
showDN (Certificate -> DistinguishedName
certSubjectDN Certificate
cert)
    , String
"issuer: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ DistinguishedName -> String
showDN (Certificate -> DistinguishedName
certIssuerDN Certificate
cert)
    ]
  where
    cert :: Certificate
cert = SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
signed

showDN :: DistinguishedName -> String
showDN :: DistinguishedName -> String
showDN DistinguishedName
dn =
    String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate
        String
", "
        [[Integer] -> String
name [Integer]
oid String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"=" String -> String -> String
forall a. [a] -> [a] -> [a]
++ ASN1CharacterString -> String
value ASN1CharacterString
cs | ([Integer]
oid, ASN1CharacterString
cs) <- DistinguishedName -> [([Integer], ASN1CharacterString)]
getDistinguishedElements DistinguishedName
dn]
  where
    name :: [Integer] -> String
name [Integer]
oid = String -> (String -> String) -> Maybe String -> String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
"." ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (Integer -> String) -> [Integer] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Integer -> String
forall a. Show a => a -> String
show [Integer]
oid) String -> String
forall a. a -> a
id (Maybe String -> String) -> Maybe String -> String
forall a b. (a -> b) -> a -> b
$ [Integer] -> [([Integer], String)] -> Maybe String
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup [Integer]
oid [([Integer], String)]
names
    value :: ASN1CharacterString -> String
value = String -> (String -> String) -> Maybe String -> String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe String
"?" String -> String
forall a. a -> a
id (Maybe String -> String)
-> (ASN1CharacterString -> Maybe String)
-> ASN1CharacterString
-> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ASN1CharacterString -> Maybe String
asn1CharacterToString
    names :: [([Integer], String)]
names =
        [ ([Integer
2, Integer
5, Integer
4, Integer
3], String
"CN")
        , ([Integer
2, Integer
5, Integer
4, Integer
6], String
"C")
        , ([Integer
2, Integer
5, Integer
4, Integer
7], String
"L")
        , ([Integer
2, Integer
5, Integer
4, Integer
8], String
"ST")
        , ([Integer
2, Integer
5, Integer
4, Integer
10], String
"O")
        , ([Integer
2, Integer
5, Integer
4, Integer
11], String
"OU")
        ]

-- | The certificates of the chain in PEM, leaf first.
chainPEM :: CertificateChain -> String
chainPEM :: CertificateChain -> String
chainPEM (CertificateChain [SignedExact Certificate]
certs) = (SignedExact Certificate -> String)
-> [SignedExact Certificate] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap SignedExact Certificate -> String
forall {a}. (Show a, Eq a, ASN1Object a) => SignedExact a -> String
pem [SignedExact Certificate]
certs
  where
    pem :: SignedExact a -> String
pem SignedExact a
signed =
        String
"-----BEGIN CERTIFICATE-----\n"
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ (ByteString -> String) -> [ByteString] -> String
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap
                ((String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n") (String -> String)
-> (ByteString -> String) -> ByteString -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> String
C8.unpack)
                (ByteString -> [ByteString]
lines64 (ByteString -> [ByteString]) -> ByteString -> [ByteString]
forall a b. (a -> b) -> a -> b
$ Base -> ByteString -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
Base -> bin -> bout
convertToBase Base
Base64 (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
$ SignedExact a -> ByteString
forall a.
(Show a, Eq a, ASN1Object a) =>
SignedExact a -> ByteString
encodeSignedObject SignedExact a
signed)
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"-----END CERTIFICATE-----\n"
    lines64 :: ByteString -> [ByteString]
lines64 ByteString
bs
        | ByteString -> Bool
B.null ByteString
bs = []
        | Bool
otherwise = let (ByteString
l, ByteString
r) = Int -> ByteString -> (ByteString, ByteString)
B.splitAt Int
64 ByteString
bs in ByteString
l ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: ByteString -> [ByteString]
lines64 ByteString
r

badCertificate :: MonadIO m => String -> m a
badCertificate :: forall (m :: * -> *) a. MonadIO m => String -> m a
badCertificate String
msg = TLSError -> m a
forall (m :: * -> *) a. MonadIO m => TLSError -> m a
throwCore (TLSError -> m a) -> TLSError -> m a
forall a b. (a -> b) -> a -> b
$ String -> AlertDescription -> TLSError
Error_Protocol String
msg AlertDescription
BadCertificate

rejectOnException :: E.SomeException -> IO CertificateUsage
rejectOnException :: SomeException -> IO CertificateUsage
rejectOnException SomeException
e = CertificateUsage -> IO CertificateUsage
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (CertificateUsage -> IO CertificateUsage)
-> CertificateUsage -> IO CertificateUsage
forall a b. (a -> b) -> a -> b
$ CertificateRejectReason -> CertificateUsage
CertificateUsageReject (CertificateRejectReason -> CertificateUsage)
-> CertificateRejectReason -> CertificateUsage
forall a b. (a -> b) -> a -> b
$ String -> CertificateRejectReason
CertificateRejectOther (String -> CertificateRejectReason)
-> String -> CertificateRejectReason
forall a b. (a -> b) -> a -> b
$ SomeException -> String
forall a. Show a => a -> String
show SomeException
e

verifyLeafKeyUsage :: MonadIO m => [ExtKeyUsageFlag] -> CertificateChain -> m ()
verifyLeafKeyUsage :: forall (m :: * -> *).
MonadIO m =>
[ExtKeyUsageFlag] -> CertificateChain -> m ()
verifyLeafKeyUsage [ExtKeyUsageFlag]
_ (CertificateChain []) = () -> m ()
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
verifyLeafKeyUsage [ExtKeyUsageFlag]
validFlags (CertificateChain (SignedExact Certificate
signed : [SignedExact Certificate]
_)) =
    Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
verified (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
        String -> m ()
forall (m :: * -> *) a. MonadIO m => String -> m a
badCertificate (String -> m ()) -> String -> m ()
forall a b. (a -> b) -> a -> b
$
            String
"certificate is not allowed for any of " String -> String -> String
forall a. [a] -> [a] -> [a]
++ [ExtKeyUsageFlag] -> String
forall a. Show a => a -> String
show [ExtKeyUsageFlag]
validFlags
  where
    cert :: Certificate
cert = SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
signed
    verified :: Bool
verified =
        case Extensions -> Maybe ExtKeyUsage
forall a. Extension a => Extensions -> Maybe a
extensionGet (Certificate -> Extensions
certExtensions Certificate
cert) of
            Maybe ExtKeyUsage
Nothing -> Bool
True -- unrestricted cert
            Just (ExtKeyUsage [ExtKeyUsageFlag]
flags) -> (ExtKeyUsageFlag -> Bool) -> [ExtKeyUsageFlag] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (ExtKeyUsageFlag -> [ExtKeyUsageFlag] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ExtKeyUsageFlag]
validFlags) [ExtKeyUsageFlag]
flags

verifyLeafKeyUsagePurpose
    :: MonadIO m => [ExtKeyUsagePurpose] -> CertificateChain -> m ()
verifyLeafKeyUsagePurpose :: forall (m :: * -> *).
MonadIO m =>
[ExtKeyUsagePurpose] -> CertificateChain -> m ()
verifyLeafKeyUsagePurpose [ExtKeyUsagePurpose]
_ (CertificateChain []) = () -> m ()
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
verifyLeafKeyUsagePurpose [ExtKeyUsagePurpose]
validPurposes (CertificateChain (SignedExact Certificate
signed : [SignedExact Certificate]
_)) =
    Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
verified (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
        String -> m ()
forall (m :: * -> *) a. MonadIO m => String -> m a
badCertificate (String -> m ()) -> String -> m ()
forall a b. (a -> b) -> a -> b
$
            String
"certificate is not allowed for any of " String -> String -> String
forall a. [a] -> [a] -> [a]
++ [ExtKeyUsagePurpose] -> String
forall a. Show a => a -> String
show [ExtKeyUsagePurpose]
validPurposes
  where
    cert :: Certificate
cert = SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
signed
    verified :: Bool
verified = case Extensions -> Maybe ExtExtendedKeyUsage
forall a. Extension a => Extensions -> Maybe a
extensionGet (Certificate -> Extensions
certExtensions Certificate
cert) of
        Maybe ExtExtendedKeyUsage
Nothing -> Bool
True
        Just (ExtExtendedKeyUsage [ExtKeyUsagePurpose]
purposes) -> (ExtKeyUsagePurpose -> Bool) -> [ExtKeyUsagePurpose] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (ExtKeyUsagePurpose -> [ExtKeyUsagePurpose] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ExtKeyUsagePurpose]
validPurposes) [ExtKeyUsagePurpose]
purposes

-- | The RSA key of the peer's leaf certificate is to be at least
-- 'supportedMinRSAKeySize' and at most 'supportedMaxRSAKeySize' bits.  The
-- keys of the rest of the chain are left to the validation of the chain.
verifyLeafKeySize :: MonadIO m => Supported -> CertificateChain -> m ()
verifyLeafKeySize :: forall (m :: * -> *).
MonadIO m =>
Supported -> CertificateChain -> m ()
verifyLeafKeySize Supported
_ (CertificateChain []) = () -> m ()
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
verifyLeafKeySize Supported
supported (CertificateChain (SignedExact Certificate
signed : [SignedExact Certificate]
_)) =
    case Certificate -> PubKey
certPubKey (Certificate -> PubKey) -> Certificate -> PubKey
forall a b. (a -> b) -> a -> b
$ SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
signed of
        PubKeyRSA PublicKey
pk
            | Int
bits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
minBits ->
                String -> m ()
forall (m :: * -> *) a. MonadIO m => String -> m a
badCertificate (String -> m ()) -> String -> m ()
forall a b. (a -> b) -> a -> b
$
                    String
"RSA key of " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
bits String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" bits is shorter than " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
minBits
            | Int
maxBits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 Bool -> Bool -> Bool
&& Int
bits Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxBits ->
                String -> m ()
forall (m :: * -> *) a. MonadIO m => String -> m a
badCertificate (String -> m ()) -> String -> m ()
forall a b. (a -> b) -> a -> b
$
                    String
"RSA key of " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
bits String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" bits is longer than " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
maxBits
          where
            bits :: Int
bits = PublicKey -> Int
RSA.public_size PublicKey
pk Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
8
        PubKey
_ -> () -> m ()
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  where
    minBits :: Int
minBits = Supported -> Int
supportedMinRSAKeySize Supported
supported
    maxBits :: Int
maxBits = Supported -> Int
supportedMaxRSAKeySize Supported
supported

extractCAname :: SignedCertificate -> DistinguishedName
extractCAname :: SignedExact Certificate -> DistinguishedName
extractCAname SignedExact Certificate
cert = Certificate -> DistinguishedName
certSubjectDN (Certificate -> DistinguishedName)
-> Certificate -> DistinguishedName
forall a b. (a -> b) -> a -> b
$ SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
cert