Tomcat and apache httpd training

Post on 10-May-2015

9.661 views 9 download

description

My training support is accompanied by a workshops-booklet

Transcript of Tomcat and apache httpd training

Tomcat and Apache httpdObjectives

version 1.1

antislashn.org Tomcat and Apache httpd - Objectives 2 / 4

Objectives

● install Java, Tomcat, Apache httpd● configure Tomcat● build and monitor database connection pools● monitor Tomcat● secure Java EE web application● understand Apache https configuration files● set up and configure mod_jk● build Tomcat clusters to ensure high availability

antislashn.org Tomcat and Apache httpd - Objectives 3 / 4

Chapters

0.Objectives

1.Java EE introduction

2.Installations

3.Configuring Tomcat

4.Servlet and JSP overview

5.Tomcat valves

6.Connecting databases

7.Security with Tomcat

antislashn.org Tomcat and Apache httpd - Objectives 4 / 4

Chapters

8.Memory Management and JMX

9.Virtual host with Apache httpd

10.Security with Apache

11.Tomcat cluster with mod_jk

Introduction

version 1.1

antislashn.org Tomcat and Apache httpd - Introduction 2 / 37

Architecture

Apachehttpdserver

mod_jkload balancer

Tomcat

Tomcat

Tomcat

internet

staticresources

dynamicresources

What we want !!!

antislashn.org Tomcat and Apache httpd - Introduction 3 / 37

The evolution of the web

● 1989 – the birth of the web● Tim Berners-Lee● distributed information system for CERN physicists and

engineers

● 1990 – the first web page● was about the WWW project

– World Wide Web● no screen-shot of the original page

antislashn.org Tomcat and Apache httpd - Introduction 4 / 37

The evolution of the web

● source : http://evolutionofweb.appspot.com/

antislashn.org Tomcat and Apache httpd - Introduction 5 / 37

Web server

● Primary function : to deliver web pages to clients● HTTP : communication protocol between client and server

● Commons features● Virtual hosting to serve many sites using one IP address● Server-side scripting to generate dynamic web pages

– CGI, Fast CGI, SSI, …● Bandwidth throttling

antislashn.org Tomcat and Apache httpd - Introduction 6 / 37

Web server

● Market share

Product Vendor May 2013 Percent

Apache httpd Apache 359 441 468 53.42 %

IIS Microsoft 112 303 412 16.69 %

nginx NGINX Inc. 104 411 087 15.52 %

GWS Google 23 029 260 3.42 %

source : Wikipedia

antislashn.org Tomcat and Apache httpd - Introduction 7 / 37

HTTP

● Hypertext Transfert Protocol● request – response protocol

– the client submits an HTTP request to the server– the server send an HTTP response

● HTTP/1.0 : original version● HTTP/1.1 : from January 1997

– RFC 2068 and 2616● HTTP/2.0 : 2014 ???

– based on SPDY (SPeeDY) ● http://www.chromium.org/spdy/spdy-whitepaper

antislashn.org Tomcat and Apache httpd - Introduction 8 / 37

HTTP

● Stateless protocol● the server does not retain information about each user● web applications implement server side session

– cookies, hidden variables or query string parameters

● Default port : 80● HTTPS : 443

antislashn.org Tomcat and Apache httpd - Introduction 9 / 37

HTTP

● Conversation sample● client request

● server response

antislashn.org Tomcat and Apache httpd - Introduction 10 / 37

HTTP

● Request methods● GET : requests a resource● HEAD : like GET request but without the response body● POST : requests that the server accept the entity enclose

in the request– might be a form

● PUT : requests that the enclose entity be store● DELETE : deletes the resource

antislashn.org Tomcat and Apache httpd - Introduction 11 / 37

HTTP

● HTTP methods (continuation)● TRACE : echoes back the received request

– for debug● OPTIONS : returns the HTTP methods that the server

supports● CONNECT : uses a proxy like a communication tunnel

– for SSL● PATCH : uses to apply partial modification to a resource

antislashn.org Tomcat and Apache httpd - Introduction 12 / 37

HTTP

● GET and POST are the most widely used by web applications

● RESTful web service uses● GET● POST● PUT● PATCH● DELETE

antislashn.org Tomcat and Apache httpd - Introduction 13 / 37

HTTP

● HTTP response status codes● 1xx : informational● 2xx : success

– 200 OK● 3xx : redirection

– 301 Moved permanently– 304 Not Modified

● 4xx : client error– 404 Not Found

● 5xx : server error– 500 Internal Server Error

antislashn.org Tomcat and Apache httpd - Introduction 14 / 37

HTTP

● HTTP authentications● BASIC access authentication

– the username and password are combined into a string● username:password

– this string is then encoded using Base64● DIGEST access authentication

– uses MD cryptographic hashing– the password is not used directly

antislashn.org Tomcat and Apache httpd - Introduction 15 / 37

Java evolution

● Language issued from a Sun project● 1990● named “Stealth” and supervised by Patrick Naugthon● James Gosling and Mike Sheridan arrived in 1994

● 1996 : first JDK publication– JDK : Java Development Kit

● 2009 : Oracle bought Sun● 2010 : James Gosling quits Oracle

antislashn.org Tomcat and Apache httpd - Introduction 16 / 37

Java evolution

● JDK 1.0 – 1996 (23 of January) : 201 classes et 8 packages

● JDK 1.1 – 1997 (19 of February) : 503 classes et 23 packages

● J2SE 1.2 – 1998 (9 of December) : 1 520 classes et 59 packages

● J2SE 1.3 – 2000 (8 of May) : 1 840 classes et 76 packages

● J2SE 1.4 – 2002 (6 of February) : 2 990 classes et 135 packages

● J2SE 5.0 – 2004 (30 of September) : 3 280 classes et 166 packages

● Java SE 6 – 2006 (11 of December) : 3780 classes et 202 packages

● Java SE 7 – 2011 (7 of July) : 4 024 classes et 209 packages

● Java SE 8 – 2014

● Java SE 9 - 2016

antislashn.org Tomcat and Apache httpd - Introduction 17 / 37

Java acronyms

● JRE : Java Runtime Environment● JDK : Java Development Kit● JVM : Java Virtual Machine● Java SE : Java Standard Edition

● earlier J2SE

● Java ME : Java Micro Edition● earlier J2ME

● Java EE : Enterprise Edition● earlier J2EE

antislashn.org Tomcat and Apache httpd - Introduction 18 / 37

Java acronyms

● JSR : Java Specification Request● users can ask new features in the Java platforms

● JCP : Java Community Process● consortium which manage the Java evolutions

● EJB : Enterprise Java Bean● JavaBean component handles by a Java EE server

● POJO : Plain Old Java Object● a very simple Java component

antislashn.org Tomcat and Apache httpd - Introduction 19 / 37

Java platforms

● Java SE● standalone applications● executed when launching the JVM

– java tool

● Java EE● the application is handled in a server

● Java ME● embedded applications● executed in a particular JVM : the KVM

antislashn.org Tomcat and Apache httpd - Introduction 20 / 37

Development cycle

● Simple view of development cyclesource Java code

file Toto.java

compilation withjavac tool

Java bytecodeToto.class

execution in the JVMjava tool

antislashn.org Tomcat and Apache httpd - Introduction 21 / 37

Java EE overview

source : Oracle

antislashn.org Tomcat and Apache httpd - Introduction 22 / 37

Java EE overview

● Java EE defines● an architecture for implementing services as multitier

applications– scalability– accessibility– manageability

source : Oracle

antislashn.org Tomcat and Apache httpd - Introduction 23 / 37

Java EE overview

● Java EE components● clients

– web clients (or thin client)● web brother which renders the page received from the server

– application clients● runs on a client machine

– GUI created with Swing

antislashn.org Tomcat and Apache httpd - Introduction 24 / 37

Java EE overview

● Web components● JSP and servlets

source : Oracle

antislashn.org Tomcat and Apache httpd - Introduction 25 / 37

Java EE overview

● Business components

source : Oracle

Enterprise Information System

antislashn.org Tomcat and Apache httpd - Introduction 26 / 37

Java EE overview

● Java EE containers● container services, provides :

– JNDI – Java Naming and Directory Interface● the application components can access the services by their names

– Java EE security model● configures a web component or EJB so that resources are accessed only

by authorized users

– Java EE transaction● specifies relationships among methods that make up a single transaction

so that all methods in one transaction are treated as a single unit

– JMS, Java EE remote connectivity, mail, data sources, ...

antislashn.org Tomcat and Apache httpd - Introduction 27 / 37

Java EE overview

● Container types

source : Oracle

antislashn.org Tomcat and Apache httpd - Introduction 28 / 37

Java EE overview

● Packaging application● application is delivered in a Java Archive (JAR) file

– WAR : Web Archive– EAR : Enterprise Archive

● contains Java EE modules

source : Oracle

antislashn.org Tomcat and Apache httpd - Introduction 29 / 37

Java EE overview

● Java EE 6 APIs

source : Oracle

antislashn.org Tomcat and Apache httpd - Introduction 30 / 37

Java EE overview

● Profiles● configurations of the Java EE platform targeted at specific

classes of applications– Web Profile– Full Profile

antislashn.org Tomcat and Apache httpd - Introduction 31 / 37

Java EE overview

● Web Profile includes EJB Lite● not the full EJB API

antislashn.org Tomcat and Apache httpd - Introduction 32 / 37

Tomcat overview

● Open source server● Java based web application container● run servlet and JPS

● Major versions on Tomcat coincide with versions of Java Servlet specification

Tomcat Servlet API JSP API JDK

7.0 3.0 2.2 1.6

6.0 2.5 2.1 1.5

5.5 2.4 2.0 1.4

antislashn.org Tomcat and Apache httpd - Introduction 33 / 37

Architecture of Tomcat

Server

Service

Connector HTTP

Connector AJP

Connector HTTPS

port 8080

port 8443

port 8009

Engine

Host

Context Context

antislashn.org Tomcat and Apache httpd - Introduction 34 / 37

Architecture of Tomcat

● Tomcat instance is the top-level component● only one instance per JVM

– multiple instances can run on separate JVM and network ports● server.xml provides an XML representation of

relationships between the different containers

<Server><Service>

<Connector /><Engine>

<Host><Context></Context>

</Host></Engine>

</Service></Server>

antislashn.org Tomcat and Apache httpd - Introduction 35 / 37

Architecture of Tomcat

● <Server> represents the entire Catalina server engine● Catalina is the Java servlet container implementation● may contain one or more <Service> containers

● <Service> holds a collection of <Connector>● connectors share one <Engine>

● <Connector> defines the port for handling request and response

antislashn.org Tomcat and Apache httpd - Introduction 36 / 37

Architecture of Tomcat

● <Engine> handles all requests received by the connectors

