crypton-x509-system 1.10.0 → 1.10.1
raw patch · 7 files changed
+339/−115 lines, 7 filesdep −Win32dep −crypton-asn1-encodingdep −crypton-pemdep ~crypton-x509-storePVP ok
version bump matches the API change (PVP)
Dependencies removed: Win32, crypton-asn1-encoding, crypton-pem, process
Dependency ranges changed: crypton-x509-store
API changes (from Hackage documentation)
+ System.X509.Common: nativeCertificates :: String -> (Ptr (Ptr Word8) -> Ptr CSize -> IO CInt) -> IO [SignedCertificate]
Files
- ChangeLog.md +13/−0
- System/X509/Common.hs +55/−15
- System/X509/MacOS.hs +11/−28
- System/X509/Win32.hs +11/−64
- cbits/macos.c +150/−0
- cbits/win32.c +93/−0
- crypton-x509-system.cabal +6/−8
ChangeLog.md view
@@ -1,5 +1,18 @@ # ChangeLog for crypton-x509-system +## 1.10.1++The system store contains only the certificates that the OS trusts for+TLS: the trust settings on macOS, and the Disallowed store and the+enhanced key usage property on Windows.++* macOS: load TLS anchors according to trust settings+ [#37](https://github.com/kazu-yamamoto/crypton-certificate/pull/37)+* Fix trust store loading+ [#38](https://github.com/kazu-yamamoto/crypton-certificate/pull/38)+* Windows: exclude disallowed roots and roots not enabled for TLS+ [#45](https://github.com/kazu-yamamoto/crypton-certificate/pull/45)+ ## 1.10.0 * Follow the breaking change in `crypton-x509` 1.10.0
System/X509/Common.hs view
@@ -1,25 +1,65 @@ module System.X509.Common ( maybeSSLCertEnvOr,+ nativeCertificates, ) where -import Data.Foldable (asum)-import Data.Maybe (fromMaybe)+import Control.Exception (bracket)+import Control.Monad (when)+import Data.Bits (shiftL, (.|.))+import qualified Data.ByteString as B+import Data.Either (rights)+import Data.Maybe (catMaybes, maybeToList)+import Data.Word (Word8)+import Data.X509 import Data.X509.CertificateStore+import Foreign.C.Types (CInt (..), CSize (..))+import Foreign.Marshal.Alloc (alloca, free)+import Foreign.Ptr (Ptr, castPtr)+import Foreign.Storable (peek) import System.Environment (lookupEnv)--getOpenSslEnvs :: IO (Maybe String)-getOpenSslEnvs =- asum- <$> traverse- lookupEnv- [ "SSL_CERT_FILE"- , "SSL_CERT_DIR"- ]+import System.FilePath (searchPathSeparator) +-- | Like OpenSSL, the certificates in @SSL_CERT_FILE@ and in the+-- directories listed in @SSL_CERT_DIR@ replace the default store if+-- either variable is set to a non-empty value. maybeSSLCertEnvOr :: IO CertificateStore -> IO CertificateStore maybeSSLCertEnvOr defaultStore = do- overrideCertPaths <- getOpenSslEnvs- case overrideCertPaths of- Nothing -> defaultStore- Just certPath -> fromMaybe mempty <$> (readCertificateStore certPath)+ file <- nonEmpty <$> lookupEnv "SSL_CERT_FILE"+ dirs <- maybe [] splitDirs <$> lookupEnv "SSL_CERT_DIR"+ case maybeToList file ++ dirs of+ [] -> defaultStore+ paths -> mconcat . catMaybes <$> mapM readCertificateStore paths+ where+ nonEmpty (Just s) | not (null s) = Just s+ nonEmpty _ = Nothing+ splitDirs s = case break (== searchPathSeparator) s of+ (d, []) -> [d | not (null d)]+ (d, _ : rest) -> [d | not (null d)] ++ splitDirs rest++-- | Certificates returned by a C function as a malloc'ed buffer of 4-byte+-- big-endian lengths each followed by DER. The first argument names the+-- caller in errors.+nativeCertificates+ :: String+ -> (Ptr (Ptr Word8) -> Ptr CSize -> IO CInt)+ -> IO [SignedCertificate]+nativeCertificates name getCerts =+ alloca $ \pbuf -> alloca $ \plen -> do+ rc <- getCerts pbuf plen+ when (rc /= 0) $+ ioError $+ userError $+ name ++ ": cannot get the trusted certificates: " ++ show rc+ bracket (peek pbuf) free $ \buf -> do+ len <- peek plen+ bs <- B.packCStringLen (castPtr buf, fromIntegral len)+ return $ rights $ map decodeSignedCertificate $ split bs+ where+ split bs+ | B.length bs < 4 = []+ | otherwise =+ let (hdr, rest) = B.splitAt 4 bs+ n = foldl (\a w -> a `shiftL` 8 .|. fromIntegral w) 0 (B.unpack hdr)+ (der, rest') = B.splitAt n rest+ in der : split rest'
System/X509/MacOS.hs view
@@ -2,37 +2,20 @@ getSystemCertificateStore, ) where -import qualified Data.ByteString.Lazy as LBS-import Data.Either-import Data.PEM (PEM (..), pemParseLBS)-import System.Process+import Data.Word (Word8)+import Foreign.C.Types+import Foreign.Ptr -import Data.X509 import Data.X509.CertificateStore-import System.X509.Common (maybeSSLCertEnvOr)--rootCAKeyChain :: FilePath-rootCAKeyChain = "/System/Library/Keychains/SystemRootCertificates.keychain"--systemKeyChain :: FilePath-systemKeyChain = "/Library/Keychains/System.keychain"+import System.X509.Common (maybeSSLCertEnvOr, nativeCertificates) -listInKeyChains :: [FilePath] -> IO [SignedCertificate]-listInKeyChains keyChains = do- (_, Just hout, _, ph) <-- createProcess- (proc "security" ("find-certificate" : "-pa" : keyChains))- { std_out = CreatePipe- }- pems <- either error id . pemParseLBS <$> LBS.hGetContents hout- let targets =- rights $- map (decodeSignedCertificate . pemContent) $- filter ((== "CERTIFICATE") . pemName) pems- _ <- targets `seq` waitForProcess ph- return targets+foreign import ccall safe "hs_x509_trusted_certificates"+ c_trustedCertificates :: Ptr (Ptr Word8) -> Ptr CSize -> IO CInt +-- | Certificates trusted as TLS anchors according to the trust settings+-- of the user, admin and system domains. getSystemCertificateStore :: IO CertificateStore getSystemCertificateStore =- maybeSSLCertEnvOr- (makeCertificateStore <$> listInKeyChains [rootCAKeyChain, systemKeyChain])+ maybeSSLCertEnvOr $+ makeCertificateStore+ <$> nativeCertificates "System.X509.MacOS" c_trustedCertificates
System/X509/Win32.hs view
@@ -1,74 +1,21 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE ForeignFunctionInterface #-}-{-# LANGUAGE ScopedTypeVariables #-}- module System.X509.Win32 ( getSystemCertificateStore, ) where -import Data.Word+import Data.Word (Word8)+import Foreign.C.Types import Foreign.Ptr-import Foreign.Storable -import qualified Control.Exception as E-import Control.Monad (when)--import qualified Data.ByteString.Internal as B--import Data.ASN1.Error-import Data.X509 import Data.X509.CertificateStore--import System.Win32.Types-import System.X509.Common (maybeSSLCertEnvOr)--type HCertStore = Ptr Word8-type PCCERT_Context = Ptr Word8--foreign import stdcall unsafe "CertOpenSystemStoreW"- c_CertOpenSystemStore :: Ptr Word8 -> LPCTSTR -> IO HCertStore-foreign import stdcall unsafe "CertCloseStore"- c_CertCloseStore :: HCertStore -> DWORD -> IO ()--foreign import stdcall unsafe "CertEnumCertificatesInStore"- c_CertEnumCertificatesInStore- :: HCertStore -> PCCERT_Context -> IO PCCERT_Context--certOpenSystemStore :: IO HCertStore-certOpenSystemStore = withTString "ROOT" $ \cstr ->- c_CertOpenSystemStore nullPtr cstr+import System.X509.Common (maybeSSLCertEnvOr, nativeCertificates) -certFromContext :: PCCERT_Context -> IO (Either String SignedCertificate)-certFromContext cctx = do- ty <- peek (castPtr cctx :: Ptr DWORD)- p <- peek (castPtr (cctx `plusPtr` pbCertEncodedPos) :: Ptr (Ptr BYTE))- len <- peek (castPtr (cctx `plusPtr` cbCertEncodedPos) :: Ptr DWORD)- process ty p len- where- process 1 p len = do- b <- B.create (fromIntegral len) $ \dst -> B.memcpy dst p (fromIntegral len)- return $ decodeSignedObject b- process ty _ _ =- return $ Left ("windows certificate store: not supported type: " ++ show ty)- pbCertEncodedPos = alignment (undefined :: Ptr (Ptr BYTE))- cbCertEncodedPos = pbCertEncodedPos + sizeOf (undefined :: Ptr (Ptr BYTE))+foreign import ccall safe "hs_x509_win32_trusted_certificates"+ c_trustedCertificates :: Ptr (Ptr Word8) -> Ptr CSize -> IO CInt +-- | Certificates in the ROOT store that are enabled for server+-- authentication and not in the Disallowed store. getSystemCertificateStore :: IO CertificateStore-getSystemCertificateStore = maybeSSLCertEnvOr $ do- store <- certOpenSystemStore- when (store == nullPtr) $ error "no store"- certs <- loop store nullPtr- c_CertCloseStore store 0- return (makeCertificateStore certs)- where- loop st ptr = do- r <- c_CertEnumCertificatesInStore st ptr- if r == nullPtr- then return []- else- do- ecert <- certFromContext r- case ecert of- Left _ -> loop st r- Right cert -> (cert :) <$> (loop st r)- `E.catch` \(_ :: ASN1Error) -> loop st r+getSystemCertificateStore =+ maybeSSLCertEnvOr $+ makeCertificateStore+ <$> nativeCertificates "System.X509.Win32" c_trustedCertificates
+ cbits/macos.c view
@@ -0,0 +1,150 @@+#include <stdint.h>+#include <stdlib.h>+#include <string.h>++#if defined(__APPLE__)++#include <CoreFoundation/CoreFoundation.h>+#include <Security/Security.h>++enum { UNDECIDED, TRUSTED, DISTRUSTED };++/* Whether a usage constraint applies to TLS in general. */+static int applies_to_tls(CFDictionaryRef c) {+ if (CFDictionaryContainsKey(c, kSecTrustSettingsApplication) ||+ CFDictionaryContainsKey(c, kSecTrustSettingsPolicyString))+ return 0;+ CFTypeRef policy = CFDictionaryGetValue(c, kSecTrustSettingsPolicy);+ if (policy == NULL)+ return 1;+ if (CFGetTypeID(policy) != SecPolicyGetTypeID())+ return 0;+ CFDictionaryRef props = SecPolicyCopyProperties((SecPolicyRef)policy);+ if (props == NULL)+ return 0;+ CFTypeRef oid = CFDictionaryGetValue(props, kSecPolicyOid);+ int ok = oid != NULL && CFEqual(oid, kSecPolicyAppleSSL);+ CFRelease(props);+ return ok;+}++/* The trust settings of a certificate in a domain. An empty array+ means "always trust" and a missing result means TrustRoot. */+static int decide(SecCertificateRef cert, SecTrustSettingsDomain domain) {+ CFArrayRef settings = NULL;+ if (SecTrustSettingsCopyTrustSettings(cert, domain, &settings) != errSecSuccess ||+ settings == NULL)+ return UNDECIDED;+ CFIndex n = CFArrayGetCount(settings);+ int decision = n == 0 ? TRUSTED : UNDECIDED;+ for (CFIndex i = 0; i < n && decision == UNDECIDED; i++) {+ CFTypeRef c = CFArrayGetValueAtIndex(settings, i);+ if (CFGetTypeID(c) != CFDictionaryGetTypeID() || !applies_to_tls(c))+ continue;+ SInt32 result = kSecTrustSettingsResultTrustRoot;+ CFTypeRef r = CFDictionaryGetValue(c, kSecTrustSettingsResult);+ if (r != NULL && CFGetTypeID(r) == CFNumberGetTypeID())+ CFNumberGetValue(r, kCFNumberSInt32Type, &result);+ if (result == kSecTrustSettingsResultTrustRoot ||+ result == kSecTrustSettingsResultTrustAsRoot)+ decision = TRUSTED;+ else if (result == kSecTrustSettingsResultDeny)+ decision = DISTRUSTED;+ /* Unspecified: look at the next constraint */+ }+ CFRelease(settings);+ return decision;+}++static const SecTrustSettingsDomain domains[] = {+ kSecTrustSettingsDomainUser,+ kSecTrustSettingsDomainAdmin,+ kSecTrustSettingsDomainSystem,+};+#define NDOMAINS (sizeof(domains) / sizeof(domains[0]))++/* Certificates trusted as TLS anchors, as a malloc'ed buffer of+ 4-byte big-endian lengths each followed by DER. The user domain+ overrides the admin domain, which overrides the system domain. */+int hs_x509_trusted_certificates(uint8_t **out, size_t *outlen) {+ *out = NULL;+ *outlen = 0;+ CFMutableSetRef all = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);+ if (all == NULL)+ return -1;+ for (size_t d = 0; d < NDOMAINS; d++) {+ CFArrayRef certs = NULL;+ OSStatus st = SecTrustSettingsCopyCertificates(domains[d], &certs);+ if (st == errSecNoTrustSettings)+ continue;+ if (st != errSecSuccess) {+ CFRelease(all);+ return (int)st;+ }+ for (CFIndex i = 0; i < CFArrayGetCount(certs); i++)+ CFSetAddValue(all, CFArrayGetValueAtIndex(certs, i));+ CFRelease(certs);+ }++ CFIndex n = CFSetGetCount(all);+ const void **certs = calloc(n > 0 ? n : 1, sizeof(void *));+ CFDataRef *ders = calloc(n > 0 ? n : 1, sizeof(CFDataRef));+ if (certs == NULL || ders == NULL) {+ free(certs);+ free(ders);+ CFRelease(all);+ return -1;+ }+ CFSetGetValues(all, certs);++ size_t total = 0;+ for (CFIndex i = 0; i < n; i++) {+ SecCertificateRef cert = (SecCertificateRef)certs[i];+ int decision = UNDECIDED;+ for (size_t d = 0; d < NDOMAINS && decision == UNDECIDED; d++)+ decision = decide(cert, domains[d]);+ if (decision != TRUSTED)+ continue;+ ders[i] = SecCertificateCopyData(cert);+ if (ders[i] != NULL)+ total += 4 + (size_t)CFDataGetLength(ders[i]);+ }++ int ret = 0;+ uint8_t *buf = malloc(total > 0 ? total : 1);+ if (buf == NULL) {+ ret = -1;+ } else {+ uint8_t *p = buf;+ for (CFIndex i = 0; i < n; i++) {+ if (ders[i] == NULL)+ continue;+ uint32_t len = (uint32_t)CFDataGetLength(ders[i]);+ p[0] = len >> 24;+ p[1] = len >> 16;+ p[2] = len >> 8;+ p[3] = len;+ memcpy(p + 4, CFDataGetBytePtr(ders[i]), len);+ p += 4 + len;+ }+ *out = buf;+ *outlen = total;+ }+ for (CFIndex i = 0; i < n; i++)+ if (ders[i] != NULL)+ CFRelease(ders[i]);+ free(ders);+ free(certs);+ CFRelease(all);+ return ret;+}++#else++int hs_x509_trusted_certificates(uint8_t **out, size_t *outlen) {+ *out = NULL;+ *outlen = 0;+ return -1;+}++#endif
+ cbits/win32.c view
@@ -0,0 +1,93 @@+#include <stdint.h>+#include <stdlib.h>+#include <string.h>++#include <windows.h>+#include <wincrypt.h>++/* Whether the enhanced key usage property allows server authentication.+ Without the property, the certificate is good for all uses; an empty+ property means it is disabled. */+static int usable_for_tls(PCCERT_CONTEXT ctx) {+ const DWORD flag = CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG;+ DWORD size = 0;+ if (!CertGetEnhancedKeyUsage(ctx, flag, NULL, &size))+ return GetLastError() == (DWORD)CRYPT_E_NOT_FOUND;+ PCERT_ENHKEY_USAGE usage = malloc(size);+ if (usage == NULL)+ return 0;+ int ok = 0;+ SetLastError(0);+ if (!CertGetEnhancedKeyUsage(ctx, flag, usage, &size)) {+ ok = GetLastError() == (DWORD)CRYPT_E_NOT_FOUND;+ } else if (usage->cUsageIdentifier == 0) {+ ok = GetLastError() == (DWORD)CRYPT_E_NOT_FOUND;+ } else {+ for (DWORD i = 0; i < usage->cUsageIdentifier; i++)+ if (strcmp(usage->rgpszUsageIdentifier[i], szOID_PKIX_KP_SERVER_AUTH) == 0)+ ok = 1;+ }+ free(usage);+ return ok;+}++static int disallowed(HCERTSTORE dis, PCCERT_CONTEXT ctx) {+ if (dis == NULL)+ return 0;+ PCCERT_CONTEXT found = CertFindCertificateInStore(+ dis, ctx->dwCertEncodingType, 0, CERT_FIND_EXISTING, ctx, NULL);+ if (found == NULL)+ return 0;+ CertFreeCertificateContext(found);+ return 1;+}++/* Root certificates usable for TLS server authentication and not in the+ Disallowed store, as a malloc'ed buffer of 4-byte big-endian lengths+ each followed by DER. */+int hs_x509_win32_trusted_certificates(uint8_t **out, size_t *outlen) {+ *out = NULL;+ *outlen = 0;+ HCERTSTORE root = CertOpenSystemStoreW(0, L"ROOT");+ if (root == NULL)+ return -1;+ HCERTSTORE dis = CertOpenSystemStoreW(0, L"Disallowed");++ int ret = 0;+ uint8_t *buf = NULL;+ size_t len = 0, cap = 0;+ PCCERT_CONTEXT ctx = NULL;+ while ((ctx = CertEnumCertificatesInStore(root, ctx)) != NULL) {+ if ((ctx->dwCertEncodingType & X509_ASN_ENCODING) == 0 ||+ !usable_for_tls(ctx) || disallowed(dis, ctx))+ continue;+ size_t n = ctx->cbCertEncoded;+ if (len + 4 + n > cap) {+ size_t newcap = (cap + 4 + n) * 2;+ uint8_t *p = realloc(buf, newcap);+ if (p == NULL) {+ CertFreeCertificateContext(ctx);+ ret = -1;+ break;+ }+ buf = p;+ cap = newcap;+ }+ buf[len] = (uint8_t)(n >> 24);+ buf[len + 1] = (uint8_t)(n >> 16);+ buf[len + 2] = (uint8_t)(n >> 8);+ buf[len + 3] = (uint8_t)n;+ memcpy(buf + len + 4, ctx->pbCertEncoded, n);+ len += 4 + n;+ }+ if (dis != NULL)+ CertCloseStore(dis, 0);+ CertCloseStore(root, 0);+ if (ret != 0) {+ free(buf);+ return ret;+ }+ *out = buf;+ *outlen = len;+ return 0;+}
crypton-x509-system.cabal view
@@ -1,6 +1,6 @@ cabal-version: >=1.10 name: crypton-x509-system-version: 1.10.0+version: 1.10.1 license: BSD3 license-file: LICENSE copyright: Vincent Hanquez <vincent@snarc.org>@@ -19,7 +19,7 @@ source-repository head type: git location: https://github.com/kazu-yamamoto/crypton-certificate- subdir: x509-system+ subdir: crypton-x509-system library exposed-modules:@@ -30,6 +30,7 @@ default-language: Haskell2010 ghc-options: -Wall+ c-sources: cbits/macos.c build-depends: base >=3 && <5, bytestring,@@ -37,18 +38,15 @@ containers, directory, filepath,- process,- crypton-pem >=0.2.4 && <0.4, crypton-x509 >=1.10 && <1.11,- crypton-x509-store >=1.10 && <1.11+ crypton-x509-store >=1.10.1 && <1.11 if os(windows) exposed-modules: System.X509.Win32 cpp-options: -DWINDOWS+ c-sources: cbits/win32.c extra-libraries: Crypt32- build-depends:- Win32,- crypton-asn1-encoding if os(osx) cpp-options: -DMACOSX+ frameworks: Security CoreFoundation