{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}

module Data.X509.CertificateStore (
    CertificateStore,
    isEmptyCertificateStore,
    makeCertificateStore,
    readCertificateStore,
    readCertificates,

    -- * Queries
    findCertificate,
    findCertificates,
    listCertificates,
) where

import Data.Char (isDigit, isHexDigit)
import Data.Either (rights)
import qualified Data.List as L
#if !(MIN_VERSION_base(4,11,0))
import           Data.Semigroup
#endif
import qualified Control.Exception as E
import Control.Monad (filterM)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map as M
import Data.PEM (PEM, pemContent, pemName, pemParseBS)
import Data.X509
import Data.X509.ReadFile (readFileCloexec)
import System.Directory (
    doesDirectoryExist,
    doesFileExist,
    getDirectoryContents,
    pathIsSymbolicLink,
 )
import System.FilePath (takeFileName, (</>))
import qualified System.IO.Error as E
#if !defined(mingw32_HOST_OS)
import System.Posix.Files (getFileStatus, isRegularFile)
#endif

-- | A Collection of certificate or store of certificates.  Several
-- certificates may have the same subject, which is compared in its
-- canonical form.
data CertificateStore
    = CertificateStore (M.Map DistinguishedName [SignedCertificate])
    | CertificateStores [CertificateStore]

isEmptyCertificateStore :: CertificateStore -> Bool
isEmptyCertificateStore :: CertificateStore -> Bool
isEmptyCertificateStore (CertificateStore Map DistinguishedName [SignedCertificate]
m) = Map DistinguishedName [SignedCertificate] -> Bool
forall k a. Map k a -> Bool
M.null Map DistinguishedName [SignedCertificate]
m
isEmptyCertificateStore (CertificateStores [CertificateStore]
l) = (CertificateStore -> Bool) -> [CertificateStore] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all CertificateStore -> Bool
isEmptyCertificateStore [CertificateStore]
l

#if MIN_VERSION_base(4,9,0)
instance Semigroup CertificateStore where
    <> :: CertificateStore -> CertificateStore -> CertificateStore
(<>) = CertificateStore -> CertificateStore -> CertificateStore
append
#endif

instance Monoid CertificateStore where
    mempty :: CertificateStore
mempty = Map DistinguishedName [SignedCertificate] -> CertificateStore
CertificateStore Map DistinguishedName [SignedCertificate]
forall k a. Map k a
M.empty
#if !(MIN_VERSION_base(4,11,0))
    mappend = append
#endif

append :: CertificateStore -> CertificateStore -> CertificateStore
append :: CertificateStore -> CertificateStore -> CertificateStore
append s1 :: CertificateStore
s1@(CertificateStore Map DistinguishedName [SignedCertificate]
_) s2 :: CertificateStore
s2@(CertificateStore Map DistinguishedName [SignedCertificate]
_) = [CertificateStore] -> CertificateStore
CertificateStores [CertificateStore
s1, CertificateStore
s2]
append (CertificateStores [CertificateStore]
l) s2 :: CertificateStore
s2@(CertificateStore Map DistinguishedName [SignedCertificate]
_) = [CertificateStore] -> CertificateStore
CertificateStores ([CertificateStore]
l [CertificateStore] -> [CertificateStore] -> [CertificateStore]
forall a. [a] -> [a] -> [a]
++ [CertificateStore
s2])
append s1 :: CertificateStore
s1@(CertificateStore Map DistinguishedName [SignedCertificate]
_) (CertificateStores [CertificateStore]
l) = [CertificateStore] -> CertificateStore
CertificateStores ([CertificateStore
s1] [CertificateStore] -> [CertificateStore] -> [CertificateStore]
forall a. [a] -> [a] -> [a]
++ [CertificateStore]
l)
append (CertificateStores [CertificateStore]
l1) (CertificateStores [CertificateStore]
l2) = [CertificateStore] -> CertificateStore
CertificateStores ([CertificateStore]
l1 [CertificateStore] -> [CertificateStore] -> [CertificateStore]
forall a. [a] -> [a] -> [a]
++ [CertificateStore]
l2)

