Full Code of dschadow/Java-Web-Security for AI

main b34e8f6a4758 cached
158 files
226.7 KB
63.0k tokens
208 symbols
1 requests
Download .txt
Showing preview only (272K chars total). Download the full file or copy to clipboard to get everything.
Repository: dschadow/Java-Web-Security
Branch: main
Commit: b34e8f6a4758
Files: 158
Total size: 226.7 KB

Directory structure:
gitextract_58dy3jvz/

├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── maven.yml
├── .gitignore
├── Ch04_OutputEscaping/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── resources/
│           │   └── ESAPI.properties
│           └── webapp/
│               ├── index.jsp
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               ├── withOutputEscaping.jsp
│               └── withoutOutputEscaping.jsp
├── Ch04_OutputEscapingJSF/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── ContactController.java
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── contact.xhtml
│               ├── index.xhtml
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch04_OutputEscapingJSP/
│   ├── pom.xml
│   └── src/
│       ├── main/
│       │   ├── java/
│       │   │   └── de/
│       │   │       └── dominikschadow/
│       │   │           └── webappsecurity/
│       │   │               ├── OutputEscapingWebAppInitializer.java
│       │   │               ├── WebConfig.java
│       │   │               ├── controller/
│       │   │               │   ├── ContactController.java
│       │   │               │   └── IndexController.java
│       │   │               └── domain/
│       │   │                   └── Contact.java
│       │   ├── resources/
│       │   │   └── logback.xml
│       │   └── webapp/
│       │       ├── WEB-INF/
│       │       │   └── views/
│       │       │       ├── contact.jsp
│       │       │       └── index.jsp
│       │       └── resources/
│       │           └── styles.css
│       └── test/
│           └── java/
│               └── de/
│                   └── dominikschadow/
│                       └── webappsecurity/
│                           └── controller/
│                               ├── ContactControllerTest.java
│                               └── IndexControllerTest.java
├── Ch05_AccessReferenceMaps/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── AccountController.java
│           │               ├── AccountIntegerController.java
│           │               ├── AccountRandomController.java
│           │               ├── AccountsDAO.java
│           │               ├── AccountsIntegerDAO.java
│           │               ├── AccountsRandomDAO.java
│           │               ├── HibernateUtil.java
│           │               └── domain/
│           │                   ├── Account.java
│           │                   └── User.java
│           ├── resources/
│           │   ├── ESAPI.properties
│           │   ├── context.xml
│           │   ├── hibernate.cfg.xml
│           │   ├── import.sql
│           │   └── logback.xml
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── account.xhtml
│               ├── accountInteger.xhtml
│               ├── accountRandom.xhtml
│               ├── index.xhtml
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch05_HSTS/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── filter/
│           │               │   └── HSTSFilter.java
│           │               └── servlets/
│           │                   └── LoginServlet.java
│           ├── resources/
│           │   └── logback.xml
│           └── webapp/
│               ├── WEB-INF/
│               │   └── web.xml
│               ├── index.jsp
│               └── styles.css
├── Ch05_SessionFixation/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── servlets/
│           │                   └── LoginServlet.java
│           ├── resources/
│           │   ├── context.xml
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch05_SessionHandling/
│   ├── pom.xml
│   └── src/
│       └── main/
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── index.xhtml
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch06_SQLInjection/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── domain/
│           │               │   └── Customer.java
│           │               └── servlets/
│           │                   ├── CustomerTable.java
│           │                   ├── HQLServlet.java
│           │                   ├── HibernateUtil.java
│           │                   ├── InitDbServlet.java
│           │                   ├── PreparedStatementServlet.java
│           │                   ├── StatementEscapingServlet.java
│           │                   └── StatementServlet.java
│           ├── resources/
│           │   ├── ESAPI.properties
│           │   ├── context.xml
│           │   ├── hibernate.cfg.xml
│           │   ├── import.sql
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch06_XPathInjection/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── servlets/
│           │                   ├── XPathEscapingServlet.java
│           │                   └── XPathServlet.java
│           ├── resources/
│           │   ├── ESAPI.properties
│           │   ├── customer.xml
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch07_CSP/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── CSPReporting.java
│           │               ├── WithCSPReportingServlet.java
│           │               ├── WithCSPServlet.java
│           │               └── WithoutCSPServlet.java
│           ├── resources/
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch07_XSS/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── beans/
│           │               │   ├── CustomerController.java
│           │               │   └── SearchController.java
│           │               ├── daos/
│           │               │   ├── CustomerDAO.java
│           │               │   └── HibernateUtil.java
│           │               └── domain/
│           │                   └── Customer.java
│           ├── resources/
│           │   ├── context.xml
│           │   ├── hibernate.cfg.xml
│           │   ├── import.sql
│           │   └── logback.xml
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── createCustomer.xhtml
│               ├── index.xhtml
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               ├── search.xhtml
│               ├── searchCustomer.xhtml
│               └── showCustomers.xhtml
├── Ch07_XSSFilter/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── filter/
│           │                   ├── BlacklistFilter.java
│           │                   ├── BlacklistRequestWrapper.java
│           │                   ├── ESAPIFilter.java
│           │                   └── ESAPIRequestWrapper.java
│           ├── resources/
│           │   └── ESAPI.properties
│           └── webapp/
│               ├── WEB-INF/
│               │   └── web.xml
│               ├── index.jsp
│               ├── outputBlacklist.jsp
│               ├── outputEsapi.jsp
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch07_XSSJSF/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── MaximumController.java
│           │               ├── StandardController.java
│           │               └── Status.java
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── index.xhtml
│               ├── maximum.xhtml
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               └── standard.xhtml
├── Ch08_CSRF/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── servlets/
│           │               │   ├── ProtectedServlet.java
│           │               │   └── UnprotectedServlet.java
│           │               └── token/
│           │                   └── CSRFTokenHandler.java
│           ├── resources/
│           │   └── logback.xml
│           └── webapp/
│               ├── form-protected.html
│               ├── form-unprotected.html
│               ├── form-working.jsp
│               ├── image-protected.html
│               ├── image-unprotected.html
│               ├── index.jsp
│               ├── requests-protected.html
│               ├── requests-unprotected.html
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               ├── xmlhttprequest-protected.html
│               └── xmlhttprequest-unprotected.html
├── LICENSE
├── README.md
└── pom.xml

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/dependabot.yml
================================================
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
  - package-ecosystem: "maven" # See documentation for possible values
    directory: "/" # Location of package manifests
    schedule:
      interval: "daily"


================================================
FILE: .github/workflows/maven.yml
================================================
name: Build

on:
  push:
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    name: JavaWebSecurity Build
    steps:
    - name: Checkout
      uses: actions/checkout@v5
    - name: Configure Java for Build
      uses: actions/setup-java@v5
      with:
        distribution: 'temurin'
        java-version: '17'
        cache: 'maven'
    - name: Build with Maven
      run: mvn -B package --file pom.xml


================================================
FILE: .gitignore
================================================
*.class
.idea
.classpath
.project
.DS_Store
*/target*
target/
.settings*
# Package Files #
*.jar
*.war
*.ear
*.iml
*.log
*.lck
.pmd
.forge_settings
accountsDB.properties
customerDB.properties

================================================
FILE: Ch04_OutputEscaping/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.dominikschadow.javawebsecurity</groupId>
		<artifactId>javawebsecurity</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>Ch04_OutputEscaping</artifactId>
	<packaging>war</packaging>
	<name>Chapter 04 - Output Escaping</name>
	<url>https://github.com/dschadow/Java-Web-Security</url>
	<description>Chapter 4 Output Escaping sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch04_OutputEscaping</description>

	<dependencies>
		<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
		<dependency>
			<groupId>org.owasp.esapi</groupId>
			<artifactId>esapi</artifactId>
		</dependency>
	</dependencies>
	
	<build>
		<finalName>Ch04_OutputEscaping</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
		<plugins>
			<plugin>
                <groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
			</plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
		</plugins>
	</build>
</project>

================================================
FILE: Ch04_OutputEscaping/src/main/resources/ESAPI.properties
================================================
# Logging
Logger.ApplicationName=Ch04_OutputEscaping

================================================
FILE: Ch04_OutputEscaping/src/main/webapp/index.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="resources/css/styles.css" />
	<title>Chapter 04 - Output Escaping</title>
</head>
<body>
	<h1>Chapter 04 - Output Escaping</h1>

	<p>This demo application shows how JavaServer Pages (JSP) can be extended with safe output escaping provided by the
        OWASP Enterprise Security API (ESAPI). Feel free to enter any attack data like
        <strong>&lt;script&gt;alert(&apos;XSS&apos;)&lt;/script&gt;</strong>.</p>

	<form name="withoutOutputEscaping" method="post" action="withoutOutputEscaping.jsp">
		<fieldset>
			<legend>Without Output Escaping</legend>
			<label for="unprotected" title="Name">Name</label>
			<input type="text" id="unprotected" name="unprotected" class="text-input" />
			<input type="submit" value="Submit" />
		</fieldset>
	</form>

	<form name="withOutputEscaping" method="post" action="withOutputEscaping.jsp">
		<fieldset>
			<legend>With Output Escaping</legend>
			<label for="protected" title="Name">Name</label>
			<input type="text" id="protected" name="protected" class="text-input" />
			<input type="submit" value="Submit" />
		</fieldset>
	</form>
</body>
</html>


================================================
FILE: Ch04_OutputEscaping/src/main/webapp/resources/css/styles.css
================================================
h1 {
    font-size: 1.5em;
}

h2 {
    font-size: 1.2em;
}

fieldset {
    width: 450px;
    font-size: 1.2em;
    margin-top: 20px;
}

input {
    display: inline-block;
    vertical-align: middle;
    width: 250px;
}

input[type=submit] {
    width: 75px;
    height: 20px;
    margin-left: 10px;
}

label {
    margin-right: 10px;
}


================================================
FILE: Ch04_OutputEscaping/src/main/webapp/withOutputEscaping.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="org.owasp.esapi.ESAPI" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="resources/css/styles.css" />
	<title>Chapter 04 - Output Escaping</title>
</head>
<body>
    <h1>Chapter 04 - Output Escaping</h1>

    <p>The provided input is printed output escaped. Output escaping is done by the Enterprise Security API (ESAPI) for
        different contexts. Only HTML is the correct context here, the others are provided for reference only. The input
        is printed into [] to show its position.</p>

    <h2>CSS</h2>
    <p>[<%= ESAPI.encoder().encodeForCSS(request.getParameter("protected")) %>]</p>

    <h2>HTML</h2>
	<p>[<%= ESAPI.encoder().encodeForHTML(request.getParameter("protected")) %>]</p>

    <h2>HTML Attribute</h2>
    <p>[<%= ESAPI.encoder().encodeForHTMLAttribute(request.getParameter("protected")) %>]</p>

    <h2>JavaScript</h2>
    <p>[<%= ESAPI.encoder().encodeForJavaScript(request.getParameter("protected")) %>]</p>

    <h2>URL</h2>
    <p>[<%= ESAPI.encoder().encodeForURL(request.getParameter("protected")) %>]</p>

    <h2>XML</h2>
    <p>[<%= ESAPI.encoder().encodeForXML(request.getParameter("protected")) %>]</p>

    <h2>XML Attribute</h2>
    <p>[<%= ESAPI.encoder().encodeForXMLAttribute(request.getParameter("protected")) %>]</p>

    <h2>XPath</h2>
    <p>[<%= ESAPI.encoder().encodeForXPath(request.getParameter("protected")) %>]</p>

    <p><a href="index.jsp">Back</a></p>
</body>
</html>

================================================
FILE: Ch04_OutputEscaping/src/main/webapp/withoutOutputEscaping.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="resources/css/styles.css" />
	<title>Chapter 04 - Output Escaping</title>
</head>
<body>
    <h1>Chapter 04 - Output Escaping</h1>

	<p>This is your input without any output escaping at all. The input is printed into [] to show its position.</p>

	<p>[<%= request.getParameter("unprotected") %>]</p>

	<p><a href="index.jsp">Back</a></p>
</body>
</html>

================================================
FILE: Ch04_OutputEscapingJSF/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0    http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.dominikschadow.javawebsecurity</groupId>
		<artifactId>javawebsecurity</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>Ch04_OutputEscapingJSF</artifactId>
	<packaging>war</packaging>
	<name>Chapter 04 - JSF Output Escaping</name>
	<url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 4 JSF Output Escaping sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch04_OutputEscapingJSF</description>

	<dependencies>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
		</dependency>
	</dependencies>

	<build>
		<finalName>Ch04_OutputEscapingJSF</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
		<plugins>
			<plugin>
                <groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

================================================
FILE: Ch04_OutputEscapingJSF/src/main/java/de/dominikschadow/webappsecurity/ContactController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serial;
import java.io.Serializable;

/**
 * Bean representing user input (no additional security related attributes).
 * 
 * @author Dominik Schadow
 */
@ManagedBean(name = "contact")
@SessionScoped
public class ContactController implements Serializable {
    @Serial
    private static final long serialVersionUID = 4083596061570021965L;

    private String firstname;
    private String lastname;

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

================================================
FILE: Ch04_OutputEscapingJSF/src/main/webapp/WEB-INF/faces-config.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
</faces-config>

================================================
FILE: Ch04_OutputEscapingJSF/src/main/webapp/WEB-INF/web.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <display-name>Ch04_OutputEscapingJSF</display-name>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

================================================
FILE: Ch04_OutputEscapingJSF/src/main/webapp/contact.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 04 - JSF Output Escaping</title>
</h:head>
<h:body>
    <h1>Chapter 04 - JSF Output Escaping</h1>

	<h:form>
        <h2>Input displayed with direct value expression</h2>
        <p>#{contact.firstname} #{contact.lastname}</p>

		<h2>Input displayed with &lt;h:outputText /&gt; element</h2>
		<p><h:outputText value="#{contact.firstname}" /><h:outputText value=" " /><h:outputText value="#{contact.lastname}" /></p>
	</h:form>

    <a href="index.xhtml">Back</a>
</h:body>
</html>

================================================
FILE: Ch04_OutputEscapingJSF/src/main/webapp/index.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 04 - JSF Output Escaping</title>
</h:head>
<h:body>
	<h1>Chapter 04 - JSF Output Escaping</h1>

    <p>This demo application shows how JavaServer Faces (JSF) handle output escaping with direct value expressions and normal elements/
        attributes. Feel free to enter any attack data like <strong>&lt;script&gt;alert(&apos;XSS&apos;)&lt;/script&gt;</strong>.</p>

    <h:form id="addContact">
        <h:panelGrid columns="2">
            <h:outputLabel value="First name" for="firstname" />
            <h:inputText value="#{contact.firstname}" label="Firstname" id="firstname"/>

            <h:outputLabel value="Last name" for="lastname" />
            <h:inputText value="#{contact.lastname}" label="Lastname" id="lastname"/>
        </h:panelGrid>
        <h:commandButton value="Submit" action="contact" />
    </h:form>
</h:body>
</html>

================================================
FILE: Ch04_OutputEscapingJSF/src/main/webapp/resources/css/styles.css
================================================
h1 {
    font-size: 1.5em;
}

h2 {
    font-size: 1.2em;
}


================================================
FILE: Ch04_OutputEscapingJSP/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>de.dominikschadow.javawebsecurity</groupId>
        <artifactId>javawebsecurity</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>Ch04_OutputEscapingJSP</artifactId>
    <packaging>war</packaging>
    <name>Chapter 04 - JSP Output Escaping</name>
    <url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 4 JSP Output Escaping sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch04_OutputEscapingJSP</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>Ch04_OutputEscapingJSP</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

================================================
FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/OutputEscapingWebAppInitializer.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 *
 * @author Dominik Schadow
 */
public class OutputEscapingWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}


================================================
FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/WebConfig.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @author Dominik Schadow
 */
@Configuration
@EnableWebMvc
@ComponentScan("de.dominikschadow.webappsecurity.controller")
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}


================================================
FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/controller/ContactController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.controller;

import de.dominikschadow.webappsecurity.domain.Contact;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 * 
 * @author Dominik Schadow
 */
@Controller
@SessionAttributes
public class ContactController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ContactController.class);

    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public String addContact(@ModelAttribute Contact contact, Model model) {
        LOGGER.info("Contact first name: {}, last name: {}", contact.getFirstname(), contact.getLastname());

        model.addAttribute("contact", contact);

        return "contact";
    }
}


================================================
FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/controller/IndexController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * Controller to handle GET requests for the home page.
 *
 * @author Dominik Schadow
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {
    @RequestMapping(method = GET)
    public String index() {
        return "index";
    }
}


================================================
FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/domain/Contact.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.domain;

/**
 * 
 * @author Dominik Schadow
 */
public class Contact {
    private String firstname;
    private String lastname;

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}


