Tomcat and Apache httpd
Objectives

version 1.1
Objectives
●

install Java, Tomcat, Apache httpd

●

configure Tomcat

●

build and monitor database connection pools

●

...
Chapters
0.Objectives
1.Java EE introduction
2.Installations
3.Configuring Tomcat
4.Servlet and JSP overview
5.Tomcat valv...
Chapters
8.Memory Management and JMX
9.Virtual host with Apache httpd
10.Security with Apache
11.Tomcat cluster with mod_j...
Introduction

version 1.1
Architecture
What we want !!!
Tomcat

internet

Apache
httpd
server
mod_jk
load balancer

Tomcat

Tomcat

static
resources...
The evolution of the web
●

1989 – the birth of the web
●
●

●

Tim Berners-Lee
distributed information system for CERN ph...
The evolution of the web
●

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

antislashn.org

Tomcat and Apache httpd - Introdu...
Web server
●

Primary function : to deliver web pages to clients
●

●

HTTP : communication protocol between client and se...
Web server
●

Market share
Product

Vendor

May 2013

Percent

Apache httpd

Apache

359 441 468

53.42 %

IIS

Microsoft
...
HTTP
●

Hypertext Transfert Protocol
●

request – response protocol
–
–

the client submits an HTTP request to the server
...
HTTP
●

Stateless protocol
●

the server does not retain information about each user

●

web applications implement server...
HTTP
●

Conversation sample
●

client request

●

server response

antislashn.org

Tomcat and Apache httpd - Introduction
...
HTTP
●

Request methods
●

GET : requests a resource

●

HEAD : like GET request but without the response body

●

POST : ...
HTTP
●

HTTP methods (continuation)
●

TRACE : echoes back the received request
–

●

●

OPTIONS : returns the HTTP method...
HTTP
●

●

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

GET

●

POST

●

PUT

●

...
HTTP
●

HTTP response status codes
●

1xx : informational

●

2xx : success
–

●

3xx : redirection
–
–

●

301 Moved perm...
HTTP
●

HTTP authentications
●

BASIC access authentication
–

the username and password are combined into a string
●

–
●...
Java evolution
●

Language issued from a Sun project
●
●

named “Stealth” and supervised by Patrick Naugthon

●

●

1990
J...
Java evolution
●

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

●

JDK 1.1 – 1997 (19 of February) : 503 cla...
Java acronyms
●

JRE : Java Runtime Environment

●

JDK : Java Development Kit

●

JVM : Java Virtual Machine

●

Java SE ...
Java acronyms
●

JSR : Java Specification Request
●

●

JCP : Java Community Process
●

●

consortium which manage the Jav...
Java platforms
●

Java SE
●

standalone applications

●

executed when launching the JVM
–

●

Java EE
●

●

java tool

th...
Development cycle
●

Simple view of development cycle
source Java code
file Toto.java

compilation with
javac tool

Java b...
Java EE overview

source : Oracle

antislashn.org

Tomcat and Apache httpd - Introduction

21 / 37
Java EE overview
●

Java EE defines
●

an architecture for implementing services as multitier
applications
–
–
–

scalabil...
Java EE overview
●

Java EE components
●

clients
–

web clients (or thin client)
●

–

application clients
●

antislashn....
Java EE overview
●

Web components
●

JSP and servlets

source : Oracle

antislashn.org

Tomcat and Apache httpd - Introdu...
Java EE overview
●

Business components

Enterprise
Information
System

source : Oracle

antislashn.org

Tomcat and Apache...
Java EE overview
●

Java EE containers
●

container services, provides :
–

JNDI – Java Naming and Directory Interface
●

...
Java EE overview
●

Container types

source : Oracle

antislashn.org

Tomcat and Apache httpd - Introduction

27 / 37
Java EE overview
●

Packaging application
●

application is delivered in a Java Archive (JAR) file
–
–

WAR : Web Archive
...
Java EE overview
●

Java EE 6 APIs

source : Oracle

antislashn.org

Tomcat and Apache httpd - Introduction

29 / 37
Java EE overview
●

Profiles
●

configurations of the Java EE platform targeted at specific
classes of applications
–
–

a...
Java EE overview
●

Web Profile includes EJB Lite
●

not the full EJB API

antislashn.org

Tomcat and Apache httpd - Intro...
Tomcat overview
●

Open source server
●
●

●

Java based web application container
run servlet and JPS

Major versions on ...
Architecture of Tomcat
Server
Service
port 8080

Connector
HTTP

Engine

port 8443

Connector
HTTPS

Host
Context

port 80...
Architecture of Tomcat
●

Tomcat instance is the top-level component
●

only one instance per JVM
–

●

multiple instances...
Architecture of Tomcat
●

<Server> represents the entire Catalina server
engine
●
●

●

Catalina is the Java servlet conta...
Architecture of Tomcat
●

●

<Engine> handles all requests received by the
connectors
<Host> defines virtual hosts
●
●

●
...
Tomcat overview
●

Tomcat is not
●

a Web Profile server

●

a httpd server
–

●

Tomcat is
●

●

Apache httpd is better

...
Installation
Java – Tomcat – Apache httpd

version 1.0
Installing Java
●

Installing Java on CentOS 6.4
●

download Sun/Oracle Java JDK
–

–
●

http://www.oracle.com/technetwork...
Installing Java
●

Installing Java on CentOS 6.4 (continuation)
●

setup JAVA_HOME
–

add JAVA_HOME in /etc/profile
export...
Installing Tomcat
●

Download Tomcat distribution
●

http://tomcat.apache.org/download-70.cgi

●

download the code distri...
Installing Tomcat
●

After downloaded, validate the distribution
●

each distribution had a PGP signature and a MD5
checks...
Installing Tomcat
●

Setup CATALINA_HOME
●

add CATALINA_HOME in /etc/profile
–

you need to be root
export CATALINA_HOME=...
Installing Tomcat
●

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

●

verifying the good installation
●
...
Installing Tomcat
●

Stopping Tomcat
cd /opt/apache-tomcat-7.0.47/bin/
./shutdown.sh

antislashn.org

Tomcat and Apache ht...
Tomcat directories

antislashn.org

Tomcat and Apache httpd - Installation

9 / 16
Tomcat directories
●

●

bin : contains the scripts for starting and stopping
Tomcat
conf : contains the configuration fil...
Tomcat directories
●

lib : contains jar files used by Tomcat

●

logs : contains server logs

●

webapps : contains web a...
Installing Apache httpd
●

Apache httpd server is installed with CentOS by
default
●

if you need to install Apache httpd
...
Installing Apache httpd
●

Stopping Apache httpd
●

as root user
/etc/init.d/httpd stop

or
apachectl stop
●

Setting the ...
Installing Apache httpd
●

Testing Apache httpd
●

open http://localhost

antislashn.org

Tomcat and Apache httpd - Instal...
Installing Apache httpd
●

Configuration file
●

●

/etc/http/conf/httpd.conf

Configure a new default web site
●

create ...
Installing Apache httpd
●

From the httpd.conf file
...
# DocumentRoot: The directory out of which you will serve your
# d...
Tomcat
architecture and configuration

version 1.0
Architecture overview
●

Tomcat consists of a nested hierarchy of components
Server
Service
connector
connector

Engine

L...
Architecture overview
●

Server
●

the server is Tomcat itself
–

it owns a port used for shut down the server
<Server por...
Architecture overview
●

Service
●
●

contains one or more Connectors

●

●

contains a single container Engine
the servic...
Architecture overview
●

Engine
●

●

●

it is a request-processing component thats represents the
Catalina Servlet engine...
Architecture overview
●

Valves
●

enable Tomcat to intercept a request and preprocess
–

like filter of Servlet Specifica...
Architecture overview
●

Loggers
●

●

report on the internal state of a component

Host
●

Engine may contains one or mor...
Architecture overview
●

Context
●

this is the web application
–

it becomes parent of servelts and filters
●

●

a web a...
Files in $CATALINA_HOME/conf
●

server.xml
●

main configuration file

●

Tomcat reads this file at startup
–

●

applicat...
Files in $CATALINA_HOME/conf
●

context.xml
●
●

default application context for any web applications
could be contains co...
Files in $CATALINA_HOME/conf
●

web.xml
●
●

provides basic servlet definition and MIME mappings

●

●

default deployment...
Files in $CATALINA_HOME/conf
●

catalina.properties
●
●

●

this file is read at startup
provides for internal packages ac...
<Server> component
●

in server.xml

●

key attributes
●

●

port : TCP port to listen for the command specified by the
sh...
<Server> component
●

key sub-elements
●

<Service>
–

●

<Listener>
–

●

a grouping of Connectors associated with an Eng...
<Service> component
●

key attributes
●

className : classe name for the service
–

●

name : name for the service
–

●

o...
Web application configuration
●

A web application consist of
●

static content
–

●

dynamic content
–

●

HTML pages, im...
Web application configuration
●

Web application structure
developer's project
war file