-- | Create a certificate store out of a list of X509 certificate
makeCertificateStore :: [SignedCertificate] -> CertificateStore
makeCertificateStore :: [SignedCertificate] -> CertificateStore
makeCertificateStore = Map DistinguishedName [SignedCertificate] -> CertificateStore
CertificateStore (Map DistinguishedName [SignedCertificate] -> CertificateStore)
-> ([SignedCertificate]
    -> Map DistinguishedName [SignedCertificate])
-> [SignedCertificate]
-> CertificateStore
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Map DistinguishedName [SignedCertificate]
 -> SignedCertificate -> Map DistinguishedName [SignedCertificate])
-> Map DistinguishedName [SignedCertificate]
-> [SignedCertificate]
-> Map DistinguishedName [SignedCertificate]
forall b a. (b -> a -> b) -> b -> [a] -> b
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
L.foldl' Map DistinguishedName [SignedCertificate]
-> SignedCertificate -> Map DistinguishedName [SignedCertificate]
accumulate Map DistinguishedName [SignedCertificate]
forall k a. Map k a
M.empty
  where
    -- the latest certificate comes first
    accumulate :: Map DistinguishedName [SignedCertificate]
-> SignedCertificate -> Map DistinguishedName [SignedCertificate]
accumulate Map DistinguishedName [SignedCertificate]
m SignedCertificate
x509 = ([SignedCertificate] -> [SignedCertificate] -> [SignedCertificate])
-> DistinguishedName
-> [SignedCertificate]
-> Map DistinguishedName [SignedCertificate]
-> Map DistinguishedName [SignedCertificate]
forall k a. Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
M.insertWith [SignedCertificate] -> [SignedCertificate] -> [SignedCertificate]
forall {a}. Eq a => [a] -> [a] -> [a]
add (SignedCertificate -> DistinguishedName
subjectKey SignedCertificate
x509) [SignedCertificate
x509] Map DistinguishedName [SignedCertificate]
m
    add :: [a] -> [a] -> [a]
add [a]
new [a]
old = [a]
new [a] -> [a] -> [a]
forall a. [a] -> [a] -> [a]
++ (a -> Bool) -> [a] -> [a]
forall a. (a -> Bool) -> [a] -> [a]
filter (a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [a]
new) [a]
old
    subjectKey :: SignedCertificate -> DistinguishedName
subjectKey = DistinguishedName -> DistinguishedName
canonicalDistinguishedName (DistinguishedName -> DistinguishedName)
-> (SignedCertificate -> DistinguishedName)
-> SignedCertificate
-> DistinguishedName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Certificate -> DistinguishedName
certSubjectDN (Certificate -> DistinguishedName)
-> (SignedCertificate -> Certificate)
-> SignedCertificate
-> DistinguishedName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SignedCertificate -> Certificate
getCertificate

-- | Find a certificate using the subject distinguished name.  If several
-- certificates have the subject, the one added last is returned.
findCertificate
    :: DistinguishedName -> CertificateStore -> Maybe SignedCertificate
findCertificate :: DistinguishedName -> CertificateStore -> Maybe SignedCertificate
findCertificate DistinguishedName
dn CertificateStore
store = case DistinguishedName -> CertificateStore -> [SignedCertificate]
findCertificates DistinguishedName
dn CertificateStore
store of
    SignedCertificate
c : [SignedCertificate]
_ -> SignedCertificate -> Maybe SignedCertificate
forall a. a -> Maybe a
Just SignedCertificate
c
    [] -> Maybe SignedCertificate
forall a. Maybe a
Nothing

-- | Find all certificates with the subject distinguished name.
findCertificates
    :: DistinguishedName -> CertificateStore -> [SignedCertificate]
findCertificates :: DistinguishedName -> CertificateStore -> [SignedCertificate]
findCertificates DistinguishedName
dn = CertificateStore -> [SignedCertificate]
lookupIn
  where
    key :: DistinguishedName