================================================
FILE: Ch04_OutputEscapingJSP/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch04_OutputEscapingJSP/src/main/webapp/WEB-INF/views/contact.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="<c:url value="/resources/styles.css" />" >
        <title>Chapter 04 - JSP Output Escaping</title>
    </head>
    <body>
        <h1>Chapter 04 - JSP Output Escaping</h1>

        <h2>Input displayed as direct value expression</h2>
        <p>${contact.firstname} ${contact.lastname}</p>

        <h2>Input displayed as out element</h2>
        <p><c:out value="${contact.firstname}" /> <c:out value="${contact.lastname}" /></p>

        <h2>Input displayed inside Spring escapeBody element as direct value expression</h2>
        <p><s:escapeBody htmlEscape="true">${contact.firstname} ${contact.lastname}</s:escapeBody></p>

        <a href="<c:url value="/" />">Back</a>
    </body>
</html>

================================================
FILE: Ch04_OutputEscapingJSP/src/main/webapp/WEB-INF/views/index.jsp
================================================
<%@ page session="false" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="<c:url value="/resources/styles.css" />" >
    <title>Chapter 04 - JSP Output Escaping</title>
</head>
<body>
	<h1>Chapter 04 - JSP Output Escaping</h1>

	<p>This demo application shows how JavaServer Pages (JSP) handle output escaping with direct value expressions and
        normal elements/ attributes. Feel free to enter any attack data like <strong>&lt;script&gt;alert(&apos;XSS&apos;)&lt;/script&gt;</strong>.</p>

	<form method="post" action="addContact">
		<fieldset>
			<legend>Add new contact</legend>
			<label for="firstname" title="First name">First name</label>
			<input type="text" id="firstname" name="firstname" class="text-input" />
			<label for="lastname" title="Last name">Last name</label>
			<input type="text" id="lastname" name="lastname" class="text-input" />
			<input type="submit" value="Submit" />
		</fieldset>
	</form>
</body>
</html>

================================================
FILE: Ch04_OutputEscapingJSP/src/main/webapp/resources/styles.css
================================================
h1 {
    font-size: 1.5em;
}

h2 {
    font-size: 1.2em;
}

fieldset {
    width: 600px;
    font-size: 1.2em;
    margin-top: 20px;
}

input {
    display: inline-block;
    vertical-align: middle;
    width: 150px;
}

input[type=submit] {
    width: 75px;
    height: 20px;
    margin-left: 10px;
}

label {
    margin-right: 10px;
}


================================================
FILE: Ch04_OutputEscapingJSP/src/test/java/de/dominikschadow/webappsecurity/controller/ContactControllerTest.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.controller;

import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
 *
 * @author Dominik Schadow
 */
public class ContactControllerTest {
    @Test
    public void testContactPage() throws Exception {
        ContactController controller = new ContactController();
        MockMvc mockMvc = standaloneSetup(controller).build();

        mockMvc.perform(post("/addContact")).andExpect(view().name("contact"));
    }
}


================================================
FILE: Ch04_OutputEscapingJSP/src/test/java/de/dominikschadow/webappsecurity/controller/IndexControllerTest.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.controller;

import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

/**
 *
 * @author Dominik Schadow
 */