● <Host> defines virtual hosts● the virtual hosts are contained in an instance of engine● each host can be a parent to one or more <Context>

component

● <Context> represents a web application

antislashn.org Tomcat and Apache httpd - Introduction 37 / 37

Tomcat overview

● Tomcat is not● a Web Profile server● a httpd server

– Apache httpd is better

● Tomcat is● just a Java EE web container

● Tomcat is part of many projects● JBoss● TomEE● ...

InstallationJava – Tomcat – Apache httpd

version 1.0

antislashn.org Tomcat and Apache httpd - Installation 2 / 16

Installing Java

● Installing Java on CentOS 6.4● download Sun/Oracle Java JDK

– http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

– select rpm● in the Terminal

– change to root user● or

– install Java JDK package●

– verify the installation●

su - sudo -i

rpm -Uvh /path/to/binary/jdk-7u45-linux-x64.rpm

java -version

antislashn.org Tomcat and Apache httpd - Installation 3 / 16

Installing Java

● Installing Java on CentOS 6.4 (continuation)● setup JAVA_HOME

– add JAVA_HOME in /etc/profile

– restart the computer and verify

export JAVA_HOME="/usr/java/latest"

echo $JAVA_HOME

antislashn.org Tomcat and Apache httpd - Installation 4 / 16

Installing Tomcat

● Download Tomcat distribution● http://tomcat.apache.org/download-70.cgi● download the code distribution

antislashn.org Tomcat and Apache httpd - Installation 5 / 16

Installing Tomcat

● After downloaded, validate the distribution● each distribution had a PGP signature and a MD5

checksum

● Extract the download file onto /opt● you need to be root

md5sum Downloads/apache-tomcat-7.0.47.zip

unzip apache-tomcat-7.0.47.zip -d /opt