antislashn.org

Tomcat and Apache...
Web application configuration
●

URL parsing
Coyote connector
/conf/server.xml
Virtual host name
/conf/server.xml

http://...
Web application configuration
●

ROOT web application
●

installed under /webapps

●

default web application
–

no contex...
Web application configuration
●

WEB-INF directory contains
●

web.xml file
–

●

classes directory
–

●

deployment descr...
Web application configuration
●

META-INF directory contains optional files
●

●

context.xml file contains the specific c...
Deployment descriptor web.xml
●

Application-specific deployement file

●

key elements
●

<context-param> : mechanism use...
Deployment descriptor web.xml
●

key elements
●

<listener> : component design to respond to event in
an application
–

●
...
Deployment descriptor web.xml
●

key elements
●

<servlet-mapping> : specifies the mapping between a
servlet and a URL pat...
Deployment descriptor web.xml
●

key elements
●

<session-config> and <session-timeout>
–

●

used to set a session timeou...
Deployment descriptor web.xml
●

key elements
●

<error-page> : error pages configuration
–

the cause may be a HTTP error...
Deployment descriptor web.xml
●

key elements
●
●
●

<security-constraint>
<security-role>
<login-config>
–
–

antislashn....
Deployment descriptor web.xml
●

key elements
●
●
●

<resource-ref>
<resource-env-ref>
<env-entry>
–

are provided for con...
Tomcat manager application
●

manager application is a web application
●

three way to interact with the manager applicati...
Tomcat manager application
●

Summary of some tasks that the manager application
can perform
●

deploy a new web applicati...
Tomcat manager application
●

Enabling access to the manager application
●

this example use the User Database Realm
–
–

...
Tomcat manager application
●

Using HTTP requests
●

URL format :

http://[hostname]:[port]/manager/text/command?parameter...
Tomcat manager application
●

Using HTTP request
●

needed to add the role manager-script
<role rolename="manager-gui"/>
<...
Servlet and JSP

version 1.1
Servlet
●

Platform-independent web application component
●

●

communicate with web client using request/response

The de...
Servlet
●

The servlet is declared in the web.xml
●

the developer compiles the servlet and deployed it in the
WEB-INF/cla...
Servlet
●

Life-cycle
class
loaded

HTTP request

no

the servlet is instantiate

yes

destroy()

yes

class
changed

no

...
Servlet
●

When the HttpServlet.service() method is
invoked
●

it reads the HTTP method type in the request

●

it uses th...
Servlet
●

