You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by bd...@apache.org on 2014/11/14 14:51:46 UTC
svn commit: r1639636 [1/4] - in /sling/trunk/contrib: ./ xss/ xss/src/
xss/src/main/ xss/src/main/java/ xss/src/main/java/org/
xss/src/main/java/org/apache/ xss/src/main/java/org/apache/sling/
xss/src/main/java/org/apache/sling/xss/ xss/src/main/java/o...
Author: bdelacretaz
Date: Fri Nov 14 13:51:45 2014
New Revision: 1639636
URL: http://svn.apache.org/r1639636
Log:
SLING-3959 - XSS module contribution
Added:
sling/trunk/contrib/xss/ (with props)
sling/trunk/contrib/xss/.gitignore
sling/trunk/contrib/xss/LICENSE
sling/trunk/contrib/xss/NOTICE
sling/trunk/contrib/xss/README.md
sling/trunk/contrib/xss/pom.xml
sling/trunk/contrib/xss/rat.exclude
sling/trunk/contrib/xss/src/
sling/trunk/contrib/xss/src/main/
sling/trunk/contrib/xss/src/main/java/
sling/trunk/contrib/xss/src/main/java/org/
sling/trunk/contrib/xss/src/main/java/org/apache/
sling/trunk/contrib/xss/src/main/java/org/apache/sling/
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/JSONUtil.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/ProtectionContext.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSAPI.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSFilter.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/HtmlToHtmlContentContext.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PlainTextToHtmlContentContext.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PolicyHandler.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIAdapterFactory.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIImpl.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSFilterImpl.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSFilterRule.java
sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/package-info.java
sling/trunk/contrib/xss/src/main/resources/
sling/trunk/contrib/xss/src/main/resources/ESAPI.properties
sling/trunk/contrib/xss/src/main/resources/SLING-INF/
sling/trunk/contrib/xss/src/main/resources/SLING-INF/content/
sling/trunk/contrib/xss/src/main/resources/SLING-INF/content/config.xml
sling/trunk/contrib/xss/src/main/resources/validation.properties
sling/trunk/contrib/xss/src/test/
sling/trunk/contrib/xss/src/test/java/
sling/trunk/contrib/xss/src/test/java/org/
sling/trunk/contrib/xss/src/test/java/org/apache/
sling/trunk/contrib/xss/src/test/java/org/apache/sling/
sling/trunk/contrib/xss/src/test/java/org/apache/sling/xss/
sling/trunk/contrib/xss/src/test/java/org/apache/sling/xss/impl/
sling/trunk/contrib/xss/src/test/java/org/apache/sling/xss/impl/XSSAPIImplTest.java
sling/trunk/contrib/xss/src/test/java/org/apache/sling/xss/impl/XSSProtectionServiceImplTest.java
Modified:
sling/trunk/contrib/pom.xml
Modified: sling/trunk/contrib/pom.xml
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/pom.xml?rev=1639636&r1=1639635&r2=1639636&view=diff
==============================================================================
--- sling/trunk/contrib/pom.xml (original)
+++ sling/trunk/contrib/pom.xml Fri Nov 14 13:51:45 2014
@@ -135,6 +135,7 @@
<module>validation</module>
<module>launchpad/karaf</module>
<module>launchpad/testing</module>
+ <module>xss</module>
<!-- disabled due to SLING-4151 for now <module>launchpad/debian</module> -->
</modules>
<profiles>
Propchange: sling/trunk/contrib/xss/
------------------------------------------------------------------------------
--- svn:ignore (added)
+++ svn:ignore Fri Nov 14 13:51:45 2014
@@ -0,0 +1,15 @@
+target
+bin
+*.iml
+*.ipr
+*.iws
+.settings
+.project
+.classpath
+.externalToolBuilders
+maven-eclipse.xml
+felix-cache
+sling-crankstart
+derby.log
+
+
Added: sling/trunk/contrib/xss/.gitignore
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/.gitignore?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/.gitignore (added)
+++ sling/trunk/contrib/xss/.gitignore Fri Nov 14 13:51:45 2014
@@ -0,0 +1,15 @@
+atlassian-ide-plugin.xml
+target
+.idea
+.classpath
+.project
+.settings
+.checkstyle
+*.iml
+*.ipr
+*.iws
+bin
+.vlt
+.vlt-sync-config.properties
+.vlt-sync.log
+.DS_Store
Added: sling/trunk/contrib/xss/LICENSE
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/LICENSE?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/LICENSE (added)
+++ sling/trunk/contrib/xss/LICENSE Fri Nov 14 13:51:45 2014
@@ -0,0 +1,290 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+The org.owasp.encoder:encoder dependency developed by OWASP and included in this package is licensed under the following conditions:
+
+ Copyright (c) 2012 Jeff Ichnowski
+ 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.
+
+ * Neither the name of the OWASP nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior written
+ permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "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 HOLDER OR CONTRIBUTORS 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.
+
+The org.owasp.esapi:esapi dependency (together with its EASPI.properties and validation.properties configuration files) developed by OWASP
+and included in this package is licensed under the following conditions:
+
+ The BSD License
+
+ Copyright (c) 2007, The OWASP Foundation
+ 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.
+
+ * Neither the name of the OWASP nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior written
+ permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "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 HOLDER OR CONTRIBUTORS 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.
+
+The org.owasp.antisamy:antisamy dependency developed by OWASP and included in this package is licensed under the following conditions:
+
+ The BSD License
+
+ Copyright (c) 2007-2011, Arshan Dabirsiaghi, Jason Li
+ 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.
+
+ * Neither the name of the OWASP nor the names of its
+ contributors may be used to endorse or promote products
+ derived from this software without specific prior written
+ permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "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 HOLDER OR CONTRIBUTORS 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.
+
Added: sling/trunk/contrib/xss/NOTICE
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/NOTICE?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/NOTICE (added)
+++ sling/trunk/contrib/xss/NOTICE Fri Nov 14 13:51:45 2014
@@ -0,0 +1,11 @@
+Apache Sling XSS Bundle
+Copyright 2014 The Apache Software Foundation
+
+The Apache Sling XSS Bundle is based on source code originally developed
+by Adobe Systems Inc. (http://www.adobe.com/).
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+
+This product includes software developed by the
+The Open Web Application Security Project (https://www.owasp.org/).
Added: sling/trunk/contrib/xss/README.md
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/README.md?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/README.md (added)
+++ sling/trunk/contrib/xss/README.md Fri Nov 14 13:51:45 2014
@@ -0,0 +1,8 @@
+Apache Sling XSS Bundle
+====
+The Apache Sling XSS Bundle provides two services for escaping and filtering XSS-prone user submitted content:
+
+1. XSSAPI
+2. XSSFilter
+
+Please check the JavaDoc of each service to find out what methods they provide.
Added: sling/trunk/contrib/xss/pom.xml
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/pom.xml?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/pom.xml (added)
+++ sling/trunk/contrib/xss/pom.xml Fri Nov 14 13:51:45 2014
@@ -0,0 +1,285 @@
+<?xml version="1.0"?>
+<!--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ ~ Licensed to the Apache Software Foundation (ASF) under one or
+ ~ more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information regarding
+ ~ copyright ownership. The ASF licenses this file to you under the
+ ~ Apache License, Version 2.0 (the "License"); you may not use
+ ~ this file except in compliance with the License. You may obtain
+ ~ a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ ~ applicable law or agreed to in writing, software distributed
+ ~ under the License is distributed on an "AS IS" BASIS, WITHOUT
+ ~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions
+ ~ and limitations under the License.
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <!-- ======================================================================= -->
+ <!-- P A R E N T P R O J E C T -->
+ <!-- ======================================================================= -->
+ <parent>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>sling</artifactId>
+ <version>20</version>
+ <relativePath/>
+ </parent>
+
+ <!-- ======================================================================= -->
+ <!-- P R O J E C T -->
+ <!-- ======================================================================= -->
+ <artifactId>org.apache.sling.xss</artifactId>
+ <packaging>bundle</packaging>
+ <version>1.0.0-SNAPSHOT</version>
+
+ <name>Apache Sling XSS Protection Bundle</name>
+ <description>
+ Apache Sling XSS Protection Bundle providing XSS protection based on the OWASP AntiSamy and OWASP Java Encoder libraries.
+ </description>
+
+ <scm>
+ <connection>scm:svn:http://svn.apache.org/repos/asf/sling/trunk/bundles/xss</connection>
+ <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/trunk/bundles/xss</developerConnection>
+ <url>http://svn.apache.org/viewvc/sling/trunk/bundles/xss</url>
+ </scm>
+
+ <!-- ======================================================================= -->
+ <!-- B U I L D -->
+ <!-- ======================================================================= -->
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-scr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>maven-sling-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Import-Package>
+ !bsh,
+ !nu.xom,
+ !org.apache.log4j.spi,
+ !org.apache.log4j.xml,
+ !org.w3c.dom.svg,
+ !org.apache.avalon.framework.logger,
+ !org.apache.commons.jxpath.*,
+ !org.apache.commons.digester.*,
+ !org.apache.tools.ant.taskdefs,
+ !org.apache.xml.resolver,
+ !org.apache.xml.resolver.readers,
+ !org.apache.log,
+ !sun.io,
+ *
+ </Import-Package>
+ <Private-Package>
+ org.apache.sling.xss.impl,
+ org.apache.batik.*,
+ org.w3c.css.sac,
+ org.apache.xerces.*,
+ org.apache.xml.serialize,
+ org.apache.commons.beanutils.*;-split-package:=merge-first,
+ org.apache.commons.configuration.*,
+ org.apache.commons.logging.impl,
+ org.cyberneko.html.*,
+ </Private-Package>
+ <Embed-Dependency>
+ antisamy;inline=true,
+ esapi;inline=true,
+ encoder;inline=true
+ </Embed-Dependency>
+ <Sling-Initial-Content>
+ SLING-INF/content;path:=/libs/sling/xss;overwrite:=true;ignoreImportProviders:=xml
+ </Sling-Initial-Content>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <!-- ======================================================================= -->
+ <!-- D E P E N D E N C I E S -->
+ <!-- ======================================================================= -->
+ <dependencies>
+ <dependency>
+ <groupId>org.owasp.antisamy</groupId>
+ <artifactId>antisamy</artifactId>
+ <version>1.5.2</version>
+ <scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>nu.xom</groupId>
+ <artifactId>com.springsource.nu.xom</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>bsh</groupId>
+ <artifactId>bsh</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.axsl.org.w3c.dom.svg</groupId>
+ <artifactId>svg-dom-java</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>commons-jxpath</groupId>
+ <artifactId>commons-jxpath</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-digester3</artifactId>
+ </exclusion>
+ <!-- #40108 - XSS protection does not work on Java 5 -->
+ <!-- Replace batik-css 1.7 with 1.6. See below. -->
+ <exclusion>
+ <groupId>org.apache.xmlgraphics</groupId>
+ <artifactId>batik-css</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <!-- <#40108 - XSS protection does not work on Java 5> -->
+ <!-- Replace batik-css 1.7 with 1.6 to avoid breaking -->
+ <!-- the build on Java 5. The batik-css 1.6 pom doesn't -->
+ <!-- have proper dependency metadata, so we need to -->
+ <!-- reconstruct the full list here. -->
+ <!-- TODO: Remove this workaround when we dump Java 5. -->
+ <dependency>
+ <groupId>batik</groupId>
+ <artifactId>batik-css</artifactId>
+ <version>1.6</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>batik</groupId>
+ <artifactId>batik-ext</artifactId>
+ <version>1.6</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>batik</groupId>
+ <artifactId>batik-util</artifactId>
+ <version>1.6</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>batik</groupId>
+ <artifactId>batik-gui-util</artifactId>
+ <version>1.6</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis-ext</artifactId>
+ <version>1.3.04</version>
+ <scope>provided</scope>
+ </dependency>
+ <!-- </#40108 - XSS protection does not work on Java 5> -->
+
+ <dependency>
+ <groupId>org.owasp.esapi</groupId>
+ <artifactId>esapi</artifactId>
+ <version>2.1.0</version>
+ <scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>nu.xom</groupId>
+ <artifactId>com.springsource.nu.xom</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>bsh</groupId>
+ <artifactId>bsh</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.axsl.org.w3c.dom.svg</groupId>
+ <artifactId>svg-dom-java</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>commons-jxpath</groupId>
+ <artifactId>commons-jxpath</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-digester3</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>org.owasp.encoder</groupId>
+ <artifactId>encoder</artifactId>
+ <scope>provided</scope>
+ <version>1.1.1</version>
+ </dependency>
+
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>jsp-api</artifactId>
+ <version>2.0</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>javax.jcr</groupId>
+ <artifactId>jcr</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.api</artifactId>
+ <version>2.2.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.jcr.api</artifactId>
+ <version>2.0.4</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.sling</groupId>
+ <artifactId>org.apache.sling.commons.json</artifactId>
+ <version>2.0.6</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>1.8.4</version>
+ <type>jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ </dependency>
+ </dependencies>
+
+</project>
Added: sling/trunk/contrib/xss/rat.exclude
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/rat.exclude?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/rat.exclude (added)
+++ sling/trunk/contrib/xss/rat.exclude Fri Nov 14 13:51:45 2014
@@ -0,0 +1,5 @@
+README.md
+.gitignore
+ESAPI.properties
+validation.properties
+rat.exclude
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/JSONUtil.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/JSONUtil.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/JSONUtil.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/JSONUtil.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,151 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss;
+
+import org.apache.sling.commons.json.JSONException;
+import org.apache.sling.commons.json.JSONObject;
+import org.apache.sling.commons.json.io.JSONWriter;
+
+/**
+ * JSON utilities
+ * <p/>
+ * Support for handling xss protected values with JSON objects and JSON writers.
+ *
+ * @since 1.0.0
+ */
+public class JSONUtil {
+
+ /**
+ * Key suffix for XSS protected properties
+ */
+ public static final String KEY_SUFFIX_XSS = "_xss";
+
+ /**
+ * Puts a xss protected value into a JSON object.
+ * The value is put under the provided key.
+ *
+ * @param object JSON object
+ * @param key Key to write
+ * @param value Value to write
+ * @param xss XSS protection filter
+ * @throws JSONException If value could not be put into the object
+ * @throws NullPointerException If xss protection filter is <code>null</code>
+ */
+ public static void putProtected(final JSONObject object, final String key, final String value, final XSSFilter xss)
+ throws JSONException {
+ final String xssValue = xss.filter(ProtectionContext.PLAIN_HTML_CONTENT, value);
+ object.put(key, xssValue);
+ }
+
+ /**
+ * Puts a value into a JSON object
+ * In addition, the xss protected value is put under the provided key appended by {@link #KEY_SUFFIX_XSS}
+ *
+ * @param object JSON object
+ * @param key Key to write
+ * @param value Value to write
+ * @param xss XSS protection filter
+ * @throws JSONException If value could not be put into the object
+ * @throws NullPointerException If xss protection filter is <code>null</code>
+ */
+ public static void putWithProtected(final JSONObject object, final String key, final String value, final XSSFilter xss)
+ throws JSONException {
+ putProtected(object, key + KEY_SUFFIX_XSS, value, xss);
+ object.put(key, value);
+ }
+
+ /**
+ * Writes a xss protected value into a JSON writer.
+ * The value is written under the provided key.
+ *
+ * @param writer JSON writer
+ * @param key Key to write
+ * @param value Value to write
+ * @param xss XSS protection filter
+ * @throws JSONException If value could not be written
+ * @throws NullPointerException If xss protection filter is <code>null</code>
+ */
+ public static void writeProtected(final JSONWriter writer, final String key, final String value, final XSSFilter xss)
+ throws JSONException {
+ final String xssValue = xss.filter(ProtectionContext.PLAIN_HTML_CONTENT, value);
+ writer.key(key).value(xssValue);
+ }
+
+ /**
+ * Writes a xss protected value array into a JSON writer.
+ * The values are written under the provided key.
+ *
+ * @param writer The JSON writer.
+ * @param key Key to use.
+ * @param values The value arrays.
+ * @param xss The XSS protection filter.
+ * @throws JSONException If an JSON specific error occurs.
+ * @throws NullPointerException If xss protection filter is <code>null</code>
+ */
+ public static void writeProtected(JSONWriter writer, String key,
+ String[] values, XSSFilter xss) throws JSONException {
+ writer.key(key);
+ writer.array();
+ for (String value : values) {
+ String xssValue = xss.filter(ProtectionContext.PLAIN_HTML_CONTENT, value);
+ writer.value(xssValue);
+ }
+ writer.endArray();
+ }
+
+ /**
+ * Writes a value into a JSON write
+ * In addition, the xss protected value is written with the provided key appended by {@link #KEY_SUFFIX_XSS}
+ *
+ * @param writer JSON writer
+ * @param key Key to write
+ * @param value Value to write
+ * @param xss XSS protection filter
+ * @throws JSONException If value could not be written
+ * @throws NullPointerException If xss protection filter is <code>null</code>
+ */
+ public static void writeWithProtected(final JSONWriter writer, final String key, final String value, final XSSFilter xss)
+ throws JSONException {
+ writeProtected(writer, key + KEY_SUFFIX_XSS, value, xss);
+ writer.key(key).value(value);
+ }
+
+ /**
+ * Writes a value array into a JSON write.
+ * In addition, the xss protected values are written with the provided key
+ * appended by {@link #KEY_SUFFIX_XSS}
+ *
+ * @param writer The JSON writer to use.
+ * @param key The key to write.
+ * @param values The value array.
+ * @param xss The xss protection filter.
+ * @throws JSONException If a JSON specific error occurs.
+ * @throws NullPointerException If xss protection filter is <code>null</code>
+ */
+ public static void writeWithProtected(JSONWriter writer, String key,
+ String[] values, XSSFilter xss) throws JSONException {
+
+ writeProtected(writer, key + KEY_SUFFIX_XSS, values, xss);
+ // and the non-xss array variant
+ writer.key(key);
+ writer.array();
+ for (String value : values) {
+ writer.value(value);
+ }
+ writer.endArray();
+ }
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/ProtectionContext.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/ProtectionContext.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/ProtectionContext.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/ProtectionContext.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss;
+
+/**
+ * This enumeration defines the context for executing XSS protection.
+ * <p/>
+ * The specified rules refer to
+ * http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
+ *
+ * @since 1.0
+ */
+public enum ProtectionContext {
+ /**
+ * Escape HTML for use inside element content (rules #6 and - to some degree - #1),
+ * using a policy to remove potentially malicous HTML
+ */
+ HTML_HTML_CONTENT("htmlToHtmlContent"),
+
+ /**
+ * Escape plain text for use inside HTML content (rule #1)
+ */
+ PLAIN_HTML_CONTENT("plainToHtmlContent");
+
+ /**
+ * The name of the protection context
+ */
+ private String name;
+
+ private ProtectionContext(String name) {
+ this.name = name;
+ }
+
+ /**
+ * Gets the name of the protection context.
+ *
+ * @return The name of the protection context
+ */
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * Gets a protection context from the specified name.
+ *
+ * @param name The name to get the protection context from
+ * @return The protection context; <code>null</code> if an invalid protection context
+ * has been specified
+ */
+ public static ProtectionContext fromName(String name) {
+ ProtectionContext[] values = values();
+ for (ProtectionContext contextToCheck : values) {
+ if (contextToCheck.getName().equals(name)) {
+ return contextToCheck;
+ }
+ }
+ return null;
+ }
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSAPI.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSAPI.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSAPI.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSAPI.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,185 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss;
+
+
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.resource.ResourceResolver;
+
+/**
+ * A service providing validators and encoders for XSS protection during the composition of HTML
+ * pages.
+ * <p/>
+ * Note: in general, validators are safer than encoders. Encoding only ensures that content within
+ * the encoded context cannot break out of said context. It requires that there be a context (for
+ * instance, a string context in Javascript), and that damage cannot be done from within the context
+ * (for instance, a javascript: URL within a href attribute.
+ * <p/>
+ * When in doubt, use a validator.
+ */
+public interface XSSAPI {
+
+ // =============================================================================================
+ // VALIDATORS
+ //
+
+ /**
+ * Validate a string which should contain an integer, returning a default value if the source is
+ * empty, can't be parsed, or contains XSS risks.
+ *
+ * @param integer the source integer
+ * @param defaultValue a default value if the source can't be used
+ * @return a sanitized integer
+ */
+ public Integer getValidInteger(String integer, int defaultValue);
+
+ /**
+ * Validate a string which should contain a long, returning a default value if the source is
+ * empty, can't be parsed, or contains XSS risks.
+ *
+ * @param source the source long
+ * @param defaultValue a default value if the source can't be used
+ * @return a sanitized integer
+ */
+ public Long getValidLong(String source, long defaultValue);
+
+ /**
+ * Validate a string which should contain a dimension, returning a default value if the source is
+ * empty, can't be parsed, or contains XSS risks. Allows integer dimensions and the keyword "auto".
+ *
+ * @param dimension the source dimension
+ * @param defaultValue a default value if the source can't be used
+ * @return a sanitized dimension
+ */
+ public String getValidDimension(String dimension, String defaultValue);
+
+ /**
+ * Sanitizes a URL for writing as an HTML href or src attribute value.
+ *
+ * @param url the source URL
+ * @return a sanitized URL (possibly empty)
+ */
+ public String getValidHref(String url);
+
+ /**
+ * Validate a Javascript token. The value must be either a single identifier, a literal number,
+ * or a literal string.
+ *
+ * @param token the source token
+ * @param defaultValue a default value to use if the source doesn't meet validity constraints.
+ * @return a string containing a single identifier, a literal number, or a literal string token
+ */
+ public String getValidJSToken(String token, String defaultValue);
+
+ /**
+ * Validate a CSS color value. Color values as specified at http://www.w3.org/TR/css3-color/#colorunits
+ * are safe and definitively allowed. Vulnerable constructs will be disallowed. Currently known
+ * vulnerable constructs include url(...), expression(...), and anything with a semicolon.
+ *
+ * @param color the color value to be used.
+ * @param defaultColor a default value to use if the input color value doesn't meet validity constraints.
+ * @return a string a css color value.
+ */
+ public String getValidCSSColor(String color, String defaultColor);
+
+ // =============================================================================================
+ // ENCODERS
+ //
+
+ /**
+ * Encodes a source string for HTML element content.
+ * DO NOT USE FOR WRITING ATTRIBUTE VALUES!
+ *
+ * @param source the input to encode
+ * @return an encoded version of the source
+ */
+ public String encodeForHTML(String source);
+
+ /**
+ * Encodes a source string for writing to an HTML attribute value.
+ * DO NOT USE FOR ACTIONABLE ATTRIBUTES (href, src, event handlers); YOU MUST USE A VALIDATOR FOR THOSE!
+ *
+ * @param source the input to encode
+ * @return an encoded version of the source
+ */
+ public String encodeForHTMLAttr(String source);
+
+ /**
+ * Encodes a source string for XML element content.
+ * DO NOT USE FOR WRITING ATTRIBUTE VALUES!
+ *
+ * @param source the input to encode
+ * @return an encoded version of the source
+ */
+ public String encodeForXML(String source);
+
+ /**
+ * Encodes a source string for writing to an XML attribute value.
+ *
+ * @param source the input to encode
+ * @return an encoded version of the source
+ */
+ public String encodeForXMLAttr(String source);
+
+ /**
+ * Encodes a source string for writing to JavaScript string content.
+ * DO NOT USE FOR WRITING TO ARBITRARY JAVASCRIPT; YOU MUST USE A VALIDATOR FOR THAT.
+ * (Encoding only ensures that the source material cannot break out of its context.)
+ *
+ * @param source the input to encode
+ * @return an encoded version of the source
+ */
+ public String encodeForJSString(String source);
+
+
+ // =============================================================================================
+ // FILTERS
+ //
+
+ /**
+ * Filters potentially user-contributed HTML to meet the AntiSamy policy rules currently in
+ * effect for HTML output (see the XSSFilter service for details).
+ *
+ * @param source a string containing the source HTML
+ * @return a string containing the sanitized HTML
+ */
+ public String filterHTML(String source);
+
+
+ // =============================================================================================
+ // JCR-based URL MAPPING
+ //
+
+ /**
+ * Returns an XSSAPI instance capable of mapping resource URLs.
+ * EITHER THIS OR THE RESOURCERESOLVER VERSION MUST BE USED WHEN VALIDATING HREFs!
+ *
+ * @param request the request from which to obtain the {@link org.apache.sling.xss.XSSAPI}
+ * @return an XSSAPI service capable of validating hrefs.
+ */
+ public XSSAPI getRequestSpecificAPI(SlingHttpServletRequest request);
+
+ /**
+ * Returns an XSSAPI instance capable of mapping resource URLs.
+ * EITHER THIS OR THE REQUEST VERSION MUST BE USED WHEN VALIDATING HREFs!
+ *
+ * @param resourceResolver the resolver from which to obtain the {@link org.apache.sling.xss.XSSAPI}
+ * @return an XSSAPI service capable of validating hrefs.
+ */
+ public XSSAPI getResourceResolverSpecificAPI(ResourceResolver resourceResolver);
+
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSFilter.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSFilter.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSFilter.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/XSSFilter.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,85 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss;
+
+/**
+ * This service should be used to protect output against potential XSS attacks.
+ * The protection is context based.
+ *
+ * @since 1.0
+ */
+public interface XSSFilter {
+
+ /**
+ * Default context.
+ */
+ ProtectionContext DEFAULT_CONTEXT = ProtectionContext.HTML_HTML_CONTENT;
+
+ /**
+ * Indicates whether or not a given source string contains XSS policy violations.
+ *
+ * @param context context to use for checking
+ * @param src source string
+ * @return true if the source is violation-free
+ * @throws NullPointerException if context is <code>null</code>
+ */
+ boolean check(ProtectionContext context, String src);
+
+ /**
+ * Indicates whether or not a given source string contains XSS policy violations.
+ *
+ * @param context context to use for checking
+ * @param src source string
+ * @param policy the name/path of the policy to use
+ * @return true if the source is violation-free
+ * @throws NullPointerException if context is <code>null</code>
+ */
+ boolean check(ProtectionContext context, String src, String policy);
+
+ /**
+ * Prevents the given source string from containing XSS stuff.
+ * <p/>
+ * The default protection context is used for checking.
+ *
+ * @param src source string
+ * @return string that does not contain XSS stuff
+ */
+ String filter(String src);
+
+ /**
+ * Protects the given source string from containing XSS stuff.
+ *
+ * @param context context to use for checking
+ * @param src source string
+ * @return string that does not contain XSS stuff
+ * @throws NullPointerException if context is <code>null</code>
+ */
+ String filter(ProtectionContext context, String src);
+
+ /**
+ * Protects the given source string from containing XSS stuff.
+ * <p/>
+ * If the context is unknown or <code>null</code> the default context is used.
+ *
+ * @param context context to use for checking
+ * @param src source string
+ * @param policy the name/path of the policy to use
+ * @return string that does not contain XSS stuff
+ * @throws NullPointerException if context is <code>null</code>
+ */
+ String filter(ProtectionContext context, String src, String policy);
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/HtmlToHtmlContentContext.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/HtmlToHtmlContentContext.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/HtmlToHtmlContentContext.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/HtmlToHtmlContentContext.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,83 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss.impl;
+
+import java.util.List;
+
+import org.owasp.validator.html.CleanResults;
+import org.owasp.validator.html.PolicyException;
+import org.owasp.validator.html.ScanException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class implements an escaping rule to be used for cleaning up existing HTML
+ * content. The output will still be HTML.
+ * <p/>
+ * The cleanup is performed using the AntiSamy library found at
+ * <a href="http://www.owasp.org/index.php/AntiSamy">http://www.owasp.org/index.php/AntiSamy</a>
+ */
+public class HtmlToHtmlContentContext implements XSSFilterRule {
+
+ /**
+ * Logger
+ */
+ private Logger log = LoggerFactory.getLogger(this.getClass());
+
+ /**
+ * @see XSSFilterRule#check(PolicyHandler, String)
+ */
+ public boolean check(final PolicyHandler policyHandler, final String str) {
+ try {
+ return policyHandler.getAntiSamy().scan(str).getNumberOfErrors() == 0;
+ } catch (final ScanException se) {
+ throw new RuntimeException("Unable to scan input");
+ } catch (final PolicyException pe) {
+ return false;
+ }
+ }
+
+ /**
+ * @see XSSFilterRule#filter(PolicyHandler, java.lang.String)
+ */
+ public String filter(final PolicyHandler policyHandler, final String str) {
+ try {
+ log.debug("Protecting (HTML -> HTML) :\n{}", str);
+ final CleanResults results = policyHandler.getAntiSamy().scan(str);
+ final String cleaned = results.getCleanHTML();
+ @SuppressWarnings("unchecked")
+ final List<String> errors = results.getErrorMessages();
+ for (final String error : errors) {
+ log.info("AntiSamy warning: {}", error);
+ }
+ log.debug("Protected (HTML -> HTML):\n{}", cleaned);
+
+ return cleaned;
+ } catch (final ScanException se) {
+ throw new RuntimeException("Unable to scan input");
+ } catch (final PolicyException pe) {
+ throw new RuntimeException("Unable to scan input");
+ }
+ }
+
+ /**
+ * @see XSSFilterRule#supportsPolicy()
+ */
+ public boolean supportsPolicy() {
+ return true;
+ }
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PlainTextToHtmlContentContext.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PlainTextToHtmlContentContext.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PlainTextToHtmlContentContext.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PlainTextToHtmlContentContext.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,77 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss.impl;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Class that provides the capability of securing input provided as plain text for
+ * HTML output.
+ */
+public class PlainTextToHtmlContentContext implements XSSFilterRule {
+
+ /**
+ * Logger
+ */
+ private final Logger log = LoggerFactory.getLogger(this.getClass());
+
+ /**
+ * @see XSSFilterRule#check(PolicyHandler, String)
+ */
+ public boolean check(final PolicyHandler policy, final String str) {
+ // there's nothing that can't be escaped, so just return true
+ return true;
+ }
+
+ /**
+ * @see XSSFilterRule#filter(PolicyHandler, java.lang.String)
+ */
+ public String filter(final PolicyHandler policy, final String str) {
+ final String cleaned = escapeXml(str);
+ log.debug("Protecting (plain text -> HTML) :\n{}\nto\n{}", str, cleaned);
+ return cleaned;
+ }
+
+ private static String escapeXml(final String input) {
+ if (input == null) {
+ return null;
+ }
+
+ final StringBuilder b = new StringBuilder(input.length());
+ for (int i = 0; i < input.length(); i++) {
+ final char c = input.charAt(i);
+ if (c == '&') {
+ b.append("&");
+ } else if (c == '<') {
+ b.append("<");
+ } else if (c == '>') {
+ b.append(">");
+ } else {
+ b.append(c);
+ }
+ }
+ return b.toString();
+ }
+
+ /**
+ * @see XSSFilterRule#supportsPolicy()
+ */
+ public boolean supportsPolicy() {
+ return false;
+ }
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PolicyHandler.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PolicyHandler.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PolicyHandler.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/PolicyHandler.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,89 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.owasp.validator.html.AntiSamy;
+import org.owasp.validator.html.Policy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Class that provides the capability of securing input provided as plain text for
+ * HTML output.
+ */
+public class PolicyHandler {
+
+ /**
+ * Logger
+ */
+ private static final Logger LOGGER = LoggerFactory.getLogger(PolicyHandler.class);
+
+ private Policy policy;
+
+ private AntiSamy antiSamy;
+
+ /**
+ * Try to load a policy from the given relative path.
+ */
+ public PolicyHandler(final ResourceResolverFactory factory, final String policyPath) throws Exception {
+ final ResourceResolver resolver = factory.getAdministrativeResourceResolver(null);
+ try {
+ final Resource rsrc = resolver.getResource(policyPath);
+ if (rsrc == null) {
+ throw new IllegalArgumentException("Could not resolve '" + policyPath + " to a valid policy resource.");
+ }
+ LOGGER.debug("Loading policy from '{}'.", rsrc.getPath());
+
+ InputStream policyStream = null;
+ // fix for classloader issue with IBM JVM: see bug #31946
+ // (currently: http://bugs.day.com/bugzilla/show_bug.cgi?id=31946)
+ Thread currentThread = Thread.currentThread();
+ ClassLoader cl = currentThread.getContextClassLoader();
+ try {
+ currentThread.setContextClassLoader(this.getClass().getClassLoader());
+ policyStream = rsrc.adaptTo(InputStream.class);
+ this.policy = Policy.getInstance(policyStream);
+ this.antiSamy = new AntiSamy(this.policy);
+ } finally {
+ if (policyStream != null) {
+ try {
+ policyStream.close();
+ } catch (final IOException ioe) {
+ // ignored as we can't do anything about this (besides logging)
+ }
+ }
+ currentThread.setContextClassLoader(cl);
+ }
+ } finally {
+ resolver.close();
+ }
+ }
+
+ public Policy getPolicy() {
+ return this.policy;
+ }
+
+ public AntiSamy getAntiSamy() {
+ return this.antiSamy;
+ }
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIAdapterFactory.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIAdapterFactory.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIAdapterFactory.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIAdapterFactory.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,94 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss.impl;
+
+import org.apache.sling.xss.XSSAPI;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Properties;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.adapter.AdapterFactory;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Adapter factory that adapts a {@link ResourceResolver} to a resourceResolver-specific
+ * {@link XSSAPI} service.
+ */
+@Component(metatype = false)
+@Service(AdapterFactory.class)
+@Properties({
+ @Property(name = "service.description", value = "Adapter for the XSSAPI service.")
+})
+@SuppressWarnings("unused")
+public class XSSAPIAdapterFactory implements AdapterFactory {
+ private static final Logger log = LoggerFactory.getLogger(XSSAPIAdapterFactory.class);
+ private static final Class<XSSAPI> XSSAPI_CLASS = XSSAPI.class;
+ private static final Class<ResourceResolver> RESOURCE_RESOLVER_CLASS = ResourceResolver.class;
+ private static final Class<SlingHttpServletRequest> SLING_REQUEST_CLASS = SlingHttpServletRequest.class;
+
+ @Reference
+ XSSAPI xssApi;
+
+ @Property(name = "adapters")
+ public static final String[] ADAPTER_CLASSES = {
+ XSSAPI_CLASS.getName()
+ };
+
+ @Property(name = "adaptables")
+ public static final String[] ADAPTABLE_CLASSES = {
+ RESOURCE_RESOLVER_CLASS.getName(),
+ SLING_REQUEST_CLASS.getName()
+ };
+
+ public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) {
+ if (adaptable instanceof ResourceResolver) {
+ return getAdapter((ResourceResolver) adaptable, type);
+ } else if (adaptable instanceof SlingHttpServletRequest) {
+ return getAdapter((SlingHttpServletRequest) adaptable, type);
+ } else {
+ log.warn("Unable to handle adaptable {}", adaptable.getClass().getName());
+ return null;
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private <AdapterType> AdapterType getAdapter(ResourceResolver resourceResolver, Class<AdapterType> type) {
+ if (resourceResolver != null) {
+ if (type == XSSAPI.class) {
+ return (AdapterType) xssApi.getResourceResolverSpecificAPI(resourceResolver);
+ }
+ }
+ log.debug("Unable to adapt resourceResolver to type {}", type.getName());
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ private <AdapterType> AdapterType getAdapter(SlingHttpServletRequest request, Class<AdapterType> type) {
+ if (request != null) {
+ if (type == XSSAPI.class) {
+ return (AdapterType) xssApi.getRequestSpecificAPI(request);
+ }
+ }
+ log.debug("Unable to adapt resourceResolver to type {}", type.getName());
+ return null;
+ }
+}
Added: sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIImpl.java
URL: http://svn.apache.org/viewvc/sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIImpl.java?rev=1639636&view=auto
==============================================================================
--- sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIImpl.java (added)
+++ sling/trunk/contrib/xss/src/main/java/org/apache/sling/xss/impl/XSSAPIImpl.java Fri Nov 14 13:51:45 2014
@@ -0,0 +1,280 @@
+/*******************************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one or
+ * more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information regarding
+ * copyright ownership. The ASF licenses this file to you under the
+ * Apache License, Version 2.0 (the "License"); you may not use
+ * this file except in compliance with the License. You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0 Unless required by
+ * applicable law or agreed to in writing, software distributed
+ * under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ ******************************************************************************/
+package org.apache.sling.xss.impl;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.sling.api.SlingHttpServletRequest;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.xss.ProtectionContext;
+import org.apache.sling.xss.XSSAPI;
+import org.apache.sling.xss.XSSFilter;
+import org.owasp.encoder.Encode;
+import org.owasp.esapi.ESAPI;
+import org.owasp.esapi.Validator;
+
+@Component
+@Service(value = XSSAPI.class)
+public class XSSAPIImpl implements XSSAPI {
+
+ // =============================================================================================
+ // VALIDATORS
+ //
+
+ @Reference
+ private XSSFilter xssFilter = null;
+
+ private Validator validator = ESAPI.validator();
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getValidInteger(String, int)
+ */
+ public Integer getValidInteger(String integer, int defaultValue) {
+ try {
+ if (integer == null || integer.length() == 0) {
+ return defaultValue;
+ } else {
+ return validator.getValidInteger("XSS", integer, -2000000000, 2000000000, false);
+ }
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getValidLong(String, long)
+ */
+ public Long getValidLong(String source, long defaultValue) {
+ try {
+ if (source == null || source.length() == 0) {
+ return defaultValue;
+ } else {
+ return validator.getValidNumber("XSS", source, -9000000000000000000L, 9000000000000000000L, false).longValue();
+ }
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getValidDimension(String, String)
+ */
+ public String getValidDimension(String dimension, String defaultValue) {
+ try {
+ if (dimension == null || dimension.length() == 0) {
+ return defaultValue;
+ } else if (dimension.matches("['\"]?auto['\"]?")) {
+ return "\"auto\"";
+ }
+ return validator.getValidInteger("XSS", dimension, -10000, 10000, false).toString();
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+ private static final String LINK_PREFIX = "<a href=\"";
+ private static final String LINK_SUFFIX = "\"></a>";
+
+ private static final String MANGLE_NAMESPACE_OUT_SUFFIX = ":";
+
+ private static final String MANGLE_NAMESPACE_OUT = "/([^:/]+):";
+
+ private static final Pattern MANGLE_NAMESPACE_PATTERN = Pattern.compile(MANGLE_NAMESPACE_OUT);
+
+ private static final String MANGLE_NAMESPACE_IN_SUFFIX = "_";
+
+ private static final String MANGLE_NAMESPACE_IN_PREFIX = "/_";
+
+ private static final String SCHEME_PATTERN = "://";
+
+ private String mangleNamespaces(String absPath) {
+ if (absPath != null) {
+ // check for absolute urls
+ final int schemeIndex = absPath.indexOf(SCHEME_PATTERN);
+ final String manglePath;
+ final String prefix;
+ if (schemeIndex != -1) {
+ final int pathIndex = absPath.indexOf("/", schemeIndex + 3);
+ if (pathIndex != -1) {
+ prefix = absPath.substring(0, pathIndex);
+ manglePath = absPath.substring(pathIndex);
+ } else {
+ prefix = absPath;
+ manglePath = "";
+ }
+ } else {
+ prefix = "";
+ manglePath = absPath;
+ }
+ if (manglePath.contains(MANGLE_NAMESPACE_OUT_SUFFIX)) {
+ final Matcher m = MANGLE_NAMESPACE_PATTERN.matcher(manglePath);
+
+ final StringBuffer buf = new StringBuffer();
+ while (m.find()) {
+ final String replacement = MANGLE_NAMESPACE_IN_PREFIX + m.group(1) + MANGLE_NAMESPACE_IN_SUFFIX;
+ m.appendReplacement(buf, replacement);
+ }
+
+ m.appendTail(buf);
+
+ absPath = prefix + buf.toString();
+
+ }
+ }
+
+ return absPath;
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getValidHref(String)
+ */
+ public String getValidHref(final String url) {
+ try {
+ // Percent-encode characters that are not allowed in unquoted
+ // HTML attributes: ", ', >, <, ` and space. We don't encode =
+ // since this would break links with query parameters.
+ String encodedUrl = url.replaceAll("\"", "%22")
+ .replaceAll("'", "%27")
+ .replaceAll(">", "%3E")
+ .replaceAll("<", "%3C")
+ .replaceAll("`", "%60")
+ .replaceAll(" ", "%20");
+ String testHtml = LINK_PREFIX + mangleNamespaces(encodedUrl) + LINK_SUFFIX;
+ // replace all & with & because filterHTML will also apply this encoding
+ testHtml = testHtml.replaceAll("&(?!amp)", "&");
+ final String safeHtml = xssFilter.filter(ProtectionContext.HTML_HTML_CONTENT, testHtml);
+ // if the xssFilter didn't like the input string we just return ""
+ // otherwise we return the mangled url without encoding
+ if (!safeHtml.equals(testHtml)) {
+ return "";
+ } else {
+ return mangleNamespaces(encodedUrl);
+ }
+ } catch (final NullPointerException e) {
+ // ProtectionContext was null - simply return an empty string
+ return "";
+ }
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getValidJSToken(String, String)
+ */
+ public String getValidJSToken(String token, String defaultValue) {
+ token = token.trim();
+ String q = token.substring(0, 1);
+ if (q.matches("['\"]") && token.endsWith(q)) {
+ String literal = token.substring(1, token.length() - 1);
+ return q + encodeForJSString(literal) + q;
+ } else if (token.matches("[0-9a-zA-Z_$][0-9a-zA-Z_$.]*")) {
+ return token;
+ } else {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getValidCSSColor(String, String)
+ */
+ public String getValidCSSColor(String color, String defaultColor) {
+ color = color.trim();
+ /*
+ * Avoid security implications by including only the characters required to specify colors in hex
+ * or functional notation. Critical characters disallowed: x (as in expression(...)),
+ * u (as in url(...)) and semi colon (as in escaping the context of the color value).
+ */
+ if (color.matches("(?i)[#a-fghlrs(+0-9-.%,) \\t\\n\\x0B\\f\\r]+")) {
+ return color;
+ }
+ // named color values
+ if (color.matches("(?i)[a-zA-Z \\t\\n\\x0B\\f\\r]+")) {
+ return color;
+ }
+ return defaultColor;
+ }
+
+ // =============================================================================================
+ // ENCODERS
+ //
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#encodeForHTML(String)
+ */
+ public String encodeForHTML(String source) {
+ return Encode.forHtml(source);
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#encodeForHTMLAttr(String)
+ */
+ public String encodeForHTMLAttr(String source) {
+ return Encode.forHtmlAttribute(source);
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#encodeForXML(String)
+ */
+ public String encodeForXML(String source) {
+ return Encode.forXml(source);
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#encodeForXMLAttr(String)
+ */
+ public String encodeForXMLAttr(String source) {
+ return Encode.forXmlAttribute(source);
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#encodeForJSString(String)
+ */
+ public String encodeForJSString(String source) {
+ return Encode.forJavaScript(source);
+ }
+
+ // =============================================================================================
+ // FILTERS
+ //
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#filterHTML(String)
+ */
+ public String filterHTML(String source) {
+ return xssFilter.filter(ProtectionContext.HTML_HTML_CONTENT, source);
+ }
+
+ // =============================================================================================
+ // JCR-NAMESPACE MANGLING
+ //
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getRequestSpecificAPI(org.apache.sling.api.SlingHttpServletRequest)
+ */
+ public XSSAPI getRequestSpecificAPI(final SlingHttpServletRequest request) {
+ return this;
+ }
+
+ /**
+ * @see org.apache.sling.xss.XSSAPI#getResourceResolverSpecificAPI(org.apache.sling.api.resource.ResourceResolver)
+ */
+ public XSSAPI getResourceResolverSpecificAPI(final ResourceResolver resourceResolver) {
+ return this;
+ }
+}