tomcat

HowTo: Tomcat exclude URL pattern form the Basic auth

Posted on

Once you setup the basic authentication in some of the case for Image directories or some other public directories  need not to be comes under the authentication.

By adding few security constrain tags to the existing authentication parameters we can exclude any URL pattern from the security

Here is my web.xml looks like

<security-constraint>
  <web-resource-collection>
    <web-resource-name>Private</web-resource-name>
    <description>Matches all pages.</description>
    <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
     <role-name>authenticated-users</role-name>
  </auth-constraint>
</security-constraint>
<security-constraint>
  <web-resource-collection>
    <web-resource-name>Public</web-resource-name>
    <description>Matches a few special pages.</description>
    <url-pattern>/index.jsp</url-pattern>
    <url-pattern>/public/*</url-pattern>
  </web-resource-collection>
  <!-- No auth-constraint has everybody to access! -->
</security-constraint>
<security-role>
  <description> logged in users </description>
  <role-name>authenticated-user</role-name>
</security-role>
<login-config>
  <auth-method>DIGEST</auth-method>
  <realm-name> watcher </realm-name>
</login-config>

The  two security constraints. The first one “Private”  matches all web resources while the second one “Public” only matches the index page and everything below “/public/”.  No order has to be follow for the security-constraint. 

The auth-constraint specifies which users need to allowed access to the matched pttern. The role-name given  that there must to refer a security-role declaration in web.xml and it must also be present in the servlet container’s user database, we also need a login-config definition for authentication method to use

The “Public” security-constraint need not to specify an auth-constraint element, which means everybody has access to the pattern matched, which is exactly we needed.

tomcat-users.xml:

 
<tomcat-users>
  <role rolename="authenticated-user" />
  <user username="myusername" password="mypass" roles="authenticated-user" />
</tomcat-users>

Now re-deploy the container.

Advertisements

HowTo: Enable HTTP to HTTPS redirection in tomcat for server under elb.

Posted on Updated on

I have installed Tomcat native method APR which is very lite to handle the serverlet request, For secure the logins, it is better to configure force redirection.

I followed the below methods,  in amazon server.

1, Configure SSL with port redirection in AWS firewall

ELB-tomcat

 

 

 

 

2, Edit the tomcat configuration for SSL redirection, Modify the below parts in the conf file.

/usr/local/apache-tomcat-7.0.47/conf/server.xml

<Connector port="80" protocol="HTTP/1.1"
 enableLookups="false"
 connectionTimeout="20000"
 redirectPort="443" />

SSL Certifice configuration in APR tomcat native method

<Connector
 protocol="HTTP/1.1"
 port="443" maxThreads="500"
 scheme="https" secure="true" SSLEnabled="true"
 SSLCertificateFile="${catalina.home}/conf/keystore/wacom.crt"
 SSLCertificateKeyFile="${catalina.home}/conf/keystore/wacom.key"
 SSLCACertificateFile="${catalina.home}/conf/keystore/wacom.intermediate.ca"
 SSLVerifyClient="optional" SSLProtocol="TLSv1"/>

3, edit the Aplications web.xml for force redirection. webapps/ROOT/WEB-INF/web.xml

<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Context</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<!-- auth-constraint goes here if you requre authentication -->
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

Verify :

curl -I http://domain.com/ROOT
HTTP/1.1 302 Found
Content-length: 0
Date: Fri, 31 Oct 2014 16:33:42 GMT
Location: https://domain.com/login;jsessionid=5B5B0B1292597816EA2C5DE89B298F74
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=5B5B0B1292597816EA2C5DE89B298F74; Path=/; HttpOnly
Connection: keep-alive

 

HowTo: Enable URL rewite for tomcat or other servlet container

Posted on Updated on

It is a URL rewrite feature which is most similar to the apache mod_rewrite, we can use the similar rules to apply the rewrite. Ensure that the ‘UrlRewriteFilter‘ JAR file is on your web-application’s classpath.  place the JAR file in your webapp under ‘/WEB-INF/lib’ will do the trick, and if you’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’s ‘/lib’ folder, particularly if you are deploying multiple webapps on your server and you want to have ‘UrlRewriteFilter‘ available to any/all of them automatically.

Download JAR from here

Read more Examples

once you have the ‘UrlRewriteFilter‘ JAR on your webapp’s classpath, the real setup can begin. Open your application’s ‘web.xml‘ file, and add the following filter configuration to your webapp

<filter>
 <filter-name>UrlRewriteFilter</filter-name>
 <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
 <init-param>
 <param-name>logLevel</param-name>
 <param-value>WARN</param-value>
 </init-param>
<init-param>
 <param-name>confPath</param-name>
 <param-value>/WEB-INF/urlrewrite.xml</param-value>
 </init-param>
</filter>
 <filter-mapping>
 <filter-name>UrlRewriteFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

This will make the serverlet container to redirect the traffic to UrlRewriteFilter.  Note that although it is not discussed on the official site, that ‘logLevel‘ parameter is absolutely essential for filter to be apply for the traffic.

If you finish adding the tags in web.xml, then move to create urlrewrite.xml in the same directory as with the web.xml. Configure the example rules  for  the URL rewrite.

<?xml version="1.0" encoding="utf-8"?>
 <!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 3.2//EN"
 "http://tuckey.org/res/dtds/urlrewrite3.2.dtd">
 <urlrewrite>
  <rule>
        <name>Domain Name Check</name>
        <condition name="host" operator="notequal">www.server.com</condition>
        <from>^(.*)$</from>
        <to type="redirect">http://www.server.com/$1</to>
    </rule>
    <rule>
        <from>/test</from>
        <to type="redirect">%{context-path}/examples</to>
    </rule>
</urlrewrite>

The first rule is for any request tot he application with IP or alternative alias Domain name added in the server has to rewrite to server.com. It can be also use to rewite for including www. in the URL .

The second rule is for the redirect the invalid application “test” to  to the examples,

Its looks like this :  http://test.com/test   –>  http://www.server.com/examples/  . Both the test.com and server.com are in the same server and same webapps

 

 

HowTo: Tomcat Logging – log customized with {X-Forwarded-For}

Posted on Updated on

Tomcat is allowing us to track back logs with enamours of information by customizing the log pattern. There is preset patten is available, we can also implement is in single line

I enabled few more information like execution time , request size , cookies etc..

Default tag should be like this

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
               prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>

Common : %{X-Forwarded-For}i %l %u %t “%r” %s %b
Combined : %{X-Forwarded-For}i %l %u %t %r %s %b %{User-Agent}i %{Referer}i %{Cookie}i

You can change either Common or Combined

I have implemented my own pattern like below, so it should more detailed

pattern="%h %{X-Forwarded-For}i %l %u %t  &quot;%r&quot; %s %b  &quot;%{User-Agent}i&quot; &quot;%{Referer}i&quot; &quot;%{Cookie}i&quot; %T"

Access Log pattern new look

-----------------------------
192.168.1.185 - - - [18/Mar/2014:10:52:06 +0530]  "GET /ajax/norm/list/status?ids=23%2C11%2C9%2C7%2C6%2C5%2C2%2C1%2C HTTP/1.1" 200 42  "Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0" "http://192.168.1.188/norm/list" "JSESSIONID=4FD1DBEB911CD2E19AA4798F9A26DCA8" 0.007
-----------------------------
Log Details : 192.168.1.185 : Remote host name (or IP address if resolveHosts is false)
– : X-Forwarded-For – : Remote logical username
– : Remote user that was authenticated
[18/Mar/2014:10:52:06 +0530]  : Date and time, in Common Log Format
GET /ajax/norm/list/…… : First line of the request (method and request URI)
HTTP/1.1 : Request protocol
200 : HTTP status code of the response
42 : Bytes sent, excluding HTTP headers (Content size)
Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0: User Agent
http://192.168.1.188/norm/list : Referer
JSESSIONID=4FD1DBEB911CD2E19AA4798F9A26DCA8 : Cookie header
0.007 : Time taken to process the request, in seconds

Once every thing has been done you can restart the tomcat to make it effect, more options are given below

%a – Remote IP address
%A – Local IP address
%b – Bytes sent, excluding HTTP headers, or ‘-‘ if zero
%B – Bytes sent, excluding HTTP headers
%h – Remote host name (or IP address if resolveHosts is false)
%H – Request protocol
%l – Remote logical username from identd (always returns ‘-‘)
%m – Request method (GET, POST, etc.)
%p – Local port on which this request was received
%q – Query string (prepended with a ‘?’ if it exists)
%r – First line of the request (method and request URI)
%s – HTTP status code of the response
%S – User session ID
%t – Date and time, in Common Log Format
%u – Remote user that was authenticated (if any), else ‘-‘
%U – Requested URL path
%v – Local server name
%D – Time taken to process the request, in millis
%T – Time taken to process the request, in seconds
%I – current request thread name (can compare later with stacktraces)
%f – X-Forwarded-For IP address
%F – X-Forwarded-For address

HowTo: How to setup basic authentication in tomcat

Posted on Updated on

Container-managed authentication methods control how a user’s credentials are verified when a web app’s protected resource is accessed. When a web application uses basic authentication (BASIC in the web.xml file’s auth-method element), Tomcat uses HTTP basic authentication to ask the web browser for a username and password whenever the browser requests a resource of that protected web application. With this authentication method, all passwords are sent across the network in base64-encoded text.

Note: using basic authentication is generally considered insecure because it does not strongly encrypt passwords, unless the site also uses HTTPS or some other form of encryption between the client and the server (for instance, a virtual private network). But, if you’re just starting to use Tomcat, or if you just want to test container-managed security with your web app, basic authentication is easy to set up and test. Just add <security-constraint> and <login-config> elements to your web app’s web.xml file, and add the appropriate <role> and <user> elements to your CATALINA_BASE/conf/tomcat-users.xml file, restart Tomcat, and Tomcat takes care of the rest.

The example below shows a web.xml excerpt from a club membership web site with a members-only subdirectory that is protected using basic authentication. Note that this effectively takes the place of the Apache web server’s .htaccess files.

For app based Basic authentication you have to edit the web.xml in //webapps/Your-app/WEB-INF/web.xml

For ROOT basic auth  CATILINA_HOME/conf/web.xml

web.xml security tags looks like this

   <security-constraint>
         <web-resource-collection>
             <web-resource-name> Subdir test </web-resource-name>
             <url-pattern> /* </url-pattern>
             <http-method> GET </http-method>
             <http-method> POST </http-method>
         </web-resource-collection>

         <auth-constraint>
             <!-- the same like in your tomcat-users.conf file -->
             <role-name> manager </role-name>
         </auth-constraint>
   </security-constraint>

   <login-config>
        <auth-method> BASIC </auth-method>
        <realm-name> iTest Web app resources</realm-name>
   </login-config>

   <security-role>
       <description> </description>
       <role-name> manager </role-name>
   </security-role>

tomcat-users.xml uncomment or add new tag for user credentials

  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
  <user username="anand" password="password" roles="manager"/>

script : Start the tomcat as service.

Posted on

This script is used to start the sevrlet container as service, which is using common-daemon for starting java process.

#!/bin/sh
#
# tomcat Start/Stop the Tomcat servlet container.
#
# chkconfig: 345 55 55
# description: Tomcat servlet container.
# processname: tomcat
##############################################################################
#
# Small shell script to show how to start/stop Tomcat using jsvc
# If you want to have Tomcat running on port 80 please modify the server.xml
# file:
#
# <!-- Define a non-SSL HTTP/1.1 Connector on port 80 -->
# <Connector className="org.apache.catalina.connector.http.HttpConnector"
# port="80" minProcessors="5" maxProcessors="75"
# enableLookups="true" redirectPort="8443"
# acceptCount="10" debug="0" connectionTimeout="60000"/>
# Download and install dependency package 
# http://mirror.symnds.com/software/Apache//commons/daemon/binaries/commons-daemon-1.0.15-bin.tar.gz
# 
# Source function library.
. /etc/rc.d/init.d/functions

set +x
JAVA_HOME=/usr/local/jdk1.7.0_45
CATALINA_HOME=/usr/local/apache-tomcat-6.0.37
DAEMON_HOME=/usr/local/apache-tomcat-6.0.37
TOMCAT_USER=tomcat
TMP_DIR=/var/tmp
CATALINA_OPTS='-Xms512M -Xmx1024M'
CLASSPATH=\
$JAVA_HOME/lib/tools.jar:\
$DAEMON_HOME/bin/commons-daemon.jar:\
$CATALINA_HOME/bin/bootstrap.jar
prog=tomcat

start() {
echo $"Starting $prog: "
 #
 # Start Tomcat
 #
 $DAEMON_HOME/bin/jsvc \
 -user $TOMCAT_USER \
 -home $JAVA_HOME \
 -Dcatalina.home=$CATALINA_HOME \
 -Djava.io.tmpdir=$TMP_DIR \
 -outfile $CATALINA_HOME/logs/catalina.out \
 -errfile '&1' \
 $CATALINA_OPTS \
 -cp $CLASSPATH \
 org.apache.catalina.startup.Bootstrap
 #
 # To get a verbose JVM
 #-verbose \
 # To get a debug of jsvc.
 #-debug \
}
stop() {
 echo $"Stopping $prog: "
 #
 # Stop Tomcat
 #
 PID=`cat /var/run/jsvc.pid`
 kill $PID
}
status() {
 if ! $JAVA_HOME/bin/jps -mlvV | grep -v "Jps" > /dev/null
 then
 echo "Stopped : $prog is no not running"
 else
 echo "Running process for tomcat"
 echo "=========================="
 $JAVA_HOME/bin/jps -mlvV | grep -v "Jps"
 fi
}

case "$1" in
 start)
 start
 ;;
 stop)
 stop
 ;;
 restart)
 stop
 sleep 2
 start
 ;;
 status)
 status
 ;;
 *)
 echo "Usage $0 {start|stop|restart|status}"
 exit 1;;
esac