public class IndexControllerTest {
    @Test
    public void testIndexPage() throws Exception {
        IndexController controller = new IndexController();
        MockMvc mockMvc = standaloneSetup(controller).build();

        mockMvc.perform(get("/")).andExpect(view().name("index"));
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.dominikschadow.javawebsecurity</groupId>
		<artifactId>javawebsecurity</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>Ch05_AccessReferenceMaps</artifactId>
	<packaging>war</packaging>
	<name>Chapter 05 - Access Reference Maps</name>
	<url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 5 Access Reference sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch05_AccessReferenceMaps</description>

    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
        </dependency>
		<dependency>
			<groupId>org.owasp.esapi</groupId>
			<artifactId>esapi</artifactId>
		</dependency>
		<dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
		</dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
	</dependencies>
	
	<build>
        <finalName>Ch05_AccessReferenceMaps</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
		<plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <contextFile>${project.basedir}/src/main/resources/context.xml</contextFile>
                </configuration>
            </plugin>
		</plugins>
	</build>
</project>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import de.dominikschadow.webappsecurity.domain.Account;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Managed bean to access an account by account id. Does not verify the given account id and therefore does not
 * provide any protection.
 *
 * @author Dominik Schadow
 */
@ManagedBean(name = "account")
@SessionScoped
public class AccountController implements Serializable {
    private Account account;
    private int userId = 42;
    private int accountId = 1;
    private transient AccountsDAO dao;
    private List<String> accountReferences = new ArrayList<>();

    public int getAccountId() {
        return accountId;
    }

    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }

    public int getUserId() {
        return userId;
    }

    public Account getAccount() {
        return account;
    }

    public List<String> getAccountReferences() {
        return accountReferences;
    }

    public AccountController() {
        dao = new AccountsDAO();

        accountReferences = dao.getAccountsForUser(userId);
    }

    public String show() {
        account = dao.loadAccount(accountId);

        return "account";
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountIntegerController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import de.dominikschadow.webappsecurity.domain.Account;
import de.dominikschadow.webappsecurity.domain.User;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Managed bean to access an account by account reference (IntegerAccessReferenceMap). Only accounts belonging to the
 * current user are contained in this map.
 *
 * @author Dominik Schadow
 */
@ManagedBean(name = "accountInteger")
@SessionScoped
public class AccountIntegerController implements Serializable {
    private List<String> accountReferences = new ArrayList<>();
    private int iaAccountId = 1;
    private int userId = 42;
    private transient AccountsIntegerDAO dao;

    public int getIaAccountId() {
        return iaAccountId;
    }

    public void setIaAccountId(int iaAccountId) {
        this.iaAccountId = iaAccountId;
    }

    public int getUserId() {
        return userId;
    }

    public Account getAccount() {
        return dao.retrieveAccount(iaAccountId);
    }

    public List<String> getAccountReferences() {
        return accountReferences;
    }

    public AccountIntegerController() {
        User currentUser = new User();
        currentUser.setUserId(userId);

        dao = new AccountsIntegerDAO();
        accountReferences = dao.loadAccountsForUser(currentUser);
    }

    public String show() {
        return "accountInteger";
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountRandomController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import de.dominikschadow.webappsecurity.domain.Account;
import de.dominikschadow.webappsecurity.domain.User;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Managed bean to access an account by account reference (RandomAccessReferenceMap). Only accounts belonging to the
 * current user are contained in this map.
 *
 * @author Dominik Schadow
 */
@ManagedBean(name = "accountRandom")
@SessionScoped
public class AccountRandomController implements Serializable {
    private List<String> accountReferences = new ArrayList<>();
    private String raAccountId = "";
    private int userId = 42;
    private transient AccountsRandomDAO dao;

    public String getRaAccountId() {
        return raAccountId;
    }

    public void setRaAccountId(String raAccountId) {
        this.raAccountId = raAccountId;
    }

    public int getUserId() {
        return userId;
    }

    public Account getAccount() {
        return dao.retrieveAccount(raAccountId);
    }

    public List<String> getAccountReferences() {
        return accountReferences;
    }

    public AccountRandomController() {
        User currentUser = new User();
        currentUser.setUserId(userId);

        dao = new AccountsRandomDAO();
        accountReferences = dao.loadAccountsForUser(currentUser);
    }

    public String show() {
        return "accountRandom";
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsDAO.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import de.dominikschadow.webappsecurity.domain.Account;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static de.dominikschadow.webappsecurity.HibernateUtil.getSessionFactory;

/**
 * Loads accounts from the in-memory-database for the unprotected managed bean.
 *
 * @author Dominik Schadow
 * @see AccountController
 */
public class AccountsDAO {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountsDAO.class);

    public List<String> getAccountsForUser(int userId) {
        return queryAccounts(userId);
    }

    public Account loadAccount(int id) {
        return queryAccount(id);
    }

    private Account queryAccount(int id) {
        try (Session session = getSessionFactory().openSession()) {
            Query query = session.createQuery("FROM Account WHERE accountId = :id");
            query.setParameter("id", id);

            return (Account) query.uniqueResult();
        } catch (HibernateException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        return null;
    }

    private List<String> queryAccounts(int userId) {
        List<String> accountReferences = new ArrayList<>();

        try (Session session = getSessionFactory().openSession()) {
            Query query = session.createNativeQuery("SELECT accountId FROM account WHERE ownerId = :id");
            query.setParameter("id", userId);

            accountReferences = query.list();

            LOGGER.info("Found {} account references", accountReferences.size());
        } catch (HibernateException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        return accountReferences;
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsIntegerDAO.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import de.dominikschadow.webappsecurity.domain.Account;
import de.dominikschadow.webappsecurity.domain.User;
import org.owasp.esapi.errors.AccessControlException;
import org.owasp.esapi.reference.IntegerAccessReferenceMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static de.dominikschadow.webappsecurity.HibernateUtil.queryUserAccounts;

/**
 * Loads accounts from the in-memory-database for the protected managed bean.
 *
 * @author Dominik Schadow
 * @see AccountIntegerController
 */
public class AccountsIntegerDAO {
    private IntegerAccessReferenceMap accounts = new IntegerAccessReferenceMap();
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountsIntegerDAO.class);

    public Account retrieveAccount(int accountId) {
        String accountReference = String.valueOf(accountId);

        try {
            return accounts.getDirectReference(accountReference);
        } catch (AccessControlException ex) {
            LOGGER.error("Access to " + accountReference + " denied", ex);

            return null;
        }
    }

    public List<String> loadAccountsForUser(User user) {
        return queryAccounts(user);
    }

    private List<String> queryAccounts(User user) {
        List<Account> ownAccounts = queryUserAccounts(user);
        LOGGER.info("Found {} account references", ownAccounts.size());

        List<String> accountReferences = new ArrayList<>();
        for (Account account : ownAccounts) {
            accounts.addDirectReference(account);
            accountReferences.add(accounts.getIndirectReference(account));
        }

        return accountReferences;
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsRandomDAO.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import de.dominikschadow.webappsecurity.domain.Account;
import de.dominikschadow.webappsecurity.domain.User;
import org.owasp.esapi.errors.AccessControlException;
import org.owasp.esapi.reference.RandomAccessReferenceMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static de.dominikschadow.webappsecurity.HibernateUtil.queryUserAccounts;

/**
 * Loads accounts from the in-memory-database for the protected managed bean.
 *
 * @author Dominik Schadow
 * @see AccountRandomController
 */
public class AccountsRandomDAO {
    private RandomAccessReferenceMap accounts = new RandomAccessReferenceMap();
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountsRandomDAO.class);

    public Account retrieveAccount(String accountReference) {
        try {
            return accounts.getDirectReference(accountReference);
        } catch (AccessControlException ex) {
            LOGGER.error("Access to " + accountReference + " denied", ex);

            return null;
        }
    }

    public List<String> loadAccountsForUser(User user) {
        return queryAccounts(user);
    }

    private List<String> queryAccounts(User user) {
        List<Account> ownAccounts = queryUserAccounts(user);
        LOGGER.info("Found {} account references", ownAccounts.size());

        List<String> accountReferences = new ArrayList<>();
        for (Account account : ownAccounts) {
            accounts.addDirectReference(account);
            accountReferences.add(accounts.getIndirectReference(account));
        }

        return accountReferences;
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/HibernateUtil.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import de.dominikschadow.webappsecurity.domain.Account;
import de.dominikschadow.webappsecurity.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;

import java.util.List;

/**
 * @author Dominik Schadow
 */
public class HibernateUtil {
    static SessionFactory sessionFactory;

    /**
     * Util class, no constructor required.
     */
    private HibernateUtil() {
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }

        return sessionFactory;
    }

    public static List<Account> queryUserAccounts(User user) {
        Session session = getSessionFactory().openSession();
        Query query = session.createQuery("FROM Account WHERE ownerId = :id");
        query.setParameter("id", user.getUserId());

        List<Account> accounts = query.list();

        session.close();

        return accounts;
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/domain/Account.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.domain;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;

/**
 * Simple account object representing one user account.
 *
 * @author Dominik Schadow
 */
@Entity
public class Account implements Serializable {
    @Id
    private int accountId;
    private String name;
    private String type;
    private int ownerId;

    public int getAccountId() {
        return accountId;
    }

    public void setAccountId(int accountId) {
        this.accountId = accountId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(int ownerId) {
        this.ownerId = ownerId;
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/domain/User.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.domain;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.io.Serializable;

/**
 * Represents a simple user.
 *
 * @author Dominik Schadow
 */
@Entity
public class User implements Serializable {
    @Id
    private int userId;
    private String name;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


================================================
FILE: Ch05_AccessReferenceMaps/src/main/resources/ESAPI.properties
================================================
# Logging
Logger.ApplicationName=Ch05_AccessReferenceMaps

================================================
FILE: Ch05_AccessReferenceMaps/src/main/resources/context.xml
================================================
<?xml version='1.0' encoding='utf-8'?>
<Context useHttpOnly="false">
    <Resource name="mapDS" auth="Container" type="javax.sql.DataSource"
              maxActive="100" maxIdle="30" maxWait="10000"
              username="sa" password="sa" driverClassName="org.h2.Driver"
              url="jdbc:h2:mem:mapDS"/>
</Context>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/resources/hibernate.cfg.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.connection.datasource">java:comp/env/mapDS</property>
        <property name="hibernate.hbm2ddl.auto">create-drop</property>
        <property name="show_sql">false</property>
        <mapping package="de.dominikschadow.webappsecurity.domain"/>
        <mapping class="de.dominikschadow.webappsecurity.domain.Account"/>
        <mapping class="de.dominikschadow.webappsecurity.domain.User"/>
    </session-factory>
</hibernate-configuration>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/resources/import.sql
================================================
INSERT INTO ACCOUNT (accountid, name, type, ownerid) VALUES (1, 'Marvin Savings', 'Savings', 42);
INSERT INTO ACCOUNT (accountid, name, type, ownerid) VALUES (2, 'Marvin Credit Card',' Credit Card', 42);
INSERT INTO ACCOUNT (accountid, name, type, ownerid) VALUES (3, 'Zaphod Savings',' Savings', 55);
INSERT INTO ACCOUNT (accountid, name, type, ownerid) VALUES (4, 'Ford Prefect Credit Card', 'Credit Card', 10);
INSERT INTO ACCOUNT (accountid, name, type, ownerid) VALUES (5, 'Ford Prefect Savings', 'Savings', 10);

================================================
FILE: Ch05_AccessReferenceMaps/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/webapp/WEB-INF/faces-config.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
</faces-config>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/webapp/WEB-INF/web.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <display-name>Ch05_AccessReferenceMaps</display-name>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/webapp/account.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 05 - Access Reference Maps</title>
</h:head>
<h:body>
	<h1>Chapter 05 - Access Reference Maps</h1>

    <p>Account details (user id #{account.userId}).</p>

    <h:panelGrid columns="2" rendered="#{account.account != null}">
        <strong>Account name</strong> <h:outputText value="#{account.account.name}" />
        <strong>Account type</strong> <h:outputText value="#{account.account.type}" />
        <strong>Account id</strong> <h:outputText value="#{account.account.accountId}" />
        <strong>Account owner</strong> <h:outputText value="#{account.account.ownerId}" />
    </h:panelGrid>

    <h:panelGrid columns="1" rendered="#{account.account == null}">
        <p>No account found</p>
    </h:panelGrid>

    <p><a href="index.xhtml">Back</a></p>
</h:body>
</html>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/webapp/accountInteger.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 05 - Access Reference Maps</title>
</h:head>
<h:body>
	<h1>Chapter 05 - Access Reference Maps</h1>

    <p>Account details (user id #{accountInteger.userId}).</p>

    <h:panelGrid columns="2" rendered="#{accountInteger.account != null}">
        <strong>Account name</strong> <h:outputText value="#{accountInteger.account.name}" />
        <strong>Account type</strong> <h:outputText value="#{accountInteger.account.type}" />
        <strong>Account id</strong> <h:outputText value="#{accountInteger.account.accountId}" />
        <strong>Account owner</strong> <h:outputText value="#{accountInteger.account.ownerId}" />
    </h:panelGrid>

    <h:panelGrid columns="1" rendered="#{accountInteger.account == null}">
        <p>No account found</p>
    </h:panelGrid>

    <p><a href="index.xhtml">Back</a></p>
</h:body>
</html>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/webapp/accountRandom.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 05 - Access Reference Maps</title>
</h:head>
<h:body>
	<h1>Chapter 05 - Access Reference Maps</h1>

    <p>Account details (user id #{accountRandom.userId}).</p>

    <h:panelGrid columns="2" rendered="#{accountRandom.account != null}">
        <strong>Account name</strong> <h:outputText value="#{accountRandom.account.name}" />
        <strong>Account type</strong> <h:outputText value="#{accountRandom.account.type}" />
        <strong>Account id</strong> <h:outputText value="#{accountRandom.account.accountId}" />
        <strong>Account owner</strong> <h:outputText value="#{accountRandom.account.ownerId}" />
    </h:panelGrid>

    <h:panelGrid columns="1" rendered="#{accountRandom.account == null}">
        <p>No account found</p>
    </h:panelGrid>

    <p><a href="index.xhtml">Back</a></p>
</h:body>
</html>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/webapp/index.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css"/>
    <title>Chapter 05 - Access Reference Maps</title>
</h:head>
<h:body>
    <h1>Chapter 05 - Access Reference Maps</h1>

    <p>Your user id is <strong>#{account.userId}</strong>.</p>

    <h2>Unprotected</h2>

    <p>Valid account references for user id #{account.userId} are <h:outputText
            value="#{account.accountReferences}"/>. All accounts between 1 and 5 are accessible.</p>

    <h:form id="unprotected">
        <h:panelGrid columns="3">
            <h:outputLabel value="Account ID" for="accountId"/>
            <h:inputText label="Account ID" value="#{account.accountId}" id="accountId">
                <f:validateLongRange minimum="1" maximum="100"/>
            </h:inputText>
            <h:commandButton value="Submit" action="#{account.show}" styleClass="send-button"/>
        </h:panelGrid>
    </h:form>

    <h2>Protected by IntegerAccessReferenceMap</h2>

    <p>Valid account references for user id #{accountInteger.userId} are <h:outputText
            value="#{accountInteger.accountReferences}"/>. Only these accounts are accessible.</p>

    <h:form id="protectedInteger">
        <h:panelGrid columns="3">
            <h:outputLabel value="Account Reference" for="iaAccountId"/>
            <h:inputText label="Account Reference" value="#{accountInteger.iaAccountId}" id="iaAccountId">
                <f:validateLongRange minimum="1" maximum="100"/>
            </h:inputText>
            <h:commandButton value="Submit" action="#{accountInteger.show}" styleClass="send-button"/>
        </h:panelGrid>
    </h:form>

    <h2>Protected by RandomAccessReferenceMap</h2>

    <p>Valid account references for user id #{accountRandom.userId} are <h:outputText
            value="#{accountRandom.accountReferences}"/>. Only these accounts are accessible.</p>

    <h:form id="protectedRandom">
        <h:panelGrid columns="3">
            <h:outputLabel value="Account Reference" for="raAccountId"/>
            <h:inputText label="Account Reference" value="#{accountRandom.raAccountId}" id="raAccountId"/>
            <h:commandButton value="Submit" action="#{accountRandom.show}" styleClass="send-button"/>
        </h:panelGrid>
    </h:form>
</h:body>
</html>

================================================
FILE: Ch05_AccessReferenceMaps/src/main/webapp/resources/css/styles.css
================================================
.send-button {
    margin-left: 25px;
}

h1 {
    font-size: 1.5em;
}

h2 {
    font-size: 1.2em;
}


================================================
FILE: Ch05_HSTS/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>javawebsecurity</artifactId>
        <groupId>de.dominikschadow.javawebsecurity</groupId>
        <version>1.0.0</version>
    </parent>
    <artifactId>Ch05_HSTS</artifactId>
    <packaging>war</packaging>
    <name>Chapter 05 - HSTS</name>
    <url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 5 HTTP Strict Transport Security (HSTS sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch05_HSTS</description>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>Ch05_HSTS</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

================================================
FILE: Ch05_HSTS/src/main/java/de/dominikschadow/webappsecurity/filter/HSTSFilter.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Filter to add the <code>Strict-Transport-Security</code> header to every response.
 *
 * @author Dominik Schadow
 */
public class HSTSFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(HSTSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {
        LOGGER.info("HSTSFilter init");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        ((HttpServletResponse) res).setHeader("Strict-Transport-Security", "max-age=12960000; includeSubdomains");
        LOGGER.info("Added Strict-Transport-Security header to response");

        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {
    }
}


================================================
FILE: Ch05_HSTS/src/main/java/de/dominikschadow/webappsecurity/servlets/LoginServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Servlet faking a user login. Invalidates the current session (and its session id) and creates a new one afterwards.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginServlet.class);
    @Serial
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        LOGGER.info("Received {} as POST parameter", name);

        // invalidate the current session
        request.getSession().invalidate();

        // create a new one and continue in the "login" process
        request.getSession(true);

        response.setContentType("text/html");

        try (PrintWriter out = response.getWriter()) {
            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Ch05_HSTS</h1>");
            out.println("<script type=\"text/javascript\">document.write(\"<p><strong>Session ID</strong> [\" + " +
                    "document.cookie + \"]</p>\")</script>");
            out.println("</body>");
            out.println("</html>");
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch05_HSTS/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch05_HSTS/src/main/webapp/WEB-INF/web.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="HSTS" version="3.0">
    <display-name>HSTS</display-name>
    <filter>
        <filter-name>HSTSFilter</filter-name>
        <filter-class>de.dominikschadow.webappsecurity.filter.HSTSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HSTSFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

================================================
FILE: Ch05_HSTS/src/main/webapp/index.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css" />
	<title>Chapter 05 - HTTP Strict Transport Security (HSTS)</title>
</head>
<body>
	<h1>Chapter 05 - HTTP Strict Transport Security (HSTS)</h1>

    <form name="login" method="post" action="LoginServlet">
        <table>
            <tr>
                <td><label for="stmt" title="Name">Name</label></td>
                <td><input type="text" id="stmt" name="name" class="text-input" /></td>
                <td><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


================================================
FILE: Ch05_HSTS/src/main/webapp/styles.css
================================================
.text-input {
    width: 250px;
}

h1 {
    font-size: 150%;
}

h2 {
    font-size: 125%;
}

td {
    font-size: 115%;
}

th {
    background-color: darkgrey;
    padding: 2pt;
    font-weight: bold;
    font-size: 125%;
}


================================================
FILE: Ch05_SessionFixation/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.dominikschadow.javawebsecurity</groupId>
		<artifactId>javawebsecurity</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>Ch05_SessionFixation</artifactId>
	<packaging>war</packaging>
	<name>Chapter 05 - Session Fixation</name>
	<url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 5 Session Fixation sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch05_SessionFixation</description>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
	</dependencies>

    <build>
        <finalName>Ch05_SessionFixation</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <contextFile>${project.basedir}/src/main/resources/context.xml</contextFile>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

================================================
FILE: Ch05_SessionFixation/src/main/java/de/dominikschadow/webappsecurity/servlets/LoginServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Servlet faking a user login. Invalidates the current session (and its session id) and creates a new one afterwards.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginServlet.class);
    @Serial
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        LOGGER.info("Received {} as POST parameter", name);

        // invalidate the current session
        request.getSession().invalidate();

        // create a new one and continue in the "login" process
        request.getSession(true);

        response.setContentType("text/html");

        try (PrintWriter out = response.getWriter()) {
            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Ch05_SessionFixation</h1>");
            out.println("<script type=\"text/javascript\">document.write(\"<p><strong>Session ID</strong> [\" + " +
                    "document.cookie + \"]</p>\")</script>");
            out.println("</body>");
            out.println("</html>");
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch05_SessionFixation/src/main/resources/context.xml
================================================
<?xml version='1.0' encoding='utf-8'?>
<Context useHttpOnly="false">

</Context>

================================================
FILE: Ch05_SessionFixation/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch05_SessionFixation/src/main/webapp/index.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css" />
	<title>Chapter 05 - Session Fixation</title>
</head>
<body>
	<h1>Chapter 05 - Session Fixation</h1>

    <script type="text/javascript">document.write("<p><strong>Session ID</strong> [" + document.cookie + "]</p>")</script>

	<form name="login" method="post" action="LoginServlet">
		<table>
			<tr>
				<td><label for="stmt" title="Name">Name</label></td>
				<td><input type="text" id="stmt" name="name" class="text-input" /></td>
				<td><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>
</body>
</html>


================================================
FILE: Ch05_SessionFixation/src/main/webapp/styles.css
================================================
.text-input {
    width: 250px;
}

h1 {
    font-size: 150%;
}

h2 {
    font-size: 125%;
}

td {
    font-size: 115%;
}

th {
    background-color: darkgrey;
    padding: 2pt;
    font-weight: bold;
    font-size: 125%;
}


================================================
FILE: Ch05_SessionHandling/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.dominikschadow.javawebsecurity</groupId>
		<artifactId>javawebsecurity</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>Ch05_SessionHandling</artifactId>
	<packaging>war</packaging>
	<name>Chapter 05 - Session Handling</name>
	<url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 5 Session Handling sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch05_SessionHandling</description>

    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
        </dependency>
	</dependencies>

    <build>
        <finalName>Ch05_SessionHandling</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

================================================
FILE: Ch05_SessionHandling/src/main/webapp/WEB-INF/faces-config.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
</faces-config>

================================================
FILE: Ch05_SessionHandling/src/main/webapp/WEB-INF/web.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <display-name>Ch05_SessionHandling</display-name>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

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

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
        <cookie-config>
            <http-only>true</http-only>
            <!-- secure is not working without a certificate and a properly configured webserver -->
            <!--<secure>true</secure>-->
        </cookie-config>
        <tracking-mode>COOKIE</tracking-mode>
    </session-config>
</web-app>

================================================
FILE: Ch05_SessionHandling/src/main/webapp/index.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 05 - Session Handling</title>
</h:head>
<h:body>
	<h1>Chapter 05 - Session Handling</h1>

    <p>Cookie information in popup is empty because of web.xml protection.</p>

    <script type="text/javascript">alert("Cookie Session ID [" + document.cookie + "]")</script>
</h:body>
</html>

================================================
FILE: Ch05_SessionHandling/src/main/webapp/resources/css/styles.css
================================================
h1 {
    font-size: 125%;
}


================================================
FILE: Ch06_SQLInjection/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>de.dominikschadow.javawebsecurity</groupId>
        <artifactId>javawebsecurity</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>Ch06_SQLInjection</artifactId>
    <packaging>war</packaging>
    <name>Chapter 06 - SQL Injection</name>
    <url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 6 SQL Injection sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch06_SQLInjection</description>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.owasp.esapi</groupId>
            <artifactId>esapi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>Ch06_SQLInjection</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <contextFile>${project.basedir}/src/main/resources/context.xml</contextFile>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/domain/Customer.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.domain;

import javax.persistence.*;

/**
 * @author Dominik Schadow
 */
@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cust_id")
    private int custId;
    private String name;
    private String status;
    @Column(name = "order_limit")
    private int orderLimit;
    private String hint;

    public int getCustId() {
        return custId;
    }

    public void setCustId(int custId) {
        this.custId = custId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getOrderLimit() {
        return orderLimit;
    }

    public void setOrderLimit(int orderLimit) {
        this.orderLimit = orderLimit;
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
    }

    @Override
    public String toString() {
        return "ID " + custId +
                ", Name " + name +
                ", Status " + status +
                ", Order Limit " + orderLimit +
                ", Hint " + hint;
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/CustomerTable.java
================================================
package de.dominikschadow.webappsecurity.servlets;

import de.dominikschadow.webappsecurity.domain.Customer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Util class to create the customers list and to create the HTML table with all queried customers.
 *
 * @author Dominik Schadow
 */
public class CustomerTable {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerTable.class);

    public static List<Customer> extractCustomers(ResultSet rs) throws SQLException {
        List<Customer> customers = new ArrayList<>();

        while (rs.next()) {
            Customer customer = new Customer();
            customer.setCustId(rs.getInt(1));
            customer.setName(rs.getString(2));
            customer.setStatus(rs.getString(3));
            customer.setOrderLimit(rs.getInt(4));

            customers.add(customer);
        }

        return customers;
    }

    public static void writeCustomers(HttpServletResponse response, String name, List<Customer> customers) {
        response.setContentType("text/html");

        try (PrintWriter out = response.getWriter()) {
            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Chapter 06 - SQL Injection</h1>");
            out.println("<p><strong>Input</strong> " + name + "</p>");
            out.println("<h2>Customer Data</h2>");
            out.println("<table>");
            out.println("<tr>");
            out.println("<th>ID</th>");
            out.println("<th>Name</th>");
            out.println("<th>Status</th>");
            out.println("<th>Order Limit</th>");
            out.println("</tr>");

            for (Customer customer : customers) {
                out.println("<tr>");
                out.println("<td>" + customer.getCustId() + "</td>");
                out.println("<td>" + customer.getName() + "</td>");
                out.println("<td>" + customer.getStatus() + "</td>");
                out.println("<td>" + customer.getOrderLimit() + "</td>");
                out.println("</tr>");
            }

            out.println("<table>");
            out.println("</body>");
            out.println("</html>");
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/HQLServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static de.dominikschadow.webappsecurity.servlets.CustomerTable.writeCustomers;
import static de.dominikschadow.webappsecurity.servlets.HibernateUtil.getSessionFactory;

/**
 * Servlet using Hibernate Query Language (HQL) to query the in-memory-database.
 * User input is not modified and used directly in the HQL query.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "HQLServlet", urlPatterns = {"/HQLServlet"})
public class HQLServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(HQLServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        LOGGER.info("Received {} as POST parameter", name);

        try (Session session = getSessionFactory().openSession()) {
            Query query = session.createQuery("FROM Customer WHERE name = :name ORDER BY custId");
            query.setParameter("name", name);

            writeCustomers(response, name, query.list());
        } catch (HibernateException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/HibernateUtil.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author Dominik Schadow
 */
public class HibernateUtil {
    static SessionFactory sessionFactory;

    /**
     * Util class, no constructor required.
     */
    private HibernateUtil() {
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }

        return sessionFactory;
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/InitDbServlet.java
================================================
package de.dominikschadow.webappsecurity.servlets;

import org.hibernate.Session;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import static de.dominikschadow.webappsecurity.servlets.HibernateUtil.getSessionFactory;

/**
 * Servlet to initialize the database with some sample data.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "InitDbServlet", urlPatterns = {"/"})
public class InitDbServlet extends HttpServlet {
    @Override
    public void init() {
        Session session = getSessionFactory().openSession();
        session.close();
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/PreparedStatementServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

import static de.dominikschadow.webappsecurity.servlets.CustomerTable.extractCustomers;
import static de.dominikschadow.webappsecurity.servlets.CustomerTable.writeCustomers;

/**
 * Servlet using a Prepared Statement to query the in-memory-database.
 * User input is not modified and used directly in the SQL query.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "PreparedStatementServlet", urlPatterns = {"/PreparedStatementServlet"})
public class PreparedStatementServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(PreparedStatementServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        LOGGER.info("Received {} as POST parameter", name);

        String query = "SELECT * FROM customer WHERE name = ? ORDER BY CUST_ID";
        ResultSet rs = null;

        try (Connection con = DriverManager.getConnection("jdbc:h2:mem:sqli", "sa", "sa"); PreparedStatement stmt = con.prepareStatement(query)) {
            stmt.setString(1, name);
            rs = stmt.executeQuery();

            writeCustomers(response, name, extractCustomers(rs));
        } catch (SQLException ex) {
            LOGGER.error(ex.getMessage(), ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
        }
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/StatementEscapingServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import org.owasp.esapi.ESAPI;
import org.owasp.esapi.codecs.OracleCodec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

import static de.dominikschadow.webappsecurity.servlets.CustomerTable.extractCustomers;
import static de.dominikschadow.webappsecurity.servlets.CustomerTable.writeCustomers;

/**
 * Servlet using a normal Statement to query the in-memory-database.
 * User input is escaped with ESAPI and used in the SQL query afterwards.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "StatementEscapingServlet", urlPatterns = {"/StatementEscapingServlet"})
public class StatementEscapingServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(StatementEscapingServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        LOGGER.info("Received {} as POST parameter", name);

        String safeName = ESAPI.encoder().encodeForSQL(new OracleCodec(), name);
        LOGGER.info("Escaped name is {}", safeName);

        String query = "SELECT * FROM customer WHERE name = '" + safeName + "' ORDER BY CUST_ID";

        LOGGER.info("Final SQL query {}", query);

        ResultSet rs = null;

        try (Connection con = DriverManager.getConnection("jdbc:h2:mem:sqli", "sa", "sa"); Statement stmt = con.createStatement()) {
            rs = stmt.executeQuery(query);

            writeCustomers(response, name, extractCustomers(rs));
        } catch (SQLException ex) {
            LOGGER.error(ex.getMessage(), ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
        }
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/StatementServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;

import static de.dominikschadow.webappsecurity.servlets.CustomerTable.extractCustomers;
import static de.dominikschadow.webappsecurity.servlets.CustomerTable.writeCustomers;

/**
 * Servlet using a normal Statement to query the in-memory-database.
 * User input is not modified and used directly in the SQL query.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "StatementServlet", urlPatterns = {"/StatementServlet"})
public class StatementServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(StatementServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        LOGGER.info("Received {} as POST parameter", name);

        String query = "SELECT * FROM customer WHERE name = '" + name + "' ORDER BY CUST_ID";

        LOGGER.info("Final SQL query {}", query);

        ResultSet rs = null;

        try (Connection con = DriverManager.getConnection("jdbc:h2:mem:sqli", "sa", "sa"); Statement stmt = con.createStatement()) {
            rs = stmt.executeQuery(query);

            writeCustomers(response, name, extractCustomers(rs));
        } catch (SQLException ex) {
            LOGGER.error(ex.getMessage(), ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
        }
    }
}


================================================
FILE: Ch06_SQLInjection/src/main/resources/ESAPI.properties
================================================
# Logging
Logger.ApplicationName=Ch06_SQLInjection

================================================
FILE: Ch06_SQLInjection/src/main/resources/context.xml
================================================
<?xml version='1.0' encoding='utf-8'?>
<Context useHttpOnly="false">
    <Resource name="sqliDS" auth="Container" type="javax.sql.DataSource"
              maxActive="100" maxIdle="30" maxWait="10000"
              username="sa" password="sa" driverClassName="org.h2.Driver"
              url="jdbc:h2:mem:sqli"/>
</Context>

================================================
FILE: Ch06_SQLInjection/src/main/resources/hibernate.cfg.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.connection.datasource">java:comp/env/sqliDS</property>
        <property name="hibernate.hbm2ddl.auto">create-drop</property>
        <property name="show_sql">false</property>
        <mapping package="de.dominikschadow.webappsecurity.domain"/>
        <mapping class="de.dominikschadow.webappsecurity.domain.Customer"/>
    </session-factory>
</hibernate-configuration>

================================================
FILE: Ch06_SQLInjection/src/main/resources/import.sql
================================================
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1001, 'Arthur Dent', 'A', 10000, '');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1002, 'Ford Prefect', 'B', 5000, '');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1003, 'Tricia Trillian McMillan', 'C', 1000, '');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1004, 'Zaphod Beeblebrox', 'D', 500, 'President of the Galaxy');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1005, 'Marvin', 'A', 100000, 'Depressive');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1006, 'Slartibartfast', 'D', 100, '42');


================================================
FILE: Ch06_SQLInjection/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch06_SQLInjection/src/main/webapp/index.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css" />
	<title>Chapter 06 - SQL Injection</title>
</head>
<body>
	<h1>Chapter 06 - SQL Injection</h1>

    <p>You can use different options to access the database. Not every field is attackable by SQL Injection.
		<strong>Valid customers are:</strong> Arthur Dent, Ford Prefect, Tricia Trillian McMillan, Zaphod Beeblebrox, Marvin, Slartibartfast</p>

	<h2>Using Statement</h2>
	
	<form name="stmt" method="post" action="StatementServlet">
		<table>
			<tr>
				<td><label for="stmt" title="Name">Name</label></td>
				<td><input type="text" id="stmt" name="name" class="text-input" /></td>
				<td><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>

    <h2>Using Statement with Escaping</h2>

    <form name="stmtEsc" method="post" action="StatementEscapingServlet">
        <table>
            <tr>
                <td><label for="stmtEsc" title="Name">Name</label></td>
                <td><input type="text" id="stmtEsc" name="name" class="text-input" /></td>
                <td><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    </form>

	<h2>Using Prepared Statement</h2>
	
	<form name="pstmt" method="post" action="PreparedStatementServlet">
		<table>
			<tr>
				<td><label for="pstmt" title="Name">Name</label></td>
				<td><input type="text" id="pstmt" name="name" class="text-input" /></td>
				<td><input type="submit" name="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>

    <h2>Using Hibernate Query Language (HQL)</h2>

    <form name="hql" method="post" action="HQLServlet">
        <table>
            <tr>
                <td><label for="hql" title="Name">Name</label></td>
                <td><input type="text" id="hql" name="name" class="text-input" /></td>
                <td><input type="submit" name="submit" value="Submit" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


================================================
FILE: Ch06_SQLInjection/src/main/webapp/styles.css
================================================
.text-input {
    width: 250px;
}

h1 {
    font-size: 1.5em;
}

h2 {
    font-size: 1.2em;
}

th {
    background-color: darkgrey;
    padding: 2pt;
    font-weight: bold;
    font-size: 1.1em;
}


================================================
FILE: Ch06_XPathInjection/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>de.dominikschadow.javawebsecurity</groupId>
        <artifactId>javawebsecurity</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>Ch06_XPathInjection</artifactId>
    <packaging>war</packaging>
    <name>Chapter 06 - XPath Injection</name>
    <url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 6 XPath Injection sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch06_XPathInjection</description>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.owasp.esapi</groupId>
            <artifactId>esapi</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>Ch06_XPathInjection</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

================================================
FILE: Ch06_XPathInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/XPathEscapingServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import org.owasp.esapi.ESAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * Servlet using an XPath expression to query the customer XML document.
 * User input is escaped before being used in the XPath expression.
 * <p>
 * Use <code>' or '1' = '1</code> or <code>'] | /* | /foo[bar='</code> as password.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "XPathEscapingServlet", urlPatterns = {"/XPathEscapingServlet"})
public class XPathEscapingServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(XPathEscapingServlet.class);
    private static Document doc;

    @Override
    public void init() {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/customer.xml")) {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(inputStream);
        } catch (SAXException | IOException | ParserConfigurationException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        LOGGER.info("Received {} and {} as parameter", name, password);

        String safeName = ESAPI.encoder().encodeForXPath(name);
        String safePassword = ESAPI.encoder().encodeForXPath(password);
        LOGGER.info("Using safe name {} and {}", safeName, safePassword);

        String xpathExpression = "/customers/customer[name='" +
                safeName +
                "' and @password='" +
                safePassword +
                "']/orderLimit";

        printOrderLimit(xpathExpression, name, response);
    }

    private void printOrderLimit(String xpath, String name, HttpServletResponse response) {
        LOGGER.info("XPath expression is {}", xpath);

        try (PrintWriter out = response.getWriter()) {
            XPathExpression expression = XPathFactory.newInstance().newXPath().compile(xpath);
            Object result = expression.evaluate(doc, XPathConstants.NODESET);

            response.setContentType("text/html");

            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Ch06_XPathInjection</h1>");
            out.println("<h2>Order limit for " + name + "</h2>");

            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                out.println("<p>" + nodes.item(i).getTextContent() + "</p>");
            }

            out.println("</body>");
            out.println("</html>");
        } catch (XPathExpressionException | IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch06_XPathInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/XPathServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.servlets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * Servlet using an XPath expression to query the customer XML document.
 * User input is not modified and used directly in the XPath expression.
 * <p>
 * Use <code>' or '1' = '1</code> or <code>'] | /* | /foo[bar='</code> as password.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "XPathServlet", urlPatterns = {"/XPathServlet"})
public class XPathServlet extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(XPathServlet.class);
    private static Document doc;

    @Override
    public void init() {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/customer.xml")) {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(inputStream);
        } catch (SAXException | IOException | ParserConfigurationException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        LOGGER.info("Received {} and {} as parameter", name, password);

        String xpathExpression = "/customers/customer[name='" +
                name +
                "' and @password='" +
                password +
                "']/orderLimit";

        printOrderLimit(xpathExpression, name, response);
    }

    private void printOrderLimit(String xpath, String name, HttpServletResponse response) {
        LOGGER.info("XPath expression is {}", xpath);

        try (PrintWriter out = response.getWriter()) {
            XPathExpression expression = XPathFactory.newInstance().newXPath().compile(xpath);
            Object result = expression.evaluate(doc, XPathConstants.NODESET);

            response.setContentType("text/html");

            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Ch06_XPathInjection</h1>");
            out.println("<h2>Order limit for " + name + "</h2>");

            NodeList nodes = (NodeList) result;
            for (int i = 0; i < nodes.getLength(); i++) {
                out.println("<p>" + nodes.item(i).getTextContent() + "</p>");
            }

            out.println("</body>");
            out.println("</html>");
        } catch (XPathExpressionException | IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch06_XPathInjection/src/main/resources/ESAPI.properties
================================================
# Logging
Logger.ApplicationName=Ch06_XPathInjection

================================================
FILE: Ch06_XPathInjection/src/main/resources/customer.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<customers>
	<customer id="1" password="Arthur">
        <name>Arthur Dent</name>
		<status>A</status>
		<orderLimit>10000</orderLimit>
	</customer>	
	<customer id="2" password="Ford">
        <name>Ford Prefect</name>
		<status>B</status>
		<orderLimit>5000</orderLimit>
	</customer>	
	<customer id="3" password="Tricia">
        <name>Tricia Trillian McMillan</name>
		<status>C</status>
		<orderLimit>1000</orderLimit>
	</customer>	
	<customer id="4" password="Zaphod">
        <name>Zaphod Beeblebrox</name>
		<status>D</status>
		<orderLimit>500</orderLimit>
	</customer>	
	<customer id="5" password="Marvin">
        <name>Marvin</name>
		<status>A</status>
		<orderLimit>100000</orderLimit>
	</customer>
    <customer id="5" password="Slartibartfast">
        <name>Slartibartfast</name>
        <status>D</status>
        <orderLimit>100</orderLimit>
    </customer>
</customers>

================================================
FILE: Ch06_XPathInjection/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch06_XPathInjection/src/main/webapp/index.jsp
================================================
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css" />
	<title>Chapter 06 - XPath Injection</title>
</head>
<body>
	<h1>Chapter 06 - XPath Injection</h1>

    <p><strong>Valid customers are:</strong> Arthur Dent, Ford Prefect, Tricia Trillian McMillan, Zaphod Beeblebrox, Marvin, Slartibartfast<br/>
    Password is always their first name.</p>

	<h2>Without Escaping</h2>
	
	<form name="stmt" method="post" action="XPathServlet">
		<table>
			<tr>
				<td><label for="name" title="Name">Name</label></td>
				<td><input type="text" id="name" name="name" class="text-input" /></td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td><label for="password" title="Password">Password</label></td>
                <td><input type="password" id="password" name="password" class="text-input" /></td>
				<td><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>

    <h2>With Escaping</h2>

    <form name="stmtEsc" method="post" action="XPathEscapingServlet">
        <table>
            <tr>
                <td><label for="name" title="Name">Name</label></td>
                <td><input type="text" id="name" name="name" class="text-input" /></td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td><label for="password" title="Password">Password</label></td>
                <td><input type="password" id="password" name="password" class="text-input" /></td>
                <td><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


================================================
FILE: Ch06_XPathInjection/src/main/webapp/styles.css
================================================
.text-input {
    width: 250px;
}

h1 {
    font-size: 150%;
}

h2 {
    font-size: 125%;
}

td {
    font-size: 115%;
}

th {
    background-color: darkgrey;
    padding: 2pt;
    font-weight: bold;
    font-size: 125%;
}


================================================
FILE: Ch07_CSP/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>de.dominikschadow.javawebsecurity</groupId>
        <artifactId>javawebsecurity</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>Ch07_CSP</artifactId>
    <packaging>war</packaging>
    <name>Chapter 07 - CSP</name>
    <url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 7 Content Security Policy (CSP) sample project. Requires a server like Apache Tomcat or the Maven Tomcat7 plugin. After starting, open the web application in your browser at http://localhost:8080/Ch07_CSP</description>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>Ch07_CSP</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

================================================
FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/CSPReporting.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serial;
import java.nio.charset.Charset;

/**
 * Simple CSP-Reporting servlet to receive and print out any JSON style CSP report with violations.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "CSPReporting", urlPatterns = {"/CSPReporting"})
public class CSPReporting extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LoggerFactory.getLogger(CSPReporting.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), Charset.defaultCharset()))) {
            StringBuilder responseBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = reader.readLine()) != null) {
                responseBuilder.append(inputStr);
            }

            LOGGER.info("\n{}", responseBuilder.toString());
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithCSPReportingServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;

/**
 * Servlet which sets the <code>Content-Security-Policy-Report-Only</code> response header and reports
 * any JavaScript code that would have been stopped by the policy.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "WithCSPReportingServlet", urlPatterns = {"/WithCSPReportingServlet"})
public class WithCSPReportingServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LoggerFactory.getLogger(WithCSPReportingServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("Processing POST request with Content Security Policy Reporting");

        String name = request.getParameter("reporting");
        LOGGER.info("Received {} as POST parameter", name);

        response.setContentType("text/html");
        // the following line only reports violations and does not block anything
        response.setHeader("Content-Security-Policy-Report-Only", "default-src 'self'; report-uri CSPReporting");

        // use the following line to activate the policy and still report all violations
        //response.setHeader("Content-Security-Policy", "default-src 'self'; report-uri CSPReporting");

        try (PrintWriter out = response.getWriter()) {
            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Ch07_CSP</h1>");
            out.println("<h2>With Content Security Policy Reporting</h2>");
            out.println("<p><strong>Hello</strong> " + name + "</p>");
            out.println("</body>");
            out.println("</html>");
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithCSPServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;

/**
 * Servlet which sets the <code>Content-Security-Policy</code> response header and stops any JavaScript code entered
 * in the textfield.
 * Any entered script-tag will not be rendered any more in the result page.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "WithCSPServlet", urlPatterns = {"/WithCSPServlet"})
public class WithCSPServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LoggerFactory.getLogger(WithCSPServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("Processing POST request with Content Security Policy");

        String name = request.getParameter("protected");
        LOGGER.info("Received {} as POST parameter", name);

        response.setContentType("text/html");
        response.setHeader("Content-Security-Policy", "default-src 'self'");
        // following line enables unsafe inline JavaScript
//        response.setHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline'");

        try (PrintWriter out = response.getWriter()) {
            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Ch07_CSP</h1>");
            out.println("<h2>With Content Security Policy</h2>");
            out.println("<p><strong>Hello</strong> " + name + "</p>");
            out.println("</body>");
            out.println("</html>");
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithoutCSPServlet.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;

/**
 * Default servlet without any additional protection. Any entered script-tag will be executed on the result page.
 *
 * @author Dominik Schadow
 */
@WebServlet(name = "WithoutCSPServlet", urlPatterns = {"/WithoutCSPServlet"})
public class WithoutCSPServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = LoggerFactory.getLogger(WithoutCSPServlet.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        LOGGER.info("Processing POST request without Content Security Policy");

        String name = request.getParameter("unprotected");
        LOGGER.info("Received {} as POST parameter", name);

        response.setContentType("text/html");

        try (PrintWriter out = response.getWriter()) {
            out.println("<html>");
            out.println("<head><link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\" /></head>");
            out.println("<body>");
            out.println("<h1>Ch07_CSP</h1>");
            out.println("<h2>Without Content Security Policy</h2>");
            out.println("<p><strong>Hello</strong> " + name + "</p>");
            out.println("</body>");
            out.println("</html>");
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }
}


================================================
FILE: Ch07_CSP/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch07_CSP/src/main/webapp/index.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css" />
	<title>Chapter 07 - Content Security Policy (CSP)</title>
</head>
<body>
	<h1>Chapter 07 - Content Security Policy (CSP)</h1>

	<h2>Without Content Security Policy</h2>
	
	<form name="withoutCSP" method="post" action="WithoutCSPServlet">
		<table>
			<tr>
				<td><label for="unprotected" title="Name">Name</label></td>
				<td><input type="text" id="unprotected" name="unprotected" class="text-input" /></td>
				<td><input type="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>

	<h2>With Content Security Policy</h2>

	<form name="withCSP" method="post" action="WithCSPServlet">
		<table>
			<tr>
				<td><label for="protected" title="Name">Name</label></td>
				<td><input type="text" id="protected" name="protected" class="text-input" /></td>
				<td><input type="submit" name="submit" value="Submit" /></td>
			</tr>
		</table>
	</form>

    <h2>With Content Security Policy Reporting</h2>

    <form name="withCSPReporting" method="post" action="WithCSPReportingServlet">
        <table>
            <tr>
                <td><label for="reporting" title="Name">Name</label></td>
                <td><input type="text" id="reporting" name="reporting" class="text-input" /></td>
                <td><input type="submit" name="submit" value="Submit" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


================================================
FILE: Ch07_CSP/src/main/webapp/styles.css
================================================
.text-input {
    width: 250px;
}

h1 {
    font-size: 150%;
}

h2 {
    font-size: 125%;
}

td {
    font-size: 115%;
}


================================================
FILE: Ch07_XSS/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>de.dominikschadow.javawebsecurity</groupId>
        <artifactId>javawebsecurity</artifactId>
        <version>1.0.0</version>
    </parent>
    <artifactId>Ch07_XSS</artifactId>
    <packaging>war</packaging>
    <name>Chapter 07 - XSS</name>
    <url>https://github.com/dschadow/Java-Web-Security</url>
    <description>Chapter 7 XSS sample project. Requires a server like Apache Tomcat or the Maven Tomcat plugin. After starting, open the web application in your browser at http://localhost:8080/Ch07_XSS</description>

    <dependencies>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>Ch07_XSS</finalName>
        <defaultGoal>tomcat7:run-war</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <contextFile>${project.basedir}/src/main/resources/context.xml</contextFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


================================================
FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/beans/CustomerController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.beans;

import de.dominikschadow.webappsecurity.daos.CustomerDAO;
import de.dominikschadow.webappsecurity.domain.Customer;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.util.List;

/**
 *
 * @author Dominik Schadow
 */
@ManagedBean(name = "customer")
@RequestScoped
public class CustomerController {
    private Customer customer;
    private CustomerDAO customerDAO;

    public CustomerController() {
        customer = new Customer();
        customerDAO = new CustomerDAO();
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public List<Customer> getCustomers() {
        return customerDAO.getAllCustomers();
    }

    public String save() {
        customerDAO.createCustomer(customer);

        return "showCustomers";
    }
}


================================================
FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/beans/SearchController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.beans;

import de.dominikschadow.webappsecurity.daos.CustomerDAO;
import de.dominikschadow.webappsecurity.domain.Customer;
import org.apache.commons.lang3.StringUtils;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import java.util.List;
import java.util.Map;

/**
 * Searches customers by the given customer name. The search string can be passed via
 * <code>customerName</code> setter method or as a <code>customerName</code> parameter.
 *
 * @author Dominik Schadow
 */
@ManagedBean(name = "search")
@RequestScoped
public class SearchController {
    private String customerName;
    private CustomerDAO customerDAO;
    private List<Customer> customers;

    public SearchController() {
        customerDAO = new CustomerDAO();
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public String search() {
        if (StringUtils.isEmpty(customerName)) {
            Map<String, String> requestMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
            customerName = requestMap.get("customerName");
        }

        Customer search = new Customer();
        search.setName(customerName);

        customers = customerDAO.findCustomers(search);

        return "searchCustomer";
    }
}


================================================
FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/daos/CustomerDAO.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.daos;

import de.dominikschadow.webappsecurity.domain.Customer;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static de.dominikschadow.webappsecurity.daos.HibernateUtil.getSessionFactory;

/**
 * Loads customers from the in-memory-database for the managed beans.
 *
 * @author Dominik Schadow
 * @see de.dominikschadow.webappsecurity.beans.CustomerController
 */
public class CustomerDAO {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerDAO.class);

    public List<Customer> getAllCustomers() {
        List<Customer> customers = new ArrayList<>();

        try (Session session = getSessionFactory().openSession()) {
            Query query = session.createQuery("FROM Customer");
            customers = query.list();

            LOGGER.info("Found {} customers", customers.size());
        } catch (HibernateException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        return customers;
    }

    public void createCustomer(Customer customer) {
        try (Session session = getSessionFactory().openSession()) {
            Transaction tx = session.beginTransaction();
            session.persist(customer);
            tx.commit();
        } catch (HibernateException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }

    public List<Customer> findCustomers(Customer customer) {
        List<Customer> customers = new ArrayList<>();

        try (Session session = getSessionFactory().openSession()) {
            Criteria criteria = session.createCriteria(Customer.class);
            criteria.add(Restrictions.like("name", "%" + customer.getName() + "%"));

            customers = criteria.list();

            LOGGER.info("Found {} customers", customers.size());
        } catch (HibernateException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }

        return customers;
    }
}


================================================
FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/daos/HibernateUtil.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.daos;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 * @author Dominik Schadow
 */
public class HibernateUtil {
    private static SessionFactory sessionFactory;

    /**
     * Util class, no constructor required.
     */
    private HibernateUtil() {
    }

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        }

        return sessionFactory;
    }
}


================================================
FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/domain/Customer.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.domain;

import javax.persistence.*;

/**
 * @author Dominik Schadow
 */
@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "cust_id")
    private int custId;
    private String name;
    private String status;
    @Column(name = "order_limit")
    private int orderLimit;
    private String hint;

    public int getCustId() {
        return custId;
    }

    public void setCustId(int custId) {
        this.custId = custId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getOrderLimit() {
        return orderLimit;
    }

    public void setOrderLimit(int orderLimit) {
        this.orderLimit = orderLimit;
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
    }

    @Override
    public String toString() {
        return "ID " + custId +
                ", Name " + name +
                ", Status " + status +
                ", Order Limit " + orderLimit +
                ", Hint " + hint;
    }
}


================================================
FILE: Ch07_XSS/src/main/resources/context.xml
================================================
<?xml version='1.0' encoding='utf-8'?>
<Context useHttpOnly="false">
    <Resource name="xssDS" auth="Container" type="javax.sql.DataSource"
              maxActive="100" maxIdle="30" maxWait="10000"
              username="sa" password="sa" driverClassName="org.h2.Driver"
              url="jdbc:h2:mem:xss"/>
</Context>

================================================
FILE: Ch07_XSS/src/main/resources/hibernate.cfg.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="hibernate.connection.datasource">java:comp/env/xssDS</property>
        <property name="hibernate.hbm2ddl.auto">create-drop</property>
        <property name="show_sql">false</property>
        <mapping package="de.dominikschadow.webappsecurity.domain"/>
        <mapping class="de.dominikschadow.webappsecurity.domain.Customer"/>
    </session-factory>
</hibernate-configuration>

================================================
FILE: Ch07_XSS/src/main/resources/import.sql
================================================
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1001, 'Arthur Dent', 'A', 10000, '');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1002, 'Ford Prefect', 'B', 5000, '');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1003, 'Tricia Trillian McMillan', 'C', 1000, '');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1004, 'Zaphod Beeblebrox', 'D', 500, 'President of the Galaxy');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1005, 'Marvin', 'A', 100000, 'Depressive');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1006, 'Slartibartfast', 'D', 100, '42');
INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1007, 'Stored XSS', 'X', 9999, '<script>alert("Stored XSS - Session ID: " + document.cookie)</script>');


================================================
FILE: Ch07_XSS/src/main/resources/logback.xml
================================================
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

================================================
FILE: Ch07_XSS/src/main/webapp/WEB-INF/faces-config.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
</faces-config>

================================================
FILE: Ch07_XSS/src/main/webapp/WEB-INF/web.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <display-name>Ch07_XSS</display-name>

    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

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

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
	
	<session-config>
	    <!-- http-only must be on false in order for a working XSS sample attack -->
		<cookie-config>
			<http-only>false</http-only>
		</cookie-config>
		<tracking-mode>COOKIE</tracking-mode>
	</session-config>
</web-app>

================================================
FILE: Ch07_XSS/src/main/webapp/createCustomer.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 07 - XSS</title>
</h:head>
<h:body>
    <h1>Chapter 07 - XSS</h1>

    <h:form>
        <h:link outcome="index" value="Home"/> | <h:link outcome="showCustomers" value="Show Customers"><f:param
            name="currency" value="EUR"/></h:link> | <h:link outcome="search" value="Search Customer"/>
    </h:form>

    <p>Enter all information to create a new customer:</p>

    <h:form id="createCustomer">
        <h:panelGrid columns="2">
            <h:outputLabel value="Name" for="name"/>
            <h:inputText value="#{customer.customer.name}" label="Name" id="name"/>

            <h:outputLabel value="Status" for="status"/>
            <h:inputText value="#{customer.customer.status}" label="Status" id="status"/>

            <h:outputLabel value="Order Limit" for="orderLimit"/>
            <h:inputText value="#{customer.customer.orderLimit}" label="Order Limit" id="orderLimit"/>

            <h:outputLabel value="Hint" for="hint" title="Customer hint with HTML enabled"/>
            <h:inputTextarea value="#{customer.customer.hint}" label="Hint" id="hint"/>
        </h:panelGrid>
        <h:commandButton value="Save" action="#{customer.save}"/>
    </h:form>
</h:body>
</html>

================================================
FILE: Ch07_XSS/src/main/webapp/index.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 07 - XSS</title>
</h:head>
<h:body>
    <h1>Chapter 07 - XSS</h1>

    <p>This demo application shows Cross-Site Scripting (XSS) with JavaServer Faces (JSF). The first block of links
    enables normal usage of the demo application (like a normal user). The second block contains attack possibilities
    with XSS.</p>

    <h2>Normal Usage</h2>

    <ul>
        <li><h:link outcome="createCustomer" value="Create Customer"/></li>
        <li>
            <h:link outcome="showCustomers" value="Show Customers">
                <f:param name="currency" value="EUR"/>
            </h:link>
        </li>
        <li><h:link outcome="search" value="Search Customer"/></li>
    </ul>

    <h2>Attacks</h2>

    <ul>
        <li><h:link outcome="showCustomers" value="Stored XSS"/></li>
        <li>
            <h:form>
                <h:commandLink action="#{search.search}" value="Reflected XSS">
                    <f:param name="customerName"
                             value="Dummy&lt;script&gt;alert('Reflected XSS - Session ID: ' + document.cookie)&lt;/script&gt;"/>
                </h:commandLink>
            </h:form>
        </li>
        <li>
            <h:link outcome="showCustomers" value="DOM Based XSS">
                <f:param name="currency"
                         value="&lt;script&gt;alert(&quot;DOM&nbsp;Based&nbsp;XSS&nbsp;-&nbsp;Session&nbsp;ID:&nbsp;&quot;+document.cookie)&lt;/script&gt;"/>
            </h:link>
        </li>
    </ul>

</h:body>
</html>

================================================
FILE: Ch07_XSS/src/main/webapp/resources/css/styles.css
================================================
th {
    font-size: 1.1em;
    font-weight: bold;
    padding: 5px;
}

td {
    padding: 5px;
}

h1 {
    font-size: 1.5em;
}

h2 {
    font-size: 1.2em;
}


================================================
FILE: Ch07_XSS/src/main/webapp/search.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 07 - XSS</title>
</h:head>
<h:body>
    <h1>Chapter 07 - XSS</h1>

    <h:form>
        <h:link outcome="index" value="Home"/> | <h:link outcome="createCustomer" value="Create Customer"/> | <h:link
            outcome="showCustomers" value="Show Customers"><f:param name="currency" value="EUR"/></h:link>
    </h:form>

    <h:form id="searchCustomers">
        <h:panelGrid columns="3">
            <h:outputLabel value="Name" for="name"/>
            <h:inputText value="#{search.customerName}" label="Name" id="name"/>
            <h:commandButton value="Search" action="#{search.search}"/>
        </h:panelGrid>
    </h:form>
</h:body>
</html>

================================================
FILE: Ch07_XSS/src/main/webapp/searchCustomer.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css"/>
    <title>Chapter 07 - XSS</title>
</h:head>
<h:body>
    <h1>Chapter 07 - XSS</h1>

    <h:form>
        <h:link outcome="index" value="Home"/> | <h:link outcome="createCustomer" value="Create Customer"/> | <h:link
            outcome="showCustomers" value="Show Customers"><f:param name="currency" value="EUR"/></h:link> | <h:link
            outcome="search" value="Search Customer"/>
    </h:form>

    <p>Your search for <strong>[<h:outputText value="#{search.customerName}"
                                             escape="false"/>]</strong> returned the following results:</p>

    <h:form>
        <h:dataTable var="c" value="#{search.customers}">
            <h:column>
                <f:facet name="header">ID</f:facet>
                <h:outputText value="#{c.custId}"/>
            </h:column>
            <h:column>
                <f:facet name="header">Name</f:facet>
                <h:outputText value="#{c.name}"/>
            </h:column>
            <h:column>
                <f:facet name="header">Status</f:facet>
                <h:outputText value="#{c.status}"/>
            </h:column>
            <h:column>
                <f:facet name="header">Order Limit</f:facet>
                <h:outputText value="#{c.orderLimit}"/>
            </h:column>
            <h:column>
                <f:facet name="header">Hint</f:facet>
                <h:outputText escape="false" value="#{c.hint}"/>
            </h:column>
        </h:dataTable>
    </h:form>
</h:body>
</html>

================================================
FILE: Ch07_XSS/src/main/webapp/showCustomers.xhtml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
    <h:outputStylesheet library="css" value="styles.css" name="styles.css" />
    <title>Chapter 07 - XSS</title>
</h:head>
<h:body>
    <h1>Chapter 07 - XSS</h1>

    <h:form>
        <h:link outcome="index" value="Home"/> | <h:link outcome="createCustomer" value="Create Customer"/> | <h:link
            outcome="search" value="Search Customer"/>
    </h:form>

    <p>These are all customers currently available in the database:</p>

    <h:form>
        <h:dataTable var="c" value="#{customer.customers}">
            <h:column>
                <f:facet name="header">ID</f:facet>
                <h:outputText value="#{c.custId}"/>
            </h:column>
            <h:column>
                <f:facet name="header">Name</f:facet>
                <h:outputText value="#{c.name}"/>
            </h:column>
            <h:column>
                <f:facet name="header">Status</f:facet>
                <h:outputText value="#{c.status}"/>
            </h:column>
            <h:column>
                <f:facet name="header">Order Limit</f:facet>
                <h:outputText value="#{c.orderLimit}"/>
                <script type="text/javascript">
                    let pos = document.URL.indexOf("currency=");
                    let currency = "EUR";

                    if (pos > 0) {
                        pos = pos + 9;
                        currency = document.URL.substring(pos, document.URL.length);
                    }

                    document.write(decodeURIComponent(currency));
                </script>
            </h:column>
            <h:column>
                <f:facet name="header">Hint</f:facet>
                <h:outputText escape="false" value="#{c.hint}"/>
            </h:column>
        </h:dataTable>
    </h:form>
</h:body>
</html>

================================================
FILE: Ch07_XSSFilter/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.dominikschadow.javawebsecurity</groupId>
		<artifactId>javawebsecurity</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>Ch07_XSSFilter</artifactId>
	<packaging>war</packaging>
	<name>Chapter 07 - XSS Filter</name>
	<url>https://github.com/dschadow/Java-Web-Security</url>
	<description>Chapter 7 XSS Filter sample project. Requires a server like Apache Tomcat. Open the web application in your browser at http://localhost:8080/Ch07_XSSFilter</description>

	<dependencies>
		<dependency>
			<groupId>org.owasp.esapi</groupId>
			<artifactId>esapi</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
	</dependencies>

	<build>
		<finalName>Ch07_XSSFilter</finalName>
		<plugins>
			<plugin>
                <groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

================================================
FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/BlacklistFilter.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Request filter calling the <code>BlacklistRequestWrapper</code> for filtering.
 *
 * @see de.dominikschadow.webappsecurity.filter.BlacklistRequestWrapper
 *
 * @author Dominik Schadow
 */
public class BlacklistFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        filterChain.doFilter(new BlacklistRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}


================================================
FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/BlacklistRequestWrapper.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.filter;

import org.owasp.esapi.ESAPI;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.regex.Pattern;

/**
 * Filter HTML tags which can be used for a XSS attack with a blacklist.<br/>
 * <p>
 * Originally based on <a href="http://www.javacodegeeks.com/2012/07/anti-cross-site-scripting-xss-filter.html">Ricardo Zuasti</a>.
 *
 * @author Dominik Schadow
 */
public class BlacklistRequestWrapper extends HttpServletRequestWrapper {
    public BlacklistRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);

        if (values == null) {
            return null;
        }

        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = stripXSS(values[i]);
        }

        return encodedValues;
    }

    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);

        return stripXSS(value);
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);

        return stripXSS(value);
    }

    private static String stripXSS(String value) {
        if (value != null) {
            value = ESAPI.encoder().canonicalize(value);

            // Avoid null characters
            value = value.replaceAll("", "");

            // Avoid anything between script tags
            Pattern scriptPattern = Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE);
            value = scriptPattern.matcher(value).replaceAll("");

            // Avoid anything in a src='...' type of expression
            scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\'(.*?)\\'", Pattern.CASE_INSENSITIVE
                    | Pattern.MULTILINE | Pattern.DOTALL);
            value = scriptPattern.matcher(value).replaceAll("");

            scriptPattern = Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE
                    | Pattern.MULTILINE | Pattern.DOTALL);
            value = scriptPattern.matcher(value).replaceAll("");

            // Remove any lonesome </script> tag
            scriptPattern = Pattern.compile("</script>", Pattern.CASE_INSENSITIVE);
            value = scriptPattern.matcher(value).replaceAll("");

            // Remove any lonesome <script ...> tag
            scriptPattern = Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
                    | Pattern.DOTALL);
            value = scriptPattern.matcher(value).replaceAll("");

            // Avoid eval(...) expressions
            scriptPattern = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
                    | Pattern.DOTALL);
            value = scriptPattern.matcher(value).replaceAll("");

            // Avoid expression(...) expressions
            scriptPattern = Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
                    | Pattern.DOTALL);
            value = scriptPattern.matcher(value).replaceAll("");

            // Avoid javascript:... expressions
            scriptPattern = Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE);
            value = scriptPattern.matcher(value).replaceAll("");

            // Avoid vbscript:... expressions
            scriptPattern = Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE);
            value = scriptPattern.matcher(value).replaceAll("");

            // Avoid onload= expressions
            scriptPattern = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
                    | Pattern.DOTALL);
            value = scriptPattern.matcher(value).replaceAll("");
        }
        return value;
    }
}

================================================
FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/ESAPIFilter.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Request filter calling the <code>ESAPIRequestWrapper</code> for filtering.
 *
 * @see de.dominikschadow.webappsecurity.filter.ESAPIRequestWrapper
 *
 * @author Dominik Schadow
 */
public class ESAPIFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        filterChain.doFilter(new ESAPIRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}


================================================
FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/ESAPIRequestWrapper.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity.filter;

import org.owasp.esapi.ESAPI;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Filter HTML tags which can be used for a XSS attack with the ESAPI library.<br/>
 *
 * @author Dominik Schadow
 */
public class ESAPIRequestWrapper extends HttpServletRequestWrapper {
    public ESAPIRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);

        if (values == null) {
            return null;
        }

        int count = values.length;
        String[] encodedValues = new String[count];

        for (int i = 0; i < count; i++) {
            encodedValues[i] = escapeHTML(values[i]);
        }

        return encodedValues;
    }

    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);

        return escapeHTML(value);
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        return escapeHTML(value);
    }

    // Modified stripXSS without blacklist
    private String escapeHTML(String value) {
        if (value != null) {
            value = ESAPI.encoder().canonicalize(value);
            value = ESAPI.encoder().encodeForHTML(value);
        }

        return value;
    }
}

================================================
FILE: Ch07_XSSFilter/src/main/resources/ESAPI.properties
================================================
# Logging
Logger.ApplicationName=Ch07_XSSFilter

================================================
FILE: Ch07_XSSFilter/src/main/webapp/WEB-INF/web.xml
================================================
<?xml version="1.0"?>
<web-app id="Ch07_XSSFilter" version="3.0"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name>Ch07_XSSFilter</display-name>
	<filter>
		<display-name>ESAPIFilter</display-name>
		<filter-name>ESAPIFilter</filter-name>
		<filter-class>de.dominikschadow.webappsecurity.filter.ESAPIFilter</filter-class>
	</filter>
    <filter>
        <display-name>BlacklistFilter</display-name>
        <filter-name>BlacklistFilter</filter-name>
        <filter-class>de.dominikschadow.webappsecurity.filter.BlacklistFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ESAPIFilter</filter-name>
        <url-pattern>/outputEsapi.jsp</url-pattern>
    </filter-mapping>
	<filter-mapping>
		<filter-name>BlacklistFilter</filter-name>
		<url-pattern>/outputBlacklist.jsp</url-pattern>
	</filter-mapping>
</web-app>


================================================
FILE: Ch07_XSSFilter/src/main/webapp/index.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Chapter 07 - XSS Filter</title>
    <link rel="stylesheet" type="text/css" href="resources/css/styles.css" />
</head>
<body>
	<h1>Chapter 07 - XSS Filter</h1>