key = DistinguishedName -> DistinguishedName
canonicalDistinguishedName DistinguishedName
dn
    lookupIn :: CertificateStore -> [SignedCertificate]
lookupIn (CertificateStore Map DistinguishedName [SignedCertificate]
m) = [SignedCertificate]
-> DistinguishedName
-> Map DistinguishedName [SignedCertificate]
-> [SignedCertificate]
forall k a. Ord k => a -> k -> Map k a -> a
M.findWithDefault [] DistinguishedName
key Map DistinguishedName [SignedCertificate]
m
    lookupIn (CertificateStores [CertificateStore]
l) = (CertificateStore -> [SignedCertificate])
-> [CertificateStore] -> [SignedCertificate]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap CertificateStore -> [SignedCertificate]
lookupIn [CertificateStore]
l

-- | List all certificates in a store
listCertificates :: CertificateStore -> [SignedCertificate]
listCertificates :: CertificateStore -> [SignedCertificate]
listCertificates (CertificateStore Map DistinguishedName [SignedCertificate]
store) = [[SignedCertificate]] -> [SignedCertificate]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[SignedCertificate]] -> [SignedCertificate])
-> [[SignedCertificate]] -> [SignedCertificate]
forall a b. (a -> b) -> a -> b
$ Map DistinguishedName [SignedCertificate] -> [[SignedCertificate]]
forall k a. Map k a -> [a]
M.elems Map DistinguishedName [SignedCertificate]
store
listCertificates (CertificateStores [CertificateStore]
l) = (CertificateStore -> [SignedCertificate])
-> [CertificateStore] -> [SignedCertificate]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap CertificateStore -> [SignedCertificate]
listCertificates [CertificateStore]
l

-- | Create certificate store by reading certificates from file or directory
--
-- This function can be used to read multiple certificates from either
-- single file (multiple PEM formatted certificates concanated) or
-- directory (one certificate per file, file names are hashes from
-- certificate).
readCertificateStore :: FilePath -> IO (Maybe CertificateStore)
readCertificateStore :: FilePath -> IO (Maybe CertificateStore)
readCertificateStore FilePath
path = do
    isDir <- FilePath -> IO Bool
doesDirectoryExist FilePath
path
    isFile <- doesFileExist path
    wrapStore
        <$> (if isDir then makeDirStore else if isFile then makeFileStore else return [])
  where
    wrapStore :: [SignedCertificate] -> Maybe CertificateStore
    wrapStore :: [SignedCertificate] -> Maybe CertificateStore
wrapStore [] = Maybe CertificateStore
forall a. Maybe a
Nothing
    wrapStore [SignedCertificate]
l = CertificateStore -> Maybe CertificateStore
forall a. a -> Maybe a
Just (CertificateStore -> Maybe CertificateStore)
-> CertificateStore -> Maybe CertificateStore
forall a b. (a -> b) -> a -> b
$ [SignedCertificate] -> CertificateStore
makeCertificateStore [SignedCertificate]
l

    makeFileStore :: IO [SignedCertificate]
makeFileStore = FilePath -> IO [SignedCertificate]
readCertificates FilePath
path
    makeDirStore :: IO [SignedCertificate]
makeDirStore = do
        certFiles <- FilePath -> IO [FilePath]
listDirectoryCerts FilePath
path
        concat <$> mapM readCertificates certFiles

-- Try to read certificate from the content of a file.
--
-- The file may contains multiple certificates.  Only the PEM blocks
-- labeled CERTIFICATE are used: a TRUSTED CERTIFICATE block carries
-- OpenSSL trust settings, which are not interpreted.  Broken blocks
-- are skipped.
readCertificates :: FilePath -> IO [SignedCertificate]
readCertificates :: FilePath -> IO [SignedCertificate]
readCertificates FilePath
file =
    IO [SignedCertificate]
