<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Codethink &#187; servlet</title>
	<atom:link href="https://codethink.no-ip.org/tags/servlet/feed" rel="self" type="application/rss+xml" />
	<link>https://codethink.no-ip.org</link>
	<description>A blog about coding, life, and other arbitrary topics</description>
	<lastBuildDate>Sun, 15 Mar 2026 21:30:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.29</generator>
	<item>
		<title>[Java] Quarantining Request Parameters</title>
		<link>https://codethink.no-ip.org/archives/663</link>
		<comments>https://codethink.no-ip.org/archives/663#comments</comments>
		<pubDate>Sat, 11 Jun 2011 23:21:41 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[servlet]]></category>
		<category><![CDATA[filter]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=663</guid>
		<description><![CDATA[This is a follow-up on an earlier post in which I described a method for modifying HTTP request parameters on the fly in a servlet/web application. I mentioned that the technique could be used to provide a filter that automatically &#8230; <a href="https://codethink.no-ip.org/archives/663">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>This is a follow-up on an <a href="http://codethink.no-ip.org/wordpress/archives/634">earlier post</a> in which I described a method for modifying HTTP request parameters on the fly in a servlet/web application.  I mentioned that the technique could be used to provide a filter that automatically quarantines any potentially unsafe parameters so that application code/business logic does not need to worry about such things as XSS and SQL injection attacks, but I didn&#8217;t provide any complete reference code for such a filter.  So today I aim to rectify that omission.  </p>
<p>As this example code builds upon the <a href="http://codethink.no-ip.org/wordpress/archives/634">OverridableHttpRequest</a> class discussed in the previous post, you will need that class (or your own comparable implementation) before you get started.  Once you have that, the code for the filter implementation is not very complex:</p>
<pre class="brush: java; title: ; notranslate">public class InputSanitizerFilter implements Filter {
	private static final Logger LOG = Logger.getLogger(InputSanitizerFilter.class);
	
	private static final String BANNED_INPUT_CHARS = &quot;.*[^a-zA-Z0-9\\@\\'\\,\\.\\/\\(\\)\\+\\=\\-\\_\\[\\]\\{\\}\\^\\!\\*\\&amp;\\%\\$\\:\\;\\? \\t]+.*&quot;;
	
	public static final String QUARANTINE_ATTRIBUTE_NAME = &quot;filter.quarantined.params&quot;;
	public static final String SUSPICIOUS_REQUEST_FLAG_NAME = &quot;filter.suspicious.request&quot;;

	@Override
	public void destroy() {
		//no work necessary
	}

	@Override
	@SuppressWarnings(&quot;unchecked&quot;)
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		//wrap the original request and set up an empty quarantine map
		OverridableHttpRequest newRequest = new OverridableHttpRequest((HttpServletRequest)request);
		Map&lt;String, String&gt; quarantine = new HashMap&lt;String, String&gt;();
		newRequest.setAttribute(QUARANTINE_ATTRIBUTE_NAME, quarantine);
		
		//inspect each parameter, and move any suspicious ones into thw quarantine area
		Enumeration&lt;String&gt; names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			String value = request.getParameter(name);
			if (value.matches(BANNED_INPUT_CHARS)) {
				//uh-oh, found something that doesn't look right, quarantine it and make sure the request is flagged as suspicious
				LOG.warn(&quot;Removing potentially malicious parameter from request:  &quot; + name);
				quarantine.put(name, value);
				newRequest.removeParameter(name);
				newRequest.setAttribute(SUSPICIOUS_REQUEST_FLAG_NAME, &quot;true&quot;);
			}
		}
		
		//done, send the modified request on down the chain
		chain.doFilter(newRequest, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		//no work necessary
	}
}</pre>
<p>Basically there is a regex that defines the set of disallowed characters (anything that is not a letter, number, standard punctuation character, or whitespace&#8230;this example will also exclude any parameters that contain newlines as the webapp that it is used in does not contain any inputs that can accept newlines, but you can obviously modify it to your liking), and every parameter in the request is inspected to see if it contains one or more banned character(s).  Any parameter that is found to include banned characters is copied into the &#8216;<em>quarantine</em>&#8216; map, and then removed as a parameter (so calling &#8216;<em>request.getParameter(&#8220;badParam&#8221;)</em>&#8216; will return <em>null</em>).  This will prevent application code from ever seeing the suspect parameter(s), unless it explicitly goes looking inside of the quarantine map (which you might do if you want to allow users to have special characters in their password, for instance).</p>
<p>Also, if one or more parameters are quarantined, the request is flagged as suspicious by setting an attribute named &#8216;<em>filter.suspicious.request</em>&#8216;.  This gives code downstream from the filter a quick way to see if the request has been modified by the filter in any way, and allows the application to make its own decisions about whether or not it wants to venture into the quarantine area to inspect the potentially unsafe data.  For instance:</p>
<pre class="brush: java; title: ; notranslate">if (request.getAttribute(InputSanitizerFilter.SUSPICIOUS_REQUEST_FLAG_NAME) != null) {
    Map&lt;String, String&gt; quarantine = (Map&lt;String, String&gt;)request.getAttribute(InputSanitizerFilter.QUARANTINE_ATTRIBUTE_NAME);
    for (String key : quarantine.keySet()) {
        System.out.println(&quot;Quarantined parameter:  name=&quot; + key + &quot;, value=&quot; + quarantine.get(key));
    }
}</pre>
<p>&#8230;or, with the right frameworks in place you might easily create something like an &#8216;<em>@IgnoresQuarantine</em>&#8216; annotation that can be applied selectively to business methods to mark a parameter (or set of parameters) as not subject to quarantine on calls to that method so that you never need to manually go looking through the quarantine area (after implementing the annotation and its backing logic).  But that&#8217;s just slightly outside of the scope for today.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/663/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Java] URL Rewriting on Tomcat (or any other servlet container)</title>
		<link>https://codethink.no-ip.org/archives/654</link>
		<comments>https://codethink.no-ip.org/archives/654#comments</comments>
		<pubDate>Tue, 07 Jun 2011 11:51:31 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[servlet]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[url-rewrite]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=654</guid>
		<description><![CDATA[Here is a very nice little utility I found recently on an unfortunately very difficult to navigate website. In case it&#8217;s not immediately apparent from that site what I am referring to, I&#8217;m talking about the &#8216;UrlRewriteFilter&#8216; utility featured near &#8230; <a href="https://codethink.no-ip.org/archives/654">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here is a very nice little utility I found recently on an unfortunately very <a href="http://www.tuckey.org/" target="_blank">difficult to navigate website</a>.  In case it&#8217;s not immediately apparent from that site what I am referring to, I&#8217;m talking about the &#8216;<em>UrlRewriteFilter</em>&#8216; utility featured near the top of the page.  This handy Filter implementation allows you to configure <a href="http://httpd.apache.org/docs/current/mod/mod_rewrite.html" target="_blank">mod_rewrite</a> style URL rewriting rules for your J2EE webapp.  If you are having trouble navigating the official site, you can use this <a href="http://urlrewritefilter.googlecode.com/files/urlrewritefilter-3.2.0.zip">direct link</a> to download &#8216;<em>UrlRewriteFilter</em>&#8216; version 3.2.</p>
<p>Sadly, apart from being difficult to navigate, some of the information on the official &#8216;<em>UrlRewriteFilter</em>&#8216; website pertaining to setup and usage of the filter is also incorrect/out of date.  This is really quite a shame, because &#8216;<em>UrlRewriteFilter</em>&#8216; is an excellent little utility and I&#8217;m quite tired of seeing people needlessly running multi-server configurations (typically <a href="http://httpd.apache.org/" target="_blank">Apache httpd</a> for static content, and something like Tomcat, Resin, Jetty, etc. for dynamic content) out of a desire to use this-or-that particular module that only works with httpd or (even worse) out of the outdated and no-longer-relevant notion that servlet containers cannot efficiently serve static content.  So in an effort to save &#8216;<em>UrlRewriteFilter</em>&#8216; from obscurity and an undeserved death at the hands of poor documentation and a shoddy distribution site, here is a complete set of instructions for getting the filter to work in your webapp.</p>
<p>First, you will need to ensure that the &#8216;<em>UrlRewriteFilter</em>&#8216; JAR file is on your web-application&#8217;s classpath.  How you do this will depend upon your build process/how you are constructing your webapp(s), but long story short placing the JAR file in your webapp under &#8216;/WEB-INF/lib&#8217; will do the trick, and if you&#8217;ve spent any time at all working with webapps you probably already have a preferred way of doing this.  Alternately, you may want to install the JAR file in your servlet container&#8217;s &#8216;/lib&#8217; folder, particularly if you are deploying multiple webapps on your server and you want to have &#8216;<em>UrlRewriteFilter</em>&#8216; available to any/all of them automatically.</p>
<p>In any case, once you have the &#8216;<em>UrlRewriteFilter</em>&#8216; JAR on your webapp&#8217;s classpath, the real setup can begin.  Open your application&#8217;s &#8216;<em>web.xml</em>&#8216; file, and add the following filter configuration to your webapp:</p>
<pre class="brush: xml; title: ; notranslate">&lt;!-- URL rewriting --&gt;
&lt;filter&gt;
    	&lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt;
      	&lt;filter-class&gt;org.tuckey.web.filters.urlrewrite.UrlRewriteFilter&lt;/filter-class&gt;
      	&lt;init-param&gt;
        	&lt;param-name&gt;logLevel&lt;/param-name&gt;
        	&lt;param-value&gt;WARN&lt;/param-value&gt;
        &lt;/init-param&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
    	&lt;filter-name&gt;UrlRewriteFilter&lt;/filter-name&gt;
    	&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;</pre>
<p>This instructs the servlet container to route every request that the server receives through the &#8216;<em>UrlRewriteFilter</em>&#8216;.  Note that although it is not discussed on the official site, that &#8216;<em>logLevel</em>&#8216; parameter is absolutely essential.  If you omit it, the filter will fail to initialize properly and yield some very bizarre behavior.  </p>
<p>Anyways, once your &#8216;<em>web.xml</em>&#8216; has been updated, the final step is to add a &#8216;<em>urlrewrite.xml</em>&#8216; file in the same directory as your &#8216;<em>web.xml</em>&#8216; file, and configure it to your liking.  Here is an example &#8216;<em>urlrewrite.xml</em>&#8216; file with a couple basic rewrite rules:</p>
<pre class="brush: xml; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!DOCTYPE urlrewrite PUBLIC &quot;-//tuckey.org//DTD UrlRewrite 3.2//EN&quot;
        &quot;http://tuckey.org/res/dtds/urlrewrite3.2.dtd&quot;&gt;
&lt;urlrewrite&gt;
    &lt;!-- user-account activation link --&gt;
    &lt;rule&gt;
    	&lt;from&gt;/activate/([a-f0-9]+)?(.*)&lt;/from&gt;
     	&lt;to&gt;/userController?action=activateUser&amp;amp;token=$1&amp;amp;$2&lt;/to&gt;
    &lt;/rule&gt;

    &lt;!-- default rules included with urlrewrite --&gt;
    &lt;rule&gt;
        &lt;note&gt;
            The rule means that requests to /test/status/ will be redirected to /rewrite-status
            the url will be rewritten.
        &lt;/note&gt;
        &lt;from&gt;/test/status/&lt;/from&gt;
        &lt;to type=&quot;redirect&quot;&gt;%{context-path}/rewrite-status&lt;/to&gt;
    &lt;/rule&gt;
    &lt;outbound-rule&gt;
        &lt;note&gt;
            The outbound-rule specifies that when response.encodeURL is called (if you are using JSTL c:url)
            the url /rewrite-status will be rewritten to /test/status/.

            The above rule and this outbound-rule means that end users should never see the
            url /rewrite-status only /test/status/ both in thier location bar and in hyperlinks
            in your pages.
        &lt;/note&gt;
        &lt;from&gt;/rewrite-status&lt;/from&gt;
        &lt;to&gt;/test/status/&lt;/to&gt;
    &lt;/outbound-rule&gt; 
&lt;/urlrewrite&gt;</pre>
<p>This defines two rules.  The first simply rewrites URL&#8217;s of the form &#8216;<em>/activate/######?[params]</em>&#8216; to something like &#8216;<em>/userController?action=activateUser&#038;token=######&#038;[params]</em>&#8216;, and the second is the default example rule that comes with &#8216;<em>UrlRewriteFilter</em>&#8216; and allows you to see a basic diagnostic page by pointing your browser at &#8216;<em>[your server]/test/status</em>&#8216;.  </p>
<p>And there you have it.  Quite simple, really, and now there&#8217;s one less reason to continue running two distinct server instances where one would do just as well.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/654/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