    <p>This demo application shows how the Enterprise Security API (ESAPI) can escape potentially dangerous input. The
        second form uses a blacklist to remove dangerous tags and attributes from the input before displaying it.
        Feel free to enter any attack data like <strong>&lt;script&gt;alert(&apos;XSS&apos;)&lt;/script&gt;</strong>
        and try to outsmart the filter.</p>

    <form method="post" name="esapiForm" action="outputEsapi.jsp">
        <fieldset>
            <legend>ESAPI Filter</legend>
            <label for="esapi" title="Name">Name</label>
            <input type="text" id="esapi" name="esapi" class="text-input" />
            <input type="submit" value="Submit" />
        </fieldset>
    </form>

    <form method="post" name="blacklistForm" action="outputBlacklist.jsp">
        <fieldset>
            <legend>Blacklist Filter</legend>
            <label for="blacklist" title="Name">Name</label>
            <input type="text" id="blacklist" name="blacklist" class="text-input" />
            <input type="submit" value="Submit" />
        </fieldset>
    </form>
</body>
</html>


================================================
FILE: Ch07_XSSFilter/src/main/webapp/outputBlacklist.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Chapter 07 - XSS Filter</title>
    <link rel="stylesheet" type="text/css" href="resources/css/styles.css" />
</head>
<body>
    <h1>Chapter 07 - XSS Filter</h1>

