xss-sanitize-0.3.7.2/src/0000755000000000000000000000000014412061552013277 5ustar0000000000000000xss-sanitize-0.3.7.2/src/Text/0000755000000000000000000000000014412061552014223 5ustar0000000000000000xss-sanitize-0.3.7.2/src/Text/HTML/0000755000000000000000000000000014412061552014767 5ustar0000000000000000xss-sanitize-0.3.7.2/src/Text/HTML/SanitizeXSS/0000755000000000000000000000000014412061552017153 5ustar0000000000000000xss-sanitize-0.3.7.2/test/0000755000000000000000000000000014412061552013467 5ustar0000000000000000xss-sanitize-0.3.7.2/src/Text/HTML/SanitizeXSS.hs0000644000000000000000000003352714412061552017521 0ustar0000000000000000{-# LANGUAGE OverloadedStrings #-} -- | Sanatize HTML to prevent XSS attacks. -- -- See README.md for more details. module Text.HTML.SanitizeXSS ( -- * Sanitize sanitize , sanitizeBalance , sanitizeXSS -- * Custom filtering , filterTags , safeTags , safeTagsCustom , clearTags , clearTagsCustom , balanceTags -- * Utilities , safeTagName , sanitizeAttribute , sanitaryURI ) where import Text.HTML.SanitizeXSS.Css import Text.HTML.TagSoup import Data.Set (Set(), member, notMember, (\\), fromList, fromAscList) import Data.Char ( toLower ) import Data.Text (Text) import qualified Data.Text as T import Network.URI ( parseURIReference, URI (..), isAllowedInURI, escapeURIString, uriScheme ) import Codec.Binary.UTF8.String ( encodeString ) import Data.Maybe (mapMaybe) -- | Sanitize HTML to prevent XSS attacks. This is equivalent to @filterTags safeTags@. sanitize :: Text -> Text sanitize = sanitizeXSS -- | alias of sanitize function sanitizeXSS :: Text -> Text sanitizeXSS = filterTags (safeTags . clearTags) -- | Sanitize HTML to prevent XSS attacks and also make sure the tags are balanced. -- This is equivalent to @filterTags (balanceTags . safeTags)@. sanitizeBalance :: Text -> Text sanitizeBalance = filterTags (balanceTags . safeTags . clearTags) -- | Filter which makes sure the tags are balanced. Use with 'filterTags' and 'safeTags' to create a custom filter. balanceTags :: [Tag Text] -> [Tag Text] balanceTags = balance [] -- | Parse the given text to a list of tags, apply the given filtering -- function, and render back to HTML. You can insert your own custom -- filtering, but make sure you compose your filtering function with -- 'safeTags' and 'clearTags' or 'safeTagsCustom' and 'clearTagsCustom'. filterTags :: ([Tag Text] -> [Tag Text]) -> Text -> Text filterTags f = renderTagsOptions renderOptions { optEscape = id -- stops &"<> from being escaped which breaks existing HTML entities , optMinimize = \x -> x `member` voidElems -- converts to , converts to } . f . canonicalizeTags . parseTagsOptions (parseOptionsEntities (const Nothing)) voidElems :: Set T.Text voidElems = fromAscList $ T.words $ T.pack "area base br col command embed hr img input keygen link meta param source track wbr" balance :: [Text] -- ^ unclosed tags -> [Tag Text] -> [Tag Text] balance unclosed [] = map TagClose $ filter (`notMember` voidElems) unclosed balance (x:xs) tags'@(TagClose name:tags) | x == name = TagClose name : balance xs tags | x `member` voidElems = balance xs tags' | otherwise = TagOpen name [] : TagClose name : balance (x:xs) tags balance unclosed (TagOpen name as : tags) = TagOpen name as : balance (name : unclosed) tags balance unclosed (t:ts) = t : balance unclosed ts -- | Filters out unsafe tags and sanitizes attributes. Use with -- filterTags to create a custom filter. safeTags :: [Tag Text] -> [Tag Text] safeTags = safeTagsCustom safeTagName sanitizeAttribute -- | Filters out unsafe tags and sanitizes attributes, like -- 'safeTags', but uses custom functions for determining which tags -- are safe and for sanitizing attributes. This allows you to add or -- remove specific tags or attributes on the white list, or to use -- your own white list. -- -- @safeTagsCustom safeTagName sanitizeAttribute@ is equivalent to -- 'safeTags'. -- -- @since 0.3.6 safeTagsCustom :: (Text -> Bool) -- ^ Select safe tags, like -- 'safeTagName' -> ((Text, Text) -> Maybe (Text, Text)) -- ^ Sanitize attributes, -- like 'sanitizeAttribute' -> [Tag Text] -> [Tag Text] safeTagsCustom _ _ [] = [] safeTagsCustom safeName sanitizeAttr (t@(TagClose name):tags) | safeName name = t : safeTagsCustom safeName sanitizeAttr tags | otherwise = safeTagsCustom safeName sanitizeAttr tags safeTagsCustom safeName sanitizeAttr (TagOpen name attributes:tags) | safeName name = TagOpen name (mapMaybe sanitizeAttr attributes) : safeTagsCustom safeName sanitizeAttr tags | otherwise = safeTagsCustom safeName sanitizeAttr tags safeTagsCustom n a (t:tags) = t : safeTagsCustom n a tags -- | Directly removes tags even if they are not closed properly. -- This is importent to clear out both the script and iframe tag -- in sequences like "" "" it "object hack" $ sanitized "" "" it "embed hack" $ sanitized "" "" it "ucase image hack" $ sanitized "" "" describe "allowedCssAttributeValue" $ do it "allows hex" $ do assert $ allowedCssAttributeValue "#abc" assert $ allowedCssAttributeValue "#123" assert $ not $ allowedCssAttributeValue "abc" assert $ not $ allowedCssAttributeValue "123abc" it "allows rgb" $ do assert $ allowedCssAttributeValue "rgb(1,3,3)" assert $ not $ allowedCssAttributeValue "rgb()" it "allows units" $ do assert $ allowedCssAttributeValue "10 px" assert $ not $ allowedCssAttributeValue "10 abc" describe "css sanitizing" $ do it "removes style when empty" $ sanitized "

" "

" it "allows any non-url value for white-listed properties" $ do let whiteCss = "

" sanitized whiteCss whiteCss it "rejects any url value" $ do let whiteCss = "

" sanitized whiteCss "

" it "rejects properties not on the white list" $ do let blackCss = "

" sanitized blackCss "

" it "rejects invalid units for grey-listed css" $ do let greyCss = "

" sanitized greyCss "

" it "allows valid units for grey-listed css" $ do let grey2Css = "

" sanitized grey2Css grey2Css describe "balancing" $ do it "adds missing elements" $ do sanitizedB "foo" "foo" it "doesn't add closing voids" $ do sanitizedB "
" "
" it "removes closing voids" $ do sanitizedB "" "" it "interleaved" $ sanitizedB "helloworld" "helloworld" describe "customized white list" $ do it "does not filter custom tags" $ do let custtag = "

" sanitizedC custtag custtag it "filters non-custom tags" $ do sanitizedC "

" "

" it "does not filter custom attributes" $ do let custattr = "

" sanitizedC custattr custattr it "filters non-custom attributes" $ do sanitizedC "

" "

" xss-sanitize-0.3.7.2/LICENSE0000644000000000000000000000252314412061552013517 0ustar0000000000000000The following license covers this documentation, and the source code, except where otherwise indicated. Copyright 2010, Greg Weber. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. xss-sanitize-0.3.7.2/Setup.lhs0000755000000000000000000000016214412061552014322 0ustar0000000000000000#!/usr/bin/env runhaskell > module Main where > import Distribution.Simple > main :: IO () > main = defaultMain xss-sanitize-0.3.7.2/xss-sanitize.cabal0000644000000000000000000000354714412061557016153 0ustar0000000000000000cabal-version: 1.12 -- This file has been generated from package.yaml by hpack version 0.35.1. -- -- see: https://github.com/sol/hpack name: xss-sanitize version: 0.3.7.2 synopsis: sanitize untrusted HTML to prevent XSS attacks description: run untrusted HTML through Text.HTML.SanitizeXSS.sanitizeXSS to prevent XSS attacks. see README.md for more details category: Web stability: Stable homepage: https://github.com/yesodweb/haskell-xss-sanitize#readme bug-reports: https://github.com/yesodweb/haskell-xss-sanitize/issues author: Greg Weber maintainer: Michael Snoyman license: BSD2 license-file: LICENSE build-type: Simple extra-source-files: README.md ChangeLog.md source-repository head type: git location: https://github.com/yesodweb/haskell-xss-sanitize library exposed-modules: Text.HTML.SanitizeXSS other-modules: Text.HTML.SanitizeXSS.Css Paths_xss_sanitize hs-source-dirs: src build-depends: attoparsec >=0.10.0.3 && <1 , base >=4.9.1 && <5 , containers , css-text >=0.1.1 && <0.2 , network-uri >=2.6 , tagsoup >=0.12.2 && <1 , text >=0.11 && <2.1 , utf8-string >=0.3 && <1.1 default-language: Haskell2010 test-suite test type: exitcode-stdio-1.0 main-is: main.hs other-modules: Text.HTML.SanitizeXSS Text.HTML.SanitizeXSS.Css Paths_xss_sanitize hs-source-dirs: test src cpp-options: -DTEST build-depends: HUnit >=1.2 , attoparsec >=0.10.0.3 && <1 , base >=4.9.1 && <5 , containers , css-text >=0.1.1 && <0.2 , hspec >=1.3 , network-uri >=2.6 , tagsoup >=0.12.2 && <1 , text >=0.11 && <2.1 , utf8-string >=0.3 && <1.1 default-language: Haskell2010 xss-sanitize-0.3.7.2/README.md0000644000000000000000000001306314412061552013772 0ustar0000000000000000# Summary [![Tests](https://github.com/yesodweb/haskell-xss-sanitize/actions/workflows/tests.yml/badge.svg)](https://github.com/yesodweb/haskell-xss-sanitize/actions/workflows/tests.yml) xss-sanitize allows you to accept html from untrusted sources by first filtering it through a white list. The white list filtering is fairly comprehensive, including support for css in style attributes, but there are limitations enumerated below. Sanitizing allows a web application to safely use a rich text editor, allow html in comments, or otherwise display untrusted HTML. If you trust the HTML (you wrote it), you do not need to use this. If you don't trust the html you probably also do not trust that the tags are balanced and should use the sanitizeBalance function. # Usage provides 2 functions in the module Text.HTML.SanitizeXSS * sanitize - filters html to prevent XSS attacks. * sanitizeBalance - same as sanitize but makes sure there are no lone opening/closing tags - useful to protect against a user's html messing up your page # Details This is not escaping! Escaping html does prevent XSS attacks. Strings (that aren't meant to be HTML) should be HTML escaped to show up properly and to prevent XSS attacks. However, escaping will ruin the display of actual HTML. This function removes any HTML tags or attributes that are not in its white-list. This may sound picky, but most HTML should make it through unchanged, making the process unnoticeable to the user but giving us safe HTML. ## Integration It is recommended to integrate this so that it is automatically used whenever an application receives untrusted html data (instead of before it is displayed). See the Yesod web framework as an example. ## Limitations ### Lowercase All tag names and attribute names are converted to lower case as a matter of convenience. If you have a use case where this is undesirable let me know. ### Balancing - sanitizeBalance The goal of this function is to prevent your html from breaking when (unknown) html with unbalanced tags are placed inside it. I would expect it to work very well in practice and don't see a downside to using it unless you have an alternative approach. However, this function does not at all guarantee valid html. In fact, it is likely that the result of balancing will still be invalid HTML. There is no guarantee for how a browser will display invalid HTML, so there is no guarantee that this function will protect your HTML from being broken by a user's html. Other possible approaches would be to run the HTML through a library like libxml2 which understands HTML or to first render the HTML in a hidden iframe or hidden div at the bottom of the page so that it is isolated, and then use JavaScript to insert it into the page where you want it. ### TagSoup Parser TagSoup is used to parse the HTML, and it does a good job. However TagSoup does not maintain all white space. TagSoup does not distinguish between the following cases: , , , In the third case, img and br tags will be output as a single self-closing tags. Other self-closing tags will be output as an open and closing pair. So ` or ` converts to ``, and ` or ` converts to ``. There are future updates to TagSoup planned so that TagSoup will be able to render tags exactly the same as they were parsed. ## Security ### Where is the white list from? Ultimately this is where your security comes from. I would expect that a faulty white list would act as a strong deterrent, but this library strives for correctness. The [source code of html5lib](https://github.com/html5lib/html5lib-python/blob/master/html5lib/filters/sanitizer.py) is the source of the white list and my implementation reference. If you feel a tag is missing from the white list, check to see if it has been added there. If anyone knows of better sources or thinks a particular tag/attribute/value may be vulnerable, please let me know. [HTML Purifier](http://htmlpurifier.org/live/smoketests/printDefinition.php) does have a more permissive and configurable (yet safe) white list if you are looking to add anything. ### Where is the code from? Original code was taken from John MacFarlane's Pandoc (with permission), but modified by Greg Weber to be faster and with parsing redone using TagSoup, and to use html5lib's white list. Michael Snoyman added the balanced tags functionality and released css-text specifically to help with css parsing. html5lib's sanitizer.py is used as a reference implementation, and most of the code should look the same. The css parsing is different: as mentioned we use a css parser, not regexes like html5lib. ### style attribute style attributes are now parsed with the css-text and autoparsec-text dependencies. They are then ran through a white list for properties and keywords. Whitespace is not preserved. This code was again translated from sanitizer.py, but uses attoparsec instead of regexes. If you don't care about stripping css you can avoid the attoparsec dependendcy by using the older < 0.3 version of this library. ### data attributes data attributes are not on the white list. The href and style attributes are white listed, but its values must pass through a white list also. This is how the data attributes could work also. ### svg and mathml A mathml white list is fully implemented. There is some support for svg styling. There is a full white list for svg elements and attributes. However, some elements are not included because they need further filtering (just like the data attributes) and this has not been done yet. xss-sanitize-0.3.7.2/ChangeLog.md0000644000000000000000000000037114412061552014662 0ustar0000000000000000# 0.3.7.2 Stops Tag Soup from escaping &"<> which breaks HTML entities # 0.3.7.1 add max height and max width as valid style attributes # 0.3.7 clear the contents of style and script tags instead of escaping them # 0.3.5.6 expose safeTagName