-> (IOError -> IO [SignedCertificate]) -> IO [SignedCertificate]
forall a. IO a -> (IOError -> IO a) -> IO a
E.catchIOError
        ([Either FilePath SignedCertificate] -> [SignedCertificate]
forall a b. [Either a b] -> [b]
rights ([Either FilePath SignedCertificate] -> [SignedCertificate])
-> (ByteString -> [Either FilePath SignedCertificate])
-> ByteString
-> [SignedCertificate]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PEM -> Either FilePath SignedCertificate)
-> [PEM] -> [Either FilePath SignedCertificate]
forall a b. (a -> b) -> [a] -> [b]
map PEM -> Either FilePath SignedCertificate
getCert ([PEM] -> [Either FilePath SignedCertificate])
-> (ByteString -> [PEM])
-> ByteString
-> [Either FilePath SignedCertificate]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PEM -> Bool) -> [PEM] -> [PEM]
forall a. (a -> Bool) -> [a] -> [a]
filter PEM -> Bool
isCert ([PEM] -> [PEM]) -> (ByteString -> [PEM]) -> ByteString -> [PEM]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [PEM]
pemBlocks (ByteString -> [SignedCertificate])
-> IO ByteString -> IO [SignedCertificate]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO ByteString
readFileCloexec FilePath
file)
        IOError -> IO [SignedCertificate]
skipIOError
  where
    isCert :: PEM -> Bool
isCert PEM
pem = PEM -> FilePath
pemName PEM
pem FilePath -> [FilePath] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [FilePath
"CERTIFICATE", FilePath
"X509 CERTIFICATE"]
    getCert :: PEM -> Either FilePath SignedCertificate
getCert = ByteString -> Either FilePath SignedCertificate
decodeSignedCertificate (ByteString -> Either FilePath SignedCertificate)
-> (PEM -> ByteString) -> PEM -> Either FilePath SignedCertificate
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PEM -> ByteString
pemContent
    skipIOError :: E.IOException -> IO [SignedCertificate]
    skipIOError :: IOError -> IO [SignedCertificate]
skipIOError IOError
_ = [SignedCertificate] -> IO [SignedCertificate]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []

-- | Parse PEM blocks one by one so that a broken block does not
-- discard the others.
pemBlocks :: B.ByteString -> [PEM]
pemBlocks :: ByteString -> [PEM]
pemBlocks = [ByteString] -> [PEM]
go ([ByteString] -> [PEM])
-> (ByteString -> [ByteString]) -> ByteString -> [PEM]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> [ByteString]
BC.lines
  where
    go :: [ByteString] -> [PEM]
go [ByteString]
ls = case (ByteString -> Bool) -> [ByteString] -> [ByteString]
forall a. (a -> Bool) -> [a] -> [a]
dropWhile (Bool -> Bool
not (Bool -> Bool) -> (ByteString -> Bool) -> ByteString -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> ByteString -> Bool
B.isPrefixOf ByteString
"-----BEGIN ") [ByteString]
ls of
        [] -> []
        ByteString