	<p>This output is filtered by a blacklist filter and removes dangerous input before displaying the data. Depending
        on your input, the next line might be empty. [] are used to indicate the position of the given input.</p>

	<p>[<%= request.getParameter("blacklist") %>]</p>

    <a href="<c:url value="/" />">Back</a>
</body>
</html>

================================================
FILE: Ch07_XSSFilter/src/main/webapp/outputEsapi.jsp
================================================
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Chapter 07 - XSS Filter</title>
    <link rel="stylesheet" type="text/css" href="resources/css/styles.css" />
</head>
<body>
    <h1>Chapter 07 - XSS Filter</h1>

    <p>This output is filtered by an ESAPI filter. This filter escapes potentially dangerous input. [] are used to
        indicate the position of the given input.</p>

    <p>[<%= request.getParameter("esapi") %>]</p>

    <a href="<c:url value="/" />">Back</a>
</body>
</html>

================================================
FILE: Ch07_XSSFilter/src/main/webapp/resources/css/styles.css
================================================
h1 {
    font-size: 1.5em;
}

fieldset {
    width: 500px;
    font-size: 1.2em;
    margin-top: 20px;
}

input {
    display: inline-block;
    vertical-align: middle;
    width: 300px;
}

input[type=submit] {
    width: 75px;
    height: 20px;
    margin-left: 10px;
}

label {
    margin-right: 10px;
}


================================================
FILE: Ch07_XSSJSF/pom.xml
================================================
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0    http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>de.dominikschadow.javawebsecurity</groupId>
		<artifactId>javawebsecurity</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>Ch07_XSSJSF</artifactId>
	<packaging>war</packaging>
	<name>Chapter 07 - XSS with JSF</name>
	<url>https://github.com/dschadow/Java-Web-Security</url>
	<description>Chapter 7 XSS with JSF sample project. Requires a server like Apache Tomcat. Open the web application in your browser at http://localhost:8080/Ch07_XSSJSF</description>