tar zxvf apache-tomcat-7.0.47.tar.gzmkdir /opt/apache-tomcat-7.0.47cp -R apache-tomcat-7.0.47/* /opt/apache-tomcat-7.0.47

or

antislashn.org Tomcat and Apache httpd - Installation 6 / 16

Installing Tomcat

● Setup CATALINA_HOME● add CATALINA_HOME in /etc/profile

– you need to be root

● perhaps you need to change the tomcat folder owner–

export CATALINA_HOME="/opt/apache-tomcat-7.0.47"

chown -R franck apache-tomcat-7.0.47/

antislashn.org Tomcat and Apache httpd - Installation 7 / 16

Installing Tomcat

● Starting Tomcat

● verifying the good installation● open localhost:8080

cd /opt/apache-tomcat-7.0.47/bin/./startup.sh

antislashn.org Tomcat and Apache httpd - Installation 8 / 16

Installing Tomcat

● Stopping Tomcatcd /opt/apache-tomcat-7.0.47/bin/./shutdown.sh

antislashn.org Tomcat and Apache httpd - Installation 9 / 16

Tomcat directories

antislashn.org Tomcat and Apache httpd - Installation 10 / 16

Tomcat directories

● bin : contains the scripts for starting and stopping Tomcat

● conf : contains the configuration files● server.xml : general server configuration file● web.xml, context.xml : global web application

configuration files● tomcat-user.xml : default user list for file-based

authentication

antislashn.org Tomcat and Apache httpd - Installation 11 / 16

Tomcat directories

● lib : contains jar files used by Tomcat● logs : contains server logs● webapps : contains web applications

● contains some default web applications– includes Tomcat manager application

● deployment directory

● temp : contains temporary files● work : contains compiled JSP pages

antislashn.org Tomcat and Apache httpd - Installation 12 / 16

Installing Apache httpd

● Apache httpd server is installed with CentOS by default● if you need to install Apache httpd

● Starting Apache httpd● in root mode

yum install httpd

/etc/init.d/httpd start

orapachectl start

antislashn.org Tomcat and Apache httpd - Installation 13 / 16

Installing Apache httpd

● Stopping Apache httpd● as root user

● Setting the Apache service to start on boot● as root user

/etc/init.d/httpd stop

orapachectl stop

chkconfig --levels 235 httpd on

antislashn.org Tomcat and Apache httpd - Installation 14 / 16

Installing Apache httpd

● Testing Apache httpd● open http://localhost

antislashn.org Tomcat and Apache httpd - Installation 15 / 16

Installing Apache httpd

● Configuration file● /etc/http/conf/httpd.conf

● Configure a new default web site● create a new folder in your home

– named www for example– create a default index.html page

● open httpd.conf in root mode● change

– DocumentRoot entry

– and <Directory "/var/www/html"> directive

antislashn.org Tomcat and Apache httpd - Installation 16 / 16

Installing Apache httpd

● From the httpd.conf file

● Restart Apache httpd

...# DocumentRoot: The directory out of which you will serve your# documents. By default, all requests are taken from this directory, but# symbolic links and aliases may be used to point to other locations.#DocumentRoot "/opt/www"

...

## This should be changed to whatever you set DocumentRoot to.#<Directory "/opt/www">...

Tomcat architecture and configuration

version 1.0

antislashn.org Tomcat and Apache httpd - Tomcat configuration 2 / 33

Architecture overview

● Tomcat consists of a nested hierarchy of components

Server

Service

connector

connector

Engine LoggerLoggerLogger ValveLoggerValve Realm

HostHostHostLoggerLoggerLoggerLogger ValveValveValve Realm

ContextContextContext ValveValveValve Realm

ValveValveWrapper

antislashn.org Tomcat and Apache httpd - Tomcat configuration 3 / 33

Architecture overview

● Server● the server is Tomcat itself

– it owns a port used for shut down the server

● only one instance by JVM– separate servers can be set up on the same machine

● separate JVM and servers configured with different ports● could be secure web application

– one web application per server● if the JVM crashes, only one application is affected

<Server port="8005" shutdown="SHUTDOWN">

antislashn.org Tomcat and Apache httpd - Tomcat configuration 4 / 33

Architecture overview

● Service● contains a single container Engine● contains one or more Connectors● the service is named for easily identify log messages

● Connectors● they connect the applications to clients● they represent the point at which request are received● they are assigned a port on the server● Coyote : default connector for HTTP/1.1

antislashn.org Tomcat and Apache httpd - Tomcat configuration 5 / 33

Architecture overview

● Engine● it is a request-processing component thats represents the

Catalina Servlet engine● it examines th HTTP headers to determine the context to

which request should be passed

● Realm● manages user authentication and authorization● by default a user must still authenticate separately to each

web application– we will see how this can be change, using sing sign-on

antislashn.org Tomcat and Apache httpd - Tomcat configuration 6 / 33

Architecture overview

● Valves● enable Tomcat to intercept a request and preprocess

– like filter of Servlet Specification but they are specific to Tomcat● Hosts, Contexts and Engines may contains Valves● they are commonly used to

– enable SSO– log requests

● a Valve is a reusable component which could be add or remove– inclusion is transparent to web application

antislashn.org Tomcat and Apache httpd - Tomcat configuration 7 / 33

Architecture overview

● Loggers● report on the internal state of a component

● Host● Engine may contains one or more Host

– one default host– zero or more virtual hosts

● in Tomcat virtual hosts are differentiates by a fully qualified hots name– www.example.com and www.example.net can both reside in the same

server

antislashn.org Tomcat and Apache httpd - Tomcat configuration 8 / 33

Architecture overview

● Context● this is the web application

– it becomes parent of servelts and filters● as StandardWrapper objects

● a web application could include– a web.xml– a context.xml

● supports dynamic reload– classes that have been changed are reloaded into memory

● may include specific error pages

antislashn.org Tomcat and Apache httpd - Tomcat configuration 9 / 33

Files in $CATALINA_HOME/conf

● server.xml● main configuration file● Tomcat reads this file at startup

– components configured in this file affect the entire Tomcat instance

● application-level context should not be made in this file– use a per-application context.xml

● tomcat-user.xml● contains user authentication and role-mapping

antislashn.org Tomcat and Apache httpd - Tomcat configuration 10 / 33

Files in $CATALINA_HOME/conf

● context.xml● default application context for any web applications● could be contains components for all the web applications

deployed in Tomcat– JDBC DataSource connection– realm– etc.

● application can customized and override this file with their own context.xml file

antislashn.org Tomcat and Apache httpd - Tomcat configuration 11 / 33

Files in $CATALINA_HOME/conf

● web.xml● default deployment descriptor for all web applications● provides basic servlet definition and MIME mappings● applications usually have their own web.xml

● catalina.policy● Java SE security model

– controls the permission to access resources● default policy file for running Tomcat in secured mode

antislashn.org Tomcat and Apache httpd - Tomcat configuration 12 / 33

Files in $CATALINA_HOME/conf

● catalina.properties● this file is read at startup● provides for internal packages access and definition

control

● logging.properties● configuration file for logging

– Tomcat uses its own implementation of Java Logging

antislashn.org Tomcat and Apache httpd - Tomcat configuration 13 / 33

<Server> component

● in server.xml● key attributes

● port : TCP port to listen for the command specified by the shutdown attribute

● shutdown : command text string used for shutting down– can be telnet to the port 8005 with SHUTDONW to take the

server down● cannot be done remotely for security reasons

antislashn.org Tomcat and Apache httpd - Tomcat configuration 14 / 33

<Server> component

● key sub-elements● <Service>

– a grouping of Connectors associated with an Engine● <Listener>

– life-cycle listeners for interception of the server's life-cycle events● <GlobalNamingResources>

– JNDI global resources

antislashn.org Tomcat and Apache httpd - Tomcat configuration 15 / 33

<Service> component

● key attributes● className : classe name for the service

– org.apache.catalina.core.StandardService by default

● name : name for the service– used in logging, administration, management

● key elements● <Connector> : one or more

– component that handles external client connections

● <Engine> : request-processing component (Catalina)

antislashn.org Tomcat and Apache httpd - Tomcat configuration 16 / 33

Web application configuration

● A web application consist of● static content

– HTML pages, image files, PDF files, …● dynamic content

– servlets, JSP, Java classes

● Web applications are usually installed under the webapps directory● deployed in a directory named after the web application

– this name is also used in the web application URL

antislashn.org Tomcat and Apache httpd - Tomcat configuration 17 / 33

Web application configuration

● Web application structuredeveloper's project

war file

antislashn.org Tomcat and Apache httpd - Tomcat configuration 18 / 33

Web application configuration

● URL parsing

http://www.example.com/bovoyage/addCaddy/5

Coyote connector/conf/server.xml

Virtual host name/conf/server.xml

context path

servlet mapping/WEB-INF/web.xml

processed by servlet

antislashn.org Tomcat and Apache httpd - Tomcat configuration 19 / 33

Web application configuration

● ROOT web application● installed under /webapps● default web application

– no context path needs to be specified● http://localhost:8080/

antislashn.org Tomcat and Apache httpd - Tomcat configuration 20 / 33

Web application configuration

● WEB-INF directory contains● web.xml file

– deployment descriptor● classes directory

– contains all compiled Java classes● lib directory

– contains packaged Java libraries (.jar)● if the libraries are to be accessed across web applications, they should be

placed under <TOMCAT_HOME>/lib

● tag directory (optional)– contains files for tags libraries

antislashn.org Tomcat and Apache httpd - Tomcat configuration 21 / 33

Web application configuration

● META-INF directory contains optional files● context.xml file contains the specific configuration for the

web application● MANIFEST.MF file

– version, vendor, …

antislashn.org Tomcat and Apache httpd - Tomcat configuration 22 / 33

Deployment descriptor web.xml

● Application-specific deployement file● key elements

● <context-param> : mechanism used for setting application-initialization parameters– contains <param-name> , <param-value>

● <filter> : reusable component that intercept the client request and response and apply some type of processing– compression, …– contains <filter-name>, <filter-class>

antislashn.org Tomcat and Apache httpd - Tomcat configuration 23 / 33

Deployment descriptor web.xml

● key elements● <listener> : component design to respond to event in

an application– session start and stop, application start and stop, …

● <servlet> : a servlet is declared by assigning it a unique name which references its fully qualified class name

<servlet><servlet-name>controleur</servlet-name><servlet-class>org.bovoyage.servlet.ControleurServlet</servlet-class>

</servlet>

antislashn.org Tomcat and Apache httpd - Tomcat configuration 24 / 33

Deployment descriptor web.xml

● key elements● <servlet-mapping> : specifies the mapping between a

servlet and a URL pattern

<servlet-mapping><servlet-name>controleur</servlet-name><url-pattern>/controleur</url-pattern>

</servlet-mapping>

<servlet-mapping><servlet-name>controleur</servlet-name><url-pattern>/index.jsp</url-pattern>

</servlet-mapping>

antislashn.org Tomcat and Apache httpd - Tomcat configuration 25 / 33

Deployment descriptor web.xml

● key elements● <session-config> and <session-timeout>

– used to set a session timeout value (mn)

● <welcome-file-list> : defines the default resource, il no resource is specified in the URL– for example http://localhost:8080/bovoyage request the index.jsp

resource

<welcome-file-list><welcome-file>index.jsp</welcome-file>

</welcome-file-list>

antislashn.org Tomcat and Apache httpd - Tomcat configuration 26 / 33

Deployment descriptor web.xml

● key elements● <error-page> : error pages configuration

– the cause may be a HTTP error or a Java exception

<error-page><error-code>404</error-code><location>/errors/oops.jsp</location>

</error-page><error-page>

<error-code>java.lang.NullPointerException</error-code><location>/errors/appProblem.jsp</location>

</error-page>

antislashn.org Tomcat and Apache httpd - Tomcat configuration 27 / 33

Deployment descriptor web.xml

● key elements● <security-constraint>● <security-role>● <login-config>

– these elements relate to the configuration of login authentication in the application

– we shall see in detail later

antislashn.org Tomcat and Apache httpd - Tomcat configuration 28 / 33

Deployment descriptor web.xml

● key elements● <resource-ref>● <resource-env-ref>● <env-entry>

– are provided for configuring resources for the web application● a database-connection pooling, ...

antislashn.org Tomcat and Apache httpd - Tomcat configuration 29 / 33

Tomcat manager application

● manager application is a web application● three way to interact with the manager application

– using the web interface– using HTTP requests

● via the browser● via scripts

– using Ant-based interface

● Access to the manager application is restricted to authorized users

antislashn.org Tomcat and Apache httpd - Tomcat configuration 30 / 33

Tomcat manager application

● Summary of some tasks that the manager application can perform● deploy a new web application● manage th currently web applications● list the available global JNDI resources● list the available security roles● display session statistics

antislashn.org Tomcat and Apache httpd - Tomcat configuration 31 / 33

Tomcat manager application

● Enabling access to the manager application● this example use the User Database Realm

– but any realm implementation can be used– the username, password and roles are initialized at startup from

the conf/tomcat-users.xml configuration file● this file needs to be edited to add a user with a role manager-gui● Tomcat need to be restarted

<tomcat-users><role rolename="manager-gui"/><user username="admin" password="adminpw" roles="manager-gui"/>

</tomcat-users>

antislashn.org Tomcat and Apache httpd - Tomcat configuration 32 / 33

Tomcat manager application

● Using HTTP requests● URL format :

http://[hostname]:[port]/manager/text/command?parameters

● commands– list, sessions, start, stop, install, remove, deploy, undeploy,

reload, serverinfo, roles, resources– the list depends of the Tomcat version – see documentation

● parameters– file:/absolute/path/to/a/directory– file:/absolute/path/to/a/webapp.war– jar:file:/absolute/path/to/a/webapp.war!

antislashn.org Tomcat and Apache httpd - Tomcat configuration 33 / 33

Tomcat manager application

● Using HTTP request● needed to add the role manager-script

● example :– http://localhost:8080/manager/text/list

<role rolename="manager-gui"/><role rolename="manager-script"/><user username="admin" password="adminpw" roles="manager-gui,manager-script"/>

Servlet and JSP

version 1.1

antislashn.org Tomcat and Apache httpd - Servlet and JSP 2 / 12

Servlet

● Platform-independent web application component● communicate with web client using request/response

● The developer extends the HttpServlet class● javax.servlet and javax.servlet.http

public class HelloServlet extends HttpServlet {public void init(ServletConfig config) throws ServletException {}public void destroy() {}protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {}protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {}

}

antislashn.org Tomcat and Apache httpd - Servlet and JSP 3 / 12

Servlet

● The servlet is declared in the web.xml● the developer compiles the servlet and deployed it in the WEB-INF/classes directory

<servlet><servlet-name>HelloServlet</servlet-name><servlet-class>org.bovoyage.servlet.HelloServlet</servlet-class>

</servlet><servlet-mapping>

<servlet-name>HelloServlet</servlet-name><url-pattern>/hello</url-pattern>

</servlet-mapping>

antislashn.org Tomcat and Apache httpd - Servlet and JSP 4 / 12

Servlet

● Life-cycle

HTTP requestclass

loaded the servlet is instantiateno

init()

classchanged

yes

service()

destroy()

the servlet is unloaded

no

yes

antislashn.org Tomcat and Apache httpd - Servlet and JSP 5 / 12

Servlet

● When the HttpServlet.service() method is invoked● it reads the HTTP method type in the request● it uses this value to determine which method to invoke

HTTP Method HttpServlet class method

GET doGet(HttpServletRequest,HttpServletResponse)

POST doPost(HttpServletRequest,HttpServletResponse)

PUT doPut(HttpServletRequest,HttpServletResponse)

DELETE doDelete(HttpServletRequest,HttpServletResponse)

HEAD doHead(HttpServletRequest,HttpServletResponse)

OPTIONS doOptions(HttpServletRequest,HttpServletResponse)

TRACE doTrace(HttpServletRequest,HttpServletResponse)

antislashn.org Tomcat and Apache httpd - Servlet and JSP 6 / 12

Servlet

● Servlet API 3.0 allows us to configure the servlet details using annotations, instead XML

@WebServlet(name="HelloServlet",urlPatterns="/hello")

public class HelloServlet extends HttpServlet{

...

}

antislashn.org Tomcat and Apache httpd - Servlet and JSP 7 / 12

JSP

● Java Server Page● Simple technology

<html><head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Hello JSP</title>

</head><body>

<h2>Hello, world</h2></body>

</html>

antislashn.org Tomcat and Apache httpd - Servlet and JSP 8 / 12

JSP● Life-cycle

● translation– the JSP file is translated to Java servlet source

● compilation– the generated servlet class is compiled

● loading– the compiled servlet is loaded in memory

● instantiation● initialization● servicing request● destruction

antislashn.org Tomcat and Apache httpd - Servlet and JSP 9 / 12

JSP

● Life-cycle

requestclass

loaded

JSPchanged

instance is unloaded

jspInit() the class is instantiate

translation

jspService()

no

response

no

yes

yes

antislashn.org Tomcat and Apache httpd - Servlet and JSP 10 / 12

Components of a JSP

● Page directive● provide global information about a JSP page

● Include directive● to insert file (text or JSP) at translation time

● Taglib directive● to use a custom tag library

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ include file="header.jsp" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

antislashn.org Tomcat and Apache httpd - Servlet and JSP 11 / 12

Component of a JSP

● Declarations● used to define Java variables and methods in the JSP

page

● Expressions● the expression is replaced with the resulting value of the

container evaluation

<%! String name="toto"; %><%! String getHello(){ return "Hello";} %>

<%= getHello() %> <%= name %>

antislashn.org Tomcat and Apache httpd - Servlet and JSP 12 / 12

JSP Expression Language (EL)

● EL is a powerful feature introduced with the version 2.0● it enable developers to easily access Java objects

...<table> <c:forEach items="${destinations}" var="destination"> <tr>

<td>${destination.region }</td> <td><a href='controleur?cde=det&id=${destination.id }'>détails</a></td>

</tr> </c:forEach></table>...

destination is a POJO

destinations is collection of POJO

Tomcat valves and filters

version 1.1

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 2 / 16

Valves and Filters

● The purpose of theses components is intercepting requests for one or more web application

● Valve is a proprietary Tomcat technology● Filter is a server-independent technology● We need a mechanism to preprocess request before it

reaches the web application● login about requests● allowing access from certain remote IPs● data compression

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 3 / 16

Valves and Filters

● Theses requirements are independent of applications● Tomcat Valves vs. Servlet Filters

● Filter is a servlet specification– it is platform-independent– filter-chaining functionality is very useful– it can only be configured on a web application level

● Valve can be better performing and robust– because Valve is part of the Tomcat engine API– it can be configured on the engine or host level

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 4 / 16

Tomcat Valves

● Tomcat uses valves internally● to manage authentication● to maintain SSL information in a request● to log request details

● Some valves are configured internally y Tomcat● BasicAuthentificationValve for the BASIC

authentication

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 5 / 16

Tomcat Valves

● Implementing a Valvepublic class SimpleLoggingValve extends ValveBase {

@Overridepublic void invoke(Request request, Response response) throws IOException,ServletException {

String remoteAddress = request.getRemoteAddr();String requestUri = request.getRequestURI();

System.out.println(">>> VALVE - URI : " + requestUri + " from "+remoteAddress);Valve nextValve = getNext();

if(nextValve!=null){nextValve.invoke(request, response);

}

}

}

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 6 / 16

Tomcat Valves

● Adding the valve to Tomcat● package the valve in a jar file● copy the jar file in <TOMCAT_HOME>/lib

● Configure the valve to be executed for all requests● modify the conf/server.xml

– in the <Host> element

<Valve className="org.antislashn.tomcat.valves.SimpleLoggingValve" />

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 7 / 16

Access Log Valve

● Tomcat prepackaged Valve● It creates log files to track client access information

● can be associated with Engin, Host or Context● its configuration is in server.xml file

<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." suffix=".txt"/>

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 8 / 16

Remote Access Valve

● Allow you to compare th IP address of the requesting client against one or more regular expression● allow or prevent the request from continuing

– two attributes● access● deny – a HTTP status code 403

<Valve className="org.apache.catalina.valves.RemoteAddrValve" deny="127.*"/>

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 9 / 16

Crawler Session Manager Valve

● Search engines employ special programs to discover and index the web sites● crawler or spiders● when hundred of separate crawler processes access the

web site, a user session will be created for each of them● this valve ensures that each unique web crawler is

associated with on user session

<Valve className="org.apache.catalina.valves.CrawlerSessionManagerValve" crawlerUserAgents="[bB]ot.*|*Yahoo! Slurp.*|.*Feedfetcher-Google.*."sessionInactiveInterval="3600" />

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 10 / 16

Dead Thread Detection Valve

● Each request from a single user is processed by a separate Java thread● sometimes these threads get stuck

– network problems– bugs

● this valve helps to detect the stuck threads– threshold attribute

<Valve className="org.apache.catalina.valves.DeadThreadDetectionValve" threshold="300" />

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 11 / 16

Servlet Filters

● Interface javax.servlet.Filter● methods

– init(FilterConfig)● initialize the filter – it is called once

– doFilter(ServletRequest, ServletResponse, FilterChain)

● this method is executed for every request● must call filterChain.doFilter(...)

– destroy()● call once, when the web application is undeployed

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 12 / 16

Servlet Filter

● Implementing a Filterpublic class TimeFilter implements Filter {

private FilterConfig config = null;

public void destroy() {config = null;

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

long debut = System.currentTimeMillis();config.getServletContext().log(">>> avant appel servlet");chain.doFilter(request, response);long fin = System.currentTimeMillis();config.getServletContext().log(">>> après appel servlet");config.getServletContext().log(">>> TEMPS : " + (fin-debut) + " ms");

}

public void init(FilterConfig fConfig) throws ServletException {config = fConfig;

}}

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 13 / 16

Servlet Filter

● Filter configuration● in the WEB-INF/web.xml

<filter> <display-name>TimeFilter</display-name> <filter-name>TimeFilter</filter-name> <filter-class>org.antislashn.web.TimeFilter</filter-class> </filter> <filter-mapping> <filter-name>TimeFilter</filter-name> <url-pattern>/test</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 14 / 16

Servlet Filter

● Filter configuration● <dispatcher> selects one of the following dispatcher

types :– REQUEST : only when the request comes directly from the client

– FORWARD : only when the request has been forwarded to a component

– INCLUDE : only when the request is being processed by a included component

– ERROR : only when the request is being processed with the error page mechanism

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 15 / 16

Request Dumper Filter

● This built in filter dumps the entire HttpServletRequest to the Tomcat log

<filter> <filter-name>DumperFilter</filter-name> <filter-class>org.apache.catalina.filters.RequestDumper</filter-class> </filter> <filter-mapping> <filter-name>DumperFilter</filter-name> <url-pattern>/*.jsp</url-pattern> </filter-mapping>

antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 16 / 16

Expires Filter

● It controls the HTTP expires header<filter> <filter-name>ExpiresFilter</filter-name> <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class> <init-param> <param-name>ExpiresByType image</param-name> <param-value>access plus 10 minutes</param-value> </init-param> <init-param> <param-name>ExpiresByType text/css</param-name> <param-value>access plus 10 minutes</param-value> </init-param> <init-param> <param-name>ExpiresByType application/javascript</param-name> <param-value>access plus 10 minutes</param-value> </init-param></filter><filter-mapping> <filter-name>ExpiresFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher></filter-mapping>

Tomcat logging

version 1.1

antislashn.org Tomcat and Apache httpd - Tomcat logging 2 / 14

Java Logging Framework

● Since Java 1.4, Java itself comes with the capable logging package java.util.logging

● Since Tomcat 6, Tomcat itself uses Java Logging instead Commons Logging API● Tomcat 6 has done away with the <Logger> element

– use the conf/logging.properties file

● Tomcat developers extend the functionality of the standard Java logging framework● this implementation is known as JULI

– Java Util Logging Interface

antislashn.org Tomcat and Apache httpd - Tomcat logging 3 / 14

Java Logging overview

● To instantiate a logger instance in th Java code, you will use static factory method, and construct a logger with the selected name

● Each logger accept messages with different logging level● based on their importance

Logger log = Logger.getLogger("org.antislashn");

log.severe("Message niveau severe");log.info("Message niveau info");log.finest("Message niveau finest");

antislashn.org Tomcat and Apache httpd - Tomcat logging 4 / 14

Java Logging overview

● Logging levels● SEVERE : used to log exceptions, errors, ...● WARNING : used to log warning messages● INFO : used to log information messages● CONFIG : used to log configuration messages,

initializations, ...● FINE : used to log detailed information, useful for

debugging purposes● FINER : more information than FINE● FINEST : logs all messages

antislashn.org Tomcat and Apache httpd - Tomcat logging 5 / 14

Java Logging overview

● Handlers● each logger has a list of handlers associated with it

– represented by an abstract class java.util.logging.Handler

● three main handlers are available– ConsoleHandler : outputs the logged messages to System.err

– FileHandler : writes the messages to a file● supporting file rotation

– SocketHandler : writes messages to the network socket

antislashn.org Tomcat and Apache httpd - Tomcat logging 6 / 14

Java Logging overview

● Formatter● each handler has one formatter

– format the log messages– two formatters are available

● SimpleFormatter– logs message with date, time, information

● XMLFormatter– writes messages

in XML format

Infos: Initializing ProtocolHandler ["http-bio-8080"]nov. 14, 2013 11:50:03 AM org.apache.coyote.AbstractProtocol init

<record> <date>2013-11-14T11:54:48</date> <millis>1384426488187</millis> <sequence>2</sequence> <logger>org.antislashn</logger> <level>FINEST</level> <class>org.antislashn.formation.log.Logger_03</class> <method>main</method> <thread>1</thread> <message>Message niveau finest</message></record>

antislashn.org Tomcat and Apache httpd - Tomcat logging 7 / 14

Java Logging overview

● Formatter● JULI adds three formatters

– OneLineFormatter : same format as SimpleFormatter, but written in a single line

– VerbatimFormatter : writes the log message only, without any additional information

– JdkLoggerFormatter : uses a compact output format with timestamps

antislashn.org Tomcat and Apache httpd - Tomcat logging 8 / 14

Java Logging overview

application Logger Handler

Formatter

out

antislashn.org Tomcat and Apache httpd - Tomcat logging 9 / 14

Java Logging overview

● Logging configuration● typically specified int the file logging.properties

– #1 : defines all handlers (comma separator)● handler is specified by his class name● there is only one instance by JVM

– #2 : default logging level for this handler– #3 : formatter for this handler

handlers= java.util.logging.ConsoleHandlerjava.util.logging.ConsoleHandler.level = ALLjava.util.logging.ConsoleHandler.formatter = java.util.logging.XMLFormatter

antislashn.org Tomcat and Apache httpd - Tomcat logging 10 / 14

JULI configuration

● Java Logging Framework guarantees than only one handler is instantiated by JVM

● JULI supports one handler per class loader● a prefix is add to each handler type

– starts with a number– and an arbitrary string– and ends with a period "."

handlers = 1catalina.org.apache.juli.FileHandler, 2localhost.org.apache.juli.FileHandler

antislashn.org Tomcat and Apache httpd - Tomcat logging 11 / 14

JULI configuration

● The defaults handlers are defined with the .handlers property● will be used for loggers that do not have a specific handler

configured

● Each handler is configured● name of the handler followed by the property

.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

1catalina.org.apache.juli.FileHandler.level = FINE1catalina.org.apache.juli.FileHandler.directory = ${catalina.base}/logs1catalina.org.apache.juli.FileHandler.prefix = catalina.

antislashn.org Tomcat and Apache httpd - Tomcat logging 12 / 14

JULI configuration

● Rotating logs● log file rotation is enable by default

● the format is {prefix}.{date}.{suffix}● the rotation an only rotate daily

1catalina.org.apache.juli.FileHandler.rotatable = true

antislashn.org Tomcat and Apache httpd - Tomcat logging 13 / 14

Servlet Logging

● Servlet API defines the logging API to be used● the logging based is performed by calls to ServletContext.log(String message) method

● developers prefer using frameworks– Servlet API Logging has become obsolete

● In Tomcat, all messages logged to Servlet log are intercepted● Tomcat provides handlers for ServletContext logs

– for each engine, host and context

antislashn.org Tomcat and Apache httpd - Tomcat logging 14 / 14

Servlet Logging

● The names follows the convention

● ENGINE : engine name● HOST : host name● CONTEXT : context name (application)● and ends with the property

org.apache.catalina.core.ContainerBase.[ENGINE].[HOST].[CONTEXT]

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFOorg.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers =

3manager.org.apache.juli.FileHandler

defined in server.xml

application name

Connecting databases

version 1.1

antislashn.org Tomcat and Apache httpd - Connectiong databases 2 / 16

JDBC overview

● JDBC – Java DataBase Connectivity● Java base data access technology● provides methods for querying and updating data in

database

Java application

JDBC library

Java API calls

MySQLJDBCdriver

OracleJDBCdriver

SQLServerJDBCdriver

antislashn.org Tomcat and Apache httpd - Connectiong databases 3 / 16

JDBC overview

● In JDBC programming, developers typically perform the following steps

1.obtain a connection to the remote database server

2.create and prepare SQL statement for execution

3.execute SQL statement

4.obtain the return result set and work with it

5.disconnect from the remote database

antislashn.org Tomcat and Apache httpd - Connectiong databases 4 / 16

JDBC overview

● ExampleString driver = "com.mysql.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/bovoyage";String user = "toto";String pswd = "totopw";

// 1 - load the driver and obtain a connectionClass.forName(driver);Connection conn = DriverManager.getConnection(url, user, pswd);

// 2 - create and prepare a SQL statementString sql = "SELECT * FROM destinations";Statement statement = conn.createStatement();

// 3 - execute SQL statement and obtain the result setResultSet rs = statement.executeQuery(sql);

// 4 - work on the result setwhile(rs.next()){System.out.println(rs.getString("region"));}

// 5 - disconnect from the remote databaseconn.close();

antislashn.org Tomcat and Apache httpd - Connectiong databases 5 / 16

JDBC overview

● The driver is loaded by his name● String type - it is usually a parameter● the developer don't know the database used

● The database is selected by a pseudo URL● DriverManager is responsible for establish the

connection to the database through the driver● the name and location of database is given as a URL

"com.mysql.jdbc.Driver"

jdbc:mysql://localhost:3306/bovoyage

protocol sub-protocol machine holdingthe database

path to the databaseon the machine

antislashn.org Tomcat and Apache httpd - Connectiong databases 6 / 16

JDBC overview

● Database connection pooling● when a web application uses JDBC

– a physical JDBC connection is establish between the application and the database

● via a TCP/IP connection

– establish such a connection is● CPU-intensive● memory-intensive● execution time-intensive

– how long hold the connection● request ?● session ?

antislashn.org Tomcat and Apache httpd - Connectiong databases 7 / 16

JDBC overview

● Database connection pooling● connection pooling reduces expensive session establish

times– connects, disconnects and reconnects

● a pool of physical connections is created when the system starts up

● when the application requires a connection one of these physical connection is provided

● when the application "closes" the connection– it is disconnected– the physical connection is merely returned to the pool

antislashn.org Tomcat and Apache httpd - Connectiong databases 8 / 16

JDBC overview

● Database connection pooling

web application

Database connectionspool manager

antislashn.org Tomcat and Apache httpd - Connectiong databases 9 / 16

JDBC overview

● The pool manager● creates the initial physical connections● manages the distribution of the physical connections

– the web application receive a logical connection– closing a logical connection does not close the physical

connection● returns and close physical connections● handles any exception or error

antislashn.org Tomcat and Apache httpd - Connectiong databases 10 / 16

JDBC overview

● The pool manager functionality may be provide by● an application server

– Tomcat, JBoss, Geronimo, GlassFish, …● a third-party pool manager vendor● a JDBC driver vendor

● Tomcat enables running web application to :● access JDBC data sources using JNDI lookup● use connection pooling value-added service

antislashn.org Tomcat and Apache httpd - Connectiong databases 11 / 16

Configuring the database connection

● The database connection is configured as a JNDI resource● as part of the <Context> element

– making the resource available only to the web application in the specified context

● in the <GlobalNamingResources> section in the server.xml file– the resource will be available to all the web applications deployed

on the Tomcat instance

antislashn.org Tomcat and Apache httpd - Connectiong databases 12 / 16

Configuring the database connection

● JNDI resource for MySQL

<Context reloadable="true"><Resource

name='jdbc/bovoyage'auth='Container' type='javax.sql.DataSource'driverClassName='com.mysql.jdbc.Driver'url='jdbc:mysql:///bovoyage'username='toto'password='totopw'maxActive='20'maxIdle='10'maxWait='10000'removeAbandoned='true' />

</Context>

antislashn.org Tomcat and Apache httpd - Connectiong databases 13 / 16

Configuring the database connection

● key attributes● name : the name of the resource will be used to reference

the same resource in the web application● auth : specifies whether the sign-on to the resource

manager to access to the resource is done by– the server, "Container" value– th application, "Application" value

● type : type of resource factory

● driverClassName : the database vendor class name

antislashn.org Tomcat and Apache httpd - Connectiong databases 14 / 16

Configuring the database connection

● key attributes● url : database connection URL

● usename and password : for database connection

● validationQuery : the server executes this query each time just before it passes the connection to the application, to check the accessibility of the database

● maxActive : maximum number of active connections

● maxIdle : maximum number of connections that should be kept in the pool at all times

antislashn.org Tomcat and Apache httpd - Connectiong databases 15 / 16

Accessing the JNDI DataSource

● The JNDI DataSource resource is available in Tomcat● We need to create a reference to the configured JNDI

resource in the web deployment descriptor web.xml

<resource-ref><res-ref-name>jdbc/bovoyage</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth>

</resource-ref>

antislashn.org Tomcat and Apache httpd - Connectiong databases 16 / 16

Accessing the JNDI DataSource

● JNDI● the name specified is relative to the root naming context,

which is define as java:comp/env● the name of the resource is jdbc/bovoyage● the full JNDI name of the resource will bejava:comp/env/jdbc/bovoyage

Context contexteJndi = new InitialContext();DataSource dataSource = (DataSource) contexteJndi.lookup("java:comp/env/jdbc/bovoyage");

Security with Tomcat

version 1.1

antislashn.org Tomcat and Apache httpd - Security with Tomcat 2 / 38

Security Realms

● Mechanism for protecting web application resources.● a resource is protected with a defined security constraint

– user role that can access to the resource

● Tomcat's realm is● collection of user names and passwords● collection of roles associated with each user

antislashn.org Tomcat and Apache httpd - Security with Tomcat 3 / 38

● Realm available in Tomcat● MemoryRealm : simple implementation that uses an xml

file (tomcat-users.xml)● JDBCRealm : supports storing username, passwords and

roles in a SQL database● JNDIRealm : implementation backed by JNDI

● DataSourceRealm : realm backed by a JNDIconfigured JDBC datasource

● UserDatabaseRealm : realm backed by a custom UserDatabase configured by JNDI

Security Realm

antislashn.org Tomcat and Apache httpd - Security with Tomcat 4 / 38

Security Realm

● Realm available in Tomcat● JaasRealm : authentication using JAAS

– Java Authentication and Authorization Service

● CombinedRealm : realm that allows usage of multiple realm at the same time

● LockOutRealm : extends CombinedRealm, to lock out users if too many incorrect login tries are detected– prevent pure force server attack

antislashn.org Tomcat and Apache httpd - Security with Tomcat 5 / 38

MemoryRealm

● The simplest realm available in Tomcat● uses an in-memory database which is read from an XML

file– on server startup

<tomcat-users><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" />

</tomcat-users>

antislashn.org Tomcat and Apache httpd - Security with Tomcat 6 / 38

MemoryRealm

● Protected a resource with a MemoryRealm● enable MemoryRealm in the conf/server.xml file

● in Engine, Host or Context element● Engine : for all the web applications● Host : for all the web applications within that host● Context : only this web application

● configure the application to use the configured MemoryRealm● in the web.xml

● add a security constraint● define a login mechanism● declare the roles used by the security constraint

<Realm className="org.apache.catalina.realm.MemoryRealm" />

antislashn.org Tomcat and Apache httpd - Security with Tomcat 7 / 38

MemoryRealm

● Configure the application● add the security constraint in the web.xml file

<security-constraint> <web-resource-collection> <web-resource-name>Administration</web-resource-name> <description>Exemple de sécurisation de ressources WEB</description> <url-pattern>/admin/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> </security-constraint>

antislashn.org Tomcat and Apache httpd - Security with Tomcat 8 / 38

MemoryRealm

● Configure the application● define the login mechanism in the web.xml file

● declare the roles used– in the web.xml file

<login-config> <auth-method>BASIC</auth-method> <realm-name>Site exemple</realm-name> </login-config>

<security-role> <role-name>admin</role-name> </security-role>

antislashn.org Tomcat and Apache httpd - Security with Tomcat 9 / 38

MemoryRealm

● Restart Tomcat to apply the changes● Navigate the browser to the URL

● a login windows is shown in the browser

antislashn.org Tomcat and Apache httpd - Security with Tomcat 10 / 38

Authentication types

● BASIC● client authenticates by entering a username and password● the browser sends the informations in plain text, Base64

encoded

● DIGEST● similarly to BASIC● username and password are digested-encoded using MD5

antislashn.org Tomcat and Apache httpd - Security with Tomcat 11 / 38

Authentication types

● FORM● client authenticates using a HTML form

– input filed names and form action are defined as part of Java Servlet specification

● the sending mechanism are customizable

● CLIENT_CERT● uses SSL (Secure Socket Layer)● client and server have their own SSL certificate● uses a mutual authentication

antislashn.org Tomcat and Apache httpd - Security with Tomcat 12 / 38

LockOutRealm

● Protection against the brute force attacks● the LockOutRealm wraps another realm

<Realm className="org.apache.catalina.realm.LockOutRealm"faiureCount="3" lockoutTime="3600">

<Realm className="org.apache.catalina.realm.MemoryRealm" />

</Realm>

how many failed attempts

how long the user will be lock out (in seconds)

antislashn.org Tomcat and Apache httpd - Security with Tomcat 13 / 38

UserDatabaseRealm

● Advanced version of MemoryRealm● can be configurable via JNDI● that allows clients to lookup objects by the know name● in the server.xml

● and used by the Context

<GlobalNamingResources> <Resource auth="Container" description="User database that can be updated and saved"

factory="org.apache.catalina.users.MemoryUserDatabaseFactory"name="UserDatabase" pathname="conf/tomcat-users.xml"type="org.apache.catalina.UserDatabase"/>

</GlobalNamingResources>

<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>

antislashn.org Tomcat and Apache httpd - Security with Tomcat 14 / 38

● Simple like the MemoryRealm, but the JDBCRealm stores all the informations in a user-defined and JDBC-compliant database● we need two tables

– one for user and password– one for user and role

JDBCRealm

antislashn.org Tomcat and Apache httpd - Security with Tomcat 15 / 38

JDBCRealm

● Add the configuration in server.xml

<JDBCRealm driverName="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost/authority?user=toto;password=totopw"userTable="users" userNameCol="user_name" userCredCol="user_pass"userRoleTable="user_roles" roleNameCol="role_name" />

antislashn.org Tomcat and Apache httpd - Security with Tomcat 16 / 38

DataSourceRealm

● DataSourceRealm is the upgraded version of JDBCRealm● allows configuration of the database connection as the

JNDI resource● similar to UserDataBaseRealm which is a JNDI

configurable version of MemoryRealm

antislashn.org Tomcat and Apache httpd - Security with Tomcat 17 / 38

DataSourceRealm

● Configuring DataSourceRealm in server.xml file

● Configuring DataSourceRealm in the Context

<GlobalNamingResources><Resource name="jdbc/authority" auth="Container"

type="javax.sql.DataSource"maxActive="100" maxIdle="30" maxWait="10000"username="toto"password="totopw"driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://localhost:3306/authenticate" />

</GlobalNamingResources>

<Realm className="org.apache.catalina.realm.DataSourceRealm"dataSourceName="jdbc/authority"userTable="users" userNameCol="user_name" userCredCol="user_pass"userRoleTable="user_roles" roleNameCol="role_name" />

antislashn.org Tomcat and Apache httpd - Security with Tomcat 18 / 38

FORM-Based authentication

● A user request a protected resource● a login form is displayed

– the user can enter a username and password● Tomcat checks the entered details

– if the entered user credentials are match in the realm● user is authenticated

– if the user has the required role the required page is displayed● authorization

– if user does not have the role, an error page is displayed● code 403

antislashn.org Tomcat and Apache httpd - Security with Tomcat 19 / 38

FORM-Based authentication

BASIC authenticate FORM authenticate

source : Oracle

antislashn.org Tomcat and Apache httpd - Security with Tomcat 20 / 38

FORM-Based authentication

● Configuration● create a login page● create an error page● configure web.xml

antislashn.org Tomcat and Apache httpd - Security with Tomcat 21 / 38

FORM-Based authentication

● Login page

<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Login</title>

</head><body><form action="j_security_check" method="POST"><table>

<tr><td>Identifiant : </td><td><input type="text" name="j_username" /></td></tr><tr><td>Mot de passe : </td><td><input type="password" name="j_password" /></td></tr><tr><td colspan="2"><input type="submit" value="ENVOYER" /></td></tr>

</table></form>

</body></html>

Java Servlet specification

antislashn.org Tomcat and Apache httpd - Security with Tomcat 22 / 38

FORM-Based authentication

● Error page

<html><head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Erreur</title>

</head><body>

<h3>Erreur d'authentification</h3></body>

</html>

antislashn.org Tomcat and Apache httpd - Security with Tomcat 23 / 38

FORM-Based authentication

● Configuration in the web.xml file

<login-config><auth-method>FORM</auth-method><form-login-config>

<form-login-page>/auth/login.jsp</form-login-page><form-error-page>/auth/erreur.jsp</form-error-page>

</form-login-config></login-config>

antislashn.org Tomcat and Apache httpd - Security with Tomcat 24 / 38

DIGEST authenticate

● UserDataBaseRealm can be configure to use DIGEST authenticate● of course, the others realms can be secure in the same

way● we need to

– select the DIGEST algorithm● in the server.xml file

– create the DIGEST password– add this password to the Realm

● here the tomcat-users.xml file

– configure the login-config● in the web.xml file

antislashn.org Tomcat and Apache httpd - Security with Tomcat 25 / 38

DIGEST authenticate

● Select the DIGEST algorithm● in server.xml file

● Create the DIGEST password● Java supports two digest algorithm

– MD5 and SHA● "totopw" is the textplain password

<Realm className="org.apache.catalina.realm.UserDatabaseRealm"resourceName="UserDatabase" digest="sha"/>

digest -a sha totopwtotopw:557860fea134517d63080a07c1d507c9dde15621

antislashn.org Tomcat and Apache httpd - Security with Tomcat 26 / 38

DIGEST authenticate

● Add this password to the Realm● tomcat-users.xml file

– old file

– now

● Configure the login-config● web.xml file

<tomcat-users><role rolename="admin" /><user username="toto" password="totopw" roles="admin" />

</tomcat-users>

<tomcat-users> <role rolename="admin" /> <user username="toto" roles="admin"

password="557860fea134517d63080a07c1d507c9dde15621" /></tomcat-users>

<login-config> <auth-method>DIGEST</auth-method> <realm-name>Site exemple</realm-name> </login-config>

antislashn.org Tomcat and Apache httpd - Security with Tomcat 27 / 38

Securing with SSL

● SSL – Secure Socket Layer● was first developed by Netscape

– more recently the IETF developed TSL – Transport Level Security is based on SSL

● IETF : Internet Engineering Task Force

● guarantee that no one can eavesdrop on or tamper with the communication between a browser and a server

● SSL is a cryptographic protocol– using symmetric pair of keys to encrypt and decrypt traffic

antislashn.org Tomcat and Apache httpd - Security with Tomcat 28 / 38

Securing with SSL

● Symmetric pair of keys● a same key is used for encryption of plaintext and

decryption of ciphertext

encryption decryption

the same key is shared

Alice BobAlice

Chuck

stole the key

?

antislashn.org Tomcat and Apache httpd - Security with Tomcat 29 / 38

Securing with SSL

● Symmetric pair of keys● the algorithms are fast● the algorithms are simple● how to share the key ????

antislashn.org Tomcat and Apache httpd - Security with Tomcat 30 / 38

Securing with SSL

● Asymmetric pair of keys● or public-key cryptography● two separate keys

– one is private● used for decryption

– one is public● used for encryption● this key is shared

● the two keys are generated by a key generation program

antislashn.org Tomcat and Apache httpd - Security with Tomcat 31 / 38

Securing with SSL

encryption decryption

Alice BobAlice

stole the key

?

● Asymmetric pair of keys● the public key is used for encryption of plaintext ● the private key is used for decryption of ciphertext

antislashn.org Tomcat and Apache httpd - Security with Tomcat 32 / 38

Securing with SSL

● Digital certificate● contains keys● a serial number● the owner's name● validity period

● Keystore● contains multiple certificates, keys

antislashn.org Tomcat and Apache httpd - Security with Tomcat 33 / 38

Securing with SSL

Web serverNavigator

hello

symmetric keygeneration

encryption decryption

all the messages usea symmetric encryption

decryptionencryption

decryptionencryption

antislashn.org Tomcat and Apache httpd - Security with Tomcat 34 / 38

Securing with SSL

● Configuring Tomcat with SSL● create our own certificate

– self-signed certificate● it will not be verified with an independent CA (Certificate Authority)

– the certificates are stored in a repository called keystore● configuring Tomcat's SSL connector● configuring resources in web application

– forcing Tomcat send resources over SSL

antislashn.org Tomcat and Apache httpd - Security with Tomcat 35 / 38

Securing with SSL

● Create a self-signed certificate● use keytool

– JAVA_HOME/bin–

● enter the required details

keytool -genkeypair -alias tomcat -keylag RSA -keystore <TOMCAT_HOME>/conf/tomcat.keystore

keystore

certificate 1

certificate 2

certificate n

tomcat.keystore filewith its is own password

each certificate has an alias and a password

antislashn.org Tomcat and Apache httpd - Security with Tomcat 36 / 38

Securing with SSL

● Configuring Tomcat's SSL connector● in server.xml file

<Connector port="8443" protocol="HTTP/1.1"SSLEnabled="true"maxThreads="150" scheme="https" secure="true"clientAuth="false"sslProtocol="TLS"keystoreFile="conf/tomcat.keystore"keystorePass="azerty"keyAlias="tomcat"keyPass="abc123" />

used by HttpServletRequest.isSecure()

no use of CLIENT_CERT

antislashn.org Tomcat and Apache httpd - Security with Tomcat 37 / 38

Securing with SSL

● Configuring resources in web application● in the web.xml

<security-constraint> <web-resource-collection> <web-resource-name>Administration</web-resource-name> <url-pattern>/admin/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>admin</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>

<Connector connectionTimeout="20000" port="8080"protocol="HTTP/1.1"redirectPort="8443" />

server.xml

antislashn.org Tomcat and Apache httpd - Security with Tomcat 38 / 38

Securing with SSL

● Try the URL … and accept the security alert

JMXJava Management eXtension

version 1.1

antislashn.org Tomcat and Apache httpd - JMX 2 / 16

JMX overview

● Java Management eXtension● specification add in Java 5● used to manage servers, applications, JVM

● JMX architecture● three levels

– instrumentation● MBean probe object

– agent– distributed services

antislashn.org Tomcat and Apache httpd - JMX 3 / 16

JMX overview

antislashn.org Tomcat and Apache httpd - JMX 4 / 16

JMX overview

client level

Services :●Timers●Notification

Connectors and adapters

MBean server

JMX agent

instrumentation MBeanMBean

MBean

JMX client

antislashn.org Tomcat and Apache httpd - JMX 5 / 16

JMX overview

● MBeans are software modules● expose the capabilities of a hardware device or software

component● different types of MBean

– Standard MBean● only this one will be discussed here

– Dynamic MBean– Model MBean– Open MBean– MXBean

antislashn.org Tomcat and Apache httpd - JMX 6 / 16

JMX – Standard MBean

● Simple● an Java interface

– same name than implementationclass suffixed with MBean

– getter → read property– setter → write property

● an Java implementation class

antislashn.org Tomcat and Apache httpd - JMX 7 / 16

JMX – Standard MBean

● The MBean is identified by its unique name● ObjectName class● two parts

– domain– properties– both separate by a colon character

jboss.deployment:flavor=URL,type=DeploymentScanner

antislashn.org Tomcat and Apache httpd - JMX 8 / 16

JMX – Standard MBean

● Java interfacepublic interface HelloMBean {

// propertiesString getName();String getColor();void setColor(String color);

// operationsvoid sayHello();double add(double a, double b);

}

antislashn.org Tomcat and Apache httpd - JMX 9 / 16

JMX – Standard MBean

● Java implementation classpublic class Hello implements HelloMBean {

private String name ="Toto Standard MBean";private String color = "vert";

@Override public String getName() {return name;

}

@Override public String getColor() {return color;

}

@Override public void setColor(String color) {this.color = color;

}

@Override public void sayHello() {System.out.println(">>> Standard MBean "+name+" - "+color);

}

@Override public double add(double a, double b) {return a+b;

}}

antislashn.org Tomcat and Apache httpd - JMX 10 / 16

JMX – Standard MBean

● Agent level - main steps● recovering a MBean server

● instantiating an ObejctName

● recording the MBean in the server

MBeanServer mbs = ManagementFactory.getPlatformMBeanServercreating();

ObjectName mBeanName = new ObjectName("antislashn.jmx:bean=Hello,type=standard");

HelloMBean mBean = new Hello();mbs.registerMBean(mBean, mBeanName);

antislashn.org Tomcat and Apache httpd - JMX 11 / 16

JMX – Standard MBean

● For securing reasons, we need to activate the JMX access● -Dcom.sun.management.jmxremote● other properties could be defined

– mandatory if remote JMX access– see the password template file in <JRE_HOME>/lib/management

java -Dcom.sun.management.jmxremote.port=3333-Dcom.sun.management.jmxremote.ssl=false-Dcom.sun.management.jmxremote.authenticate=falseMonAppliJava

antislashn.org Tomcat and Apache httpd - JMX 12 / 16

JMX – Standard MBean

● We can now use jconsole or jvisualvm

antislashn.org Tomcat and Apache httpd - JMX 13 / 16

Tomcat and JMX

● Working with the JMX proxy● add the role manager-jmx● the URL for accessing the JMX proxy is as follow

– http://<host>:<port>/manager/jmxproxy/<operation details>– example

● http://localhost:8080/manager/jmxproxy/list

antislashn.org Tomcat and Apache httpd - JMX 14 / 16

Tomcat and JMX

● Using jconsole to monitor Tomcat● we must enable the JMX support inside Tomcat

– add a file called● setenv.sh in Linux● setenv.bat in Windows

– with the following line

● restart Tomcat

set CATALINA_OPTS=-Dcom.sun.management.jmxremote

antislashn.org Tomcat and Apache httpd - JMX 15 / 16

Tomcat and JMX

● Start jconsole

antislashn.org Tomcat and Apache httpd - JMX 16 / 16

Tomcat and JMX

● Go to the mbeans tab

Configuring Apache httpd

version 1.1

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 2 / 12

Configuration files

● Main configuration file● usually called httpd.conf

– <apache_home>/conf/httpd.conf in Windows– /etc/httpd/conf/httpd.conf in CentOS– /etc/apache2/httpd.conf in Unbuntu

● the file references the modules folder– enabled directory

● other configuration files can be added with using the Include directive

● MIME document types are defined in mime.type file● .htaccess file contains directives for one web site

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 3 / 12

Configuration files

● Directives placed in httpd.conf file apply to the entire server

● To change the configuration for only a part of the server● placing the directives in one of the following sections

– Directory, DirectoryMatch– Files, FilesMatch– Location, LocationMatch– VirtualHost

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 4 / 12

Configuration

● Syntax● one directive per line

– backslash "\" must be used as the last character on one line to indicate that the directive continue onto the next line

– some directives are block directives

● hash "#" on the begin of a line indicates a comment– comments may not be included on a line after a directive

● directives are case-sensitive

<Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all</Directory>

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 5 / 12

Configuration

● Terms used to describe directives● description● syntax● default● context

– server configuration : the directive may be used only in httpd.conf– virtual host– directory : the directive may be used inside <Directory>, <Location>, <Files> and <Proxy>

– .htaccess

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 6 / 12

Configuration

● Terms used to describe directives● status

– core : the directive is part of the server– MPM : Multi-Processing Module– base : standards Apache module– extension : modules included with Apache, but not enabled– experimental

● module● compatibility● comments

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 7 / 12

Configuration

● Examples

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 8 / 12

Configuration

● Binding to listen on a specific addresses and port● Listen directive

– default – examples

● Modules● extended feature are available through modules● a module can be loaded by the LoadModule directive

Listen 80

Listen 90 Listen 192.168.0.45:80

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 9 / 12

Default web site

● The default web site● DocumentRoot directive

● if DocumentRoot changed, you need to change the <Directory ...> directive to the same directory

DocumentRoot "/opt/www/"

<Directory "/opt/www/">

Options Indexes FollowSymLinks

AllowOverride None

Order allow,deny Allow from all

</Directory>

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 10 / 12

Default resource

● DirectoryIndex● set the list of resources to look for when the client request

a default one– http://www.example.com/

● if none of the resources exist and Indexes option is set, the server will generate its own listing of the directory– see the Options directives

DirectoryIndex index.html index.php

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 11 / 12

Log files

● Default location● CentOS : /var/log/httpd

● ErrorLog directive● LogLevel directive

– debug, info, notice, warn, error, crit, alert, emerg● default : warn

● LogFormat directive defines format nicknameLogFormat "%h %l %u %t \"%r\" %>s %b" common

antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 12 / 12

Log files

● Server error log is the most important log file● Other logs use CustomLog directive

● or TransferLog directive– does not allow the log format to specified– uses the mots recently defined LogFormat

● access log configuration

CustomLog logs/access_log combined

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

::1 - - [20/Nov/2013:03:41:22 -0800] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20131029 Firefox/17.0"

Apache httpdVirtual host

version 1.0

antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 2 / 6

Virtual host overview

● Practice of running more than web site on a single machine● can be

– IP-based● an IP address per web site

– name-based● more than web site per IP address

antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 3 / 6

Name-based virtual hosts

● You must have DNS entries● use hosts file

– /etc/hosts in CentOS

– C:\Windows\System32\drivers\etc\hosts in Windows

127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4::1 localhost localhost.localdomain localhost6 localhost6.localdomain6

127.0.0.1 localhost toto.exemple::1 localhost toto.exemple

antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 4 / 6

Name-based virtual hosts

NameVirtualHost *:80

<VirtualHost *:80>DocumentRoot /www/example1ServerName www.toto.exempleServerAlias www.toto.example toto.example

</VirtualHost>

<VirtualHost *:80>DocumentRoot /www/example2ServerName www.example.org

</VirtualHost>

antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 5 / 6

IP-based virtual hosts

● the server has two IP addresses

● on one (172.20.30.40) we will serve the "main" (server.domain.com)

● on the other (172.20.30.50) we will serve two or more virtual hosts

Listen 80

# This is the "main" server running on 172.20.30.40ServerName server.domain.comDocumentRoot /www/mainserver

# This is the other addressNameVirtualHost 172.20.30.50

<VirtualHost 172.20.30.50>DocumentRoot /www/example1ServerName www.example.com

# Other directives here ...

</VirtualHost>

<VirtualHost 172.20.30.50>DocumentRoot /www/example2ServerName www.example.org

# Other directives here ...

</VirtualHost>

antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 6 / 6

IP-based virtual hosts

<VirtualHost 192.168.0.1:80>ServerAdmin webmaster@smallco.example.comDocumentRoot /groups/smallco/wwwServerName smallco.example.comErrorLog /groups/smallco/logs/error_logTransferLog /groups/smallco/logs/access_log

</VirtualHost>

<VirtualHost 192.168.0.2:80>ServerAdmin webmaster@baygroup.example.orgDocumentRoot /groups/baygroup/wwwServerName baygroup.example.comErrorLog /groups/baygroup/logs/error_logTransferLog /groups/baygroup/logs/access_log

</VirtualHost>

Apache httpdSecurity

version 1.1

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 2 / 31

Security tips

● Keep up to date● Permissions an ServerRoot directories

● Apache is started by the root user● it switches to the user defines by the User directive to serve

hits– in httpd.conf

● Beware of SSI, CGI, aliases● Watching your logs

User apacheGroup apache

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 3 / 31

Options directive

● Controls which server features are available in a particular directory● Syntax

● option can be set to● None : none of the extra features are enabled● All : all options except for MultiView is permitted● ExecCGI : execution of CGI scripts is permitted

– cf. mod_cgi module

● FollowSymLinks : the server will follow symbolic links

Options [+|-] option [[+|-] option] ...

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 4 / 31

Options directive

● option can be set to● Include : server-side includes (SSI) are permitted

– cf. mod_include module

● IncludeNOEXEC : SSI is permitted but CGI are disabled● Indexes : if no default resource match with

DirectoryIndexe, the server will return a formatted listing of the directory– cf. mod_include module

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 5 / 31

Options directive

● option can be set to● MultiViews : content negotiated is allowed

– cf. mod_negotiation module– the server can choose the best presentation of a resource based

on the browsed-supplied preferences● language, encoding, charset

● SymLinksIsOwnerMatch : server only follows symbolic links if the target resource is owned by the same user as the link

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 6 / 31

Allow directive

● Affects which hosts can access resources● access can be controlled by

– hostname– IP address, IP range address– other characteristics of the client request captured in the

environment variables● syntax

Allow from all|host|env=[!]env-variable [host|env=[!]env-variable] ...

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 7 / 31

Allow directive

● The first argument is always from

Allow from allall hosts are allowed access (subject to the configuration of the Deny and Order directives)

Allow from example.orgAllow from .com toto.net

hosts whose name match, or end in, with the string areallowed accessthis configuration will cause Apache to perform a double DNSlookup per client access

Allow from 10.1.2.3Allow from 192.168.1.104 192.168.1.205 an IP address of a host allowed access

Allow from 10.1Allow from 10 172.20 192.168.2 the first 1 to 3 bytes of an IP address

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 8 / 31

Allow directive

● Examples

Allow from 10.1.10.0.0/255.255.0.0 a network a.b.c.d and a netmask w.x.y.z

Allow from 2001::db8::a00::20ff::fea7::ccea IP v6 addresses

SetEnvIf User-Agent ^KnockKnock/2\.0 let_me_in<Directory /docroot>

Order Deny,AllowDeny from allAllow from env=let_me_in

</Directory>

browsers with a user-agent string beginning with KnockKnock/2.0 will be allowed to accessall others will be denied

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 9 / 31

Deny Directive

● This directive allows access to the server to be restricted on hostname, IP address or environment variable● the arguments for the Deny directive are identical to the

arguments for the Allow directive

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 10 / 31

Order Directive

● This directive, along with the Allow and Deny directives, controls a three pass access control● first pass processes all Allow and Deny directives

– as specified by the Order directives

● second pass parses the rest of the directives (Deny or Allow)

● third pass applies to all request which do not match either the first two

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 11 / 31

Order Directive

● Ordering is one of :● no whitespace is allowed between keywords

Allow,Deny First all Allow directives are evaluated, at least one must match, or the request is rejected

Next all Deny directives are evaluated, if any match the request is rejected

Last any request which not match an Allow or Deny are denied by default

Deny,Allow First all Deny directives are evaluated, if any match, the request is denied unless it also matches an Allow directives

All request which do not match any Allow or Deny directives are permitted

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 12 / 31

Order directive

● Summary

Match Allow,Deny result Deny,Allow result

match Allow only request allowed request allowed

match Deny only request denied request denied

no match default to second directive : DENIED

default to second directive : ALLOWED

match both Allow and Deny final match controls : DENIED final match controls : ALLOWED

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 13 / 31

Order directive

● Examples

Order Allow,DenyAllow from example.comDeny from foo.example.com

all hosts in the example.com domain are allowed access, except the hosts which are in foo.example.com subdomainall hosts not in the example.com domain are denied access

Order Deny,AllowDeny from allAllow from example.com

all hosts in example.com domain are allowed accessall other hosts are denied access

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 14 / 31

Authentication

● Authentication is simple● client sends his name and password● server looks up of names and passwords

● It is also possible to group a number of people into named groups

● Each username-password pair is valid for a particular realm

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 15 / 31

Authentication

● The browser asks for an URL● The server sends back "Authentication Required" and

the realm● code 401

● If the browser already has a username-password for that realm, it sends the request again with the username-password● if not, it prompts the user and sends that

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 16 / 31

Authentication

web site

realm (AuthName directive)

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 17 / 31

Authentication

● Two authentication type● see the AuthType directive● Basic

– mod_auth_basic module

● Digest – mod_auth_digest module

● Based on two fundamental informations● authentication provider

– AuthDigestProvider, AuthBasicProvider directives

● authorization– Require directive

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 18 / 31

Authentication

● Example

● AuthName : name of the realm● AuthType : Basic or Digest● AuthUserFile : passwords file● Required : group, user or valid-user

<Directory d:/www/autorise>AuthName "Royaume secret"AuthType Basicrequire valid-userAuthUserFile D:/passwords

</Directory>

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 19 / 31

Authenticate

● <Limit> directive● access controls are normally effective for all HTTP

methods● this directive restricts the access of the access control to

the nominated HTTP methods

● see also <LimitExcept> directive

<Limit POST PUT DELETE>Require valid-user

</Limit>

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 20 / 31

Basic authentication

● AuthType Basic directive● client authenticates by entering a username and password● the browser sends the informations in plain-text, Base64

encoded

● Steps● create a password file● configure the server to request a password and tell the

server which user are allowed access● optional : create a group-users file

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 21 / 31

Basic authentication

● Create the password file● the file is placed somewhere not accessible from the web● use the htpasswd utility that came with Apache

– in CentOs : /usr/bin directory– in Ubuntu : /usr/local/apache2/bin

● see htpasswd documentation– http://httpd.apache.org/docs/2.2/programs/htpasswd.html

htpasswd [ -c ] [ -m ] [ -D ] passwdfile username

htpasswd -b [ -c ] [ -m | -d | -p | -s ] [ -D ] passwdfile username password

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 22 / 31

Basic authentication

● Create the group file● simple text-plain● each line of group contains a groupname followed by the

list of user groups–

● Configure the server

<Directory d:/www/autorise>AuthName "Royaume secret"AuthType Basicrequire group chefAuthUserFile D:/htpasswdAuthGroupFile D:/htgroup

</Directory>

mygroup: bob joe anne

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 23 / 31

Basic authenticate

● Require directive● selects which authenticated users can access a resource

– only the name users can access the resource–

– only users in the named groups can access the resource–

– all valid users can access the resource

Require user userid [userid] ...

Require group group-name [group-name] ...

Require valid-user

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 24 / 31

Digest authenticate

● Use MD5 digest authentication● Similar steps as Basic authentication

● use the mod_auth_digest module● AuthType Digest directive● used the htdigest utility

htdigest [ -c ] passwdfile realm username

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 25 / 31

Digest authenticate

● Example

<Directory d:/www/autorise>AuthName "Royaume"AuthType Digestrequire valid-userAuthDigestFile D:\dgpwd

</Directory>

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 26 / 31

Satisfy directive

● This directive is useful if access to a particular area is being restricted by both username-password and client host address● syntax

<Directory d:/www/autorise>allow from 192.168.1AuthName "Royaume secret"AuthType Basicrequire valid-user

AuthBasicProvider fileAuthUserFile D:/htpasswdSatisfy Any

</Directory>

Satisfy Any | All

users on the network have unrestricted accessbut require users outside provide a password

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 27 / 31

Authentication

● The AuthDigestProvider and AuthBasicProvider directive set which provider is used to authenticate the users● default :

– AuthDigestProvider file– AuthBasicProvider file

● other providers– dbm : use DBM file, see mod_authn_dbm module

– dbd : use SQL queries, see mod_authn_dbd module

– ldap : use LDAP, see mod_authnz_ldap module

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 28 / 31

Apache HTTPS in CentOS

● Create a self-signed certificate● if not installed, install mod_ssl

● create a new directory for the certificate files

● create a self-signed certificate

yum install mod_ssl

mkdir /etc/httpd/ssl

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/httpd/ssl/apache.key-out /etc/httpd/ssl/apache.crt

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 29 / 31

Apache HTTPS in CentOS

● The command openssl will prompt terminal to display a lists of field that need to be filled in● the mots important is "Common Name"

– enter the domain name, or the site's IP address

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 30 / 31

Apache HTTPS in CentOS

● In the httpd.conf file● uncomment the line for loading the mod_ssl module

● add a Listen 443 directive● configure the secure web site

● restart Apache httpd

LoadModule ssl_module modules/mod_ssl.so

<VirtualHost *:443> DocumentRoot "/var/www/secur" SSLEngine on SSLCertificateFile /etc/httpd/sslapache.crt SSLCertificateKeyFile /etc/httpd/sslapache.key</VirtualHost>

/etc/init.d/httpd restart

antislashn.org Tomcat and Apache httpd - Security with Apache httpd 31 / 31

Apache HTTPS in CentOS

● Test the secure site● https://localhost/● the navigator protests because it is a self-signed certificate

– the certificate is not validated with any third party– you have to import it in the browser

Tomcat cluster with mod_jk

version 1.1

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 2 / 19

Overview

● It is possible to closely integrate Apache httpd and Tomcat● Apache web server is optimized for high-performance

content serving– static content

● Tomcat only serves the dynamic content● mod_jk module is also a load balancer

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 3 / 19

Overview

● mod_jk

Apache

staticcontent

Tomcat

connector

800980

request dynamiccontent

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 4 / 19

Overview

● Load balancing with mod_jk

Apache

Tomcat

AJPconnector

80request

Tomcat

AJPconnector

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 5 / 19

mod_jk download on Windows

● Download from the Tomcat web site● follow the "Tomcat connectors" link

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 6 / 19

mod_jk download on Windows

● follow the "Binary Releases" link

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 7 / 19

mod_jk installation on CentOS

● Unfortunately there is no more binaries for Linux● we have to

– download the mod-jk source– prepare the compilation– compile and install the module

● Download the mod_jk source

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 8 / 19

mod_jk installation on CentOS

● Prepare the installation● install compilers

● extract files

● Compile and install

yum install -y httpd-devel gcc gcc-c++ make libtool

tar -xf tomcat-connectors-1.2.37-src.tar.gz

cd tomcat-connectors-1.2.37-src/native/./configure --with-apxs=/usr/sbin/apxsmakelibtool --finish /usr/lib64/httpd/modulesmake install

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 9 / 19

Configuration files

● Two files will be created● a configuration file for the mod_jk Apache module

– named mod_jk.conf● in the Apache configuration directory

● a mod_jk configuration file– which describes the cluster nodes

● the workers

– named worker.properties

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 10 / 19

mod_jk.conf file

● Minimal configuration

LoadModule jk_module modules/mod_jk.soJkWorkersFile conf/workers.properties

JkLogFile logs/mod_jk.log

# Set the jk log level [debug/error/info]JkLogLevel info

# Select the timestamp log formatJkLogStampFormat "[%a %b %d %H:%M:%S %Y] "

JkMount /jmx-console/* worker1

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 11 / 19

mod_jk.conf file

● JkWorkerFiles● name of a worker file for the Tomcat servlet container

● JkMount● a mount point for a context to a Tomcat worker

● JkUnMount● an exclusion mount point for a context to a Tomcat worker

● see the reference guide● http://tomcat.apache.org/connectors-doc/reference/workers.html

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 12 / 19

mod_jk.conf file

● Example

# send all the request ended by /servlet to workers1JkMount /servlet/* worker1# the requests for gif resources will not send to worker1JkUnMount /var/www/my_appli/images /servlet/*.gif

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 13 / 19

workers.properties file

● Here, only one worker is declared

● Set up the configuration● in the httpd.conf file

● restart Apache web server● check the URL : http://localhost/jmx-console/

worker.list=worker1

# Set properties for worker1 (ajp13)worker.worker1.type=ajp13worker.worker1.host=localhostworker.worker1.port=8009

Include conf/mod_jk.conf

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 14 / 19

High availability

source : Wikipedia

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 15 / 19

Load Balancing

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 16 / 19

Load Balancing

● In production environment, the amount of requests requires multiple application servers running● all the requests can be handled in timely manner● it is a safety potion if one of the server crashes● it is necessary to manage session affinity

– for HTTP sessions

● Here we use two Tomcat instances● we have to change the port number if th two instances are

in th same machine

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 17 / 19

Load balancing – mod_jk configuration# Define list of workers that will be used# for mapping requestsworker.list=loadbalancer

# Define Node1# modify the host as your host IP or DNS name.worker.noeud1.port=8109worker.noeud1.host=127.0.0.1worker.noeud1.type=ajp13worker.noeud1.lbfactor=1

# Define Node2# modify the host as your host IP or DNS name.worker.noeud2.port=8209worker.noeud2.host= 127.0.0.1worker.noeud2.type=ajp13worker.noeud2.lbfactor=1

# Load-balancing behaviourworker.loadbalancer.type=lbworker.loadbalancer.balance_workers=noeud1,noeud2worker.loadbalancer.sticky_session=1

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 18 / 19

Session affinity

● sticky_session property tells the load balancer to keep requests belonging to the same session forwarded to the same worker● one session = one user

● Session replication is another strategy for dealing with user sessions● useful when a server crashes● add a jvmRoute attribute in each Tomcat, with the

appropriate worker<Engine name="jboss.web" defaultHost="localhost" jvmRoute="noeud1">

antislashn.org Tomcat and Apache httpd - Tomcat cluster with mod_jk 19 / 19

Web application

● Web applications need to be marked as distributable● in the WEB-INF/web.xml file

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<distributable /> ...

antislashn.org Tomcat and Apache httpd - copyleft 1 / 3

Bibliography

● Web● http://httpd.apache.org/docs/2.2/en/● http://tomcat.apache.org/tomcat-7.0-doc/index.html● http://tomcat.apache.org/connectors-doc/

● Books● Tomcat 7 – Apress

● Aleska Vukotic and James Goodwill● Professional Apache Tomcat 6 – Wrox

● Vivek Chopra, Sing Li and Jeff Genender

antislashn.org Tomcat and Apache httpd - copyleft 2 / 3

copyleft

Support de formation créé par

Franck SIMON

http://www.franck-simon.com

antislashn.org Tomcat and Apache httpd - copyleft 3 / 3

copyleft

Cette œuvre est mise à disposition sous licence Attribution

Pas d'Utilisation Commerciale

Partage dans les Mêmes Conditions 3.0 France.

Pour voir une copie de cette licence, visitez http://creativecommons.org/licenses/by-nc-sa/3.0/fr/

ou écrivez à

Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.

Installing ARP component

version 1.1

antislashn.org Tomcat and Apache httpd - APR component 2 / 5

Installing APR component

● Optional component● catalina.log :

● Apache Portable Runtime● this library improves stability and performance when

Tomcat is connect to a native web server like Apache http

INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on

antislashn.org Tomcat and Apache httpd - APR component 3 / 5

Installing APR component

● Install APR using the following steps● in root mode

● if autoconf is missing– dowload autoconf at : ftp://ftp.gnu.org/gnu/autoconf– install autoconf

tar zxvf apr-1.4.8.tar.gzcd apr-1.4.8./buildconf./configuremake install

tar zxvf autoconf-2.59.tar.gzcd autoconf-2.59makemake install

antislashn.org Tomcat and Apache httpd - APR component 4 / 5

Installing APR component

● For using APR component, we need to install the APR JNI wrapper● JNI : Java Native Interface● wrapper sources are packaged as a file in the bin directory

– tomcat-native.tar.gz● if you don't need OpenSSL support

– use --without-ssl option– otherwise you can download OpenSSL at www.openssl.org

antislashn.org Tomcat and Apache httpd - APR component 5 / 5

Installing APR component

● Installation steps

● After installing add the APR directory

tar zxvf tomcat-native.tar.gzcd tomcat-native/jni/native./configure --without-sslmake install

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/apr/lib