packages feed

jose-jwt-botan 0.13.0 → 0.14.0

raw patch · 14 files changed

+80/−52 lines, 14 filesnew-uploader

Files

CHANGELOG.md view
@@ -1,3 +1,13 @@+# Change Log++All notable changes to this project will be documented in this file.+This project adheres to [Semantic Versioning](http://semver.org/).++0.14.0+------++* Use botan for `ES384` and `ES512` verification, this makes the verification ~x7.5 faster and reduces time by ~87% by @taimoorzaeem in #3.+ 0.13.0 ------ 
Jose/Internal/Base64.hs view
@@ -1,4 +1,4 @@-{-# LANGUAGE OverloadedStrings, FlexibleContexts, CPP #-}+{-# LANGUAGE FlexibleContexts, CPP #-} {-# OPTIONS_HADDOCK hide #-}  -- | JWT-style base64 encoding and decoding
Jose/Internal/Crypto.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE LambdaCase #-} {-# OPTIONS_HADDOCK prune #-}  -- | Internal functions for encrypting and signing / decrypting@@ -49,7 +50,7 @@ import           Crypto.Random (MonadRandom, getRandomBytes) import           Crypto.MAC.HMAC (HMAC (..), hmac) import           Data.Bits (xor)-import           Data.Bifunctor (first)+import           Data.Bifunctor (first, second) import           Data.ByteArray (ByteArray, ScrubbedBytes) import qualified Data.ByteArray as BA import           Data.ByteString (ByteString)@@ -167,46 +168,44 @@          -> ByteString      -- ^ The signature to check          -> Either JwtError Bool -- ^ Whether the signature is correct ecVerify a key msg sig = case a of-    ES256 -> case ECDSA.public_q key of-        ECC.Point x y -> unsafePerformIO $-            -- Here we catch the BotanException and raise it to a Left, text-icu does something similar-            -- https://github.com/haskell/text-icu/blob/413cc4bcceed473bd10a2e854ddb0f41e56c5cc9/Data/Text/ICU/Regex/Pure.hs#L116-L119-            (Right <$> verifyES256 (i2osp x) (i2osp y) msg sig) `catch`-            \(err :: Botan.SomeBotanException) -> return (Left (BotanError (T.pack (displayException err))))-        ECC.PointO -> Right False-    ES384 -> go SHA384-    ES512 -> go SHA512+    ES256 -> verifyWithExceptionCatch "secp256r1" "SHA-256"+    ES384 -> verifyWithExceptionCatch "secp384r1" "SHA-384"+    ES512 -> verifyWithExceptionCatch "secp521r1" "SHA-512"     _     -> Right False   where-    (r, s) = B.splitAt (B.length sig `div` 2) sig-    ecSig  = ECDSA.Signature (os2ip r) (os2ip s)-    go h   = Right (ECDSA.verify h key ecSig msg)+    verifyWithExceptionCatch cur hash =+      case ECDSA.public_q key of+          ECC.Point x y -> unsafePerformIO $+              -- Here we catch the BotanException and raise it to a Left, text-icu does something similar+              -- https://github.com/haskell/text-icu/blob/413cc4bcceed473bd10a2e854ddb0f41e56c5cc9/Data/Text/ICU/Regex/Pure.hs#L116-L119+              (Right <$> verifyESAlgo cur hash (i2osp x) (i2osp y) msg sig) `catch`+              \(err :: Botan.SomeBotanException) -> return (Left (BotanError (T.pack (displayException err))))+          ECC.PointO -> Right False -- Use NOINLINE to prevent the action execution more than once as recommended by GHC docs -- https://downloads.haskell.org/ghc/latest/docs/libraries/base-4.22.0.0-66f8/GHC-IO-Unsafe.html#v:unsafePerformIO {-# NOINLINE ecVerify #-} --- ES256 is really just a convention to combine the P-256 curve, the SHA-256 hash and the R || S signature-verifyES256 :: ByteString -> ByteString -> ByteString -> ByteString -> IO Bool-verifyES256 xBytes yBytes message signature =+-- ESXXX algorithms combine the curve, the SHA hash and the R || S signature+verifyESAlgo :: ByteString -> ByteString -> ByteString -> ByteString -> ByteString -> ByteString -> IO Bool+verifyESAlgo pcurve sha xBytes yBytes message signature =     -- brackets are used to ensure the allocated objects from botan are released     bracket Botan.mpInit Botan.mpDestroy $ \x ->         bracket Botan.mpInit Botan.mpDestroy $ \y -> do             -- Awkard interface as mentioned in the API docs but this sets x and y             Botan.mpFromBin x xBytes             Botan.mpFromBin y yBytes-            let p256curve = "secp256r1"                 -- Botan throws an exception on invalid keys, see BOTAN_FFI_ERROR_BAD_PARAMETER on                 -- https://github.com/randombit/botan/blob/3.12.0/src/lib/ffi/ffi_pkey_algs.cpp#L120-L140 which is mapped to BadParameterException.                 -- Here we catch the exception as a normal verification failure, this so the upper level `decode` function                 -- doesn't abort when trying the verification with another key.-                loadKey = (Just <$> Botan.pubKeyLoadECDSA x y p256curve) `catch` \(_ :: Botan.BadParameterException) -> pure Nothing-            bracket loadKey (mapM_ Botan.pubKeyDestroy) $ \loaded -> case loaded of-                Nothing -> pure False-                Just pubKey ->-                    -- StandardFormatSignature is R || S-                    bracket (Botan.verifyCreate pubKey "SHA-256" Botan.StandardFormatSignature) Botan.verifyDestroy $ \ctx -> do-                        Botan.verifyUpdate ctx message-                        Botan.verifyFinish ctx signature+            let loadKey = (Just <$> Botan.pubKeyLoadECDSA x y pcurve) `catch` \(_ :: Botan.BadParameterException) -> pure Nothing+            bracket loadKey (mapM_ Botan.pubKeyDestroy) $ \case+              Nothing -> pure False+              Just pubKey ->+                -- StandardFormatSignature is R || S+                bracket (Botan.verifyCreate pubKey sha Botan.StandardFormatSignature) Botan.verifyDestroy $ \ctx -> do+                    Botan.verifyUpdate ctx message+                    Botan.verifyFinish ctx signature  -- | Generates the symmetric key (content management key) and IV --@@ -424,7 +423,7 @@             a' = txor t (BA.take 8 b)             r' = BA.drop 8 b             next = doRound enc (i+1) (a', rs) j-        in (fst next, r' : snd next)+        in second (r' :) next  txor :: ByteArray ba => Word8 -> ba -> ba txor t b =@@ -465,4 +464,4 @@             a' = BA.take 8 b             r' = BA.drop 8 b             next = doRound dec (i-1) (a', rs) j-        in (fst next, r' : snd next)+        in second (r' :) next
Jose/Internal/Parser.hs view
@@ -68,9 +68,7 @@             s <- sig (jwsAlg h)             pure $ DecodableJws h (Payload payload) s (SigTarget (B.concat [raw, ".", payloadB64]))         JweH h ->-            DecodableJwe-                <$> pure h-                <*> encryptedCEK+            (DecodableJwe h <$> encryptedCEK)                 <*> iv (jweEnc h)                 <*> encryptedPayload                 <*> authTag (jweEnc h)
Jose/Jwe.hs view
@@ -53,6 +53,7 @@ import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL+import Data.Either (fromRight) import Data.Maybe (isNothing) import Jose.Types import qualified Jose.Internal.Base64 as B64@@ -122,7 +123,7 @@             let alg = jweAlg hdr                 enc = jweEnc hdr             (dummyCek, _) <- lift $ generateCmkAndIV enc-            let decryptedCek = either (const dummyCek) id $ decodeCek alg ek+            let decryptedCek = fromRight dummyCek $ decodeCek alg ek                 cek = if BA.length decryptedCek == BA.length dummyCek                         then decryptedCek                         else dummyCek
Jose/Jwk.hs view
@@ -1,4 +1,4 @@-{-# LANGUAGE OverloadedStrings, DeriveGeneric, RecordWildCards, CPP #-}+{-# LANGUAGE OverloadedStrings, DeriveGeneric, RecordWildCards, CPP, LambdaCase #-} {-# OPTIONS_HADDOCK prune #-}  module Jose.Jwk@@ -245,8 +245,7 @@ newtype JwkBytes = JwkBytes {bytes :: ByteString} deriving (Show)  instance FromJSON KeyType where-    parseJSON = withText "KeyType" $ \t ->-        case t of+    parseJSON = withText "KeyType" $ \case           "RSA" -> pure Rsa           "OKP" -> pure Okp           "EC"  -> pure Ec@@ -261,8 +260,7 @@                     Oct -> String "oct"  instance FromJSON KeyUse where-    parseJSON = withText "KeyUse" $ \t ->-        case t of+    parseJSON = withText "KeyUse" $ \case           "sig" -> pure Sig           "enc" -> pure Enc           _     -> fail "'use' value must be either 'sig' or 'enc'"@@ -273,8 +271,7 @@                     Enc -> String "enc"  instance FromJSON EcCurve where-    parseJSON = withText "EcCurve" $ \t ->-        case t of+    parseJSON = withText "EcCurve" $ \case           "P-256" -> pure P_256           "P-384" -> pure P_384           "P-521" -> pure P_521
Jose/Jws.hs view
@@ -180,7 +180,7 @@   decode :: JwsVerifier -> ByteString -> Either JwtError Jws-decode verify jwt = decodeEither (\alg msg sig -> Right (verify alg msg sig)) jwt+decode verify = decodeEither (\alg msg sig -> Right (verify alg msg sig))  -- helper for making ecVerify (returns Either .. Bool) work with the other verify algorithms like rsaVerify (all return Bool) decodeEither :: (JwsAlg -> ByteString -> ByteString -> Either JwtError Bool)
Jose/Jwt.hs view
@@ -102,7 +102,7 @@             unless (isNothing e || e == Just (JweEncoding (jweAlg hdr) (jweEnc hdr))) $                 throwE (BadAlgorithm "Expected encoding doesn't match JWE header")             ks <- checkKeys $ filter (canDecodeJwe hdr) keySet-            msum <$> (mapM decodeWithJwe ks)+            msum <$> mapM decodeWithJwe ks     case decoded of         Nothing  -> throwE $ KeyError "None of the keys was able to decode the JWT"         Just jwtContent -> return jwtContent
Jose/Types.hs view
@@ -132,10 +132,10 @@ instance FromJSON JwtClaims where #if MIN_VERSION_aeson(2,0,0)     parseJSON v@(Object o) = case KM.lookup "aud" o of-        Just (a@(String _)) -> genericParseJSON claimsOptions $ Object $ KM.insert "aud" (Array $ Data.Vector.singleton a) o+        Just a@(String _) -> genericParseJSON claimsOptions $ Object $ KM.insert "aud" (Array $ Data.Vector.singleton a) o #else     parseJSON v@(Object o) = case H.lookup "aud" o of-        Just (a@(String _)) -> genericParseJSON claimsOptions $ Object $ H.insert "aud" (Array $ singleton a) o+        Just a@(String _) -> genericParseJSON claimsOptions $ Object $ H.insert "aud" (Array $ singleton a) o #endif         _                   -> genericParseJSON claimsOptions v     parseJSON _            = fail "JwtClaims must be an object"
README.md view
@@ -1,4 +1,4 @@-# `jose-jwt`+# `jose-jwt-botan`  A Haskell implementation of the JSON Object Signing and Encryption (JOSE) specifications and the related [JWT specification](http://tools.ietf.org/html/draft-ietf-oauth-json-web-token), as used, for example, in [OpenID Connect](http://openid.net/connect/). 
benchmarks/loadtest-jwt/Main.hs view
@@ -51,7 +51,7 @@     times = 10  -- | PostgREST supports more algorithms (see https://github.com/PostgREST/postgrest/issues/5379) but we only load test these variants-data CliAlgorithm = RS256 | ES256 | Ed25519 deriving (Show)+data CliAlgorithm = RS256 | ES256 | ES384 | ES512 | Ed25519 deriving (Show)  readCLI :: IO CliAlgorithm readCLI = O.execParser $ O.info (O.helper <*> algo) (O.progDesc "JWT Verification Loadtest")@@ -59,6 +59,8 @@     algo = O.option (O.eitherReader readAlgo) $ O.long "algorithm"     readAlgo "RS256" = Right RS256     readAlgo "ES256" = Right ES256+    readAlgo "ES384" = Right ES384+    readAlgo "ES512" = Right ES512     readAlgo "Ed25519" = Right Ed25519     readAlgo _ = Left "Unknown algorithm" @@ -80,6 +82,8 @@           let keySize = 4096 `div` 8           in  (JOSE.RS256, JOSE.RSAGenParam keySize)         ES256 -> (JOSE.ES256, JOSE.ECGenParam JOSE.P_256)+        ES384 -> (JOSE.ES384, JOSE.ECGenParam JOSE.P_384)+        ES512 -> (JOSE.ES512, JOSE.ECGenParam JOSE.P_521)         Ed25519 -> (JOSE.EdDSA, JOSE.OKPGenParam JOSE.Ed25519)   privateKey <- JOSE.genJWK params   case JSON.fromJSON $ JSON.toJSON $ view JOSE.asPublicKey privateKey of
jose-jwt-botan.cabal view
@@ -1,5 +1,5 @@ Name:               jose-jwt-botan-Version:            0.13.0+Version:            0.14.0 Synopsis:           JSON Object Signing and Encryption Library using Botan Homepage:           https://github.com/PostgREST/jose-jwt-botan Bug-Reports:        https://github.com/PostgREST/jose-jwt-botan/issues@@ -15,7 +15,7 @@     It requires the botan C++ library, see more details on https://github.com/haskell-cryptography/botan#installation  Author:             Luke Taylor <tekul.hs@gmail.com>-Maintainer:         Steve Chavez <stevechavezast@gmail.com>+Maintainer:         Steve Chavez <stevechavezast@gmail.com>, Taimoor Zaeem <taimoorzaeem@gmail.com> License:            BSD3 License-File:       LICENSE Build-Type:         Simple
tests/Tests/JweSpec.hs view
@@ -291,8 +291,7 @@ instance Arbitrary JWEAlgs where   arbitrary = do     a <- elements [RSA1_5, RSA_OAEP, RSA_OAEP_256, A128KW, A192KW, A256KW]-    e <- arbitrary-    return $ JWEAlgs a e+    JWEAlgs a <$> arbitrary  instance Arbitrary RNG where   arbitrary = RNG . B.pack <$> vector 600
tests/Tests/JwsSpec.hs view
@@ -60,7 +60,7 @@          it "decodes the JWT to the expected header and payload with the JWK" $ do           let Just k21 = decodeStrict' a21jwk-          fstWithRNG (Jwt.decode [k21] (Just (JwsEncoding RS256)) a21) @?= (Right $ Jws (defJwsHdr {jwsAlg = RS256}, a21Payload))+          fstWithRNG (Jwt.decode [k21] (Just (JwsEncoding RS256)) a21) @?= Right (Jws (defJwsHdr {jwsAlg = RS256}, a21Payload))          it "decodes the successfully without verification" $ do            let Right (_, claims) = decodeClaims a21 :: Either JwtError (JwtHeader, JwtClaims)@@ -85,6 +85,16 @@           let Just k31 = decodeStrict' a31jwk           fstWithRNG (Jwt.decode [k31] Nothing a31) @?= fmap Jws a31decoded +        let a41decoded = Right (defJwsHdr {jwsAlg = ES384}, a41Payload)+        it "decodes the JWT to the expected header and payload (ES384)" $ do+          let Just k41 = decodeStrict' a41jwk+          fstWithRNG (Jwt.decode [k41] Nothing a41) @?= fmap Jws a41decoded++        let a51decoded = Right (defJwsHdr {jwsAlg = ES512}, a51Payload)+        it "decodes the JWT to the expected header and payload (ES512)" $ do+          let Just k51 = decodeStrict' a51jwk+          fstWithRNG (Jwt.decode [k51] Nothing a51) @?= fmap Jws a51decoded+         it "does not evaluate another key after successful verification" $ do           let Just k31 = decodeStrict' a31jwk           fstWithRNG (Jwt.decode [k31, error "second key"] Nothing a31)@@ -120,7 +130,7 @@       context "When using RFC8037 Appendix A data" $ do         let ed25519JwtDecoded = Right (defJwsHdr { jwsAlg = EdDSA }, ed25519Payload)             Just pubKey = decodeStrict' ed25519PubJwk-            Just (secKey@(Ed25519PrivateJwk kPr kPub _)) = decodeStrict' ed25519SecJwk+            Just secKey@(Ed25519PrivateJwk kPr kPub _) = decodeStrict' ed25519SecJwk             sign = Ed25519.sign kPr kPub         it "decodes the JWT to the expected header and payload" $ do           fstWithRNG (Jwt.decode [pubKey] Nothing ed25519Jwt) @?= fmap Jws ed25519JwtDecoded@@ -145,7 +155,7 @@      describe "Ed448 signing and verification" $ do       let Just pubKey = decodeStrict' ed448PubJwk-          Just (secKey@(Ed448PrivateJwk kPr kPub _)) = decodeStrict' ed448SecJwk+          Just secKey@(Ed448PrivateJwk kPr kPub _) = decodeStrict' ed448SecJwk           sign = Ed448.sign kPr kPub        context "" $ do@@ -204,6 +214,16 @@ a31 = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8ISlSApmWQxfKTUJqPP3-Kg6NU1Q" a31jwk = "{\"kty\":\"EC\", \"crv\":\"P-256\", \"x\":\"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU\", \"y\":\"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0\", \"d\":\"jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI\" }" +a41Header = "{\"alg\":\"ES384\"}" :: B.ByteString+a41Payload = a11Payload+a41 = "eyJhbGciOiJFUzM4NCJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.J5KsPUDh01I4VMNYJN8PAOQ7pu43Gm6ebmXKG3Oiq4nbf1flsDPpHbjCh3iZ9VkEFimXVmMwYV32k4-h-u4r_IMYQIh9MgoD6KIR7V1i7WdgWKljtpfg_hY1iZJjgsnG"+a41jwk = "{\"kty\":\"EC\", \"crv\":\"P-384\", \"x\":\"t5ORPpXPEm1Gs1fBSO2s47_4loJ4kt4uinoaeAJVKY8tZNSj1cUGJDxS0HpY3mxo\", \"y\":\"AwP1so-gWo3EZbOPPo98u8Ll1ibQltVnlWNpnTHAl7gaE9cwUzWzeBeMyKoG6jBT\", \"d\":\"rI5_8ULHoMIbX-fgV8en97qCRO3iUZT5gvc44ziH_R-e6Pe463qJ5KGCj9FHuIV4\" }"+++a51Header = "{\"alg\":\"ES512\"}" :: B.ByteString+a51Payload = a11Payload+a51 = "eyJhbGciOiJFUzUxMiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.AYSexs7jt7oRsug2k3xBpZyHDdprRXe3B9_du10Vv5mdFVg7MEVetDN8cnj73gegqpSRyvlmGij-VOVdQZDc15PvAZ3YnjO-lhXY24FCbzsB0KPCpGKlj_HGGiUdba81cS3ik6m6bwpUZkZJ1WJX6Mfr0GrZM2OjzvQ1CZAH1vCk0TYu"+a51jwk = "{\"kty\":\"EC\", \"crv\":\"P-521\", \"x\":\"ANyj1CiuSAv0TbSCbnYvYEJJZIQzBEDS1G6BIhpmgmGBrCdF-o_C0JQpzPX1XPXMLMvSERnAG8gYjyauE5jG1BAu\", \"y\":\"AAW1oGYSlzQglXgdhuPmrQt4lZh9fjTiyV7Em6pO3hECI-y1HZxt52vKSCk9i0rWzeWftJLgpnDqXc1WeyduKgJk\", \"d\":\"AI0vxgEegWyl4kLmv6EE24hwlQOj8xIv52BC8eDnoHlpTildltDR98_K2XjC23XfhNFEQ2X2W1RcXopg5J5qG_Oa\" }"  hmacKey = B.pack [     3, 35, 53, 75, 43, 15, 165, 188, 131, 126, 6, 101, 119, 123, 166,