	<dependencies>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
		</dependency>
	</dependencies>

	<build>
		<finalName>Ch07_XSSJSF</finalName>
		<plugins>
			<plugin>
                <groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

================================================
FILE: Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/MaximumController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serial;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Bean representing user input into the maximum protected output page
 * (with additional security related attributes).
 *
 * @author Dominik Schadow
 */
@ManagedBean(name = "maximum")
@SessionScoped
public class MaximumController implements Serializable {
    @Serial
    private static final long serialVersionUID = 600561947836364528L;
    private String input = "<script>alert('XSS with JSF')</script>";
    private Map<String, String> maximumMap = null;
    private Status[] maximumArray = null;

    public Map<String, String> getMaximumMap() {
        return maximumMap;
    }

    public Status[] getMaximumArray() {
        return maximumArray;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;

        maximumMap = new LinkedHashMap<>();
        maximumMap.put(input, input);

        maximumArray = new Status[1];
        maximumArray[0] = new Status(input);
    }
}

================================================
FILE: Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/StandardController.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serial;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Bean representing user input into the standard protected output page
 * (no additional security related attributes).
 *
 * @author Dominik Schadow
 */
@ManagedBean(name = "standard")
@SessionScoped
public class StandardController implements Serializable {
    @Serial
    private static final long serialVersionUID = 4083596061570021965L;

    private String input = "<script>alert('XSS with JSF')</script>";

    private Map<String, String> standardMap = null;
    private Status[] standardArray = null;

    public Map<String, String> getStandardMap() {
        return standardMap;
    }

    public Status[] getStandardArray() {
        return standardArray;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;

        standardMap = new LinkedHashMap<>();
        standardMap.put(input, input);

        standardArray = new Status[1];
        standardArray[0] = new Status(input);
    }
}

================================================
FILE: Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/Status.java
================================================
/*
 * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de
 *
 * This file is part of the Java-Web-Security project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.dominikschadow.webappsecurity;

import java.io.Serial;
import java.io.Serializable;

/**
 * Represents one Status array entry.
 *
 * @author Dominik Schadow
 */
public class Status implements Serializable {
    @Serial
    private static final long serialVersionUID = -5176873476153674154L;
    private String label;
    private String value;

    public Status(String text) {
        this.label = text;
        this.value = text;
    }

    public String getLabel() {
        return label;
    }

