packages feed

crypton-x509 1.11.0 → 1.11.1

raw patch · API changes only · 4 files changed · show whitespace changes · browse crypton-x509-1.11.1

+331/−47 lines, 4 filesPVP ok

API changes (from Hackage documentation)

No changes to the public API.

version bump matches the API change (PVP)

Files

ChangeLog.md view
@@ -1,5 +1,17 @@ # ChangeLog for crypton-x509 +## 1.11.1++The signed bytes of a signed object are taken from the input instead of+being re-encoded, and everything the signature does not cover must be in+DER.  Differently encoded copies of a certificate no longer keep a valid+signature with a different fingerprint, and a malformed length no longer+makes `getSignedData` throw.  Reported by José Lorenzo Rodríguez.++* Take the signed bytes of a signed object as received+* Require DER outside the signed part of a signed object+* Read a signed object's values without copying them+ ## 1.11.0  Certificates are represented without losing information: RSA-PSS
Data/X509/Signed.hs view
@@ -42,12 +42,12 @@ ) where  import Control.Arrow (first)+import Control.Monad (guard) import Data.ASN1.BinaryEncoding-import qualified Data.ASN1.BinaryEncoding.Raw as Raw (toByteString) import Data.ASN1.BitArray import Data.ASN1.Encoding-import Data.ASN1.Stream import Data.ASN1.Types+import Data.Bits (shiftL, (.&.), (.|.)) import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.X509.AlgorithmIdentifier@@ -166,21 +166,35 @@     :: (Show a, Eq a, ASN1Object a)     => ByteString     -> Either String (SignedExact a)-decodeSignedObject b = either Left parseSigned $ safeDecode $ decodeASN1Repr' BER b+decodeSignedObject b = either Left parseSigned $ safeDecode $ decodeASN1' BER b   where-    -- the following implementation is very inefficient.-    -- uses reverse and containing, move to a better solution eventually-    parseSigned l = case getConstructedEndRepr l of+    parseSigned l = case l of+        -- The common case, a SEQUENCE of a SEQUENCE and two more values,+        -- read without copying the outer SEQUENCE: the decoder's values are+        -- balanced, every Start having a matching End of the same type, so+        -- an End where a value is expected is the outer SEQUENCE's.+        Start Sequence : xs+            | null (dropValues 1 xs)+            , Start Sequence : ys <- xs ->+                let (sigAlgSeq, rem2) = splitIn (dropValues 1 ys)+                    (sigSeq, rem3) = splitIn rem2+                 in parts+                        (fromASN1 (contents ys))+                        sigAlgSeq+                        sigSeq+                        (case rem3 of [End _] -> True; _ -> False)+        _ -> case splitValue l of             (outer, []) -> onSequence outer $ \l2 ->-            let (objRepr, rem1) = getConstructedEndRepr l2-                (sigAlgSeq, rem2) = getConstructedEndRepr rem1-                (sigSeq, rem3) = getConstructedEndRepr rem2-                obj = onSequence objRepr (fromASN1 . map fst)-             in case (obj, map fst sigSeq) of-                    _ | not (null rem3) -> Left "signed object error: trailing data"+                let (objSeq, rem1) = splitValue l2+                    (sigAlgSeq, rem2) = splitValue rem1+                    (sigSeq, rem3) = splitValue rem2+                 in parts (onSequence objSeq fromASN1) sigAlgSeq sigSeq (null rem3)+            _ -> Left "signed object error: trailing data"+    parts obj sigAlgSeq sigSeq noTrailing =+        case (obj, sigSeq) of+            _ | not noTrailing -> Left "signed object error: trailing data"             (Right (o, []), [BitString signature]) ->-                        let rawObj = Raw.toByteString $ concatMap snd objRepr-                         in case fromASN1 $ map fst sigAlgSeq of+                case fromASN1 sigAlgSeq of                     Left err -> Left ("signed object error sigalg: " ++ err)                     Right (sigAlg, []) ->                         let signed =@@ -189,20 +203,187 @@                                     , signedAlg = sigAlg                                     , signedSignature = bitArrayGetData signature                                     }-                                     in Right $+                         in case signedBytes b of+                                Just rawObj ->+                                    Right $                                         SignedExact                                             { getSigned = signed                                             , exactObjectRaw = rawObj                                             , encodeSignedObject = b                                             }+                                Nothing -> Left "signed object error: invalid encoding"                     Right _ -> Left "signed object error sigalg: trailing data"             (Right (_, []), _) -> Left "signed object error: invalid signature"             (Right (_, remObj), _) ->                 Left $ ("signed object error: remaining stream in object: " ++ show remObj)             (Left err, _) -> Left $ ("signed object error: " ++ err)-        _ -> Left "signed object error: trailing data"-    onSequence ((Start Sequence, _) : l) f =+    onSequence (Start Sequence : l) f =         case reverse l of-            ((End Sequence, _) : l2) -> f $ reverse l2+            (End Sequence : l2) -> f $ reverse l2             _ -> Left "signed object error: invalid sequence"     onSequence _ _ = Left "signed object error: expecting a sequence"++-- | The first value of a list, with all its contents if it starts a+-- construction, and the rest of the list.+splitValue :: [ASN1] -> ([ASN1], [ASN1])+splitValue [] = ([], [])+splitValue (x@(Start _) : xs) = (x : takeValues 1 xs, dropValues 1 xs)+splitValue (x : xs) = ([x], xs)++-- | As 'splitValue', for a list that ends with the 'End' of the+-- construction it is in: that 'End' is not a value.+splitIn :: [ASN1] -> ([ASN1], [ASN1])+splitIn xs@(End _ : _) = ([], xs)+splitIn xs = splitValue xs++-- | The values up to and including the 'End' that closes @i@ open+-- constructions.+takeValues :: Int -> [ASN1] -> [ASN1]+takeValues 0 _ = []+takeValues _ [] = []+takeValues i (y : ys) = y : takeValues (depth i y) ys++-- | The values before the 'End' that closes the construction they are in.+contents :: [ASN1] -> [ASN1]+contents = go (0 :: Int)+  where+    go _ [] = []+    go 0 (End _ : _) = []+    go i (y : ys) = y : go (depth i y) ys++-- | The values after the 'End' that closes @i@ open constructions.+dropValues :: Int -> [ASN1] -> [ASN1]+dropValues 0 ys = ys+dropValues _ [] = []+dropValues i (y : ys) = dropValues (depth i y) ys++depth :: Int -> ASN1 -> Int+depth i (Start _) = i + 1+depth i (End _) = i - 1+depth i _ = i++-- | The bytes of the signed object, as received: the header and contents of+-- the first value inside the outer construction of an encoding that+-- 'decodeASN1'' accepted with BER.+--+-- The signed object is read as the decoder reads it.  Everything else is+-- not covered by the signature, so it must be in DER: the outer SEQUENCE+-- covering the whole input, the signature algorithm, and the signature+-- BIT STRING with no unused bits.+signedBytes :: ByteString -> Maybe ByteString+signedBytes b = do+    (0x30, start, outerEnd) <- derHeader 0+    guard (outerEnd == B.length b)+    end <- valueEnd start+    guard (end >= start && end <= outerEnd)+    algEnd <- derValue end+    (0x03, sigStart, sigEnd) <- derHeader algEnd+    guard (sigEnd == outerEnd && sigStart < sigEnd && B.index b sigStart == 0)+    Just (B.take (end - start) (B.drop start b))+  where+    -- A DER header at i: identifier octet, start and end of contents.+    derHeader i = do+        w <- byte i+        guard (w .&. 0x1f /= 0x1f)+        (n, j) <- derLength (i + 1)+        guard (n <= B.length b - j)+        Just (w, j, j + n)++    -- A definite length in its shortest form, at most 4 octets.+    derLength i = do+        l <- byte i+        if l < 0x80+            then Just (fromIntegral l, i + 1)+            else do+                let k = fromIntegral (l .&. 0x7f)+                guard (k >= 1 && k <= 4 && k <= B.length b - (i + 1))+                let ls = B.take k (B.drop (i + 1) b)+                    n = B.foldl' (\a x -> (a `shiftL` 8) .|. fromIntegral x) 0 ls+                guard (if k == 1 then n >= 0x80 else B.head ls /= 0)+                Just (n, i + 1 + k)++    -- The end of a DER value at i.+    derValue i = do+        (w, j, e) <- derHeader i+        if w .&. 0x20 /= 0 then derContents j e else Just e+    derContents j e+        | j == e = Just e+        | otherwise = do+            k <- derValue j+            guard (k <= e)+            derContents k e++    valueEnd i = do+        h <- header i+        let j = hdrEnd h+        case hdrLength h of+            Nothing+                | hdrConstructed h -> contentsEnd j+                | otherwise -> Nothing+            Just n+                | hdrConstructed h -> if n >= 0 then Just (j + n) else Nothing+                -- A primitive length that does not fit an Int is read as+                -- empty contents.+                | n <= 0 -> Just j+                | otherwise -> Just (j + n)++    -- The end of indefinite-length contents starting at i: after the+    -- end-of-contents header that closes them.+    contentsEnd i+        | i >= B.length b = Nothing+        | otherwise = do+            h <- header i+            if isEOC h then Just (hdrEnd h) else valueEnd i >>= contentsEnd++    isEOC h = hdrUniversal h && hdrTag h == 0++    header :: Int -> Maybe Header+    header i = do+        w <- byte i+        let universal = w < 0x40+            constructed = w .&. 0x20 /= 0+        if w .&. 0x1f /= 0x1f+            then len universal (fromIntegral (w .&. 0x1f)) constructed (i + 1)+            else do+                t <- byte (i + 1)+                if t == 0x80 then Nothing else longTag universal constructed 0 (i + 1)+    longTag universal constructed acc i = do+        t <- byte i+        let acc' = (acc `shiftL` 7) + fromIntegral (t .&. 0x7f)+        if t .&. 0x80 /= 0+            then longTag universal constructed acc' (i + 1)+            else len universal acc' constructed (i + 1)+    len universal tag constructed i = do+        l <- byte i+        let hdr = Header universal tag constructed+        case l of+            _ | l < 0x80 -> Just (hdr (Just (fromIntegral l)) (i + 1))+            0x80 -> Just (hdr Nothing (i + 1))+            _ -> do+                let k = fromIntegral (l .&. 0x7f)+                if k > B.length b - (i + 1)+                    then Nothing+                    else+                        Just $+                            hdr+                                ( Just+                                    ( B.foldl'+                                        (\a x -> (a `shiftL` 8) .|. fromIntegral x)+                                        0+                                        (B.take k (B.drop (i + 1) b))+                                    )+                                )+                                (i + 1 + k)+    byte i+        | i < B.length b = Just (B.index b i)+        | otherwise = Nothing++-- | A header: universal class, tag, constructed, length ('Nothing' for an+-- indefinite length), and the position after it.+data Header = Header+    { hdrUniversal :: !Bool+    , hdrTag :: !Int+    , hdrConstructed :: !Bool+    , hdrLength :: !(Maybe Int)+    , hdrEnd :: !Int+    }
Tests/Tests.hs view
@@ -26,10 +26,13 @@ import Data.ASN1.BitArray (toBitArray) import Data.ASN1.Encoding (decodeASN1', encodeASN1') import Data.ASN1.Types+import Data.Bits (shiftR, (.|.))+import qualified Data.Bits as Bits import Data.ByteArray (convert) import Data.List (isInfixOf, nub, sort) import Data.Maybe (fromJust) import Data.Proxy (Proxy (..))+import Data.Word (Word8) import Data.X509 import Data.X509.EC (ecPubKeyCurveName) @@ -719,6 +722,17 @@ modifiedCertificate :: ([ASN1] -> [ASN1]) -> Either String SignedCertificate modifiedCertificate f = decodeSignedCertificate $ encodeASN1' DER $ f asn1   where+    asn1 = either (error . show) id $ decodeASN1' DER sampleCertificate++-- | A DER certificate with a dummy signature.+sampleCertificate :: B.ByteString+sampleCertificate =+    encodeSignedObject $+        fst $+            objectToSignedExact+                (\_ -> (B.pack [1], SignatureALG HashSHA256 PubKeyALG_RSA, ()))+                cert+  where     t = timeConvert (Date 2020 January 1) :: DateTime     dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]     cert =@@ -731,13 +745,6 @@             dn             (PubKeyRSA (RSA.PublicKey 1 0x7f 3))             (Extensions Nothing)-    encoded =-        encodeSignedObject $-            fst $-                objectToSignedExact-                    (\_ -> (B.pack [1], SignatureALG HashSHA256 PubKeyALG_RSA, ()))-                    cert-    asn1 = either (error . show) id $ decodeASN1' DER encoded  isLeft' :: Either a b -> Bool isLeft' = either (const True) (const False)@@ -749,6 +756,88 @@         && isLeft' (modifiedCertificate (\l -> init l ++ [IntVal 1, End Sequence]))         && isLeft' (modifiedCertificate (\l -> Start Set : init (drop 1 l) ++ [End Set])) +-- | The DER encodings of the signed object, the signature algorithm and+-- the signature of 'sampleCertificate', and their contents.+sampleParts+    :: ( (B.ByteString, B.ByteString)+       , (B.ByteString, B.ByteString)+       , (B.ByteString, B.ByteString)+       )+sampleParts = case B.unpack sampleCertificate of+    0x30 : _ -> (value tbs, value alg, value sig)+    _ -> error "sampleParts"+  where+    asn1 = either (error . show) id $ decodeASN1' DER sampleCertificate+    (tbs, rest1) = splitASN1 (init (drop 1 asn1))+    (alg, rest2) = splitASN1 rest1+    (sig, _) = splitASN1 rest2+    value l = let e = encodeASN1' DER l in (e, B.drop (B.length e - contentLength l) e)+    contentLength l = B.length (encodeASN1' DER (contentsOf l))+    contentsOf l@(Start _ : _) = init (drop 1 l)+    contentsOf [BitString _] = []+    contentsOf _ = []+    splitASN1 (x@(Start _) : xs) = go (1 :: Int) [x] xs+    splitASN1 (x : xs) = ([x], xs)+    splitASN1 [] = ([], [])+    go 0 acc xs = (reverse acc, xs)+    go i acc (y : ys) = go (i + d y) (y : acc) ys+    go _ acc [] = (reverse acc, [])+    d (Start _) = 1+    d (End _) = -1+    d _ = 0++-- | A DER header and contents.+derTLV :: [Word8] -> B.ByteString -> B.ByteString+derTLV tag body = B.pack (tag ++ derLength (B.length body)) <> body+  where+    derLength n+        | n < 0x80 = [fromIntegral n]+        | otherwise = let ls = bytesOf n in fromIntegral (0x80 .|. length ls) : ls++-- | A header and contents with a length one octet longer than necessary.+nonMinimalTLV :: [Word8] -> B.ByteString -> B.ByteString+nonMinimalTLV tag body = B.pack (tag ++ fromIntegral (0x81 + length ls) : 0 : ls) <> body+  where+    ls = bytesOf (B.length body)++bytesOf :: Int -> [Word8]+bytesOf 0 = [0]+bytesOf n = reverse (go n)+  where+    go 0 = []+    go m = fromIntegral (m Bits..&. 0xff) : go (m `shiftR` 8)++-- The signed bytes are taken as received, so a different encoding of the+-- signed object changes them.+property_signed_bytes_as_received :: Bool+property_signed_bytes_as_received =+    signedData sampleCertificate == Just tbs+        && signedData nonMinimal == Just (nonMinimalTLV [0x30] tbsBody)+        && signedData highTag == Just (derTLV [0x3f, 0x10] tbsBody)+  where+    ((tbs, tbsBody), (alg, _), (sig, _)) = sampleParts+    nonMinimal = derTLV [0x30] (nonMinimalTLV [0x30] tbsBody <> alg <> sig)+    highTag = derTLV [0x30] (derTLV [0x3f, 0x10] tbsBody <> alg <> sig)+    signedData = either (const Nothing) (Just . getSignedData) . decodeSignedCertificate++-- Everything not covered by the signature must be in DER.+property_signed_envelope_der :: Bool+property_signed_envelope_der =+    not (isLeft' (decodeSignedCertificate (derTLV [0x30] (tbs <> alg <> sig))))+        && all+            (isLeft' . decodeSignedCertificate)+            [ B.pack [0x30, 0x80] <> tbs <> alg <> sig <> B.pack [0, 0]+            , B.pack [0, 0] <> sampleCertificate+            , derTLV [0x30] (tbs <> alg <> derTLV [0x03] (B.cons 0x30 (B.drop 1 sigBody)))+            , derTLV [0x30] (tbs <> nonMinimalTLV [0x30] algBody <> sig)+            , derTLV [0x30] (tbs <> alg <> nonMinimalTLV [0x03] sigBody)+            , nonMinimalTLV [0x30] (tbs <> alg <> sig)+            , derTLV [0x3f, 0x10] (tbs <> alg <> sig)+            , derTLV [0x30] (tbs <> derTLV [0x3f, 0x10] algBody <> sig)+            ]+  where+    ((tbs, _), (alg, algBody), (sig, sigBody)) = sampleParts+ property_duplicate_extensions :: Bool property_duplicate_extensions =     isLeft'@@ -1299,6 +1388,8 @@                     , testProperty "SAN keeps all name forms" property_san_keeps_names                     , testProperty "lazy decode error" property_lazy_decode_error                     , testProperty "signed object" property_signed_strict+                    , testProperty "signed bytes as received" property_signed_bytes_as_received+                    , testProperty "DER outside the signed object" property_signed_envelope_der                     , testProperty "duplicate extensions" property_duplicate_extensions                     , testProperty "RSA key trailing data" property_rsa_pubkey_trailing                     , testProperty "PSS hash" property_pss_hash
crypton-x509.cabal view
@@ -1,6 +1,6 @@ cabal-version:      >=1.10 name:               crypton-x509-version:            1.11.0+version:            1.11.1 license:            BSD3 license-file:       LICENSE copyright:          Vincent Hanquez <vincent@snarc.org>@@ -45,7 +45,7 @@         bytestring,         containers,         crypton >=2.1.8 && <2.4,-        crypton-asn1-encoding >=0.10.0 && <0.11,+        crypton-asn1-encoding >=0.10.0 && <0.12,         crypton-asn1-parse >=0.10.0 && <0.11,         crypton-asn1-types >=0.4.1 && <0.5,         crypton-pem >=0.2.4 && <0.4,