001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.markdown.extensions.attributesanitizer;
020
021import com.vladsch.flexmark.html.AttributeProvider;
022import com.vladsch.flexmark.html.HtmlRenderer;
023import com.vladsch.flexmark.html.IndependentAttributeProviderFactory;
024import com.vladsch.flexmark.html.renderer.AttributablePart;
025import com.vladsch.flexmark.html.renderer.LinkResolverContext;
026import com.vladsch.flexmark.util.ast.Node;
027import com.vladsch.flexmark.util.data.MutableDataHolder;
028import com.vladsch.flexmark.util.html.MutableAttributes;
029
030import java.util.ArrayList;
031import java.util.Locale;
032import java.util.Set;
033
034/**
035 * {@link HtmlRenderer.HtmlRendererExtension} which strips dangerous
036 * author-supplied attributes from the rendered HTML. Flexmark's
037 * AttributesExtension applies attribute lists such as
038 * <code>{onclick=...}</code> written by page authors to the rendered elements
039 * without any filtering, so without this extension any author could attach
040 * <code>on*</code> event handlers (stored XSS), <code>style</code> overlays or
041 * <code>javascript:</code> URLs to rendered content.
042 * {@code HtmlRenderer.ESCAPE_HTML} does not cover extension-assigned
043 * attributes.
044 *
045 * <p>
046 * This extension must be registered <em>after</em> {@code AttributesExtension},
047 * so its attribute provider runs last and sees the final attribute set of each
048 * node.</p>
049 */
050public class AttributeSanitizerExtension implements HtmlRenderer.HtmlRendererExtension {
051
052    private static Boolean escapeHtml = true;
053    /**
054     * Attributes whose value is a URL, and must therefore not carry a
055     * script-capable scheme.
056     */
057    private static final Set< String> URL_ATTRIBUTES = Set.of(""
058            + "href", "src", "xlink:href",
059            "action", "formaction",
060            "background", "background-color", 
061            "poster", "data", "cite");
062
063    public static AttributeSanitizerExtension create() {
064        return new AttributeSanitizerExtension();
065    }
066
067    /**
068     * {@inheritDoc}
069     */
070    @Override
071    public void rendererOptions(final MutableDataHolder options) {
072        escapeHtml = HtmlRenderer.ESCAPE_HTML.get(options);
073        if (escapeHtml==null) {
074            escapeHtml = true;
075        }
076    }
077
078    /**
079     * {@inheritDoc}
080     */
081    @Override
082    public void extend(final HtmlRenderer.Builder rendererBuilder, final String rendererType) {
083        rendererBuilder.attributeProviderFactory(new IndependentAttributeProviderFactory() {
084
085            @Override
086            public AttributeProvider apply(final LinkResolverContext context) {
087                return AttributeSanitizerExtension::sanitize;
088            }
089
090        });
091    }
092
093    /**
094     * Removes every <code>on*</code> event handler, the <code>style</code> and
095     * <code>srcdoc</code> attributes, and any URL-valued attribute whose value
096     * carries a script-capable scheme.
097     *
098     * @param node the node being rendered
099     * @param part the attributable part of the node
100     * @param attributes the final attribute set of the node, mutated in place
101     */
102    static void sanitize(final Node node, final AttributablePart part, final MutableAttributes attributes) {
103        if (!escapeHtml) {
104            return;
105        }
106        for (final String name : new ArrayList<>(attributes.keySet())) {
107            final String attribute = name.trim().toLowerCase(Locale.ENGLISH);
108            if (attribute.startsWith("on") || "style".equals(attribute) || "srcdoc".equals(attribute)) {
109                attributes.remove(name);
110            } else if (URL_ATTRIBUTES.contains(attribute) && hasForbiddenScheme(attributes.getValue(name))) {
111                attributes.remove(name);
112            }
113        }
114    }
115
116    static boolean hasForbiddenScheme(final String value) {
117        if (value == null) {
118            return false;
119        }
120        // browsers ignore ASCII control characters and whitespace when parsing URL schemes, so strip them first
121        final String url = value.toLowerCase(Locale.ENGLISH).replaceAll("[\\x00-\\x20]", "");
122        return url.startsWith("javascript:") || url.startsWith("vbscript:") || url.startsWith("data:");
123    }
124
125}