summaryrefslogtreecommitdiff
path: root/TLSA.hs
blob: ecf033cd5cd9b896180cba54124d677d100d25d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}
module TLSA
    ( TLSA(..)
    , CertUsage(..)
    , Selector(..)
    , MatchingType(..)
    , fromByteString
    , toByteString
    , match
    , Validation(..)
    , validate
    , validate2
    ) where

import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as L
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Crypto.Hash.SHA512 as SHA512
import Data.X509  {-        ( certPubKey, Certificate(..), SignedCertificate, getCertificate
                          , getSigned, getSignedData, signedObject, objectToSignedExact
                          , SignatureALG(SignatureALG_Unknown), SignedExact
                          , encodeSignedObject, decodeSignedObject ) -}
import Data.ASN1.Types    ( toASN1, ASN1Object, fromASN1 )
import Data.ASN1.Encoding ( encodeASN1, decodeASN1 )
import Data.Time.Clock.POSIX ( posixSecondsToUTCTime )

import Data.ASN1.BinaryEncoding
import Control.Applicative
import Data.Word
import Data.Maybe
import Data.List
import Data.Monoid

{- INLINE fromWord8 #-}
fromWord8 :: Enum a => Word8 -> a
fromWord8 = toEnum . fromEnum

{- INLINE toWord8 -}
toWord8 :: Enum a => a -> Word8
toWord8 = toEnum . fromEnum

-- | The Certificate Usage Field as described in RFC 6698, section 2.1.1.
--
-- It is used by the 'validate' function in making a 'Validation' decision.
data CertUsage

    -- | This usage limits which CA can be used to issue certificates for a
    -- given service on a host.  PKIX-validated TLS connections for the domain
    -- should be considered invalid if the certification path does not include
    -- at least one certificate that 'match'es the 'TLSA' record.
    = CAConstraint

    -- | This usage limits which end entity certificate can be used by a given
    -- service on a host.  The TLS connection for the domain should be
    -- considered invalid if the end entity certificate does not 'match' the
    -- 'TLSA' record.
    | ServiceCertificateConstraint

    -- | This usage allows a domain name administrator to specify a new trust
    -- anchor.  This is useful if the domain issues its own certificates under
    -- its own CA that is not expected to be in the end users' collection of
    -- trust anchors.  When conducting PKIX validation for the domain, any
    -- certificate 'match'ing the 'TLSA' record can be treated as a trust
    -- anchor that does not require further validation.
    | TrustAnchorAssertion

    -- | This usage allows for a domain name administrator to issue
    -- certificates for a domain without involving a third-party CA.  The end
    -- entity certificate MUST 'match' the 'TLSA' record.  Unlike for a
    -- 'ServiceCertificateConstraint', PKIX validation should not be performed.
    | DomainIssued

    | CertUsage Word8
 deriving (Eq, Ord, Show, Read)

instance Enum CertUsage where
    fromEnum CAConstraint                 = 0
    fromEnum ServiceCertificateConstraint = 1
    fromEnum TrustAnchorAssertion         = 2
    fromEnum DomainIssued                 = 3
    fromEnum (CertUsage n)                = fromEnum n
    toEnum 0 = CAConstraint
    toEnum 1 = ServiceCertificateConstraint
    toEnum 2 = TrustAnchorAssertion
    toEnum 3 = DomainIssued
    toEnum n = CertUsage (toEnum n)

-- | Indicates what sort of object should be compared with 'associationData'.
data Selector
    = FullCertificate      -- ^ x.509 certificate
    | SubjectPublicKeyInfo -- ^ PKCS #8 formatted public key
    | Selector Word8       -- ^ value 255 reserved for private use
 deriving (Eq,Ord,Show)

instance Enum Selector where
    fromEnum FullCertificate      = 0
    fromEnum SubjectPublicKeyInfo = 1
    fromEnum (Selector n)         = fromEnum n
    toEnum 0   = FullCertificate
    toEnum 1   = SubjectPublicKeyInfo
    toEnum n = Selector (toEnum n)

-- | Is 'associationData' an object of the form specified by 'Selector' or is
-- it only a hash of it?
data MatchingType
    = Match_Exact
    | Match_SHA256
    | Match_SHA512
    | Match Word8 -- ^ value 255 is reserved for private use
 deriving (Eq,Ord,Show)

instance Enum MatchingType where
    fromEnum Match_Exact  = 0
    fromEnum Match_SHA256 = 1
    fromEnum Match_SHA512 = 2
    fromEnum (Match n)    = fromEnum n
    toEnum 0 = Match_Exact
    toEnum 1 = Match_SHA256
    toEnum 2 = Match_SHA512
    toEnum n = Match (toEnum n)


-- | The parsed RDATA field of a TLSA DNS resource record (type 52) as
-- described in RFC 6698.
--
-- The 'match' function uses 'selector', 'matchingType' and 'associationData'
-- to implement a predicate on certificates obtained via the TLS protocol.  The
-- 'certUsage' field indicates what that predicate means.
data TLSA = TLSA
    { certUsage       :: CertUsage
    , selector        :: Selector
    , matchingType    :: MatchingType
    , associationData :: BS.ByteString
    }
 deriving (Eq, Ord, Show)

-- | Parse RDATA for a TLSA resource record.
fromByteString :: BS.ByteString -> TLSA
fromByteString bs = TLSA (fromWord8 cu)
                         (fromWord8 sel)
                         (fromWord8 mat)
                         dta
 where
    (csm,dta) = BS.splitAt 3 bs
    (cu,sel,mat) =
        case BS.unpack csm of
            [cu,sel,mat] -> (cu,sel,mat)
            [cu,sel]     -> (cu,sel,0)
            [cu]         -> (cu,0,0)
            []           -> (0,0,0)

-- | Encode a valid RDATA field for a TLSA DNS record.
toByteString :: TLSA -> BS.ByteString
toByteString (TLSA cu sel mat dta) = csm <> dta
 where
    csm = BS.pack [ toWord8 cu
                  , toWord8 sel
                  , toWord8 mat ]

-- | Returns 'True' if the given certificate matches the given 'TLSA' object.
-- The algorithm for matching depends on the values of 'selector' and
-- 'matchingType' as described in RFC 6698.
match :: TLSA -> SignedCertificate -> Bool
match tlsa cert = fromMaybe False $
    (== associationData tlsa) <$> (hash <*> material)

 where
    key = encodeASN1 DER $ toASN1 keyobj []
        where keyobj = certPubKey $ getCertificate cert

    encoded_cert = L.fromChunks [encodeSignedObject cert]

    material :: Maybe L.ByteString
    material =
        case selector tlsa of
            FullCertificate      -> Just encoded_cert
            SubjectPublicKeyInfo -> Just key
            _                    -> Nothing

    hash :: Maybe (L.ByteString -> BS.ByteString)
    hash =
        case matchingType tlsa of
            Match_Exact  -> Just L.toStrict
            Match_SHA256 -> Just SHA256.hashlazy
            Match_SHA512 -> Just SHA512.hashlazy
            _            -> Nothing

unsigned :: (Show a, ASN1Object a, Eq a) => a -> SignedExact a
unsigned obj = fst $ objectToSignedExact fakeSign obj
 where fakeSign = const $ ("", SignatureALG_Unknown [], ())

data Validation
    = Failed [TLSA]
    -- ^ All of the given constraints failed.
    | TrustAnchors [SignedCertificate] [SignedCertificate]
    -- ^ Perform PKI validation with the given additional trust anchors.  The
    -- first list are trust anchors that occured in the chain.  The second list
    -- are anchors that did not occur in the chain.  If 'certVersion' == (-1)
    -- for any certificate in the second list, then all fields except
    -- 'certPubKey' should be ignored.
    | Passed
    -- ^ Valid end entity. Do not perform PKI.


-- comb [1,2,3] = [([],[1,2,3]),([1],[2,3]),([2,1],[3])]
comb cs = matchLength cs $ iterate sweepLeft ([],cs)
    where sweepLeft (xs,y:ys) = (y:xs,ys)
          matchLength = zipWith (flip const)

-- O(n²) worst case
-- O(n) best case
-- op is an antisymmetric operation
connectedChain op x [] = [x]
connectedChain op x xs = 
    case filter ((x `op`) . snd) $ comb xs of
        []          -> [x]
        (as,y:bs):_ -> x : connectedChain op y (bs++as)

allChains :: (a -> a -> Bool) -> a -> [a] -> [[a]]
allChains op x [] = [[x]]
allChains op x xs | null ts   = [[x]]
                  | otherwise = ts >>= f
 where
    ts = filter  ((x `op`) . head . snd) $ comb xs
    f (as,y:bs) = map (x:) $ allChains op y (as++bs)

-- | > validate2 isIssuedBy isSignedBy rs cert otherCerts
--
--   * isIssuedBy - validates one link in a certificate chain
--
--   * isSignedBy - True if the certificate is signed by the key
--
--   * rs - A set of TLSA records obtained from DNS
--
--   * cert - The end entity target cert to verify
--
--   * otherCerts - Other relevent certificates
--
--  Returns:
--
--   * @ Nothing @ - The end entity certificate is valid.
--
--   * @ Just chains @ - A set of connected certificate chains.
--                   The certificate is valid if and only if there
--                   exists a chain that contains a CA certificate
--                   that is issued by a trust anchor.
--
validate2 :: (SignedCertificate -> SignedCertificate -> Bool)
            -> (SignedCertificate -> PubKey -> Bool)
            -> [TLSA] -> SignedCertificate -> [SignedCertificate] -> Maybe [[SignedCertificate]]
validate2 isIssuedBy isSignedBy rs cert chain
    | some domainIssued    = Nothing
    | any hasAnchor chains = Nothing
    | otherwise            = Just $ filter satisfiesConstraints chains
  where
    domainIssued = filter (`match` cert) daneEEs

    chains = allChains isIssuedBy cert chain

    hasAnchor cs = some anchors
                    || some [ c | c <- cs, cert <- certs, c `isIssuedBy` cert ]
                    || some [ c | c <- cs, key <- keys, c `isSignedBy` key ]
     where
        (bs,ns) = partition (null . snd) $ pairings match daneTAs cs
        anchors = concatMap snd ns
        absent  = mapMaybe (certOrKey . fst) bs
        certs = mapMaybe rightToMaybe absent
        keys  = mapMaybe leftToMaybe  absent
        rightToMaybe (Right x) = Just x
        rightToMaybe _         = Nothing
        leftToMaybe  (Left x)  = Just x
        leftToMaybe  _         = Nothing

    satisfiesConstraints (c:cs) = any eeSatisfied pkixEEs
                                  || any caSatisfied pkixTAs
     where
        eeSatisfied = (`match` c)
        caSatisfied r = any (r `match`) cs

    some = not . null

    r .~ u = certUsage r == u
    (daneEEs,rs2) = partition (.~ DomainIssued)                 rs
    (daneTAs,rs3) = partition (.~ TrustAnchorAssertion)         rs2
    (pkixEEs,rs4) = partition (.~ ServiceCertificateConstraint) rs3
    (pkixTAs,_)   = partition (.~ CAConstraint)                 rs4

pairings op = loop
     where
        loop []     cs = []
        loop (m:ms) cs =
            case filter (op m . head . snd) $ comb cs of
                []          -> (m,[]):loop ms cs
                (as,b:bs):_ -> (m,[b]):loop ms (as++bs)

validate :: [TLSA] -> SignedCertificate -> [SignedCertificate] -> Validation
validate rs cert chain
    | some domainIssued               = Passed
    | null constraints || some passed = TrustAnchors anchors absent
    | otherwise                       = Failed constraints
  where
    domainIssued = filter (`match` cert) daneEEs
    (bs,ns) = partition (null . snd) $ pairings match daneTAs (cert:chain)
    anchors = concatMap snd ns
    absent  = mapMaybe (extractCert . fst) bs

    constraints = pkixEEs   ++ pkixTAs
    passed      = passedEEs ++ passedTAs
      where
        passedEEs = filter (`match` cert) pkixEEs
        -- TODO
        -- These passedTAs are only truly passed if the
        -- certs that match them are reachable.
        -- Where a cert is "reachable" if it is the end entity
        -- cert or if it is the issuer of a reachable cert.
        passedTAs = filter (`matchAny` (cert:chain)) pkixTAs
        matchAny t = any (t `match`)

    some = not . null

    r .~ u = certUsage r == u
    (daneEEs,rs2) = partition (.~ DomainIssued)                 rs
    (daneTAs,rs3) = partition (.~ TrustAnchorAssertion)         rs2
    (pkixEEs,rs4) = partition (.~ ServiceCertificateConstraint) rs3
    (pkixTAs,_)   = partition (.~ CAConstraint)                 rs4

certOrKey :: TLSA -> Maybe (Either PubKey SignedCertificate)
certOrKey tlsa@(matchingType->Match_Exact) =
    case selector tlsa of
        FullCertificate -> either (const Nothing)
                                  (Just . Right)
                                  (decodeSignedObject $ associationData tlsa)
        SubjectPublicKeyInfo -> do
            a <- hush $ decodeASN1 DER $ L.fromChunks [associationData tlsa]
            (key,_) <- hush $ fromASN1 a 
            return $ Left key
 where
        hush (Left _) = Nothing
        hush (Right a) = Just a

extractCert :: TLSA -> Maybe SignedCertificate
extractCert tlsa@(matchingType->Match_Exact) =
    case selector tlsa of
        FullCertificate -> either (const Nothing)
                                  Just
                                  (decodeSignedObject $ associationData tlsa)
        SubjectPublicKeyInfo -> do
            a <- hush $ decodeASN1 DER $ L.fromChunks [associationData tlsa]
            (key,_) <- hush $ fromASN1 a 
            return $ certificateFromKey key
 where
        hush (Left _) = Nothing
        hush (Right a) = Just a
extractCert _ = Nothing

certificateFromKey :: PubKey -> SignedCertificate
certificateFromKey key = unsigned cert
 where
    cert = Certificate { certPubKey = key
                       , certVersion = (-1)
                       , certSerial = 0
                       , certSignatureAlg = SignatureALG_Unknown []
                       , certIssuerDN = DistinguishedName []
                       , certValidity = ( posixSecondsToUTCTime (-1/0)
                                        , posixSecondsToUTCTime (1/0))
                       , certSubjectDN = DistinguishedName []
                       , certExtensions = Extensions Nothing
                       }