    public String getValue() {
        return value;
    }
}


================================================
FILE: Ch07_XSSJSF/src/main/webapp/WEB-INF/faces-config.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
</faces-config>

================================================
FILE: Ch07_XSSJSF/src/main/webapp/WEB-INF/web.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http:/
Download .txt
gitextract_58dy3jvz/

├── .github/
│   ├── dependabot.yml
│   └── workflows/
│       └── maven.yml
├── .gitignore
├── Ch04_OutputEscaping/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── resources/
│           │   └── ESAPI.properties
│           └── webapp/
│               ├── index.jsp
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               ├── withOutputEscaping.jsp
│               └── withoutOutputEscaping.jsp
├── Ch04_OutputEscapingJSF/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── ContactController.java
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── contact.xhtml
│               ├── index.xhtml
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch04_OutputEscapingJSP/
│   ├── pom.xml
│   └── src/
│       ├── main/
│       │   ├── java/
│       │   │   └── de/
│       │   │       └── dominikschadow/
│       │   │           └── webappsecurity/
│       │   │               ├── OutputEscapingWebAppInitializer.java
│       │   │               ├── WebConfig.java
│       │   │               ├── controller/
│       │   │               │   ├── ContactController.java
│       │   │               │   └── IndexController.java
│       │   │               └── domain/
│       │   │                   └── Contact.java
│       │   ├── resources/
│       │   │   └── logback.xml
│       │   └── webapp/
│       │       ├── WEB-INF/
│       │       │   └── views/
│       │       │       ├── contact.jsp
│       │       │       └── index.jsp
│       │       └── resources/
│       │           └── styles.css
│       └── test/
│           └── java/
│               └── de/
│                   └── dominikschadow/
│                       └── webappsecurity/
│                           └── controller/
│                               ├── ContactControllerTest.java
│                               └── IndexControllerTest.java
├── Ch05_AccessReferenceMaps/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── AccountController.java
│           │               ├── AccountIntegerController.java
│           │               ├── AccountRandomController.java
│           │               ├── AccountsDAO.java
│           │               ├── AccountsIntegerDAO.java
│           │               ├── AccountsRandomDAO.java
│           │               ├── HibernateUtil.java
│           │               └── domain/
│           │                   ├── Account.java
│           │                   └── User.java
│           ├── resources/
│           │   ├── ESAPI.properties
│           │   ├── context.xml
│           │   ├── hibernate.cfg.xml
│           │   ├── import.sql
│           │   └── logback.xml
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── account.xhtml
│               ├── accountInteger.xhtml
│               ├── accountRandom.xhtml
│               ├── index.xhtml
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch05_HSTS/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── filter/
│           │               │   └── HSTSFilter.java
│           │               └── servlets/
│           │                   └── LoginServlet.java
│           ├── resources/
│           │   └── logback.xml
│           └── webapp/
│               ├── WEB-INF/
│               │   └── web.xml
│               ├── index.jsp
│               └── styles.css
├── Ch05_SessionFixation/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── servlets/
│           │                   └── LoginServlet.java
│           ├── resources/
│           │   ├── context.xml
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch05_SessionHandling/
│   ├── pom.xml
│   └── src/
│       └── main/
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── index.xhtml
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch06_SQLInjection/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── domain/
│           │               │   └── Customer.java
│           │               └── servlets/
│           │                   ├── CustomerTable.java
│           │                   ├── HQLServlet.java
│           │                   ├── HibernateUtil.java
│           │                   ├── InitDbServlet.java
│           │                   ├── PreparedStatementServlet.java
│           │                   ├── StatementEscapingServlet.java
│           │                   └── StatementServlet.java
│           ├── resources/
│           │   ├── ESAPI.properties
│           │   ├── context.xml
│           │   ├── hibernate.cfg.xml
│           │   ├── import.sql
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch06_XPathInjection/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── servlets/
│           │                   ├── XPathEscapingServlet.java
│           │                   └── XPathServlet.java
│           ├── resources/
│           │   ├── ESAPI.properties
│           │   ├── customer.xml
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch07_CSP/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── CSPReporting.java
│           │               ├── WithCSPReportingServlet.java
│           │               ├── WithCSPServlet.java
│           │               └── WithoutCSPServlet.java
│           ├── resources/
│           │   └── logback.xml
│           └── webapp/
│               ├── index.jsp
│               └── styles.css
├── Ch07_XSS/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── beans/
│           │               │   ├── CustomerController.java
│           │               │   └── SearchController.java
│           │               ├── daos/
│           │               │   ├── CustomerDAO.java
│           │               │   └── HibernateUtil.java
│           │               └── domain/
│           │                   └── Customer.java
│           ├── resources/
│           │   ├── context.xml
│           │   ├── hibernate.cfg.xml
│           │   ├── import.sql
│           │   └── logback.xml
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── createCustomer.xhtml
│               ├── index.xhtml
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               ├── search.xhtml
│               ├── searchCustomer.xhtml
│               └── showCustomers.xhtml
├── Ch07_XSSFilter/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               └── filter/
│           │                   ├── BlacklistFilter.java
│           │                   ├── BlacklistRequestWrapper.java
│           │                   ├── ESAPIFilter.java
│           │                   └── ESAPIRequestWrapper.java
│           ├── resources/
│           │   └── ESAPI.properties
│           └── webapp/
│               ├── WEB-INF/
│               │   └── web.xml
│               ├── index.jsp
│               ├── outputBlacklist.jsp
│               ├── outputEsapi.jsp
│               └── resources/
│                   └── css/
│                       └── styles.css
├── Ch07_XSSJSF/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── MaximumController.java
│           │               ├── StandardController.java
│           │               └── Status.java
│           └── webapp/
│               ├── WEB-INF/
│               │   ├── faces-config.xml
│               │   └── web.xml
│               ├── index.xhtml
│               ├── maximum.xhtml
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               └── standard.xhtml
├── Ch08_CSRF/
│   ├── pom.xml
│   └── src/
│       └── main/
│           ├── java/
│           │   └── de/
│           │       └── dominikschadow/
│           │           └── webappsecurity/
│           │               ├── servlets/
│           │               │   ├── ProtectedServlet.java
│           │               │   └── UnprotectedServlet.java
│           │               └── token/
│           │                   └── CSRFTokenHandler.java
│           ├── resources/
│           │   └── logback.xml
│           └── webapp/
│               ├── form-protected.html
│               ├── form-unprotected.html
│               ├── form-working.jsp
│               ├── image-protected.html
│               ├── image-unprotected.html
│               ├── index.jsp
│               ├── requests-protected.html
│               ├── requests-unprotected.html
│               ├── resources/
│               │   └── css/
│               │       └── styles.css
│               ├── xmlhttprequest-protected.html
│               └── xmlhttprequest-unprotected.html
├── LICENSE
├── README.md
└── pom.xml
Download .txt
SYMBOL INDEX (208 symbols across 49 files)

FILE: Ch04_OutputEscapingJSF/src/main/java/de/dominikschadow/webappsecurity/ContactController.java
  class ContactController (line 30) | @ManagedBean(name = "contact")
    method getFirstname (line 39) | public String getFirstname() {
    method setFirstname (line 43) | public void setFirstname(String firstname) {
    method getLastname (line 47) | public String getLastname() {
    method setLastname (line 51) | public void setLastname(String lastname) {

FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/OutputEscapingWebAppInitializer.java
  class OutputEscapingWebAppInitializer (line 26) | public class OutputEscapingWebAppInitializer extends AbstractAnnotationC...
    method getRootConfigClasses (line 27) | @Override
    method getServletConfigClasses (line 32) | @Override
    method getServletMappings (line 37) | @Override

FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/WebConfig.java
  class WebConfig (line 32) | @Configuration
    method viewResolver (line 36) | @Bean
    method configureDefaultServletHandling (line 45) | @Override

FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/controller/ContactController.java
  class ContactController (line 34) | @Controller
    method addContact (line 39) | @RequestMapping(value = "/addContact", method = RequestMethod.POST)

FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/controller/IndexController.java
  class IndexController (line 30) | @Controller
    method index (line 33) | @RequestMapping(method = GET)

FILE: Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/domain/Contact.java
  class Contact (line 24) | public class Contact {
    method getFirstname (line 28) | public String getFirstname() {
    method setFirstname (line 32) | public void setFirstname(String firstname) {
    method getLastname (line 36) | public String getLastname() {
    method setLastname (line 40) | public void setLastname(String lastname) {

FILE: Ch04_OutputEscapingJSP/src/test/java/de/dominikschadow/webappsecurity/controller/ContactControllerTest.java
  class ContactControllerTest (line 31) | public class ContactControllerTest {
    method testContactPage (line 32) | @Test

FILE: Ch04_OutputEscapingJSP/src/test/java/de/dominikschadow/webappsecurity/controller/IndexControllerTest.java
  class IndexControllerTest (line 31) | public class IndexControllerTest {
    method testIndexPage (line 32) | @Test

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountController.java
  class AccountController (line 34) | @ManagedBean(name = "account")
    method getAccountId (line 43) | public int getAccountId() {
    method setAccountId (line 47) | public void setAccountId(int accountId) {
    method getUserId (line 51) | public int getUserId() {
    method getAccount (line 55) | public Account getAccount() {
    method getAccountReferences (line 59) | public List<String> getAccountReferences() {
    method AccountController (line 63) | public AccountController() {
    method show (line 69) | public String show() {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountIntegerController.java
  class AccountIntegerController (line 35) | @ManagedBean(name = "accountInteger")
    method getIaAccountId (line 43) | public int getIaAccountId() {
    method setIaAccountId (line 47) | public void setIaAccountId(int iaAccountId) {
    method getUserId (line 51) | public int getUserId() {
    method getAccount (line 55) | public Account getAccount() {
    method getAccountReferences (line 59) | public List<String> getAccountReferences() {
    method AccountIntegerController (line 63) | public AccountIntegerController() {
    method show (line 71) | public String show() {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountRandomController.java
  class AccountRandomController (line 35) | @ManagedBean(name = "accountRandom")
    method getRaAccountId (line 43) | public String getRaAccountId() {
    method setRaAccountId (line 47) | public void setRaAccountId(String raAccountId) {
    method getUserId (line 51) | public int getUserId() {
    method getAccount (line 55) | public Account getAccount() {
    method getAccountReferences (line 59) | public List<String> getAccountReferences() {
    method AccountRandomController (line 63) | public AccountRandomController() {
    method show (line 71) | public String show() {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsDAO.java
  class AccountsDAO (line 38) | public class AccountsDAO {
    method getAccountsForUser (line 41) | public List<String> getAccountsForUser(int userId) {
    method loadAccount (line 45) | public Account loadAccount(int id) {
    method queryAccount (line 49) | private Account queryAccount(int id) {
    method queryAccounts (line 62) | private List<String> queryAccounts(int userId) {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsIntegerDAO.java
  class AccountsIntegerDAO (line 38) | public class AccountsIntegerDAO {
    method retrieveAccount (line 42) | public Account retrieveAccount(int accountId) {
    method loadAccountsForUser (line 54) | public List<String> loadAccountsForUser(User user) {
    method queryAccounts (line 58) | private List<String> queryAccounts(User user) {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsRandomDAO.java
  class AccountsRandomDAO (line 38) | public class AccountsRandomDAO {
    method retrieveAccount (line 42) | public Account retrieveAccount(String accountReference) {
    method loadAccountsForUser (line 52) | public List<String> loadAccountsForUser(User user) {
    method queryAccounts (line 56) | private List<String> queryAccounts(User user) {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/HibernateUtil.java
  class HibernateUtil (line 32) | public class HibernateUtil {
    method HibernateUtil (line 38) | private HibernateUtil() {
    method getSessionFactory (line 41) | public static SessionFactory getSessionFactory() {
    method queryUserAccounts (line 49) | public static List<Account> queryUserAccounts(User user) {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/domain/Account.java
  class Account (line 29) | @Entity
    method getAccountId (line 37) | public int getAccountId() {
    method setAccountId (line 41) | public void setAccountId(int accountId) {
    method getName (line 45) | public String getName() {
    method setName (line 49) | public void setName(String name) {
    method getType (line 53) | public String getType() {
    method setType (line 57) | public void setType(String type) {
    method getOwnerId (line 61) | public int getOwnerId() {
    method setOwnerId (line 65) | public void setOwnerId(int ownerId) {

FILE: Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/domain/User.java
  class User (line 29) | @Entity
    method getUserId (line 35) | public int getUserId() {
    method setUserId (line 39) | public void setUserId(int userId) {
    method getName (line 43) | public String getName() {
    method setName (line 47) | public void setName(String name) {

FILE: Ch05_HSTS/src/main/java/de/dominikschadow/webappsecurity/filter/HSTSFilter.java
  class HSTSFilter (line 32) | public class HSTSFilter implements Filter {
    method init (line 35) | @Override
    method doFilter (line 40) | @Override
    method destroy (line 48) | @Override

FILE: Ch05_HSTS/src/main/java/de/dominikschadow/webappsecurity/servlets/LoginServlet.java
  class LoginServlet (line 37) | @WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
    method doPost (line 43) | @Override

FILE: Ch05_SessionFixation/src/main/java/de/dominikschadow/webappsecurity/servlets/LoginServlet.java
  class LoginServlet (line 37) | @WebServlet(name = "LoginServlet", urlPatterns = {"/LoginServlet"})
    method doPost (line 43) | @Override

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/domain/Customer.java
  class Customer (line 25) | @Entity
    method getCustId (line 37) | public int getCustId() {
    method setCustId (line 41) | public void setCustId(int custId) {
    method getName (line 45) | public String getName() {
    method setName (line 49) | public void setName(String name) {
    method getStatus (line 53) | public String getStatus() {
    method setStatus (line 57) | public void setStatus(String status) {
    method getOrderLimit (line 61) | public int getOrderLimit() {
    method setOrderLimit (line 65) | public void setOrderLimit(int orderLimit) {
    method getHint (line 69) | public String getHint() {
    method setHint (line 73) | public void setHint(String hint) {
    method toString (line 77) | @Override

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/CustomerTable.java
  class CustomerTable (line 20) | public class CustomerTable {
    method extractCustomers (line 23) | public static List<Customer> extractCustomers(ResultSet rs) throws SQL...
    method writeCustomers (line 39) | public static void writeCustomers(HttpServletResponse response, String...

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/HQLServlet.java
  class HQLServlet (line 40) | @WebServlet(name = "HQLServlet", urlPatterns = {"/HQLServlet"})
    method doPost (line 44) | @Override

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/HibernateUtil.java
  class HibernateUtil (line 26) | public class HibernateUtil {
    method HibernateUtil (line 32) | private HibernateUtil() {
    method getSessionFactory (line 35) | public static SessionFactory getSessionFactory() {

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/InitDbServlet.java
  class InitDbServlet (line 15) | @WebServlet(name = "InitDbServlet", urlPatterns = {"/"})
    method init (line 17) | @Override

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/PreparedStatementServlet.java
  class PreparedStatementServlet (line 38) | @WebServlet(name = "PreparedStatementServlet", urlPatterns = {"/Prepared...
    method doPost (line 42) | @Override

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/StatementEscapingServlet.java
  class StatementEscapingServlet (line 40) | @WebServlet(name = "StatementEscapingServlet", urlPatterns = {"/Statemen...
    method doPost (line 44) | @Override

FILE: Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/StatementServlet.java
  class StatementServlet (line 38) | @WebServlet(name = "StatementServlet", urlPatterns = {"/StatementServlet"})
    method doPost (line 42) | @Override

FILE: Ch06_XPathInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/XPathEscapingServlet.java
  class XPathEscapingServlet (line 50) | @WebServlet(name = "XPathEscapingServlet", urlPatterns = {"/XPathEscapin...
    method init (line 55) | @Override
    method doPost (line 66) | @Override
    method printOrderLimit (line 85) | private void printOrderLimit(String xpath, String name, HttpServletRes...

FILE: Ch06_XPathInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/XPathServlet.java
  class XPathServlet (line 49) | @WebServlet(name = "XPathServlet", urlPatterns = {"/XPathServlet"})
    method init (line 54) | @Override
    method doPost (line 65) | @Override
    method printOrderLimit (line 80) | private void printOrderLimit(String xpath, String name, HttpServletRes...

FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/CSPReporting.java
  class CSPReporting (line 38) | @WebServlet(name = "CSPReporting", urlPatterns = {"/CSPReporting"})
    method doPost (line 44) | @Override

FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithCSPReportingServlet.java
  class WithCSPReportingServlet (line 37) | @WebServlet(name = "WithCSPReportingServlet", urlPatterns = {"/WithCSPRe...
    method doPost (line 43) | @Override

FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithCSPServlet.java
  class WithCSPServlet (line 38) | @WebServlet(name = "WithCSPServlet", urlPatterns = {"/WithCSPServlet"})
    method doPost (line 44) | @Override

FILE: Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithoutCSPServlet.java
  class WithoutCSPServlet (line 36) | @WebServlet(name = "WithoutCSPServlet", urlPatterns = {"/WithoutCSPServl...
    method doPost (line 42) | @Override

FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/beans/CustomerController.java
  class CustomerController (line 31) | @ManagedBean(name = "customer")
    method CustomerController (line 37) | public CustomerController() {
    method getCustomer (line 42) | public Customer getCustomer() {
    method setCustomer (line 46) | public void setCustomer(Customer customer) {
    method getCustomers (line 50) | public List<Customer> getCustomers() {
    method save (line 54) | public String save() {

FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/beans/SearchController.java
  class SearchController (line 36) | @ManagedBean(name = "search")
    method SearchController (line 43) | public SearchController() {
    method getCustomerName (line 47) | public String getCustomerName() {
    method setCustomerName (line 51) | public void setCustomerName(String customerName) {
    method getCustomers (line 55) | public List<Customer> getCustomers() {
    method search (line 59) | public String search() {

FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/daos/CustomerDAO.java
  class CustomerDAO (line 41) | public class CustomerDAO {
    method getAllCustomers (line 44) | public List<Customer> getAllCustomers() {
    method createCustomer (line 59) | public void createCustomer(Customer customer) {
    method findCustomers (line 69) | public List<Customer> findCustomers(Customer customer) {

FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/daos/HibernateUtil.java
  class HibernateUtil (line 26) | public class HibernateUtil {
    method HibernateUtil (line 32) | private HibernateUtil() {
    method getSessionFactory (line 35) | public static SessionFactory getSessionFactory() {

FILE: Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/domain/Customer.java
  class Customer (line 25) | @Entity
    method getCustId (line 37) | public int getCustId() {
    method setCustId (line 41) | public void setCustId(int custId) {
    method getName (line 45) | public String getName() {
    method setName (line 49) | public void setName(String name) {
    method getStatus (line 53) | public String getStatus() {
    method setStatus (line 57) | public void setStatus(String status) {
    method getOrderLimit (line 61) | public int getOrderLimit() {
    method setOrderLimit (line 65) | public void setOrderLimit(int orderLimit) {
    method getHint (line 69) | public String getHint() {
    method setHint (line 73) | public void setHint(String hint) {
    method toString (line 77) | @Override

FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/BlacklistFilter.java
  class BlacklistFilter (line 31) | public class BlacklistFilter implements Filter {
    method doFilter (line 32) | @Override
    method init (line 38) | @Override
    method destroy (line 42) | @Override

FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/BlacklistRequestWrapper.java
  class BlacklistRequestWrapper (line 33) | public class BlacklistRequestWrapper extends HttpServletRequestWrapper {
    method BlacklistRequestWrapper (line 34) | public BlacklistRequestWrapper(HttpServletRequest servletRequest) {
    method getParameterValues (line 38) | @Override
    method getParameter (line 55) | @Override
    method getHeader (line 62) | @Override
    method stripXSS (line 69) | private static String stripXSS(String value) {

FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/ESAPIFilter.java
  class ESAPIFilter (line 31) | public class ESAPIFilter implements Filter {
    method doFilter (line 32) | @Override
    method init (line 38) | @Override
    method destroy (line 42) | @Override

FILE: Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/ESAPIRequestWrapper.java
  class ESAPIRequestWrapper (line 30) | public class ESAPIRequestWrapper extends HttpServletRequestWrapper {
    method ESAPIRequestWrapper (line 31) | public ESAPIRequestWrapper(HttpServletRequest servletRequest) {
    method getParameterValues (line 35) | @Override
    method getParameter (line 53) | @Override
    method getHeader (line 60) | @Override
    method escapeHTML (line 67) | private String escapeHTML(String value) {

FILE: Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/MaximumController.java
  class MaximumController (line 33) | @ManagedBean(name = "maximum")
    method getMaximumMap (line 42) | public Map<String, String> getMaximumMap() {
    method getMaximumArray (line 46) | public Status[] getMaximumArray() {
    method getInput (line 50) | public String getInput() {
    method setInput (line 54) | public void setInput(String input) {

FILE: Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/StandardController.java
  class StandardController (line 33) | @ManagedBean(name = "standard")
    method getStandardMap (line 44) | public Map<String, String> getStandardMap() {
    method getStandardArray (line 48) | public Status[] getStandardArray() {
    method getInput (line 52) | public String getInput() {
    method setInput (line 56) | public void setInput(String input) {

FILE: Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/Status.java
  class Status (line 28) | public class Status implements Serializable {
    method Status (line 34) | public Status(String text) {
    method getLabel (line 39) | public String getLabel() {
    method getValue (line 43) | public String getValue() {

FILE: Ch08_CSRF/src/main/java/de/dominikschadow/webappsecurity/servlets/ProtectedServlet.java
  class ProtectedServlet (line 42) | @WebServlet(name = "ProtectedServlet", urlPatterns = {"/ProtectedServlet"})
    method doGet (line 48) | @Override
    method doPost (line 95) | @Override

FILE: Ch08_CSRF/src/main/java/de/dominikschadow/webappsecurity/servlets/UnprotectedServlet.java
  class UnprotectedServlet (line 37) | @WebServlet(name = "UnprotectedServlet", urlPatterns = {"/UnprotectedSer...
    method doGet (line 43) | @Override
    method doPost (line 69) | @Override

FILE: Ch08_CSRF/src/main/java/de/dominikschadow/webappsecurity/token/CSRFTokenHandler.java
  class CSRFTokenHandler (line 36) | public final class CSRFTokenHandler {
    method CSRFTokenHandler (line 43) | private CSRFTokenHandler() {
    method getToken (line 46) | private static String getToken() throws NoSuchAlgorithmException, NoSu...
    method getToken (line 52) | public static String getToken(HttpSession session) throws ServletExcep...
    method isValid (line 68) | public static boolean isValid(HttpServletRequest request) throws Servl...
Condensed preview — 158 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (257K chars).
[
  {
    "path": ".github/dependabot.yml",
    "chars": 503,
    "preview": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where "
  },
  {
    "path": ".github/workflows/maven.yml",
    "chars": 438,
    "preview": "name: Build\n\non:\n  push:\n  pull_request:\n    branches: [ main ]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    name: Jav"
  },
  {
    "path": ".gitignore",
    "chars": 191,
    "preview": "*.class\n.idea\n.classpath\n.project\n.DS_Store\n*/target*\ntarget/\n.settings*\n# Package Files #\n*.jar\n*.war\n*.ear\n*.iml\n*.log"
  },
  {
    "path": "Ch04_OutputEscaping/pom.xml",
    "chars": 1775,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch04_OutputEscaping/src/main/resources/ESAPI.properties",
    "chars": 52,
    "preview": "# Logging\nLogger.ApplicationName=Ch04_OutputEscaping"
  },
  {
    "path": "Ch04_OutputEscaping/src/main/webapp/index.jsp",
    "chars": 1421,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch04_OutputEscaping/src/main/webapp/resources/css/styles.css",
    "chars": 336,
    "preview": "h1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.2em;\n}\n\nfieldset {\n    width: 450px;\n    font-size: 1.2em;\n    margi"
  },
  {
    "path": "Ch04_OutputEscaping/src/main/webapp/withOutputEscaping.jsp",
    "chars": 1720,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<%@ page import=\"org.owasp.esapi."
  },
  {
    "path": "Ch04_OutputEscaping/src/main/webapp/withoutOutputEscaping.jsp",
    "chars": 672,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch04_OutputEscapingJSF/pom.xml",
    "chars": 1469,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch04_OutputEscapingJSF/src/main/java/de/dominikschadow/webappsecurity/ContactController.java",
    "chars": 1534,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch04_OutputEscapingJSF/src/main/webapp/WEB-INF/faces-config.xml",
    "chars": 337,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<faces-config version=\"2.2\"\n              xmlns=\"http://xmlns.jcp.org/xml/ns/java"
  },
  {
    "path": "Ch04_OutputEscapingJSF/src/main/webapp/WEB-INF/web.xml",
    "chars": 944,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n         xmlns:xsi=\"http://ww"
  },
  {
    "path": "Ch04_OutputEscapingJSF/src/main/webapp/contact.xhtml",
    "chars": 839,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch04_OutputEscapingJSF/src/main/webapp/index.xhtml",
    "chars": 1207,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch04_OutputEscapingJSF/src/main/webapp/resources/css/styles.css",
    "chars": 59,
    "preview": "h1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.2em;\n}\n"
  },
  {
    "path": "Ch04_OutputEscapingJSP/pom.xml",
    "chars": 2852,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:sc"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/OutputEscapingWebAppInitializer.java",
    "chars": 1286,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/WebConfig.java",
    "chars": 1895,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/controller/ContactController.java",
    "chars": 1731,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/controller/IndexController.java",
    "chars": 1187,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/java/de/dominikschadow/webappsecurity/domain/Contact.java",
    "chars": 1169,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/webapp/WEB-INF/views/contact.jsp",
    "chars": 1060,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<%@ taglib prefix=\"c\" uri=\"http:/"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/webapp/WEB-INF/views/index.jsp",
    "chars": 1183,
    "preview": "<%@ page session=\"false\" %>\n<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<%@ t"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/main/webapp/resources/styles.css",
    "chars": 336,
    "preview": "h1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.2em;\n}\n\nfieldset {\n    width: 600px;\n    font-size: 1.2em;\n    margi"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/test/java/de/dominikschadow/webappsecurity/controller/ContactControllerTest.java",
    "chars": 1444,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch04_OutputEscapingJSP/src/test/java/de/dominikschadow/webappsecurity/controller/IndexControllerTest.java",
    "chars": 1422,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/pom.xml",
    "chars": 2280,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountController.java",
    "chars": 2022,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountIntegerController.java",
    "chars": 2186,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountRandomController.java",
    "chars": 2189,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsDAO.java",
    "chars": 2544,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsIntegerDAO.java",
    "chars": 2428,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/AccountsRandomDAO.java",
    "chars": 2370,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/HibernateUtil.java",
    "chars": 1793,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/domain/Account.java",
    "chars": 1644,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/java/de/dominikschadow/webappsecurity/domain/User.java",
    "chars": 1271,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/resources/ESAPI.properties",
    "chars": 57,
    "preview": "# Logging\nLogger.ApplicationName=Ch05_AccessReferenceMaps"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/resources/context.xml",
    "chars": 324,
    "preview": "<?xml version='1.0' encoding='utf-8'?>\n<Context useHttpOnly=\"false\">\n    <Resource name=\"mapDS\" auth=\"Container\" type=\"j"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/resources/hibernate.cfg.xml",
    "chars": 816,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE hibernate-configuration PUBLIC\n        \"-//Hibernate/Hibernate Configur"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/resources/import.sql",
    "chars": 517,
    "preview": "INSERT INTO ACCOUNT (accountid, name, type, ownerid) VALUES (1, 'Marvin Savings', 'Savings', 42);\nINSERT INTO ACCOUNT (a"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/webapp/WEB-INF/faces-config.xml",
    "chars": 337,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<faces-config version=\"2.2\"\n              xmlns=\"http://xmlns.jcp.org/xml/ns/java"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/webapp/WEB-INF/web.xml",
    "chars": 946,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n         xmlns:xsi=\"http://ww"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/webapp/account.xhtml",
    "chars": 1138,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/webapp/accountInteger.xhtml",
    "chars": 1187,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/webapp/accountRandom.xhtml",
    "chars": 1180,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/webapp/index.xhtml",
    "chars": 2585,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch05_AccessReferenceMaps/src/main/webapp/resources/css/styles.css",
    "chars": 100,
    "preview": ".send-button {\n    margin-left: 25px;\n}\n\nh1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.2em;\n}\n"
  },
  {
    "path": "Ch05_HSTS/pom.xml",
    "chars": 2005,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www"
  },
  {
    "path": "Ch05_HSTS/src/main/java/de/dominikschadow/webappsecurity/filter/HSTSFilter.java",
    "chars": 1677,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_HSTS/src/main/java/de/dominikschadow/webappsecurity/servlets/LoginServlet.java",
    "chars": 2551,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_HSTS/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch05_HSTS/src/main/webapp/WEB-INF/web.xml",
    "chars": 724,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://java"
  },
  {
    "path": "Ch05_HSTS/src/main/webapp/index.jsp",
    "chars": 771,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html>\n<html>\n<head>\n\t<m"
  },
  {
    "path": "Ch05_HSTS/src/main/webapp/styles.css",
    "chars": 223,
    "preview": ".text-input {\n    width: 250px;\n}\n\nh1 {\n    font-size: 150%;\n}\n\nh2 {\n    font-size: 125%;\n}\n\ntd {\n    font-size: 115%;\n}"
  },
  {
    "path": "Ch05_SessionFixation/pom.xml",
    "chars": 2091,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch05_SessionFixation/src/main/java/de/dominikschadow/webappsecurity/servlets/LoginServlet.java",
    "chars": 2562,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch05_SessionFixation/src/main/resources/context.xml",
    "chars": 80,
    "preview": "<?xml version='1.0' encoding='utf-8'?>\n<Context useHttpOnly=\"false\">\n\n</Context>"
  },
  {
    "path": "Ch05_SessionFixation/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch05_SessionFixation/src/main/webapp/index.jsp",
    "chars": 868,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch05_SessionFixation/src/main/webapp/styles.css",
    "chars": 223,
    "preview": ".text-input {\n    width: 250px;\n}\n\nh1 {\n    font-size: 150%;\n}\n\nh2 {\n    font-size: 125%;\n}\n\ntd {\n    font-size: 115%;\n}"
  },
  {
    "path": "Ch05_SessionHandling/pom.xml",
    "chars": 1616,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch05_SessionHandling/src/main/webapp/WEB-INF/faces-config.xml",
    "chars": 337,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<faces-config version=\"2.2\"\n              xmlns=\"http://xmlns.jcp.org/xml/ns/java"
  },
  {
    "path": "Ch05_SessionHandling/src/main/webapp/WEB-INF/web.xml",
    "chars": 1308,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n         xmlns:xsi=\"http://ww"
  },
  {
    "path": "Ch05_SessionHandling/src/main/webapp/index.xhtml",
    "chars": 643,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch05_SessionHandling/src/main/webapp/resources/css/styles.css",
    "chars": 28,
    "preview": "h1 {\n    font-size: 125%;\n}\n"
  },
  {
    "path": "Ch06_SQLInjection/pom.xml",
    "chars": 2529,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:sc"
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/domain/Customer.java",
    "chars": 2024,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/CustomerTable.java",
    "chars": 2608,
    "preview": "package de.dominikschadow.webappsecurity.servlets;\n\nimport de.dominikschadow.webappsecurity.domain.Customer;\nimport org."
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/HQLServlet.java",
    "chars": 2225,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/HibernateUtil.java",
    "chars": 1243,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/InitDbServlet.java",
    "chars": 595,
    "preview": "package de.dominikschadow.webappsecurity.servlets;\n\nimport org.hibernate.Session;\n\nimport javax.servlet.annotation.WebSe"
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/PreparedStatementServlet.java",
    "chars": 2533,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/StatementEscapingServlet.java",
    "chars": 2770,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_SQLInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/StatementServlet.java",
    "chars": 2518,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_SQLInjection/src/main/resources/ESAPI.properties",
    "chars": 50,
    "preview": "# Logging\nLogger.ApplicationName=Ch06_SQLInjection"
  },
  {
    "path": "Ch06_SQLInjection/src/main/resources/context.xml",
    "chars": 324,
    "preview": "<?xml version='1.0' encoding='utf-8'?>\n<Context useHttpOnly=\"false\">\n    <Resource name=\"sqliDS\" auth=\"Container\" type=\""
  },
  {
    "path": "Ch06_SQLInjection/src/main/resources/hibernate.cfg.xml",
    "chars": 746,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE hibernate-configuration PUBLIC\n        \"-//Hibernate/Hibernate Configur"
  },
  {
    "path": "Ch06_SQLInjection/src/main/resources/import.sql",
    "chars": 708,
    "preview": "INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1001, 'Arthur Dent', 'A', 10000, '');\nINSERT INT"
  },
  {
    "path": "Ch06_SQLInjection/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch06_SQLInjection/src/main/webapp/index.jsp",
    "chars": 2220,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch06_SQLInjection/src/main/webapp/styles.css",
    "chars": 197,
    "preview": ".text-input {\n    width: 250px;\n}\n\nh1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.2em;\n}\n\nth {\n    background-color"
  },
  {
    "path": "Ch06_XPathInjection/pom.xml",
    "chars": 2108,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:sc"
  },
  {
    "path": "Ch06_XPathInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/XPathEscapingServlet.java",
    "chars": 4398,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_XPathInjection/src/main/java/de/dominikschadow/webappsecurity/servlets/XPathServlet.java",
    "chars": 4122,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch06_XPathInjection/src/main/resources/ESAPI.properties",
    "chars": 52,
    "preview": "# Logging\nLogger.ApplicationName=Ch06_XPathInjection"
  },
  {
    "path": "Ch06_XPathInjection/src/main/resources/customer.xml",
    "chars": 926,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<customers>\n\t<customer id=\"1\" password=\"Arthur\">\n        <name>Arthur Dent</name>"
  },
  {
    "path": "Ch06_XPathInjection/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch06_XPathInjection/src/main/webapp/index.jsp",
    "chars": 1683,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n    <link rel=\"styles"
  },
  {
    "path": "Ch06_XPathInjection/src/main/webapp/styles.css",
    "chars": 223,
    "preview": ".text-input {\n    width: 250px;\n}\n\nh1 {\n    font-size: 150%;\n}\n\nh2 {\n    font-size: 125%;\n}\n\ntd {\n    font-size: 115%;\n}"
  },
  {
    "path": "Ch07_CSP/pom.xml",
    "chars": 1993,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www"
  },
  {
    "path": "Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/CSPReporting.java",
    "chars": 2131,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithCSPReportingServlet.java",
    "chars": 2899,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithCSPServlet.java",
    "chars": 2731,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_CSP/src/main/java/de/dominikschadow/webappsecurity/WithoutCSPServlet.java",
    "chars": 2420,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_CSP/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch07_CSP/src/main/webapp/index.jsp",
    "chars": 1674,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch07_CSP/src/main/webapp/styles.css",
    "chars": 121,
    "preview": ".text-input {\n    width: 250px;\n}\n\nh1 {\n    font-size: 150%;\n}\n\nh2 {\n    font-size: 125%;\n}\n\ntd {\n    font-size: 115%;\n}"
  },
  {
    "path": "Ch07_XSS/pom.xml",
    "chars": 2411,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/"
  },
  {
    "path": "Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/beans/CustomerController.java",
    "chars": 1620,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/beans/SearchController.java",
    "chars": 2239,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/daos/CustomerDAO.java",
    "chars": 2888,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/daos/HibernateUtil.java",
    "chars": 1247,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSS/src/main/java/de/dominikschadow/webappsecurity/domain/Customer.java",
    "chars": 2024,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSS/src/main/resources/context.xml",
    "chars": 322,
    "preview": "<?xml version='1.0' encoding='utf-8'?>\n<Context useHttpOnly=\"false\">\n    <Resource name=\"xssDS\" auth=\"Container\" type=\"j"
  },
  {
    "path": "Ch07_XSS/src/main/resources/hibernate.cfg.xml",
    "chars": 745,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE hibernate-configuration PUBLIC\n        \"-//Hibernate/Hibernate Configur"
  },
  {
    "path": "Ch07_XSS/src/main/resources/import.sql",
    "chars": 885,
    "preview": "INSERT INTO CUSTOMER (CUST_ID, NAME, STATUS, ORDER_LIMIT, HINT) VALUES (1001, 'Arthur Dent', 'A', 10000, '');\nINSERT INT"
  },
  {
    "path": "Ch07_XSS/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/WEB-INF/faces-config.xml",
    "chars": 342,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<faces-config version=\"2.2\"\r\n              xmlns=\"http://xmlns.jcp.org/xml/ns/ja"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/WEB-INF/web.xml",
    "chars": 1160,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n         xmlns:xsi=\"http://ww"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/createCustomer.xhtml",
    "chars": 1601,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/index.xhtml",
    "chars": 1893,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/resources/css/styles.css",
    "chars": 156,
    "preview": "th {\n    font-size: 1.1em;\n    font-weight: bold;\n    padding: 5px;\n}\n\ntd {\n    padding: 5px;\n}\n\nh1 {\n    font-size: 1.5"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/search.xhtml",
    "chars": 1053,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/searchCustomer.xhtml",
    "chars": 1887,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch07_XSS/src/main/webapp/showCustomers.xhtml",
    "chars": 2090,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n        \"http://ww"
  },
  {
    "path": "Ch07_XSSFilter/pom.xml",
    "chars": 1560,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/BlacklistFilter.java",
    "chars": 1495,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/BlacklistRequestWrapper.java",
    "chars": 4701,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/ESAPIFilter.java",
    "chars": 1479,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSSFilter/src/main/java/de/dominikschadow/webappsecurity/filter/ESAPIRequestWrapper.java",
    "chars": 2173,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSSFilter/src/main/resources/ESAPI.properties",
    "chars": 47,
    "preview": "# Logging\nLogger.ApplicationName=Ch07_XSSFilter"
  },
  {
    "path": "Ch07_XSSFilter/src/main/webapp/WEB-INF/web.xml",
    "chars": 1011,
    "preview": "<?xml version=\"1.0\"?>\n<web-app id=\"Ch07_XSSFilter\" version=\"3.0\"\n\txmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"h"
  },
  {
    "path": "Ch07_XSSFilter/src/main/webapp/index.jsp",
    "chars": 1583,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch07_XSSFilter/src/main/webapp/outputBlacklist.jsp",
    "chars": 866,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<%@ taglib prefix=\"c\" uri=\"http:/"
  },
  {
    "path": "Ch07_XSSFilter/src/main/webapp/outputEsapi.jsp",
    "chars": 804,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<%@ taglib prefix=\"c\" uri=\"http:/"
  },
  {
    "path": "Ch07_XSSFilter/src/main/webapp/resources/css/styles.css",
    "chars": 306,
    "preview": "h1 {\n    font-size: 1.5em;\n}\n\nfieldset {\n    width: 500px;\n    font-size: 1.2em;\n    margin-top: 20px;\n}\n\ninput {\n    di"
  },
  {
    "path": "Ch07_XSSJSF/pom.xml",
    "chars": 1362,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/MaximumController.java",
    "chars": 1880,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/StandardController.java",
    "chars": 1894,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSSJSF/src/main/java/de/dominikschadow/webappsecurity/Status.java",
    "chars": 1255,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch07_XSSJSF/src/main/webapp/WEB-INF/faces-config.xml",
    "chars": 337,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<faces-config version=\"2.2\"\n              xmlns=\"http://xmlns.jcp.org/xml/ns/java"
  },
  {
    "path": "Ch07_XSSJSF/src/main/webapp/WEB-INF/web.xml",
    "chars": 933,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n         xmlns:xsi=\"http://ww"
  },
  {
    "path": "Ch07_XSSJSF/src/main/webapp/index.xhtml",
    "chars": 1182,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n        \"http://"
  },
  {
    "path": "Ch07_XSSJSF/src/main/webapp/maximum.xhtml",
    "chars": 1516,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n        \"http://"
  },
  {
    "path": "Ch07_XSSJSF/src/main/webapp/resources/css/styles.css",
    "chars": 135,
    "preview": ".text-input {\n    width: 250px;\n}\n\n.send-button {\n    margin-left: 25px;\n}\n\nh1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-"
  },
  {
    "path": "Ch07_XSSJSF/src/main/webapp/standard.xhtml",
    "chars": 1334,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\r\n        \"http://"
  },
  {
    "path": "Ch08_CSRF/pom.xml",
    "chars": 1639,
    "preview": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocat"
  },
  {
    "path": "Ch08_CSRF/src/main/java/de/dominikschadow/webappsecurity/servlets/ProtectedServlet.java",
    "chars": 5287,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch08_CSRF/src/main/java/de/dominikschadow/webappsecurity/servlets/UnprotectedServlet.java",
    "chars": 3951,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of the Java-Web-Security projec"
  },
  {
    "path": "Ch08_CSRF/src/main/java/de/dominikschadow/webappsecurity/token/CSRFTokenHandler.java",
    "chars": 2589,
    "preview": "/*\n * Copyright (C) 2015 Dominik Schadow, info@dominikschadow.de\n *\n * This file is part of Java-Web-Security\n.\n * \n * L"
  },
  {
    "path": "Ch08_CSRF/src/main/resources/logback.xml",
    "chars": 321,
    "preview": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/form-protected.html",
    "chars": 673,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/form-unprotected.html",
    "chars": 677,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/form-working.jsp",
    "chars": 1392,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/image-protected.html",
    "chars": 421,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/image-unprotected.html",
    "chars": 425,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/index.jsp",
    "chars": 828,
    "preview": "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\" pageEncoding=\"UTF-8\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DT"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/requests-protected.html",
    "chars": 1034,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/requests-unprotected.html",
    "chars": 980,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/resources/css/styles.css",
    "chars": 94,
    "preview": ".text-input {\n    width: 250px;\n}\n\nh1 {\n    font-size: 1.5em;\n}\n\nh2 {\n    font-size: 1.2em;\n}\n"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/xmlhttprequest-protected.html",
    "chars": 765,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "Ch08_CSRF/src/main/webapp/xmlhttprequest-unprotected.html",
    "chars": 785,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <title>Chapter 08 - CSRF</title>\n    <link rel=\"s"
  },
  {
    "path": "LICENSE",
    "chars": 11325,
    "preview": "Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licens"
  },
  {
    "path": "README.md",
    "chars": 7362,
    "preview": "Java-Web-Security\n==============\n\nThis repository contains the complete code samples from my book **Java-Web-Security - "
  },
  {
    "path": "pom.xml",
    "chars": 9104,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
  }
]

About this extraction

This page contains the full source code of the dschadow/Java-Web-Security GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 158 files (226.7 KB), approximately 63.0k tokens, and a symbol index with 208 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!