begin : [ByteString]
rest -> case (ByteString -> Bool)
-> [ByteString] -> ([ByteString], [ByteString])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (ByteString -> ByteString -> Bool
B.isPrefixOf ByteString
"-----END ") [ByteString]
rest of
            ([ByteString]
body, ByteString
end : [ByteString]
rest') ->
                (FilePath -> [PEM])
-> ([PEM] -> [PEM]) -> Either FilePath [PEM] -> [PEM]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either ([PEM] -> FilePath -> [PEM]
forall a b. a -> b -> a
const []) [PEM] -> [PEM]
forall a. a -> a
id (ByteString -> Either FilePath [PEM]
pemParseBS (ByteString -> Either FilePath [PEM])
-> ByteString -> Either FilePath [PEM]
forall a b. (a -> b) -> a -> b
$ [ByteString] -> ByteString
BC.unlines (ByteString
begin ByteString -> [ByteString] -> [ByteString]
forall a. a -> [a] -> [a]
: [ByteString]
body [ByteString] -> [ByteString] -> [ByteString]
forall a. [a] -> [a] -> [a]
++ [ByteString
end]))
                    [PEM] -> [PEM] -> [PEM]
forall a. [a] -> [a] -> [a]
++ [ByteString] -> [PEM]
go [ByteString]
rest'
            ([ByteString], [ByteString])
_ -> []

-- List all the path susceptible to contains a certificate in a directory
--
-- if the parameter is not a directory, hilarity follows.
listDirectoryCerts :: FilePath -> IO [FilePath]
listDirectoryCerts :: FilePath -> IO [FilePath]
listDirectoryCerts FilePath
path =
    IO [FilePath]
getDirContents IO [FilePath] -> ([FilePath] -> IO [FilePath]) -> IO [FilePath]
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (FilePath -> IO Bool) -> [FilePath] -> IO [FilePath]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM FilePath -> IO Bool
keep
  where
    -- hashed names are usually symbolic links to other files in the
    -- directory, but are regular files on Android, for instance
    keep :: FilePath -> IO Bool
keep FilePath
p = do
        regular <- FilePath -> IO Bool
isRegular FilePath
p
        if regular && isHashedFile (takeFileName p)
            then not <$> pathIsSymbolicLink p
            else return regular
    isHashedFile :: FilePath -> Bool
isHashedFile FilePath
s =
        FilePath -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length FilePath
s Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
10
            Bool -> Bool -> Bool
&& Char -> Bool
isDigit (FilePath
s FilePath -> Int -> Char
forall a. HasCallStack => [a] -> Int -> a
!! Int
9)
            Bool -> Bool -> Bool
&& (FilePath
s FilePath -> Int -> Char
forall a. HasCallStack => [a] -> Int -> a
!! Int
8) Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.'
            Bool -> Bool -> Bool
&& (Char -> Bool) -> FilePath -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isHexDigit (Int -> FilePath -> FilePath
forall a. Int -> [a] -> [a]
take Int
8 FilePath
s)
    isCert :: FilePath -> Bool
isCert FilePath
x = Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ FilePath -> FilePath -> Bool
forall a. Eq a => [a] -> [a] -> Bool
L.isPrefixOf FilePath
"." FilePath
x

    getDirContents :: IO [FilePath]
getDirContents =
        IO [FilePath] -> (IOError -> IO [FilePath]) -> IO [FilePath]
forall a. IO a -> (IOError -> IO a) -> IO a
E.catchIOError
            ((FilePath -> FilePath) -> [FilePath] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map (FilePath
path FilePath -> FilePath -> FilePath
</>) ([FilePath] -> [FilePath])
-> ([FilePath] -> [FilePath]) -> [FilePath] -> [FilePath]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (FilePath -> Bool) -> [FilePath] -> [FilePath]
forall a. (a -> Bool) -> [a] -> [a]
filter FilePath -> Bool
isCert ([FilePath] -> [FilePath]) -> IO [FilePath] -> IO [FilePath]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO [FilePath]
getDirectoryContents FilePath
path)
            IOError -> IO [FilePath]
emptyPaths
      where
        emptyPaths :: E.IOException -> IO [FilePath]
        emptyPaths :: IOError -> IO [FilePath]
emptyPaths IOError
_ = [FilePath] -> IO [FilePath]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []

-- | Whether the path is a regular file, following symbolic links.
isRegular :: FilePath -> IO Bool
#if defined(mingw32_HOST_OS)
isRegular = doesFileExist
#else
isRegular :: FilePath -> IO Bool
isRegular FilePath
p =
    IO Bool -> (IOError -> IO Bool) -> IO Bool
forall a. IO a -> (IOError -> IO a) -> IO a
E.catchIOError (FileStatus -> Bool
isRegularFile (FileStatus -> Bool) -> IO FileStatus -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> FilePath -> IO FileStatus
getFileStatus FilePath
p) (\IOError
_ -> Bool -> IO Bool
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False)
#endif