yesod-csp 0.2.8.0 → 0.3.0.0
raw patch · 7 files changed
+409/−46 lines, 7 filesdep +base64-bytestringdep +bytestringdep +entropydep ~textPVP ok
version bump matches the API change (PVP)
Dependencies added: base64-bytestring, bytestring, entropy, wai-extra
Dependency ranges changed: text
API changes (from Hackage documentation)
+ Yesod.Csp: AllowDownloads :: SandboxOptions
+ Yesod.Csp: AllowModals :: SandboxOptions
+ Yesod.Csp: AllowOrientationLock :: SandboxOptions
+ Yesod.Csp: AllowPointerLock :: SandboxOptions
+ Yesod.Csp: AllowPopups :: SandboxOptions
+ Yesod.Csp: AllowPopupsToEscapeSandbox :: SandboxOptions
+ Yesod.Csp: AllowPresentation :: SandboxOptions
+ Yesod.Csp: AllowStorageAccessByUserActivation :: SandboxOptions
+ Yesod.Csp: AllowTopNavigationByUserActivation :: SandboxOptions
+ Yesod.Csp: AllowTopNavigationToCustomProtocols :: SandboxOptions
+ Yesod.Csp: Hash :: HashAlgorithm -> Text -> Source
+ Yesod.Csp: RequireTrustedTypesForScript :: Directive
+ Yesod.Csp: Sha256 :: HashAlgorithm
+ Yesod.Csp: Sha384 :: HashAlgorithm
+ Yesod.Csp: Sha512 :: HashAlgorithm
+ Yesod.Csp: TrustedTypes :: [Text] -> Directive
+ Yesod.Csp: UnsafeHashes :: Source
+ Yesod.Csp: UpgradeInsecureRequests :: Directive
+ Yesod.Csp: WasmUnsafeEval :: Source
+ Yesod.Csp: cspMiddlewareReportOnly :: DirectiveList -> Middleware
+ Yesod.Csp: cspPolicyReportOnly :: MonadHandler m => DirectiveList -> m ()
+ Yesod.Csp: cspWarnings :: DirectiveList -> [Text]
+ Yesod.Csp: data HashAlgorithm
+ Yesod.Csp: getCspNonce :: MonadHandler m => m Text
+ Yesod.Csp: instance GHC.Classes.Eq Yesod.Csp.HashAlgorithm
+ Yesod.Csp: instance GHC.Internal.Data.Data.Data Yesod.Csp.HashAlgorithm
+ Yesod.Csp: instance GHC.Internal.Show.Show Yesod.Csp.HashAlgorithm
+ Yesod.Csp.TH: requireTrustedTypesFor :: Parser Directive
+ Yesod.Csp.TH: trustedTypes :: Parser Directive
+ Yesod.Csp.TH: upgradeInsecureRequests :: Parser Directive
- Yesod.Csp: BaseUri :: EscapedURI -> Directive
+ Yesod.Csp: BaseUri :: SourceList -> Directive
Files
- CHANGELOG.md +18/−0
- readme.md +67/−0
- src/Yesod/Csp.hs +155/−16
- src/Yesod/Csp/Example.hs +9/−6
- src/Yesod/Csp/TH.hs +54/−21
- test/Test.hs +99/−2
- yesod-csp.cabal +7/−1
CHANGELOG.md view
@@ -1,5 +1,23 @@ # Changelog +## Version 0.3.0.0+++ **Breaking:** `BaseUri` now takes a `SourceList` instead of an `EscapedURI`, so `base-uri 'none'` and `base-uri 'self'` can be expressed++ Fix directive injection via `report-to`: characters that are not valid in an HTTP token are now dropped from the group name++ Restrict nonces to base64 and base64url characters; commas, line breaks and other characters are now dropped++ Escape commas in URIs so they can no longer split the header into several policies++ Fix directive injection via `plugin-types`: only `type/subtype` is rendered, restricted to valid MIME type characters++ Add hash sources, `'unsafe-hashes'` and `'wasm-unsafe-eval'`++ Add `upgrade-insecure-requests`, `require-trusted-types-for` and `trusted-types`++ Add the remaining sandbox flags, such as `allow-popups` and `allow-modals`++ Add `cspPolicyReportOnly` and `cspMiddlewareReportOnly` for `Content-Security-Policy-Report-Only`++ Add `cspWarnings`, which lists risky combinations such as `data:` in `script-src`++ `escapeAndParseURI` keeps a leading `*.` in the host, so wildcard subdomains such as `https://*.example.com` can be expressed++ Add `getCspNonce`, which returns a random nonce per request, and use it in the examples instead of a fixed nonce++ Accept the standard quoted keywords `'unsafe-inline'`, `'unsafe-eval'` and `'strict-dynamic'` in the `csp` quasi-quoter++ Stop rendering a trailing space for `MetaSource`++ Document that `*` and `'none'` drop other sources, that `plugin-types` and `prefetch-src` are obsolete, and that `cspMiddleware` keeps headers set by handlers+ ## Version 0.2.8.0 + Add support for CSP Level 3 directives: `report-to`, `worker-src`, `manifest-src` and `prefetch-src`
+ readme.md view
@@ -0,0 +1,67 @@+# yesod-csp++The aim of this library is to make it easy to add correct [Content Security Policy](https://content-security-policy.com/) headers to your responses. This reduces the risk of loading bad assets or scripts.++## Using the data types++The following code:++```haskell+getHomeR :: Handler Html+getHomeR = do+ cspPolicy [ScriptSrc (Self :| []), StyleSrc (Https :| [Self])]+ defaultLayout [whamlet|hello|]+```++will ensure that a `Content-Security-Policy: script-src 'self'; style-src https: 'self'` header is set. In this example we only want to load scripts from our own domain, and we only want styles that come from our domain or over https.++Use `getCspPolicy` to see the header a policy produces, and check that it matches what you need.++## Adding a policy to every response++`cspMiddleware` is a WAI middleware that adds the same policy to every response:++```haskell+main :: IO ()+main = toWaiApp App >>= run 3000 . cspMiddleware [DefaultSrc (Self :| [])]+```++A header set by a handler with `cspPolicy` is kept as well. The browser then enforces both policies, so a resource must be allowed by each.++## Nonces++A nonce only protects you if it is unpredictable and changes with every response. `getCspNonce` returns a random nonce for the current request, and returns the same value on every call within that request:++```haskell+getHomeR :: Handler Html+getHomeR = do+ n <- getCspNonce+ cspPolicy [ScriptSrc (nonce n :| [])]+ defaultLayout [whamlet|<script nonce=#{n}>alert("hi");|]+```++## Template Haskell support++The `csp` quasi-quoter from `Yesod.Csp.TH` lets you write policies in the familiar CSP syntax instead of building the data types yourself. The policy is parsed at compile time, so a malformed policy is a compile error:++```haskell+getHomeR :: Handler Html+getHomeR = do+ cspPolicy [csp|img-src 'self' https:; script-src https://foo.com|]+ ...+```++You can add URLs and nonces from the surrounding scope with `$`:++```haskell+getHomeR :: Handler Html+getHomeR = do+ let url = fromJust (escapeAndParseURI "https://cdn.example.com")+ n <- getCspNonce+ cspPolicy [csp|img-src 'self' $url; script-src $nonce-n|]+ ...+```++## Examples++[This module](https://github.com/pSub/yesod-csp/blob/master/src/Yesod/Csp/Example.hs) contains a host of runnable example Yesod handlers which set various CSP headers.
src/Yesod/Csp.hs view
@@ -5,22 +5,31 @@ -- This helps reduce the risk of exposure to XSS and bad assets. module Yesod.Csp ( cspPolicy+ , cspPolicyReportOnly , getCspPolicy , cspMiddleware+ , cspMiddlewareReportOnly+ , cspWarnings , EscapedURI , escapeAndParseURI , escapedTextForNonce , nonce+ , getCspNonce , DirectiveList , Directive(..) , SourceList , Source(..)+ , HashAlgorithm(..) , SandboxOptions(..) , textSource ) where import Codec.MIME.Type as Mime+import Control.Applicative ((<|>))+import Control.Monad (guard)+import qualified Data.ByteString.Base64 as B64 import qualified Data.CaseInsensitive as CI+import Data.Char (isAlphaNum, isAscii) import Data.Data (Data) import Data.List.NonEmpty import Data.Text (Text)@@ -28,6 +37,7 @@ import qualified Data.Text.Encoding as TE import Data.Typeable (Typeable) import Network.URI+import System.Entropy (getEntropy) import Yesod.Core import Network.Wai (Middleware, mapResponseHeaders, modifyResponse)@@ -45,8 +55,14 @@ cspPolicy :: (MonadHandler m) => DirectiveList -> m () cspPolicy = addHeader cspHeaderName . directiveListToHeader -cspHeaderName :: Text+-- | Like 'cspPolicy', but adds a "Content-Security-Policy-Report-Only" header:+-- violations are only reported, not blocked.+cspPolicyReportOnly :: (MonadHandler m) => DirectiveList -> m ()+cspPolicyReportOnly = addHeader cspReportOnlyHeaderName . directiveListToHeader++cspHeaderName, cspReportOnlyHeaderName :: Text cspHeaderName = "Content-Security-Policy"+cspReportOnlyHeaderName = "Content-Security-Policy-Report-Only" -- | Returns a generated Content-Security-Policy header. getCspPolicy :: DirectiveList -> Text@@ -54,18 +70,52 @@ -- | Creates a WAI 'Middleware' to add a Content-Security-Policy -- header to every response.+--+-- A header set by a handler with 'cspPolicy' is kept, not replaced. The+-- browser then enforces both policies, so a resource must be allowed by each. cspMiddleware :: DirectiveList -> Middleware-cspMiddleware = addHeaderMiddleware . mkHeader . directiveListToHeader+cspMiddleware = headerMiddleware cspHeaderName++-- | Like 'cspMiddleware', but adds a "Content-Security-Policy-Report-Only" header.+cspMiddlewareReportOnly :: DirectiveList -> Middleware+cspMiddlewareReportOnly = headerMiddleware cspReportOnlyHeaderName++headerMiddleware :: Text -> DirectiveList -> Middleware+headerMiddleware name = addHeaderMiddleware . mkHeader . directiveListToHeader where addHeaderMiddleware = modifyResponse . mapResponseHeaders . insertAt 5- mkHeader dltext = (cspHeaderNameBS, TE.encodeUtf8 dltext)- cspHeaderNameBS = CI.mk $ TE.encodeUtf8 cspHeaderName+ mkHeader dltext = (CI.mk $ TE.encodeUtf8 name, TE.encodeUtf8 dltext) +-- | Lists risky combinations in a policy that are allowed but weaken it,+-- e.g. @data:@ in @script-src@. Returns an empty list if none are found.+cspWarnings :: DirectiveList -> [Text]+cspWarnings ds = Prelude.concatMap warn ds+ where+ warn (ScriptSrc x) = scriptWarnings "script-src" x+ warn (DefaultSrc x) | not (Prelude.any isScriptSrc ds) = scriptWarnings "default-src" x+ warn (Sandbox o) | AllowScripts `elem` o && AllowSameOrigin `elem` o =+ ["sandbox: allow-scripts with allow-same-origin lets the framed page remove its own sandbox"]+ warn _ = []+ scriptWarnings k x =+ [k <> ": data: allows scripts from data: URIs" | DataScheme `elem` x]+ ++ [k <> ": 'unsafe-inline' without a nonce or hash allows inline scripts" | UnsafeInline `elem` x, not (Prelude.any isNonceOrHash x)]+ isScriptSrc (ScriptSrc _) = True+ isScriptSrc _ = False+ isNonceOrHash (Nonce _) = True+ isNonceOrHash (Hash _ _) = True+ isNonceOrHash _ = False+ insertAt :: Int -> a -> [a] -> [a] insertAt n x xs = let (h, t) = Prelude.splitAt n xs in h ++ x : t +-- | A URI that is safe to put into a CSP header. Build it with 'escapeAndParseURI'.+--+-- The 'Data' instances of this type and of nonces exist only so the @csp@+-- quasi-quoter can lift policies. Generic traversals (e.g. SYB's @everywhere@)+-- can rewrite the strings inside them without escaping, so do not run them+-- over a 'DirectiveList'. newtype EscapedURI = EscapedURI { uri :: URI } deriving (Eq, Data, Typeable) newtype EscapedText = EscapedText { text :: String } deriving (Eq, Data, Typeable)@@ -77,23 +127,51 @@ show x = mconcat ["'nonce-", text x, "'"] toEscape :: String-toEscape = ";'* "+toEscape = ";,'* " notEscapable :: Char -> Bool notEscapable = not . flip elem toEscape --- | Escapes ';' '\'' and ' ', and parses to URI+-- | Escapes ';' ',' '\'' '*' and ' ', and parses to URI.+-- A leading @*.@ in the host is kept as a wildcard subdomain, e.g. @https://*.example.com@. escapeAndParseURI :: Text -> Maybe EscapedURI-escapeAndParseURI = fmap EscapedURI . parseURI . escapeURIString notEscapable . T.unpack+escapeAndParseURI t = fmap EscapedURI (wildcardHost <|> parse t)+ where parse = parseURI . escapeURIString notEscapable . T.unpack+ wildcardHost = do+ let (s, r) = T.breakOn "://*." t+ u <- parse (s <> "://" <> T.drop 5 r)+ a <- uriAuthority u+ -- the "://*." must directly follow the scheme, not appear later in the URI+ guard (uriScheme u == T.unpack s ++ ":" && not (null (uriRegName a)))+ return u { uriAuthority = Just a { uriRegName = "*." ++ uriRegName a } } --- | Escapes Text to be a valid nonce value+-- | Escapes Text to be a valid nonce value by keeping only base64 and+-- base64url characters (and @=@ padding); everything else is dropped. escapedTextForNonce :: String -> EscapedText-escapedTextForNonce = EscapedText . Prelude.filter notEscapable+escapedTextForNonce = EscapedText . Prelude.filter isBase64Char+ where isBase64Char c = (isAscii c && isAlphaNum c) || c `elem` ("+/-_=" :: String) -- | Escapes a Text value, returning a valid Nonce nonce :: Text -> Source nonce = Nonce . escapedTextForNonce . T.unpack +newtype CspNonce = CspNonce Text++-- | Returns a nonce for the current request: 18 bytes from the system's+-- cryptographically secure random number generator, base64-encoded.+-- Every call within the same request returns the same value, so it can be+-- used both in the header and in the @nonce@ attribute of your tags.+--+-- > getExample :: Handler Html+-- > getExample = do+-- > n <- getCspNonce+-- > cspPolicy [ScriptSrc (nonce n :| [])]+-- > defaultLayout [whamlet|<script nonce=#{n}>alert("hi");|]+getCspNonce :: MonadHandler m => m Text+getCspNonce = do+ CspNonce n <- cached $ CspNonce . TE.decodeUtf8 . B64.encode <$> liftIO (getEntropy 18)+ return n+ directiveListToHeader :: DirectiveList -> Text directiveListToHeader = T.intercalate "; " . fmap textDirective @@ -104,7 +182,7 @@ wrap k x = mconcat [k, " ", textSourceList x] textSourceList :: SourceList -> Text-textSourceList = T.unwords . toList . filtered+textSourceList = T.unwords . Prelude.filter (not . T.null) . toList . filtered where filtered = fmap textSource . filterOut -- * and none should be alone if present@@ -114,7 +192,10 @@ | otherwise = x -- | Represents a location from which assets may be loaded.-data Source = Wildcard+data Source = -- | @*@. Any other source in the same list is dropped, so+ -- @Wildcard :| [UnsafeInline]@ renders as just @*@.+ Wildcard+ -- | @'none'@. Any other source in the same list is dropped. | None | Self | DataScheme@@ -123,9 +204,17 @@ | UnsafeInline | UnsafeEval | StrictDynamic+ | UnsafeHashes+ | WasmUnsafeEval | Nonce EscapedText+ -- | A base64 hash of an allowed inline script or style.+ | Hash HashAlgorithm Text+ -- | Used internally by the @csp@ quasi-quoter for antiquotes; renders as nothing. | MetaSource Text deriving (Eq, Show, Data, Typeable) +-- | Algorithm of a 'Hash' source.+data HashAlgorithm = Sha256 | Sha384 | Sha512 deriving (Eq, Show, Data, Typeable)+ -- | A list of allowed sources for a directive. type SourceList = NonEmpty Source @@ -139,6 +228,14 @@ textSource UnsafeInline = "'unsafe-inline'" textSource UnsafeEval = "'unsafe-eval'" textSource StrictDynamic = "'strict-dynamic'"+textSource UnsafeHashes = "'unsafe-hashes'"+textSource WasmUnsafeEval = "'wasm-unsafe-eval'"+textSource (Hash a h) = mconcat ["'", alg a, "-", T.filter isBase64Char h, "'"]+ where alg Sha256 = "sha256"+ alg Sha384 = "sha384"+ alg Sha512 = "sha512"+ -- filtered on render, so no hash value can inject quotes or directives+ isBase64Char c = isAscii c && (isAlphaNum c || c `elem` ("+/=-_" :: String)) textSource (MetaSource _) = "" textSource (Nonce x) = (T.pack . show) x @@ -164,19 +261,30 @@ | FrameSrc SourceList -- | Applies a sandbox to the result. <http://content-security-policy.com/ See here> for more info. | Sandbox [SandboxOptions]+ -- | Deprecated in CSP Level 3 in favour of 'ReportTo', but still the+ -- only reporting directive some browsers support; send both. | ReportUri EscapedURI -- | CSP level 2 directives | FrameAncestors SourceList | ChildSrc SourceList | FormAction SourceList- | BaseUri EscapedURI+ | BaseUri SourceList+ -- | Removed from the CSP specification and ignored by current browsers.+ -- Use @ObjectSrc (None :| [])@ to block plugins instead. | PluginTypes MimeTypeList -- | CSP level 3 directives | WorkerSrc SourceList | ManifestSrc SourceList+ -- | Removed from the CSP specification; browsers may ignore it. | PrefetchSrc SourceList -- | Names a reporting group defined by the @Reporting-Endpoints@ (or @Report-To@) response header.+ -- Characters that are not valid in an HTTP token are dropped when rendering. | ReportTo Text+ | UpgradeInsecureRequests+ -- | @require-trusted-types-for 'script'@+ | RequireTrustedTypesForScript+ -- | Allowed Trusted Types policy names, e.g. @[\"myPolicy\", \"'allow-duplicates'\"]@.+ | TrustedTypes [Text] deriving (Eq, Show, Data, Typeable) @@ -184,7 +292,17 @@ data SandboxOptions = AllowForms | AllowScripts | AllowSameOrigin- | AllowTopNavigation deriving (Eq, Show, Data, Typeable)+ | AllowTopNavigation+ | AllowDownloads+ | AllowModals+ | AllowOrientationLock+ | AllowPointerLock+ | AllowPopups+ | AllowPopupsToEscapeSandbox+ | AllowPresentation+ | AllowStorageAccessByUserActivation+ | AllowTopNavigationByUserActivation+ | AllowTopNavigationToCustomProtocols deriving (Eq, Show, Data, Typeable) textDirective :: Directive -> Text textDirective (DefaultSrc x) = w "default-src" x@@ -203,12 +321,33 @@ textSandbox AllowScripts = "allow-scripts" textSandbox AllowSameOrigin = "allow-same-origin" textSandbox AllowTopNavigation = "allow-top-navigation"+ textSandbox AllowDownloads = "allow-downloads"+ textSandbox AllowModals = "allow-modals"+ textSandbox AllowOrientationLock = "allow-orientation-lock"+ textSandbox AllowPointerLock = "allow-pointer-lock"+ textSandbox AllowPopups = "allow-popups"+ textSandbox AllowPopupsToEscapeSandbox = "allow-popups-to-escape-sandbox"+ textSandbox AllowPresentation = "allow-presentation"+ textSandbox AllowStorageAccessByUserActivation = "allow-storage-access-by-user-activation"+ textSandbox AllowTopNavigationByUserActivation = "allow-top-navigation-by-user-activation"+ textSandbox AllowTopNavigationToCustomProtocols = "allow-top-navigation-to-custom-protocols" textDirective (FrameAncestors x) = w "frame-ancestors" x textDirective (ChildSrc x) = w "child-src" x textDirective (FormAction x) = w "form-action" x-textDirective (BaseUri t) = mconcat ["base-uri ", (T.pack . show) t]-textDirective (PluginTypes t) = mconcat ["plugin-types ", (T.unwords . fmap Mime.showType . toList) t]+textDirective (BaseUri x) = w "base-uri" x+textDirective (PluginTypes t) = mconcat ["plugin-types ", (T.unwords . fmap textMimeType . toList) t]+ -- only type/subtype, restricted to RFC 6838 name chars, so ';', spaces and CR/LF cannot inject directives+ where textMimeType = T.filter isMimeChar . Mime.showMIMEType . Mime.mimeType+ isMimeChar c = isAscii c && (isAlphaNum c || c `elem` ("!#$&-^_.+/" :: String)) textDirective (WorkerSrc x) = w "worker-src" x textDirective (ManifestSrc x) = w "manifest-src" x textDirective (PrefetchSrc x) = w "prefetch-src" x-textDirective (ReportTo t) = mconcat ["report-to ", t]+textDirective (ReportTo t) = mconcat ["report-to ", T.filter isTokenChar t]+ -- RFC 9110 token; keeps ';', ',', whitespace and CR/LF from injecting directives or policies+ where isTokenChar c = (isAscii c && isAlphaNum c) || c `elem` ("!#$%&'*+-.^_`|~" :: String)+textDirective UpgradeInsecureRequests = "upgrade-insecure-requests"+textDirective RequireTrustedTypesForScript = "require-trusted-types-for 'script'"+textDirective (TrustedTypes []) = "trusted-types"+textDirective (TrustedTypes ns) = T.unwords ("trusted-types" : fmap (T.filter isPolicyChar) ns)+ -- policy-name chars plus '*' and quotes for keywords; no ';', ',' or whitespace+ where isPolicyChar c = isAscii c && (isAlphaNum c || c `elem` ("-#=_/@.%*'" :: String))
src/Yesod/Csp/Example.hs view
@@ -104,6 +104,8 @@ cdn = Host (fromJust $ escapeAndParseURI "https://cdn.com") +-- | Shows the literal nonce syntax only. A fixed nonce gives no protection;+-- use 'getCspNonce' as in the examples below. getExample8R :: Handler Html getExample8R = do cspPolicy [csp|script-src 'nonce-foo'|]@@ -114,19 +116,20 @@ getExample9R :: Handler Html getExample9R = do- let n = "foo"+ n <- getCspNonce cspPolicy [csp|script-src $nonce-n|] defaultLayout $ [whamlet|- <script nonce="foo">+ <script nonce=#{n}> alert("ayyyy"); |] +-- | The script's nonce does not match the header, so the browser blocks it. getExample10R :: Handler Html getExample10R = do- let n = "bar"+ n <- getCspNonce cspPolicy [csp|script-src $nonce-n|] defaultLayout $ [whamlet|- <script nonce="foo">+ <script nonce="wrong"> alert("ayyyy"); |] @@ -141,10 +144,10 @@ getExample12R :: Handler Html getExample12R = do- let n = "foo"+ n <- getCspNonce cspPolicy [csp|script-src strict-dynamic unsafe-inline $nonce-n|] defaultLayout $ [whamlet|- <script nonce="foo">+ <script nonce=#{n}> alert("ayyyy"); |]
src/Yesod/Csp/TH.hs view
@@ -8,6 +8,9 @@ , pluginTypes , sandbox , sandboxOptions+ , upgradeInsecureRequests+ , requireTrustedTypesFor+ , trustedTypes , directive , csp ) where@@ -54,6 +57,9 @@ <|> self <|> dataScheme <|> https+ <|> unsafeHashes+ <|> wasmUnsafeEval+ <|> hash <|> host <|> unsafeInline <|> unsafeEval@@ -72,6 +78,15 @@ n <- takeTill (== '\'') _ <- char '\'' return $ nonce n+ unsafeHashes = string "'unsafe-hashes'" *> pure UnsafeHashes+ wasmUnsafeEval = string "'wasm-unsafe-eval'" *> pure WasmUnsafeEval+ hash = do+ _ <- char '\''+ a <- (string "sha256" *> pure Sha256) <|> (string "sha384" *> pure Sha384) <|> (string "sha512" *> pure Sha512)+ _ <- char '-'+ h <- takeTill (== '\'')+ _ <- char '\''+ return $ Hash a h host :: Parser Source host = do u <- takeTill separated@@ -86,9 +101,11 @@ (Just ';') -> return Https Nothing -> return Https _ -> fail "https"- unsafeInline = string "unsafe-inline" *> pure UnsafeInline- unsafeEval = string "unsafe-eval" *> pure UnsafeEval- strictDynamic = string "strict-dynamic" *> pure StrictDynamic+ -- quoted is the standard CSP form; unquoted is kept for compatibility+ keyword k = string ("'" <> k <> "'") <|> string k+ unsafeInline = keyword "unsafe-inline" *> pure UnsafeInline+ unsafeEval = keyword "unsafe-eval" *> pure UnsafeEval+ strictDynamic = keyword "strict-dynamic" *> pure StrictDynamic separated :: Char -> Bool separated x = x == ';' || x == ' '@@ -114,6 +131,7 @@ <|> workerSrc <|> manifestSrc <|> prefetchSrc+ <|> baseUri where defaultSrc = d "default-src" DefaultSrc scriptSrc = d "script-src" ScriptSrc styleSrc = d "style-src" StyleSrc@@ -129,6 +147,7 @@ workerSrc = d "worker-src" WorkerSrc manifestSrc = d "manifest-src" ManifestSrc prefetchSrc = d "prefetch-src" PrefetchSrc+ baseUri = d "base-uri" BaseUri d x y = string x >> s >> slist >>= mkWithSource y slist = sepBy1 source (char ' ') s = spaces@@ -154,15 +173,6 @@ then fail "reportTo" -- n.b. compile time error else return $ ReportTo g -baseUri :: Parser Directive-baseUri = do- _ <- string "base-uri"- _ <- spaces- u <- takeTill separated- case escapeAndParseURI u of- Nothing -> fail "baseUri" -- n.b. compile time error- Just uri -> return $ BaseUri uri- pluginTypes :: Parser Directive pluginTypes = do _ <- string "plugin-types"@@ -180,19 +190,42 @@ return $ Sandbox x sandboxOptions :: Parser SandboxOptions-sandboxOptions = allowForms- <|> allowScripts- <|> allowSameOrigin- <|> allowTopNavigation- where allowForms = string "allow-forms" *> pure AllowForms- allowScripts = string "allow-scripts" *> pure AllowScripts- allowSameOrigin = string "allow-same-origin" *> pure AllowSameOrigin- allowTopNavigation = string "allow-top-navigation" *> pure AllowTopNavigation+-- longer names first, where one is a prefix of another+sandboxOptions = choice $ fmap (\(n, o) -> string n *> pure o)+ [ ("allow-forms", AllowForms)+ , ("allow-scripts", AllowScripts)+ , ("allow-same-origin", AllowSameOrigin)+ , ("allow-top-navigation-by-user-activation", AllowTopNavigationByUserActivation)+ , ("allow-top-navigation-to-custom-protocols", AllowTopNavigationToCustomProtocols)+ , ("allow-top-navigation", AllowTopNavigation)+ , ("allow-downloads", AllowDownloads)+ , ("allow-modals", AllowModals)+ , ("allow-orientation-lock", AllowOrientationLock)+ , ("allow-pointer-lock", AllowPointerLock)+ , ("allow-popups-to-escape-sandbox", AllowPopupsToEscapeSandbox)+ , ("allow-popups", AllowPopups)+ , ("allow-presentation", AllowPresentation)+ , ("allow-storage-access-by-user-activation", AllowStorageAccessByUserActivation)+ ] +upgradeInsecureRequests :: Parser Directive+upgradeInsecureRequests = string "upgrade-insecure-requests" *> pure UpgradeInsecureRequests++requireTrustedTypesFor :: Parser Directive+requireTrustedTypesFor = string "require-trusted-types-for" *> spaces *> string "'script'" *> pure RequireTrustedTypesForScript++trustedTypes :: Parser Directive+trustedTypes = do+ _ <- string "trusted-types"+ _ <- spaces+ ns <- sepBy (takeWhile1 (not . separated)) (char ' ')+ return $ TrustedTypes ns+ separator :: Parser () separator = comma *> (spaces *> pure ()) where comma = string ";" directive :: Parser DirectiveList directive = sepBy (spaces *> d) separator <* (spaces *> endOfInput)- where d = withSourceList <|> reportUri <|> reportTo <|> baseUri <|> pluginTypes <|> sandbox+ where d = withSourceList <|> reportUri <|> reportTo <|> pluginTypes <|> sandbox+ <|> upgradeInsecureRequests <|> requireTrustedTypesFor <|> trustedTypes
test/Test.hs view
@@ -5,7 +5,11 @@ {-# LANGUAGE TypeFamilies #-} import Codec.MIME.Parse (parseMIMEType)+import Codec.MIME.Type (MIMEType (..), Type (..)) import Data.Attoparsec.Text+import qualified Data.ByteString.Lazy as BL+import Data.Text (Text)+import Network.Wai.Test (simpleBody) import Data.List.NonEmpty import Data.Maybe import Test.Hspec@@ -18,6 +22,8 @@ mkYesod "Test" [parseRoutes| / HomeR GET /nocsp NoCspR GET+/reportonly ReportOnlyR GET+/nonce NonceR GET |] instance Yesod Test@@ -27,10 +33,23 @@ cspPolicy [ScriptSrc (Self :| []), StyleSrc (Https :| [Self])] defaultLayout [whamlet|hello|] +getReportOnlyR :: Handler Html+getReportOnlyR = do+ cspPolicyReportOnly [ScriptSrc (Self :| [])]+ defaultLayout [whamlet|hello|]+ getNoCspR :: Handler Html getNoCspR = do defaultLayout [whamlet|hello|] +-- Responds with the request's nonce, after checking it is stable within the request.+getNonceR :: Handler Text+getNonceR = do+ n <- getCspNonce+ n' <- getCspNonce+ cspPolicy [ScriptSrc (nonce n :| [])]+ return $ if n == n' then n else "nonce changed within the request"+ main :: IO () main = hspec $ tests >> middlewareTest @@ -44,9 +63,44 @@ let dom = fromJust $ escapeAndParseURI "https://foo.com/bar *" header = getCspPolicy [ScriptSrc (Host dom :| [])] assertEq "foo.com script-src" header "script-src https://foo.com/bar%20%2A"+ yit "works with wildcard subdomains" $ do+ let header = getCspPolicy [ScriptSrc (Host (fromJust $ escapeAndParseURI "https://*.foo.com:443/x") :| [])]+ assertEq "wildcard subdomain" header "script-src https://*.foo.com:443/x"+ assertEq "wildcard only at host start" (show <$> escapeAndParseURI "https://foo.com/a://*.b") (Just "https://foo.com/a://%2A.b")+ assertEq "bare wildcard host stays escaped" (show <$> escapeAndParseURI "https://*") (Just "https://%2A")+ assertEq "wildcard in quasi-quoter" [csp|script-src https://*.foo.com|] [ScriptSrc (Host (fromJust $ escapeAndParseURI "https://*.foo.com") :| [])]+ yit "works with CSP Level 3 sources" $ do+ let header = getCspPolicy [ScriptSrc (Hash Sha256 "abc+/=" :| [UnsafeHashes, WasmUnsafeEval])]+ assertEq "level 3 sources" header "script-src 'sha256-abc+/=' 'unsafe-hashes' 'wasm-unsafe-eval'"+ assertEq "hash is filtered" (textSource (Hash Sha512 "x'; script-src *")) "'sha512-xscript-src'"+ yit "works with upgrade-insecure-requests and trusted types" $ do+ let header = getCspPolicy [UpgradeInsecureRequests, RequireTrustedTypesForScript, TrustedTypes ["foo", "'allow-duplicates'", "x; y"]]+ assertEq "trusted types" header "upgrade-insecure-requests; require-trusted-types-for 'script'; trusted-types foo 'allow-duplicates' xy"+ assertEq "no policies" (getCspPolicy [TrustedTypes []]) "trusted-types"+ yit "warns about risky combinations" $ do+ assertEq "data: in script-src" (cspWarnings [ScriptSrc (Self :| [DataScheme])]) ["script-src: data: allows scripts from data: URIs"]+ assertEq "default-src counts when no script-src" (Prelude.length (cspWarnings [DefaultSrc (UnsafeInline :| [])])) 1+ assertEq "default-src ignored with script-src" (cspWarnings [DefaultSrc (UnsafeInline :| []), ScriptSrc (Self :| [])]) []+ assertEq "unsafe-inline with nonce" (cspWarnings [ScriptSrc (UnsafeInline :| [nonce "abc"])]) []+ assertEq "sandbox" (Prelude.length (cspWarnings [Sandbox [AllowScripts, AllowSameOrigin]])) 1+ assertEq "safe policy" (cspWarnings [ScriptSrc (Self :| []), Sandbox [AllowScripts]]) []+ yit "escapes commas in domains" $ do+ let dom = fromJust $ escapeAndParseURI "https://foo.com,script-src"+ header = getCspPolicy [ScriptSrc (Host dom :| [])]+ assertEq "comma in host" header "script-src https://foo.com%2Cscript-src"+ yit "escapes commas in report-uri" $ do+ let dom = fromJust $ escapeAndParseURI "https://foo.com/a,b"+ header = getCspPolicy [ReportUri dom]+ assertEq "comma in report-uri" header "report-uri https://foo.com/a%2Cb" yit "works with nonce-source" $ do let header = getCspPolicy [ScriptSrc (nonce "foo" :| [])] assertEq "basic nonce-source" header "script-src 'nonce-foo'"+ yit "keeps base64 and base64url nonces intact" $ do+ let header = getCspPolicy [ScriptSrc (nonce "aB3+/9-_==" :| [])]+ assertEq "base64 nonce-source" header "script-src 'nonce-aB3+/9-_=='"+ yit "strips non-base64 characters from nonces" $ do+ let header = getCspPolicy [ScriptSrc (nonce "a,b\r\nX-Injected: yes; 'c'" :| [])]+ assertEq "nonce injection" header "script-src 'nonce-abX-Injectedyesc'" yit "works with report_uri" $ do let dom = fromJust $ escapeAndParseURI "https://foo.com" header = getCspPolicy [ReportUri dom]@@ -57,10 +111,21 @@ yit "enforces nones" $ do let header = getCspPolicy [ScriptSrc (None :| [Https])] assertEq "none should be alone" header "script-src 'none'"+ yit "renders meta sources as nothing" $ do+ let header = getCspPolicy [ScriptSrc (Self :| [MetaSource "x"])]+ assertEq "no trailing space" header "script-src 'self'" yit "works with plugin-types" $ do let dom = pure $ fromJust $ parseMIMEType "text/plain" header = getCspPolicy [PluginTypes dom] assertEq "plugin-types" header "plugin-types text/plain"+ yit "plugin-types drops params and cannot inject directives" $ do+ let evil = Type (Other "x" "y; script-src *\r\nX-Evil: injected") []+ withParams = fromJust $ parseMIMEType "text/plain; charset=utf-8"+ header = getCspPolicy [PluginTypes (evil :| [withParams])]+ assertEq "plugin-types" header "plugin-types x/yscript-srcX-Evilinjected text/plain"+ yit "works with base-uri" $ do+ let header = getCspPolicy [BaseUri (None :| [])]+ assertEq "base-uri" header "base-uri 'none'" yit "works with worker-src" $ do let header = getCspPolicy [WorkerSrc (Self :| [])] assertEq "worker-src" header "worker-src 'self'"@@ -73,10 +138,31 @@ yit "works with report-to" $ do let header = getCspPolicy [ReportTo "csp-endpoint"] assertEq "report-to" header "report-to csp-endpoint"- ydescribe "Headers" $+ yit "prevents directive injection via report-to" $ do+ let header = getCspPolicy [DefaultSrc (Self :| []), ReportTo "g; script-src * 'unsafe-inline'"]+ assertEq "report-to injection" header "default-src 'self'; report-to gscript-src*'unsafe-inline'"+ yit "strips policy separators and line breaks from report-to" $ do+ let header = getCspPolicy [ReportTo "g,\r\nX-Injected: yes"]+ assertEq "report-to separators" header "report-to gX-Injectedyes"+ ydescribe "Headers" $ do yit "get set" $ do get HomeR assertHeader "Content-Security-Policy" "script-src 'self'; style-src https: 'self'"+ yit "report-only" $ do+ get ReportOnlyR+ assertHeader "Content-Security-Policy-Report-Only" "script-src 'self'"+ ydescribe "Nonces" $+ yit "are fresh per request and match the header" $ do+ let responseNonce = withResponse $ \r -> do+ let n = BL.toStrict (simpleBody r)+ assertEq "nonce length" 24 (BL.length (simpleBody r))+ assertHeader "Content-Security-Policy" ("script-src 'nonce-" <> n <> "'")+ return n+ get NonceR+ n1 <- responseNonce+ get NonceR+ n2 <- responseNonce+ assertNotEq "fresh nonce per request" n1 n2 ydescribe "Sandboxes" $ do yit "works when empty" $ do let header = getCspPolicy [Sandbox []]@@ -95,12 +181,19 @@ assertEq "https:" (parseOnly source "https:") (Right Https) assertEq "unsafe-inline" (parseOnly source "unsafe-inline") (Right UnsafeInline) assertEq "unsafe-eval" (parseOnly source "unsafe-eval") (Right UnsafeEval)+ assertEq "'unsafe-inline'" (parseOnly source "'unsafe-inline'") (Right UnsafeInline)+ assertEq "'unsafe-eval'" (parseOnly source "'unsafe-eval'") (Right UnsafeEval)+ assertEq "'strict-dynamic'" (parseOnly source "'strict-dynamic'") (Right StrictDynamic) assertEq "default-src self data:" (parseOnly withSourceList "default-src 'self' data:") (Right $ DefaultSrc (Self :| [DataScheme])) assertEq "report-uri http://hello.com" (parseOnly reportUri "report-uri http://hello.com") (Right $ ReportUri (fromJust (escapeAndParseURI "http://hello.com"))) assertEq "report-to csp-endpoint" (parseOnly reportTo "report-to csp-endpoint") (Right $ ReportTo "csp-endpoint") assertEq "worker-src self" (parseOnly withSourceList "worker-src 'self'") (Right $ WorkerSrc (Self :| [])) assertEq "manifest-src self" (parseOnly withSourceList "manifest-src 'self'") (Right $ ManifestSrc (Self :| [])) assertEq "prefetch-src self" (parseOnly withSourceList "prefetch-src 'self'") (Right $ PrefetchSrc (Self :| []))+ assertEq "base-uri self" [csp|base-uri 'self'|] [BaseUri (Self :| [])]+ assertEq "level 3 sources th" [csp|script-src 'sha384-ab+c=' 'unsafe-hashes' 'wasm-unsafe-eval'|] [ScriptSrc (Hash Sha384 "ab+c=" :| [UnsafeHashes, WasmUnsafeEval])]+ assertEq "level 3 directives th" [csp|upgrade-insecure-requests; require-trusted-types-for 'script'; trusted-types foo 'allow-duplicates'|] [UpgradeInsecureRequests, RequireTrustedTypesForScript, TrustedTypes ["foo", "'allow-duplicates'"]]+ assertEq "sandbox prefixes" (parseOnly sandbox "sandbox allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation allow-popups") (Right $ Sandbox [AllowPopupsToEscapeSandbox, AllowTopNavigationByUserActivation, AllowPopups]) assertEq "sandbox allow-forms allow-scripts" (parseOnly sandbox "sandbox allow-forms allow-scripts") (Right $ Sandbox [AllowForms, AllowScripts]) yit "works with lists" $ do let resultHttps = [ImgSrc $ Self :| [Https], ScriptSrc $ Host (fromJust $ escapeAndParseURI "https://foo.com") :| []]@@ -119,6 +212,9 @@ assertEq "with th" [csp|img-src 'self' https:; script-src https://foo.com|] result let url = fromJust $ escapeAndParseURI "https://foo.com" assertEq "with antiquoting" [csp|img-src 'self' https:; script-src $url|] result+ yit "works with quoted keywords and th" $ do+ let result = [ScriptSrc $ Self :| [UnsafeInline, StrictDynamic]]+ assertEq "quoted keywords" [csp|script-src 'self' 'unsafe-inline' 'strict-dynamic'|] result yit "works with th and newlines" $ do let attempt = [csp| default-src 'self'@@ -131,6 +227,7 @@ yit "works" $ do get NoCspR assertHeader "Content-Security-Policy" "frame-ancestors 'self'"+ assertHeader "Content-Security-Policy-Report-Only" "upgrade-insecure-requests" where- getApp = cspMiddleware [FrameAncestors (Self :| [])] <$>+ getApp = cspMiddleware [FrameAncestors (Self :| [])] . cspMiddlewareReportOnly [UpgradeInsecureRequests] <$> toWaiAppPlain Test
yesod-csp.cabal view
@@ -2,7 +2,7 @@ -- documentation, see http://haskell.org/cabal/users-guide/ name: yesod-csp-version: 0.2.8.0+version: 0.3.0.0 synopsis: Add CSP headers to Yesod apps description: Add CSP headers to Yesod apps. This helps reduce exposure to XSS attacks and bad assets. license: MIT@@ -13,6 +13,7 @@ build-type: Simple cabal-version: >=1.10 extra-source-files: CHANGELOG.md+ , readme.md source-repository head type: git@@ -36,6 +37,8 @@ , wai >= 3.2.3 && < 3.3 , case-insensitive >= 1.2.1 && < 1.3 , mime >= 0.4.0.0 && < 0.5+ , entropy >= 0.4.1.10 && < 0.5+ , base64-bytestring >= 1.2.1 && < 1.3 hs-source-dirs: src default-language: Haskell2010 ghc-options: -Wall@@ -55,4 +58,7 @@ , attoparsec , template-haskell , mime+ , bytestring+ , text+ , wai-extra default-language: Haskell2010