Servlet API 3.0 allows us to configure the servlet
details using annotations, instead XML
@WebServlet(
name="He...
JSP
●

Java Server Page

●

Simple technology
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UT...
JSP
●

Life-cycle
●

translation
–

●

compilation
–

●

the JSP file is translated to Java servlet source
the generated s...
JSP
●

Life-cycle
request

no

class
loaded
yes

yes

JSP
changed

instance is unloaded

translation

jspInit()

the class...
Components of a JSP
●

Page directive
●

provide global information about a JSP page

<%@ page language="java" contentType...
Component of a JSP
●

Declarations
●

used to define Java variables and methods in the JSP
page
<%! String name="toto"; %>...
JSP Expression Language (EL)
●

EL is a powerful feature introduced with the version
2.0
●

it enable developers to easily...
Tomcat
valves and filters

version 1.1
Valves and Filters
●

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

●

Valve ...
Valves and Filters
●

Theses requirements are independent of applications

●

Tomcat Valves vs. Servlet Filters
●

Filter ...
Tomcat Valves
●

Tomcat uses valves internally
●
●

to maintain SSL information in a request

●

●

to manage authenticati...
Tomcat Valves
●

Implementing a Valve

public class SimpleLoggingValve extends ValveBase {
@Override
public void invoke(Re...
Tomcat Valves
●

Adding the valve to Tomcat
●
●

●

package the valve in a jar file
copy the jar file in <TOMCAT_HOME>/lib...
Access Log Valve
●

Tomcat prepackaged Valve

●

It creates log files to track client access information
●

can be associa...
Remote Access Valve
●

Allow you to compare th IP address of the requesting
client against one or more regular expression
...
Crawler Session Manager Valve
●

Search engines employ special programs to discover
and index the web sites
●
●

●

crawle...
Dead Thread Detection Valve
●

Each request from a single user is processed by a
separate Java thread
●

sometimes these t...
Servlet Filters
●

Interface javax.servlet.Filter
●

methods
–

init(FilterConfig)
●

–

doFilter(ServletRequest, ServletR...
Servlet Filter
●

Implementing a Filter

public class TimeFilter implements Filter {
private FilterConfig config = null;
p...
Servlet Filter
●

Filter configuration
●

in the WEB-INF/web.xml
<filter>
<display-name>TimeFilter</display-name>
<filter-...
Servlet Filter
●

Filter configuration
●

<dispatcher> selects one of the following dispatcher
types :
–

REQUEST : only w...
Request Dumper Filter
●

This built in filter dumps the entire
HttpServletRequest to the Tomcat log
<filter>
<filter-name>...
Expires Filter
●

It controls the HTTP expires header
<filter>
<filter-name>ExpiresFilter</filter-name>
<filter-class>org....
Tomcat logging

version 1.1
Java Logging Framework
●

●

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

To instantiate a logger instance in th Java code, you
will use static factory method, and constru...
Java Logging overview
●

Logging levels
●

SEVERE : used to log exceptions, errors, ...

●

WARNING : used to log warning ...
Java Logging overview
●

Handlers
●

each logger has a list of handlers associated with it
–

●

represented by an abstrac...
Java Logging overview
●

Formatter
●

each handler has one formatter
–
–

format the log messages
two formatters are avail...
Java Logging overview
●

Formatter
●

JULI adds three formatters
–

–

–

antislashn.org

OneLineFormatter : same format a...
Java Logging overview

application

Logger

Handler

out

Formatter

antislashn.org

Tomcat and Apache httpd - Tomcat logg...
Java Logging overview
●

Logging configuration
●

typically specified int the file logging.properties
handlers= java.util....
JULI configuration
●

●

Java Logging Framework guarantees than only one
handler is instantiated by JVM
JULI supports one ...
JULI configuration
●

The defaults handlers are defined with the
.handlers property
●

will be used for loggers that do no...
JULI configuration
●

Rotating logs
●

log file rotation is enable by default
1catalina.org.apache.juli.FileHandler.rotata...
Servlet Logging
●

Servlet API defines the logging API to be used
●

●

the logging based is performed by calls to
Servlet...
Servlet Logging
●

The names follows the convention
org.apache.catalina.core.ContainerBase.[ENGINE].[HOST].[CONTEXT]
●

EN...
Connecting databases

version 1.1
JDBC overview
●

JDBC – Java DataBase Connectivity
●
●

Java base data access technology
provides methods for querying and...
JDBC overview
●

In JDBC programming, developers typically perform
the following steps
1.obtain a connection to the remote...
JDBC overview
●

Example
String
String
String
String

driver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://localhost:3306...
JDBC overview
●

The driver is loaded by his name
●
●

●

String type - it is usually a parameter

the developer don't kno...
JDBC overview
●

Database connection pooling
●

when a web application uses JDBC
–

a physical JDBC connection is establis...
JDBC overview
●

Database connection pooling
●

connection pooling reduces expensive session establish
times
–

●

●

●

c...
JDBC overview
●

Database connection pooling
Database connections
pool manager

web application

antislashn.org

Tomcat an...
JDBC overview
●

The pool manager
●

creates the initial physical connections

●

manages the distribution of the physical...
JDBC overview
●

The pool manager functionality may be provide by
●

an application server
–

Tomcat, JBoss, Geronimo, Gla...
Configuring the database connection
●

The database connection is configured as a JNDI
resource
●

as part of the <Context...
Configuring the database connection
●

JNDI resource for MySQL
<Context reloadable="true">
<Resource
name='jdbc/bovoyage'
...
Configuring the database connection
●

key attributes
●

●

name : the name of the resource will be used to reference
the ...
Configuring the database connection
●

key attributes
●

url : database connection URL

●

usename and password : for data...
Accessing the JNDI DataSource
●
●

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

JNDI
●

●
●

the name specified is relative to the root naming context,
which is define a...
Security with Tomcat

version 1.1
Security Realms
●

Mechanism for protecting web application resources.
●

a resource is protected with a defined security ...
Security Realm
●

Realm available in Tomcat
●

●

●

●

●

MemoryRealm : simple implementation that uses an xml
file (tomc...
Security Realm
●

Realm available in Tomcat
●

JaasRealm : authentication using JAAS
–

●

●

Java Authentication and Auth...
MemoryRealm
●

The simplest realm available in Tomcat
●

uses an in-memory database which is read from an XML
file
–

on s...
MemoryRealm
●

Protected a resource with a MemoryRealm
●

enable MemoryRealm in the conf/server.xml file
●

in Engine, Hos...
MemoryRealm
●

Configure the application
●

add the security constraint in the web.xml file
<security-constraint>
<web-res...
MemoryRealm
●

Configure the application
●

define the login mechanism in the web.xml file
<login-config>
<auth-method>BAS...
MemoryRealm
●

Restart Tomcat to apply the changes

●

Navigate the browser to the URL
●

a login windows is shown in the ...
Authentication types
●

BASIC
●
●

●

client authenticates by entering a username and password
the browser sends the infor...
Authentication types
●

FORM
●

client authenticates using a HTML form
–

●

●

input filed names and form action are defi...
LockOutRealm
●

Protection against the brute force attacks
●

the LockOutRealm wraps another realm
how many failed
attempt...
UserDatabaseRealm
●

Advanced version of MemoryRealm
●

can be configurable via JNDI

●

that allows clients to lookup obj...
JDBCRealm
●

Simple like the MemoryRealm, but the JDBCRealm
stores all the informations in a
user-defined and JDBC-complia...
JDBCRealm
●

Add the configuration in server.xml
<JDBCRealm driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql:/...
DataSourceRealm
●

DataSourceRealm is the upgraded version of
JDBCRealm
●

●

allows configuration of the database connect...
DataSourceRealm
●

Configuring DataSourceRealm in server.xml file
<GlobalNamingResources>
<Resource name="jdbc/authority" ...
FORM-Based authentication
●

A user request a protected resource
●

a login form is displayed
–

●

the user can enter a u...
FORM-Based authentication
BASIC authenticate

FORM authenticate

source : Oracle

antislashn.org

Tomcat and Apache httpd ...
FORM-Based authentication
●

Configuration
●

create a login page

●

create an error page

●

configure web.xml

antislas...
FORM-Based authentication
●

Login page
Java Servlet
specification

<html>
<head>
<meta http-equiv="Content-Type" content=...
FORM-Based authentication
●

Error page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859...
FORM-Based authentication
●

Configuration in the web.xml file
<login-config>
<auth-method>FORM</auth-method>
<form-login-...
DIGEST authenticate
●

UserDataBaseRealm can be configure to use
DIGEST authenticate
●

●

of course, the others realms ca...
DIGEST authenticate
●

Select the DIGEST algorithm
●

in server.xml file
<Realm className="org.apache.catalina.realm.UserD...
DIGEST authenticate
●

Add this password to the Realm
●

tomcat-users.xml file
–

<tomcat-users>
<role rolename="admin" />...
Securing with SSL
●

SSL – Secure Socket Layer
●

was first developed by Netscape
–

more recently the IETF developed TSL ...
Securing with SSL
●

Symmetric pair of keys
●

a same key is used for encryption of plaintext and
decryption of ciphertext...
Securing with SSL
●

Symmetric pair of keys
●

the algorithms are fast

●

the algorithms are simple

●

how to share the ...
Securing with SSL
●

Asymmetric pair of keys
●

or public-key cryptography

●

two separate keys
–

one is private
●

–

o...
Securing with SSL
●

Asymmetric pair of keys
●

the public key is used for encryption of plaintext

●

the private key is ...
Securing with SSL
●

Digital certificate
●
●

a serial number

●

the owner's name

●

●

contains keys

validity period

...
Securing with SSL
Navigator

Web server
hello

symmetric key
generation

encryption

decryption

decryption
encryption

de...
Securing with SSL
●

Configuring Tomcat with SSL
●

create our own certificate
–

self-signed certificate
●

–

it will no...
Securing with SSL
●

Create a self-signed certificate
●

use keytool
–

JAVA_HOME/bin

–
keytool -genkeypair -alias tomcat...
Securing with SSL
●

Configuring Tomcat's SSL connector
●

in server.xml file
<Connector port="8443" protocol="HTTP/1.1"
S...
Securing with SSL
●

Configuring resources in web application
●

in the web.xml

<security-constraint>
<web-resource-colle...
Securing with SSL
●

Try the URL … and accept the security alert

antislashn.org

Tomcat and Apache httpd - Security with ...
JMX
Java Management eXtension

version 1.1
JMX overview
●

Java Management eXtension
●
●

●

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

J...
JMX overview

antislashn.org

Tomcat and Apache httpd - JMX

3 / 16
JMX overview
JMX client

client level

Connectors and adapters
JMX agent

Services :
●Timers
●Notification

MBean server

...
JMX overview
●

MBeans are software modules
●

●

expose the capabilities of a hardware device or software
component
diffe...
JMX – Standard MBean
●

Simple
●

an Java interface
–
–
–

●

same name than implementation
class suffixed with MBean
gett...
JMX – Standard MBean
●

The MBean is identified by its unique name
●

ObjectName class

●

two parts
–
–
–

domain
propert...
JMX – Standard MBean
●

Java interface
public interface HelloMBean {
// properties
String getName();
String getColor();
vo...
JMX – Standard MBean
●

Java implementation class
public class Hello implements HelloMBean {
private String name ="Toto St...
JMX – Standard MBean
●

Agent level - main steps
●

recovering a MBean server
MBeanServer mbs = ManagementFactory.getPlatf...
JMX – Standard MBean
●

For securing reasons, we need to activate the JMX
access
●

-Dcom.sun.management.jmxremote

●

oth...
JMX – Standard MBean
●

We can now use jconsole or jvisualvm

antislashn.org

Tomcat and Apache httpd - JMX

12 / 16
Tomcat and JMX
●

Working with the JMX proxy
●

add the role manager-jmx

●

the URL for accessing the JMX proxy is as fol...
Tomcat and JMX
●

Using jconsole to monitor Tomcat
●

we must enable the JMX support inside Tomcat
–

add a file called
●
...
Tomcat and JMX
●

Start jconsole

antislashn.org

Tomcat and Apache httpd - JMX

15 / 16
Tomcat and JMX
●

Go to the mbeans tab

antislashn.org

Tomcat and Apache httpd - JMX

16 / 16
Configuring Apache httpd

version 1.1
Configuration files
●

Main configuration file
●

usually called httpd.conf
–
–
–

<apache_home>/conf/httpd.conf in Window...
Configuration files
●

●

Directives placed in httpd.conf file apply to the entire
server
To change the configuration for ...
Configuration
●

Syntax
●

one directive per line
–
–

backslash "" must be used as the last character on one line to
indi...
Configuration
●

Terms used to describe directives
●

description

●

syntax

●

default

●

context
–
–
–

–

antislashn....
Configuration
●

Terms used to describe directives
●

status
–
–
–
–
–

core : the directive is part of the server
MPM : M...
Configuration
●

Examples

antislashn.org

Tomcat and Apache httpd - Configuring Apache httpd

7 / 12
Configuration
●

Binding to listen on a specific addresses and port
●

Listen directive
–
–

●

Listen 80
default
examples...
Default web site
●

The default web site
●

DocumentRoot directive
–

●

DocumentRoot "/opt/www/"

if DocumentRoot changed...
Default resource
●

DirectoryIndex
●

set the list of resources to look for when the client request
a default one
–

http:...
Log files
●

Default location
●

●

CentOS : /var/log/httpd

ErrorLog directive
●

LogLevel directive
–

debug, info, noti...
Log files
●

Server error log is the most important log file

●

Other logs use CustomLog directive
●

or TransferLog dire...
Apache httpd
Virtual host

version 1.0
Virtual host overview
●

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

can be
–

IP-based
●

–

name-based...
Name-based virtual hosts
●

You must have DNS entries
●

use hosts file
–

/etc/hosts in CentOS

127.0.0.1 localhost local...
Name-based virtual hosts
NameVirtualHost *:80
<VirtualHost *:80>
DocumentRoot /www/example1
ServerName www.toto.exemple
Se...
IP-based virtual hosts
●

the server has two IP
addresses
●

●

Listen 80

on one (172.20.30.40) we
will serve the "main"
...
IP-based virtual hosts
<VirtualHost 192.168.0.1:80>
ServerAdmin webmaster@smallco.example.com
DocumentRoot /groups/smallco...
Apache httpd
Security

version 1.1
Security tips
●

Keep up to date

●

Permissions an ServerRoot directories
●
●

Apache is started by the root user
it swit...
Options directive
●

Controls which server features are available in a
particular directory
●

●

Syntax

Options [+|-] op...
Options directive
●

option can be set to
●

Include : server-side includes (SSI) are permitted
–

●
●

cf. mod_include mo...
Options directive
●

option can be set to
●

MultiViews : content negotiated is allowed
–
–

cf. mod_negotiation module
th...
Allow directive
●

Affects which hosts can access resources
●

access can be controlled by
–
–
–

●

hostname
IP address, ...
Allow directive
●

The first argument is always from
Allow from all

all hosts are allowed access
(subject to the configur...
Allow directive
●

Examples

Allow from 10.1.10.0.0/255.255.0.0
Allow from 2001::db8::a00::20ff::fea7::ccea

SetEnvIf User...
Deny Directive
●

This directive allows access to the server to be
restricted on hostname, IP address or environment
varia...
Order Directive
●

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

first...
Order Directive
●

Ordering is one of :
●

no whitespace is allowed between keywords

Allow,Deny

First all Allow directiv...
Order directive
●

Summary

Match

Allow,Deny result

Deny,Allow result

match Allow only

request allowed

request allowe...
Order directive
●

Examples

Order Deny,Allow
Deny from all
Allow from example.com

Order Allow,Deny
Allow from example.co...
Authentication
●

Authentication is simple
●
●

●

●

client sends his name and password
server looks up of names and pass...
Authentication
●
●

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

●

code 4...
Authentication

web site

realm
(AuthName directive)

antislashn.org

Tomcat and Apache httpd - Security with Apache httpd...
Authentication
●

Two authentication type
●

see the AuthType directive

●

Basic
–

●

Digest
–

●

mod_auth_basic module...
Authentication
●

Example
<Directory d:/www/autorise>
AuthName "Royaume secret"
AuthType Basic
require valid-user
AuthUser...
Authenticate
●

<Limit> directive
●

●

access controls are normally effective for all HTTP
methods
this directive restric...
Basic authentication
●

AuthType Basic directive
●
●

●

client authenticates by entering a username and password
the brow...
Basic authentication
●

Create the password file
●

the file is placed somewhere not accessible from the web

●

use the h...
Basic authentication
●

Create the group file
●
●

simple text-plain
each line of group contains a groupname followed by t...
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Tomcat and apache httpd training
Upcoming SlideShare
Loading in...5
×

Tomcat and apache httpd training

10,646

Published on

My training support is accompanied by a workshops-booklet

Published in: Technology
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
10,646
On Slideshare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
311
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Tomcat and apache httpd training

  1. 1. Tomcat and Apache httpd Objectives version 1.1
  2. 2. 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 2/4
  3. 3. 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 3/4
  4. 4. Chapters 8.Memory Management and JMX 9.Virtual host with Apache httpd 10.Security with Apache 11.Tomcat cluster with mod_jk antislashn.org Tomcat and Apache httpd - Objectives 4/4
  5. 5. Introduction version 1.1
  6. 6. Architecture What we want !!! Tomcat internet Apache httpd server mod_jk load balancer Tomcat Tomcat static resources antislashn.org Tomcat and Apache httpd - Introduction dynamic resources 2 / 37
  7. 7. 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 3 / 37
  8. 8. The evolution of the web ● source : http://evolutionofweb.appspot.com/ antislashn.org Tomcat and Apache httpd - Introduction 4 / 37
  9. 9. 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 5 / 37
  10. 10. 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 6 / 37
  11. 11. 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) ● antislashn.org http://www.chromium.org/spdy/spdy-whitepaper Tomcat and Apache httpd - Introduction 7 / 37
  12. 12. 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 8 / 37
  13. 13. HTTP ● Conversation sample ● client request ● server response antislashn.org Tomcat and Apache httpd - Introduction 9 / 37
  14. 14. 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 10 / 37
  15. 15. HTTP ● HTTP methods (continuation) ● TRACE : echoes back the received request – ● ● OPTIONS : returns the HTTP methods that the server supports CONNECT : uses a proxy like a communication tunnel – ● for debug for SSL PATCH : uses to apply partial modification to a resource antislashn.org Tomcat and Apache httpd - Introduction 11 / 37
  16. 16. 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 12 / 37
  17. 17. HTTP ● HTTP response status codes ● 1xx : informational ● 2xx : success – ● 3xx : redirection – – ● 301 Moved permanently 304 Not Modified 4xx : client error – ● 200 OK 404 Not Found 5xx : server error – antislashn.org 500 Internal Server Error Tomcat and Apache httpd - Introduction 13 / 37
  18. 18. 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 – – antislashn.org uses MD cryptographic hashing the password is not used directly Tomcat and Apache httpd - Introduction 14 / 37
  19. 19. Java evolution ● Language issued from a Sun project ● ● named “Stealth” and supervised by Patrick Naugthon ● ● 1990 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 15 / 37
  20. 20. 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 16 / 37
  21. 21. Java acronyms ● JRE : Java Runtime Environment ● JDK : Java Development Kit ● JVM : Java Virtual Machine ● Java SE : Java Standard Edition ● ● Java ME : Java Micro Edition ● ● earlier J2SE earlier J2ME Java EE : Enterprise Edition ● antislashn.org earlier J2EE Tomcat and Apache httpd - Introduction 17 / 37
  22. 22. Java acronyms ● JSR : Java Specification Request ● ● JCP : Java Community Process ● ● consortium which manage the Java evolutions EJB : Enterprise Java Bean ● ● users can ask new features in the Java platforms 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 18 / 37
  23. 23. Java platforms ● Java SE ● standalone applications ● executed when launching the JVM – ● Java EE ● ● java tool 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 19 / 37
  24. 24. Development cycle ● Simple view of development cycle source Java code file Toto.java compilation with javac tool Java bytecode Toto.class execution in the JVM java tool antislashn.org Tomcat and Apache httpd - Introduction 20 / 37
  25. 25. Java EE overview source : Oracle antislashn.org Tomcat and Apache httpd - Introduction 21 / 37
  26. 26. 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 22 / 37
  27. 27. Java EE overview ● Java EE components ● clients – web clients (or thin client) ● – application clients ● antislashn.org web brother which renders the page received from the server runs on a client machine – GUI created with Swing Tomcat and Apache httpd - Introduction 23 / 37
  28. 28. Java EE overview ● Web components ● JSP and servlets source : Oracle antislashn.org Tomcat and Apache httpd - Introduction 24 / 37
  29. 29. Java EE overview ● Business components Enterprise Information System source : Oracle antislashn.org Tomcat and Apache httpd - Introduction 25 / 37
  30. 30. Java EE overview ● Java EE containers ● container services, provides : – JNDI – Java Naming and Directory Interface ● – Java EE security model ● – antislashn.org configures a web component or EJB so that resources are accessed only by authorized users Java EE transaction ● – the application components can access the services by their names 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, ... Tomcat and Apache httpd - Introduction 26 / 37
  31. 31. Java EE overview ● Container types source : Oracle antislashn.org Tomcat and Apache httpd - Introduction 27 / 37
  32. 32. 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 28 / 37
  33. 33. Java EE overview ● Java EE 6 APIs source : Oracle antislashn.org Tomcat and Apache httpd - Introduction 29 / 37
  34. 34. Java EE overview ● Profiles ● configurations of the Java EE platform targeted at specific classes of applications – – antislashn.org Web Profile Full Profile Tomcat and Apache httpd - Introduction 30 / 37
  35. 35. Java EE overview ● Web Profile includes EJB Lite ● not the full EJB API antislashn.org Tomcat and Apache httpd - Introduction 31 / 37
  36. 36. 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 JSP API JDK 7.0 3.0 2.2 1.6 6.0 2.5 2.1 1.5 5.5 antislashn.org Servlet API 2.4 2.0 1.4 Tomcat and Apache httpd - Introduction 32 / 37
  37. 37. Architecture of Tomcat Server Service port 8080 Connector HTTP Engine port 8443 Connector HTTPS Host Context port 8009 antislashn.org Context Connector AJP Tomcat and Apache httpd - Introduction 33 / 37
  38. 38. 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 34 / 37
  39. 39. 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 35 / 37
  40. 40. 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 36 / 37
  41. 41. Tomcat overview ● Tomcat is not ● a Web Profile server ● a httpd server – ● Tomcat is ● ● Apache httpd is better just a Java EE web container Tomcat is part of many projects ● JBoss ● TomEE ● ... antislashn.org Tomcat and Apache httpd - Introduction 37 / 37
  42. 42. Installation Java – Tomcat – Apache httpd version 1.0
  43. 43. 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 ● – rpm -Uvh /path/to/binary/jdk-7u45-linux-x64.rpm verify the installation ● antislashn.org sudo -i install Java JDK package ● – su - or java -version Tomcat and Apache httpd - Installation 2 / 16
  44. 44. Installing Java ● Installing Java on CentOS 6.4 (continuation) ● setup JAVA_HOME – add JAVA_HOME in /etc/profile export JAVA_HOME="/usr/java/latest" – restart the computer and verify echo $JAVA_HOME antislashn.org Tomcat and Apache httpd - Installation 3 / 16
  45. 45. Installing Tomcat ● Download Tomcat distribution ● http://tomcat.apache.org/download-70.cgi ● download the code distribution antislashn.org Tomcat and Apache httpd - Installation 4 / 16
  46. 46. Installing Tomcat ● After downloaded, validate the distribution ● each distribution had a PGP signature and a MD5 checksum md5sum Downloads/apache-tomcat-7.0.47.zip ● Extract the download file onto /opt ● you need to be root unzip apache-tomcat-7.0.47.zip -d /opt or tar zxvf apache-tomcat-7.0.47.tar.gz mkdir /opt/apache-tomcat-7.0.47 cp -R apache-tomcat-7.0.47/* /opt/apache-tomcat-7.0.47 antislashn.org Tomcat and Apache httpd - Installation 5 / 16
  47. 47. Installing Tomcat ● Setup CATALINA_HOME ● add CATALINA_HOME in /etc/profile – you need to be root export CATALINA_HOME="/opt/apache-tomcat-7.0.47" ● perhaps you need to change the tomcat folder owner – antislashn.org chown -R franck apache-tomcat-7.0.47/ Tomcat and Apache httpd - Installation 6 / 16
  48. 48. Installing Tomcat ● Starting Tomcat cd /opt/apache-tomcat-7.0.47/bin/ ./startup.sh ● verifying the good installation ● open localhost:8080 antislashn.org Tomcat and Apache httpd - Installation 7 / 16
  49. 49. Installing Tomcat ● Stopping Tomcat cd /opt/apache-tomcat-7.0.47/bin/ ./shutdown.sh antislashn.org Tomcat and Apache httpd - Installation 8 / 16
  50. 50. Tomcat directories antislashn.org Tomcat and Apache httpd - Installation 9 / 16
  51. 51. 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 10 / 16
  52. 52. 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 11 / 16
  53. 53. Installing Apache httpd ● Apache httpd server is installed with CentOS by default ● if you need to install Apache httpd yum install httpd ● Starting Apache httpd ● in root mode /etc/init.d/httpd start or apachectl start antislashn.org Tomcat and Apache httpd - Installation 12 / 16
  54. 54. Installing Apache httpd ● Stopping Apache httpd ● as root user /etc/init.d/httpd stop or apachectl stop ● Setting the Apache service to start on boot ● as root user chkconfig --levels 235 httpd on antislashn.org Tomcat and Apache httpd - Installation 13 / 16
  55. 55. Installing Apache httpd ● Testing Apache httpd ● open http://localhost antislashn.org Tomcat and Apache httpd - Installation 14 / 16
  56. 56. 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 – – antislashn.org DocumentRoot entry and <Directory "/var/www/html"> directive Tomcat and Apache httpd - Installation 15 / 16
  57. 57. Installing Apache httpd ● From the httpd.conf file ... # 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"> ... ● Restart Apache httpd antislashn.org Tomcat and Apache httpd - Installation 16 / 16
  58. 58. Tomcat architecture and configuration version 1.0
  59. 59. Architecture overview ● Tomcat consists of a nested hierarchy of components Server Service connector connector Engine Logger Logger Logger Host Host Host Valve Logger Valve Realm Logger Logger Logger Valve Valve Valve Realm Valve Valve Valve Realm Context Context Context Valve Valve Wrapper antislashn.org Tomcat and Apache httpd - Tomcat configuration 2 / 33
  60. 60. Architecture overview ● Server ● the server is Tomcat itself – it owns a port used for shut down the server <Server port="8005" shutdown="SHUTDOWN"> ● only one instance by JVM – separate servers can be set up on the same machine ● ● antislashn.org 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 Tomcat and Apache httpd - Tomcat configuration 3 / 33
  61. 61. Architecture overview ● Service ● ● contains one or more Connectors ● ● contains a single container Engine 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 4 / 33
  62. 62. 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 – antislashn.org we will see how this can be change, using sing sign-on Tomcat and Apache httpd - Tomcat configuration 5 / 33
  63. 63. 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 – antislashn.org inclusion is transparent to web application Tomcat and Apache httpd - Tomcat configuration 6 / 33
  64. 64. 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 ● antislashn.org 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 Tomcat and Apache httpd - Tomcat configuration 7 / 33
  65. 65. Architecture overview ● Context ● this is the web application – it becomes parent of servelts and filters ● ● a web application could include – – ● a web.xml a context.xml supports dynamic reload – ● as StandardWrapper objects classes that have been changed are reloaded into memory may include specific error pages antislashn.org Tomcat and Apache httpd - Tomcat configuration 8 / 33
  66. 66. Files in $CATALINA_HOME/conf ● server.xml ● main configuration file ● Tomcat reads this file at startup – ● application-level context should not be made in this file – ● components configured in this file affect the entire Tomcat instance use a per-application context.xml tomcat-user.xml ● contains user authentication and role-mapping antislashn.org Tomcat and Apache httpd - Tomcat configuration 9 / 33
  67. 67. 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 10 / 33
  68. 68. Files in $CATALINA_HOME/conf ● web.xml ● ● provides basic servlet definition and MIME mappings ● ● default deployment descriptor for all web applications 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 11 / 33
  69. 69. 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 – antislashn.org Tomcat uses its own implementation of Java Logging Tomcat and Apache httpd - Tomcat configuration 12 / 33
  70. 70. <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 ● antislashn.org cannot be done remotely for security reasons Tomcat and Apache httpd - Tomcat configuration 13 / 33
  71. 71. <Server> component ● key sub-elements ● <Service> – ● <Listener> – ● a grouping of Connectors associated with an Engine life-cycle listeners for interception of the server's life-cycle events <GlobalNamingResources> – antislashn.org JNDI global resources Tomcat and Apache httpd - Tomcat configuration 14 / 33
  72. 72. <Service> component ● key attributes ● className : classe name for the service – ● name : name for the service – ● org.apache.catalina.core.StandardService by default 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 15 / 33
  73. 73. Web application configuration ● A web application consist of ● static content – ● dynamic content – ● HTML pages, image files, PDF files, … servlets, JSP, Java classes Web applications are usually installed under the webapps directory ● deployed in a directory named after the web application – antislashn.org this name is also used in the web application URL Tomcat and Apache httpd - Tomcat configuration 16 / 33
  74. 74. Web application configuration ● Web application structure developer's project war file antislashn.org Tomcat and Apache httpd - Tomcat configuration 17 / 33
  75. 75. Web application configuration ● URL parsing Coyote connector /conf/server.xml Virtual host name /conf/server.xml http://www.example.com/bovoyage/addCaddy/5 context path processed by servlet servlet mapping /WEB-INF/web.xml antislashn.org Tomcat and Apache httpd - Tomcat configuration 18 / 33
  76. 76. Web application configuration ● ROOT web application ● installed under /webapps ● default web application – no context path needs to be specified ● antislashn.org http://localhost:8080/ Tomcat and Apache httpd - Tomcat configuration 19 / 33
  77. 77. Web application configuration ● WEB-INF directory contains ● web.xml file – ● classes directory – ● deployment descriptor 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) – antislashn.org contains files for tags libraries Tomcat and Apache httpd - Tomcat configuration 20 / 33
  78. 78. Web application configuration ● META-INF directory contains optional files ● ● context.xml file contains the specific configuration for the web application MANIFEST.MF file – antislashn.org version, vendor, … Tomcat and Apache httpd - Tomcat configuration 21 / 33
  79. 79. 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 – – antislashn.org compression, … contains <filter-name>, <filter-class> Tomcat and Apache httpd - Tomcat configuration 22 / 33
  80. 80. 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 23 / 33
  81. 81. 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 24 / 33
  82. 82. 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 25 / 33
  83. 83. 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 26 / 33
  84. 84. Deployment descriptor web.xml ● key elements ● ● ● <security-constraint> <security-role> <login-config> – – antislashn.org these elements relate to the configuration of login authentication in the application we shall see in detail later Tomcat and Apache httpd - Tomcat configuration 27 / 33
  85. 85. Deployment descriptor web.xml ● key elements ● ● ● <resource-ref> <resource-env-ref> <env-entry> – are provided for configuring resources for the web application ● antislashn.org a database-connection pooling, ... Tomcat and Apache httpd - Tomcat configuration 28 / 33
  86. 86. 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 29 / 33
  87. 87. 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 30 / 33
  88. 88. 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 31 / 33
  89. 89. 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 – – – antislashn.org file:/absolute/path/to/a/directory file:/absolute/path/to/a/webapp.war jar:file:/absolute/path/to/a/webapp.war! Tomcat and Apache httpd - Tomcat configuration 32 / 33
  90. 90. Tomcat manager application ● Using HTTP request ● needed to add the role manager-script <role rolename="manager-gui"/> <role rolename="manager-script"/> <user username="admin" password="adminpw" roles="manager-gui,manager-script"/> ● example : – antislashn.org http://localhost:8080/manager/text/list Tomcat and Apache httpd - Tomcat configuration 33 / 33
  91. 91. Servlet and JSP version 1.1
  92. 92. 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 2 / 12
  93. 93. 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 3 / 12
  94. 94. Servlet ● Life-cycle class loaded HTTP request no the servlet is instantiate yes destroy() yes class changed no the servlet is unloaded antislashn.org service() Tomcat and Apache httpd - Servlet and JSP init() 4 / 12
  95. 95. 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 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 antislashn.org HttpServlet class method doTrace(HttpServletRequest,HttpServletResponse) Tomcat and Apache httpd - Servlet and JSP 5 / 12
  96. 96. 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 6 / 12
  97. 97. 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 7 / 12
  98. 98. JSP ● Life-cycle ● translation – ● compilation – ● the JSP file is translated to Java servlet source 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 8 / 12
  99. 99. JSP ● Life-cycle request no class loaded yes yes JSP changed instance is unloaded translation jspInit() the class is instantiate no response antislashn.org jspService() Tomcat and Apache httpd - Servlet and JSP 9 / 12
  100. 100. Components of a JSP ● Page directive ● provide global information about a JSP page <%@ page language="java" contentType="text/html; charset=UTF-8" ● pageEncoding="UTF-8"%> Include directive ● to insert file (text or JSP) at translation time <%@ include file="header.jsp" %> ● Taglib directive ● to use a custom tag library <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> antislashn.org Tomcat and Apache httpd - Servlet and JSP 10 / 12
  101. 101. Component of a JSP ● Declarations ● used to define Java variables and methods in the JSP page <%! String name="toto"; %> <%! String getHello(){ return "Hello";} %> ● Expressions ● the expression is replaced with the resulting value of the container evaluation <%= getHello() %> <%= name %> antislashn.org Tomcat and Apache httpd - Servlet and JSP 11 / 12
  102. 102. JSP Expression Language (EL) ● EL is a powerful feature introduced with the version 2.0 ● it enable developers to easily access Java objects destinations is collection of POJO ... <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 antislashn.org Tomcat and Apache httpd - Servlet and JSP 12 / 12
  103. 103. Tomcat valves and filters version 1.1
  104. 104. 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 2 / 16
  105. 105. 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 – – antislashn.org because Valve is part of the Tomcat engine API it can be configured on the engine or host level Tomcat and Apache httpd - Tomcat valves and filters 3 / 16
  106. 106. Tomcat Valves ● Tomcat uses valves internally ● ● to maintain SSL information in a request ● ● to manage authentication 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 4 / 16
  107. 107. Tomcat Valves ● Implementing a Valve public class SimpleLoggingValve extends ValveBase { @Override public 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 5 / 16
  108. 108. 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 6 / 16
  109. 109. 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 7 / 16
  110. 110. 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 8 / 16
  111. 111. 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 9 / 16
  112. 112. 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 10 / 16
  113. 113. Servlet Filters ● Interface javax.servlet.Filter ● methods – init(FilterConfig) ● – doFilter(ServletRequest, ServletResponse, FilterChain) ● ● – this method is executed for every request must call filterChain.doFilter(...) destroy() ● antislashn.org initialize the filter – it is called once call once, when the web application is undeployed Tomcat and Apache httpd - Tomcat valves and filters 11 / 16
  114. 114. Servlet Filter ● Implementing a Filter public 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 12 / 16
  115. 115. 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 13 / 16
  116. 116. 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 14 / 16
  117. 117. 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 15 / 16
  118. 118. 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> antislashn.org Tomcat and Apache httpd - Tomcat valves and filters 16 / 16
  119. 119. Tomcat logging version 1.1
  120. 120. 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 – antislashn.org Java Util Logging Interface Tomcat and Apache httpd - Tomcat logging 2 / 14
  121. 121. 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 Logger log = Logger.getLogger("org.antislashn"); ● Each logger accept messages with different logging level ● based on their importance log.severe("Message niveau severe"); log.info("Message niveau info"); log.finest("Message niveau finest"); antislashn.org Tomcat and Apache httpd - Tomcat logging 3 / 14
  122. 122. 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 4 / 14
  123. 123. 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 ● – antislashn.org supporting file rotation SocketHandler : writes messages to the network socket Tomcat and Apache httpd - Tomcat logging 5 / 14
  124. 124. Java Logging overview ● Formatter ● each handler has one formatter – – format the log messages two formatters are available ● SimpleFormatter – logs message with date, time, information Infos: Initializing ProtocolHandler ["http-bio-8080"] nov. 14, 2013 11:50:03 AM org.apache.coyote.AbstractProtocol init ● antislashn.org XMLFormatter – writes messages in XML format <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> Tomcat and Apache httpd - Tomcat logging 6 / 14
  125. 125. Java Logging overview ● Formatter ● JULI adds three formatters – – – antislashn.org 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 Tomcat and Apache httpd - Tomcat logging 7 / 14
  126. 126. Java Logging overview application Logger Handler out Formatter antislashn.org Tomcat and Apache httpd - Tomcat logging 8 / 14
  127. 127. Java Logging overview ● Logging configuration ● typically specified int the file logging.properties handlers= java.util.logging.ConsoleHandler java.util.logging.ConsoleHandler.level = ALL java.util.logging.ConsoleHandler.formatter = java.util.logging.XMLFormatter – #1 : defines all handlers (comma separator) ● ● – – antislashn.org 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 Tomcat and Apache httpd - Tomcat logging 9 / 14
  128. 128. 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 10 / 14
  129. 129. JULI configuration ● The defaults handlers are defined with the .handlers property ● will be used for loggers that do not have a specific handler configured .handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler ● Each handler is configured ● name of the handler followed by the property 1catalina.org.apache.juli.FileHandler.level = FINE 1catalina.org.apache.juli.FileHandler.directory = ${catalina.base}/logs 1catalina.org.apache.juli.FileHandler.prefix = catalina. antislashn.org Tomcat and Apache httpd - Tomcat logging 11 / 14
  130. 130. JULI configuration ● Rotating logs ● log file rotation is enable by default 1catalina.org.apache.juli.FileHandler.rotatable = true ● the format is {prefix}.{date}.{suffix} ● the rotation an only rotate daily antislashn.org Tomcat and Apache httpd - Tomcat logging 12 / 14
  131. 131. 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 – antislashn.org for each engine, host and context Tomcat and Apache httpd - Tomcat logging 13 / 14
  132. 132. Servlet Logging ● The names follows the convention org.apache.catalina.core.ContainerBase.[ENGINE].[HOST].[CONTEXT] ● ENGINE : engine name ● HOST : host name ● CONTEXT : context name (application) ● and ends with the property defined in server.xml application name org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.org.apache.juli.FileHandler antislashn.org Tomcat and Apache httpd - Tomcat logging 14 / 14
  133. 133. Connecting databases version 1.1
  134. 134. JDBC overview ● JDBC – Java DataBase Connectivity ● ● Java base data access technology provides methods for querying and updating data in database Java application Java API calls JDBC library MySQL JDBC driver antislashn.org Oracle JDBC driver SQLServer JDBC driver Tomcat and Apache httpd - Connectiong databases 2 / 16
  135. 135. 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 3 / 16
  136. 136. JDBC overview ● Example String String String String driver = "com.mysql.jdbc.Driver"; url = "jdbc:mysql://localhost:3306/bovoyage"; user = "toto"; pswd = "totopw"; // 1 - load the driver and obtain a connection Class.forName(driver); Connection conn = DriverManager.getConnection(url, user, pswd); // 2 - create and prepare a SQL statement String sql = "SELECT * FROM destinations"; Statement statement = conn.createStatement(); // 3 - execute SQL statement and obtain the result set ResultSet rs = statement.executeQuery(sql); // 4 - work on the result set while(rs.next()){ System.out.println(rs.getString("region")); } // 5 - disconnect from the remote database conn.close(); antislashn.org Tomcat and Apache httpd - Connectiong databases 4 / 16
  137. 137. JDBC overview ● The driver is loaded by his name ● ● ● String type - it is usually a parameter the developer don't know the database used "com.mysql.jdbc.Driver" 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 jdbc:mysql://localhost:3306/bovoyage protocol antislashn.org sub-protocol machine holding the database Tomcat and Apache httpd - Connectiong databases path to the database on the machine 5 / 16
  138. 138. JDBC overview ● Database connection pooling ● when a web application uses JDBC – a physical JDBC connection is establish between the application and the database ● – establish such a connection is ● ● ● – CPU-intensive memory-intensive execution time-intensive how long hold the connection ● ● antislashn.org via a TCP/IP connection request ? session ? Tomcat and Apache httpd - Connectiong databases 6 / 16
  139. 139. 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 – – antislashn.org it is disconnected the physical connection is merely returned to the pool Tomcat and Apache httpd - Connectiong databases 7 / 16
  140. 140. JDBC overview ● Database connection pooling Database connections pool manager web application antislashn.org Tomcat and Apache httpd - Connectiong databases 8 / 16
  141. 141. 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 9 / 16
  142. 142. 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 10 / 16
  143. 143. 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 – antislashn.org the resource will be available to all the web applications deployed on the Tomcat instance Tomcat and Apache httpd - Connectiong databases 11 / 16
  144. 144. 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 12 / 16
  145. 145. 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 13 / 16
  146. 146. 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 14 / 16
  147. 147. 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 15 / 16
  148. 148. 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 be java:comp/env/jdbc/bovoyage Context contexteJndi = new InitialContext(); DataSource dataSource = (DataSource) contexteJndi.lookup("java:comp/env/jdbc/bovoyage"); antislashn.org Tomcat and Apache httpd - Connectiong databases 16 / 16
  149. 149. Security with Tomcat version 1.1
  150. 150. 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 2 / 38
  151. 151. Security Realm ● 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 antislashn.org Tomcat and Apache httpd - Security with Tomcat 3 / 38
  152. 152. 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 – antislashn.org prevent pure force server attack Tomcat and Apache httpd - Security with Tomcat 4 / 38
  153. 153. 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 5 / 38
  154. 154. 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 <Realm className="org.apache.catalina.realm.MemoryRealm" /> ● 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 antislashn.org Tomcat and Apache httpd - Security with Tomcat 6 / 38
  155. 155. 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 7 / 38
  156. 156. MemoryRealm ● Configure the application ● define the login mechanism in the web.xml file <login-config> <auth-method>BASIC</auth-method> <realm-name>Site exemple</realm-name> </login-config> ● declare the roles used – in the web.xml file <security-role> <role-name>admin</role-name> </security-role> antislashn.org Tomcat and Apache httpd - Security with Tomcat 8 / 38
  157. 157. 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 9 / 38
  158. 158. 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 10 / 38
  159. 159. 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 11 / 38
  160. 160. LockOutRealm ● Protection against the brute force attacks ● the LockOutRealm wraps another realm how many failed attempts how long the user will be lock out (in seconds) <Realm className="org.apache.catalina.realm.LockOutRealm" faiureCount="3" lockoutTime="3600"> <Realm className="org.apache.catalina.realm.MemoryRealm" /> </Realm> antislashn.org Tomcat and Apache httpd - Security with Tomcat 12 / 38
  161. 161. UserDatabaseRealm ● Advanced version of MemoryRealm ● can be configurable via JNDI ● that allows clients to lookup objects by the know name ● in the server.xml <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> ● and used by the Context <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> antislashn.org Tomcat and Apache httpd - Security with Tomcat 13 / 38
  162. 162. JDBCRealm ● Simple like the MemoryRealm, but the JDBCRealm stores all the informations in a user-defined and JDBC-compliant database ● we need two tables – – antislashn.org one for user and password one for user and role Tomcat and Apache httpd - Security with Tomcat 14 / 38
  163. 163. 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 15 / 38
  164. 164. 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 16 / 38
  165. 165. DataSourceRealm ● Configuring DataSourceRealm in server.xml file <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> ● Configuring DataSourceRealm in the Context <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 17 / 38
  166. 166. 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 ● – 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 ● antislashn.org user is authenticated code 403 Tomcat and Apache httpd - Security with Tomcat 18 / 38
  167. 167. FORM-Based authentication BASIC authenticate FORM authenticate source : Oracle antislashn.org Tomcat and Apache httpd - Security with Tomcat 19 / 38
  168. 168. FORM-Based authentication ● Configuration ● create a login page ● create an error page ● configure web.xml antislashn.org Tomcat and Apache httpd - Security with Tomcat 20 / 38
  169. 169. FORM-Based authentication ● Login page Java Servlet specification <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> antislashn.org Tomcat and Apache httpd - Security with Tomcat 21 / 38
  170. 170. 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 22 / 38
  171. 171. 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 23 / 38
  172. 172. 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 ● – – create the DIGEST password add this password to the Realm ● – here the tomcat-users.xml file configure the login-config ● antislashn.org in the server.xml file in the web.xml file Tomcat and Apache httpd - Security with Tomcat 24 / 38
  173. 173. DIGEST authenticate ● Select the DIGEST algorithm ● in server.xml file <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" digest="sha"/> ● Create the DIGEST password ● Java supports two digest algorithm – ● MD5 and SHA "totopw" is the textplain password digest -a sha totopw totopw:557860fea134517d63080a07c1d507c9dde15621 antislashn.org Tomcat and Apache httpd - Security with Tomcat 25 / 38
  174. 174. DIGEST authenticate ● Add this password to the Realm ● tomcat-users.xml file – <tomcat-users> <role rolename="admin" /> <user username="toto" password="totopw" roles="admin" /> </tomcat-users> – ● old file now <tomcat-users> <role rolename="admin" /> <user username="toto" roles="admin" password="557860fea134517d63080a07c1d507c9dde15621" /> </tomcat-users> Configure the login-config ● web.xml file antislashn.org <login-config> <auth-method>DIGEST</auth-method> <realm-name>Site exemple</realm-name> </login-config> Tomcat and Apache httpd - Security with Tomcat 26 / 38
  175. 175. 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 – antislashn.org using symmetric pair of keys to encrypt and decrypt traffic Tomcat and Apache httpd - Security with Tomcat 27 / 38
  176. 176. Securing with SSL ● Symmetric pair of keys ● a same key is used for encryption of plaintext and decryption of ciphertext the same key is shared encryption Alice decryption Bob ? stole the key Chuck antislashn.org Tomcat and Apache httpd - Security with Tomcat 28 / 38
  177. 177. 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 29 / 38
  178. 178. Securing with SSL ● Asymmetric pair of keys ● or public-key cryptography ● two separate keys – one is private ● – one is public ● ● ● used for decryption 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 30 / 38
  179. 179. Securing with SSL ● Asymmetric pair of keys ● the public key is used for encryption of plaintext ● the private key is used for decryption of ciphertext encryption Alice decryption Bob ? stole the key antislashn.org Tomcat and Apache httpd - Security with Tomcat 31 / 38
  180. 180. Securing with SSL ● Digital certificate ● ● a serial number ● the owner's name ● ● contains keys validity period Keystore ● contains multiple certificates, keys antislashn.org Tomcat and Apache httpd - Security with Tomcat 32 / 38
  181. 181. Securing with SSL Navigator Web server hello symmetric key generation encryption decryption decryption encryption decryption encryption all the messages use a symmetric encryption antislashn.org Tomcat and Apache httpd - Security with Tomcat 33 / 38
  182. 182. 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 – antislashn.org forcing Tomcat send resources over SSL Tomcat and Apache httpd - Security with Tomcat 34 / 38
  183. 183. Securing with SSL ● Create a self-signed certificate ● use keytool – JAVA_HOME/bin – keytool -genkeypair -alias tomcat -keylag RSA -keystore <TOMCAT_HOME>/conf/tomcat.keystore ● enter the required details keystore certificate 1 tomcat.keystore file with its is own password each certificate has an alias and a password certificate 2 certificate n antislashn.org Tomcat and Apache httpd - Security with Tomcat 35 / 38
  184. 184. 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" /> antislashn.org used by HttpServletRequest.isSecure() no use of CLIENT_CERT Tomcat and Apache httpd - Security with Tomcat 36 / 38
  185. 185. 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> server.xml <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" /> antislashn.org Tomcat and Apache httpd - Security with Tomcat 37 / 38
  186. 186. Securing with SSL ● Try the URL … and accept the security alert antislashn.org Tomcat and Apache httpd - Security with Tomcat 38 / 38
  187. 187. JMX Java Management eXtension version 1.1
  188. 188. JMX overview ● Java Management eXtension ● ● ● specification add in Java 5 used to manage servers, applications, JVM JMX architecture ● three levels – instrumentation ● – – antislashn.org MBean probe object agent distributed services Tomcat and Apache httpd - JMX 2 / 16
  189. 189. JMX overview antislashn.org Tomcat and Apache httpd - JMX 3 / 16
  190. 190. JMX overview JMX client client level Connectors and adapters JMX agent Services : ●Timers ●Notification MBean server instrumentation antislashn.org MBean MBean MBean Tomcat and Apache httpd - JMX 4 / 16
  191. 191. JMX overview ● MBeans are software modules ● ● expose the capabilities of a hardware device or software component different types of MBean – Standard MBean ● – – – – antislashn.org only this one will be discussed here Dynamic MBean Model MBean Open MBean MXBean Tomcat and Apache httpd - JMX 5 / 16
  192. 192. JMX – Standard MBean ● Simple ● an Java interface – – – ● same name than implementation class suffixed with MBean getter → read property setter → write property an Java implementation class antislashn.org Tomcat and Apache httpd - JMX 6 / 16
  193. 193. 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 7 / 16
  194. 194. JMX – Standard MBean ● Java interface public interface HelloMBean { // properties String getName(); String getColor(); void setColor(String color); // operations void sayHello(); double add(double a, double b); } antislashn.org Tomcat and Apache httpd - JMX 8 / 16
  195. 195. JMX – Standard MBean ● Java implementation class public 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); } } antislashn.org @Override public double add(double a, double b) { return a+b; } Tomcat and Apache httpd - JMX 9 / 16
  196. 196. JMX – Standard MBean ● Agent level - main steps ● recovering a MBean server MBeanServer mbs = ManagementFactory.getPlatformMBeanServercreating(); ● instantiating an ObejctName ObjectName mBeanName = new ObjectName("antislashn.jmx:bean=Hello,type=standard"); ● recording the MBean in the server HelloMBean mBean = new Hello(); mbs.registerMBean(mBean, mBeanName); antislashn.org Tomcat and Apache httpd - JMX 10 / 16
  197. 197. 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=false MonAppliJava antislashn.org Tomcat and Apache httpd - JMX 11 / 16
  198. 198. JMX – Standard MBean ● We can now use jconsole or jvisualvm antislashn.org Tomcat and Apache httpd - JMX 12 / 16
  199. 199. 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 ● antislashn.org http://localhost:8080/manager/jmxproxy/list Tomcat and Apache httpd - JMX 13 / 16
  200. 200. 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 set CATALINA_OPTS=-Dcom.sun.management.jmxremote ● restart Tomcat antislashn.org Tomcat and Apache httpd - JMX 14 / 16
  201. 201. Tomcat and JMX ● Start jconsole antislashn.org Tomcat and Apache httpd - JMX 15 / 16
  202. 202. Tomcat and JMX ● Go to the mbeans tab antislashn.org Tomcat and Apache httpd - JMX 16 / 16
  203. 203. Configuring Apache httpd version 1.1
  204. 204. 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 2 / 12
  205. 205. 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 – – Files, FilesMatch – Location, LocationMatch – antislashn.org Directory, DirectoryMatch VirtualHost Tomcat and Apache httpd - Configuring Apache httpd 3 / 12
  206. 206. 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 <Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory> ● 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 antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 4 / 12
  207. 207. Configuration ● Terms used to describe directives ● description ● syntax ● default ● context – – – – antislashn.org 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 Tomcat and Apache httpd - Configuring Apache httpd 5 / 12
  208. 208. 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 6 / 12
  209. 209. Configuration ● Examples antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 7 / 12
  210. 210. Configuration ● Binding to listen on a specific addresses and port ● Listen directive – – ● Listen 80 default examples Listen 90 Listen 192.168.0.45:80 Modules ● extended feature are available through modules ● a module can be loaded by the LoadModule directive antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 8 / 12
  211. 211. Default web site ● The default web site ● DocumentRoot directive – ● DocumentRoot "/opt/www/" if DocumentRoot changed, you need to change the <Directory ...> directive to the same directory <Directory "/opt/www/"> Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 9 / 12
  212. 212. Default resource ● DirectoryIndex ● set the list of resources to look for when the client request a default one – http://www.example.com/ DirectoryIndex index.html index.php ● if none of the resources exist and Indexes option is set, the server will generate its own listing of the directory – antislashn.org see the Options directives Tomcat and Apache httpd - Configuring Apache httpd 10 / 12
  213. 213. 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 nickname LogFormat "%h %l %u %t "%r" %>s %b" common antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 11 / 12
  214. 214. 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 LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined CustomLog logs/access_log 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" antislashn.org Tomcat and Apache httpd - Configuring Apache httpd 12 / 12
  215. 215. Apache httpd Virtual host version 1.0
  216. 216. Virtual host overview ● Practice of running more than web site on a single machine ● can be – IP-based ● – name-based ● antislashn.org an IP address per web site more than web site per IP address Tomcat and Apache httpd - Virtual host with Apache httpd 2/6
  217. 217. Name-based virtual hosts ● You must have DNS entries ● use hosts file – /etc/hosts in CentOS 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 – C:WindowsSystem32driversetchosts in Windows 127.0.0.1 ::1 antislashn.org localhost toto.exemple localhost toto.exemple Tomcat and Apache httpd - Virtual host with Apache httpd 3/6
  218. 218. Name-based virtual hosts NameVirtualHost *:80 <VirtualHost *:80> DocumentRoot /www/example1 ServerName www.toto.exemple ServerAlias www.toto.example toto.example </VirtualHost> <VirtualHost *:80> DocumentRoot /www/example2 ServerName www.example.org </VirtualHost> antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 4/6
  219. 219. IP-based virtual hosts ● the server has two IP addresses ● ● Listen 80 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 # This is the "main" server running on 172.20.30.40 ServerName server.domain.com DocumentRoot /www/mainserver # This is the other address NameVirtualHost 172.20.30.50 <VirtualHost 172.20.30.50> DocumentRoot /www/example1 ServerName www.example.com # Other directives here ... </VirtualHost> <VirtualHost 172.20.30.50> DocumentRoot /www/example2 ServerName www.example.org # Other directives here ... </VirtualHost> antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 5/6
  220. 220. IP-based virtual hosts <VirtualHost 192.168.0.1:80> ServerAdmin webmaster@smallco.example.com DocumentRoot /groups/smallco/www ServerName smallco.example.com ErrorLog /groups/smallco/logs/error_log TransferLog /groups/smallco/logs/access_log </VirtualHost> <VirtualHost 192.168.0.2:80> ServerAdmin webmaster@baygroup.example.org DocumentRoot /groups/baygroup/www ServerName baygroup.example.com ErrorLog /groups/baygroup/logs/error_log TransferLog /groups/baygroup/logs/access_log </VirtualHost> antislashn.org Tomcat and Apache httpd - Virtual host with Apache httpd 6/6
  221. 221. Apache httpd Security version 1.1
  222. 222. 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 User apache Group apache ● Beware of SSI, CGI, aliases ● Watching your logs antislashn.org Tomcat and Apache httpd - Security with Apache httpd 2 / 31
  223. 223. Options directive ● Controls which server features are available in a particular directory ● ● Syntax Options [+|-] option [[+|-] option] ... 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 antislashn.org Tomcat and Apache httpd - Security with Apache httpd 3 / 31
  224. 224. 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 – antislashn.org cf. mod_include module Tomcat and Apache httpd - Security with Apache httpd 4 / 31
  225. 225. 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 5 / 31
  226. 226. 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 6 / 31
  227. 227. Allow directive ● The first argument is always from Allow from all all hosts are allowed access (subject to the configuration of the Deny and Order directives) hosts whose name match, or end in, with the string are allowed access this configuration will cause Apache to perform a double DNS lookup per client access Allow from example.org Allow from .com toto.net Allow from 10.1.2.3 Allow from 192.168.1.104 192.168.1.205 an IP address of a host allowed access Allow from 10.1 Allow 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 7 / 31
  228. 228. Allow directive ● Examples Allow from 10.1.10.0.0/255.255.0.0 Allow from 2001::db8::a00::20ff::fea7::ccea SetEnvIf User-Agent ^KnockKnock/2.0 let_me_in <Directory /docroot> Order Deny,Allow Deny from all Allow from env=let_me_in </Directory> antislashn.org a network a.b.c.d and a netmask w.x.y.z IP v6 addresses browsers with a user-agent string beginning with KnockKnock/2.0 will be allowed to access all others will be denied Tomcat and Apache httpd - Security with Apache httpd 8 / 31
  229. 229. 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 9 / 31
  230. 230. 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 10 / 31
  231. 231. 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 11 / 31
  232. 232. 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 12 / 31
  233. 233. Order directive ● Examples Order Deny,Allow Deny from all Allow from example.com Order Allow,Deny Allow from example.com Deny from foo.example.com antislashn.org all hosts in example.com domain are allowed access all other hosts are denied access all hosts in the example.com domain are allowed access, except the hosts which are in foo.example.com subdomain all hosts not in the example.com domain are denied access Tomcat and Apache httpd - Security with Apache httpd 13 / 31
  234. 234. 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 14 / 31
  235. 235. 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 15 / 31
  236. 236. Authentication web site realm (AuthName directive) antislashn.org Tomcat and Apache httpd - Security with Apache httpd 16 / 31
  237. 237. Authentication ● Two authentication type ● see the AuthType directive ● Basic – ● Digest – ● mod_auth_basic module mod_auth_digest module Based on two fundamental informations ● authentication provider – ● AuthDigestProvider, AuthBasicProvider directives authorization – antislashn.org Require directive Tomcat and Apache httpd - Security with Apache httpd 17 / 31
  238. 238. Authentication ● Example <Directory d:/www/autorise> AuthName "Royaume secret" AuthType Basic require valid-user AuthUserFile D:/passwords </Directory> ● AuthName : name of the realm ● AuthType : Basic or Digest ● AuthUserFile : passwords file ● Required : group, user or valid-user antislashn.org Tomcat and Apache httpd - Security with Apache httpd 18 / 31
  239. 239. 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 <Limit POST PUT DELETE> Require valid-user </Limit> ● see also <LimitExcept> directive antislashn.org Tomcat and Apache httpd - Security with Apache httpd 19 / 31
  240. 240. 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 20 / 31
  241. 241. 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 21 / 31
  242. 242. Basic authentication ● Create the group file ● ● simple text-plain each line of group contains a groupname followed by the list of user groups – mygroup: bob joe anne ● Configure the server <Directory d:/www/autorise> AuthName "Royaume secret" AuthType Basic require group chef AuthUserFile D:/htpasswd AuthGroupFile D:/htgroup </Directory> antislashn.org Tomcat and Apache httpd - Security with Apache httpd 22 / 31
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×