diff --git a/.gitignore b/.gitignore index c785967b3..fb3ff0300 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,8 @@ /.settings/org.eclipse.wst.validation.prefs /.externalToolBuilders/ .project -/target +*/target/* +mongo-data/* .classpath .idea/ .settings/ @@ -29,9 +30,15 @@ src/main/webapp/plugin_lessons/*.jar src/main/webapp/users/*.props classes/* *.iml +pom.xml.versionsBackup /*.iml .extract/* UserDatabase.mv.db webgoat-container/src/main/webapp/users/guest.org.owasp.webgoat.plugin.*.props -webgoat-container/src/main/webapp/plugin_lessons/dist-*.pom \ No newline at end of file +webgoat-container/src/main/webapp/plugin_lessons/dist-*.pom +webgoat-lessons/**/target +**/*.jar +**/.DS_Store +webgoat-server/mongo-data/* +webgoat-lessons/vulnerable-components/dependency-reduced-pom.xml diff --git a/.travis.yml b/.travis.yml index d4c6df9f6..ff681acfb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,59 +1,53 @@ +services: + - docker language: java jdk: - - oraclejdk7 - - oraclejdk8 +- oraclejdk8 install: "/bin/true" script: - - mvn clean install -q - - git clone -b develop https://github.com/WebGoat/WebGoat-Lessons.git - - mvn -file ./WebGoat-Lessons/pom.xml clean package -q - - cp -fa ./WebGoat-Lessons/target/plugins/*.jar ./webgoat-container/src/main/webapp/plugin_lessons/ - # Start the container this will make sure we do not see the debug logging of the Tomcat 7 Maven plugin - # which seems to always be set to DEBUG this will fail the build because we generate too much logging - - nohup bash -c "java -jar ./webgoat-standalone/target/webgoat-standalone-7.1-SNAPSHOT-exec.jar --port 8888 2>&1 &" - - if [[ $TRAVIS_PULL_REQUEST == "false" ]]; then mvn "-Dbuild.number=$TRAVIS_BUILD_NUMBER" -q clean install failsafe:integration-test; else mvn -q failsafe:integration-test; fi +- 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: - - $HOME/.m2 + - "$HOME/.m2" before_deploy: - - export WEBGOAT_CONTAINTER_TARGET_DIR=$HOME/build/$TRAVIS_REPO_SLUG/webgoat-container/target - - export WEBGOAT_STANDALONE_TARGET_DIR=$HOME/build/$TRAVIS_REPO_SLUG/webgoat-standalone/target + - export WEBGOAT_SERVER_TARGET_DIR=$HOME/build/$TRAVIS_REPO_SLUG/webgoat-server/target + - export WEBWOLF_TARGET_DIR=$HOME/build/$TRAVIS_REPO_SLUG/webwolf/target - export WEBGOAT_ARTIFACTS_FOLDER=$HOME/build/$TRAVIS_REPO_SLUG/Deployable_Artifacts/ - - mkdir $WEBGOAT_ARTIFACTS_FOLDER - - cp -fa $WEBGOAT_CONTAINTER_TARGET_DIR/* $WEBGOAT_ARTIFACTS_FOLDER/ - - cp -fa $WEBGOAT_STANDALONE_TARGET_DIR/* $WEBGOAT_ARTIFACTS_FOLDER/ - - echo "Contents of artifcts folder:" + - mkdir -p $WEBGOAT_ARTIFACTS_FOLDER + - cp -fa $WEBGOAT_SERVER_TARGET_DIR/*.jar $WEBGOAT_ARTIFACTS_FOLDER/ + - cp -fa $WEBWOLF_TARGET_DIR/*.jar $WEBGOAT_ARTIFACTS_FOLDER/ + - echo "Contents of artifacts folder:" - ls $WEBGOAT_ARTIFACTS_FOLDER deploy: - provider: s3 - access_key_id: AKIAJQLKPGHXRH2AH5QA - secret_access_key: - secure: 45+SwWlPFujD9FOOFLA9Lz0CaePVrn/SEsAhAn0Ve9sYpI0VsijZNymh6D29t93jBXgZoGhu/v0QJkcAA/71fQM+nGMBJjB5wmVFJ1c2A4k7tfWCVbBRI0aHGpJu12j+7BLuSfPCmCAFQGoVo7dWzfqeODe5j9Qpe9fsiQVnrKI= - bucket: webgoat-war - skip_cleanup: true - acl: public_read - local_dir: "$WEBGOAT_ARTIFACTS_FOLDER" - on: - repo: WebGoat/WebGoat - branch: develop - jdk: oraclejdk8 -after_success: - - mvn versioneye:update -q - - mvn cobertura:cobertura coveralls:report -q -notifications: - slack: - secure: S9VFew5NSE8WDzYD1VDBUULKKT0fzgblQACznwQ85699b2yeX9TX58N3RZvRS1JVagVP1wu2xOrwN2g+AWx4Ro3UBZD5XG86uTJWpCLD4cRWHBoGMH2TfvI7/IzsWmgxH4MBxFRvZr/eEhlVAux+N9H4EoEdS4CKsJXEqV37PlA= + - provider: script + skip_cleanup: true + script: bash scripts/deploy-webgoat.sh + on: + repo: WebGoat/WebGoat + tags: true + - provider: script + skip_cleanup: true + script: bash scripts/deploy-webgoat.sh + on: + repo: WebGoat/WebGoat + branch: develop + - provider: releases + skip_cleanup: true + overwrite: true + api_key: + #api-key from webgoat-github user + secure: pJOLBnl6427PcVg/tVy/qB18JC7b8cKpffau+IP0pjdSt7KUfBdBY3QuJ7mrM65zRoVILzggLckaew2PlRmYQRdumyWlyRn44XiJ9KO4n6Bsufbz+ictB4ggtozpp9+I9IIUh1TmqypL9lhkX2ONM9dSHmyblYpAAgMuYSK8FYc= + file_glob: true + file: $WEBGOAT_ARTIFACTS_FOLDER/* + on: + repo: WebGoat/WebGoat + tags: true env: global: - - secure: "ZLZKz6lGt8YZ+NhkZPBAlI235+lEmu37Tcf+yTwh5yXuHAlnvvF6hPui7rANA/stbYGOIqIdhGOXbdrwyTU4Pvg78VwJOwsa9RtHJfou3pg4Ud9i0/dEeVl8aakmg2HDaWYGcFox8X1ViVc5UWjuBLztfJKQUEx0buJoWdMSf2E=" -addons: - sauce_connect: true - coverity_scan: - project: - name: "WebGoat/WebGoat" - description: "Coverity Scan from Travis CI Build Automation" - notification_email: doug.morato@owasp.org - build_command_prepend: "mvn clean" - build_command: "mvn -DskipTests=true install" - branch_pattern: coverity_scan - + #Docker login + - secure: XgPc0UKRTUI70I4YWNQpThPPWeQIxkmzh1GNoR/SSDC2GPIBq3EfkkbSQewqil8stTy+S1/xSzc0JXG8NTn7UOxHVHA/2nhI6jX9E+DKtXQ89YwmaDNQjkbMjziAtDCIex+5TRykxNfkxj6VPYbDssrzI7iJXOIZVj/HoyO3O5E= + #Docker password + - secure: aly5TKBUK9sIiqtMbytNNPZHQhC0a7Yond5tEtuJ8fO+j/KZB4Uro3I6BhzYjGWFb5Kndd0j2TXHPFvtOl402J1CmFsY3v0BhilQd0g6zOssp5T0A73m8Jgq4ItV8wQJJy2bQsXqL1B+uFYieYPiMchj7JxWW0vBn7TV5b68l6U= diff --git a/CREATE_RELEASE.MD b/CREATE_RELEASE.MD new file mode 100644 index 000000000..885c7a2fc --- /dev/null +++ b/CREATE_RELEASE.MD @@ -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 +mvn versions:set < +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. + + diff --git a/README.MD b/README.MD index a0a8d7ed9..67f2b3b0e 100644 --- a/README.MD +++ b/README.MD @@ -1,17 +1,13 @@ -# 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=master&service=github)](https://coveralls.io/github/WebGoat/WebGoat?branch=master) +[![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 Information -### The WebGoat Lesson Server, is currently **UNDER MAJOR DEVELOMENT**. -As of November 18th 2016, the version "7.1" is considered the first **STABLE** version of a major architecture and UI changes. - -#### Older/Legacy version of WebGoat an be found at: [WebGoat-Legacy](https://github.com/WebGoat/WebGoat-Legacy) +# Introduction WebGoat is a deliberately insecure web application maintained by [OWASP](http://www.owasp.org/) designed to teach web application security lessons. @@ -20,20 +16,9 @@ This program is a demonstration of common server-side application flaws. The exercises are intended to be used by people to learn about application security and penetration testing techniques. -* [Home Page](http://webgoat.github.io) -* [OWASP Project Home Page](http://www.owasp.org/index.php/Category:OWASP_WebGoat_Project) -* [Source Code](https://github.com/WebGoat/WebGoat) -* [Easy-Run Download](https://s3.amazonaws.com/webgoat-war/webgoat-container-7.0.1-war-exec.jar) -* [Wiki](https://github.com/WebGoat/WebGoat/wiki) -* [FAQ (old info):](http://code.google.com/p/webgoat/wiki/FAQ) -* [Project Leader - Direct to Bruce Mayhew](mailto:webgoat@owasp.org) -* [Mailing List - WebGoat Community - For most questions](mailto:owasp-webgoat@lists.owasp.org) -* [Artifacts generated from Continuous Integration](http://webgoat-war.s3-website-us-east-1.amazonaws.com/) -* [Output from our Travis.CI Build server](https://travis-ci.org/WebGoat/WebGoat) - **WARNING 1:** *While running this program your machine will be extremely -vulnerable to attack. You should to disconnect from the Internet while using -this program.* WebGoat's default configuration binds to localhost to minimize +vulnerable to attack. You should disconnect from the Internet while using +this program.* WebGoat's default configuration binds to localhost to minimize the exposure. **WARNING 2:** *This program is for educational purposes only. If you attempt @@ -42,171 +27,147 @@ 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.* -# Easy Run ( For non-developers ) +# Run Instructions: -Every successful build of the WebGoat Lessons Container and the WebGoat Lessons in our Continuous Integration Server -creates an "Easy Run" Executable JAR file, which contains the WebGoat Lessons Server, the lessons and a embedded Tomcat server. +## 1. Run using Docker -You can check for the "Last Modified" date of our "Easy Run" jar file [HERE](http://webgoat-war.s3-website-us-east-1.amazonaws.com/) - -The "Easy Run" JAR file offers a no hassle approach to testing and running WebGoat. Follow these instructions if you -wish to simply try/test/run the current development version of WebGoat - -### Prerequisites: -* Java VM 1.8 - -## Standalone - -#### 1. Download the easy run executable jar file which contains all the lessons and a embedded Tomcat server: - -https://s3.amazonaws.com/webgoat-war/webgoat-standalone-7.1-SNAPSHOT-exec.jar - -#### 2. Run it using java: - -Open a command shell/window, browse to where you downloaded the easy run jar and type: +From time to time we publish a new development preview of WebGoat 8 on Docker HUB, you can download this version +[https://hub.docker.com/r/webgoat/webgoat-8.0/](https://hub.docker.com/r/webgoat/webgoat-8.0/). +First install Docker, then open a command shell/window and type: ```Shell -java -jar webgoat-standalone-7.0.1-exec.jar [-p | --p ] [-a | --address
] +docker pull webgoat/webgoat-8.0 +docker run -p 8080:8080 -it webgoat/webgoat-8.0 /home/webgoat/start.sh ``` -Using the `--help` option will show the allowed command line arguments. +Wait for the Docker container to start, and run `docker ps` to verify it's running. -#### 3. Browse to the url shown in the console and happy hacking ! +- If you are using `docker-machine`, verify the machine IP using `docker-machine env` +- If you are using `boot2docker` on OSX, verify the IP by running `docker network inspect bridge` +- Otherwise, the host will be bound to localhost -## Vagrant +Once you have the IP and port, you'll want to navigate to the `/WebGoat` path in the URL. For example: -To run WebGoat with Vagrant you must first have Vagrant and Virtualbox installed. +``` +http://192.168.99.100:8080/WebGoat +``` + +Here you'll be able to register a new user and get started. + +_Please note: this version may not be completely in sync with the develop branch._ + +## 2. Standalone + +Download the latest WebWolf release from [https://github.com/WebGoat/WebGoat/releases](https://github.com/WebGoat/WebGoat/releases) + +```Shell +java -jar webgoat-server-<>.jar +``` + +By default WebGoat starts at port 8080 in order to change this use the following property: + +```Shell +java -jar webgoat-server-<>.jar --server.port=9090 +``` + +You can specify one of the following arguments when starting WebGoat: + +```Shell +java -jar webgoat-server-<>.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 + +### Prerequisites: + +* Java 8 +* Maven > 3.2.1 +* Your favorite IDE +* Git, or Git support in your IDE + +Open a command shell/window: + +```Shell +git clone git@github.com:WebGoat/WebGoat.git +``` + +Now let's start by compiling the project. + +```Shell +cd WebGoat +git checkout <> +mvn clean install +``` + +Now we are ready to run the project. WebGoat 8.x is using Spring-Boot. + +```Shell +mvn -pl webgoat-server spring-boot:run +``` +... you should be running webgoat on localhost:8080/WebGoat momentarily + + +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 + +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 $ vagrant up ``` -Once you see the message 'Browse to http://localhost:9999/WebGoat and happy hacking! you can open a -browser. - - -# For Developers - -## Vagrant - -For an easy development experience you can use Vagrant. Note you should have Vagrant and Virtualbox installed on your system. - -```shell - $ cd WebGoat/webgoat-images/vagrant-developers - $ vagrant up -``` - Once the provisioning is complete login to the Virtualbox with username vagrant and password vagrant. The source code will be available in the home directory. -## Set up manual -Follow these instructions if you wish to run Webgoat and modify the source code as well. +# Building a new Docker image -### Prerequisites: +NOTE: Travis will create a new Docker image automatically when making a new release. -* Java 1.8 -* Maven > 2.0.9 -* Your favorite IDE, with Maven awareness: Netbeans/IntelliJ/Eclipse with m2e installed. -* Git, or Git support in your IDE - -## The Easy Way: Developer Edition run using Linux or Mac -The __webgoat_developer_bootstrap.sh__ script will clone the necessary repositories, call the maven goals in order -launch Tomcat listening on localhost:8080 +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: ```Shell -mkdir WebGoat-Workspace -cd WebGoat-Workspace -curl -o webgoat_developer_bootstrap.sh https://raw.githubusercontent.com/WebGoat/WebGoat/master/webgoat_developer_bootstrap.sh -./webgoat_developer_bootstrap.sh +cd WebGoat/ +mvn install +cd webgoat-server +docker build -t webgoat/webgoat-8.0 . +docker tag webgoat/webgoat-8.0 webgoat/webgoat-8.0:8.0 +docker login +docker push webgoat/webgoat-8.0 ``` -## The Manual Way: Developer Edition! - -#### Cloning the Lesson Server and the Lessons project: - -Open a command shell/window, navigate to where you wish to download the source and type: +### Docker on ARM (Raspberry Pi) +On a Raspberry Pi (it has yet been tested with a Raspberry Pi 3 and the hypriot Docker image) you need to build JFFI for +ARM first. This is needed by the docker-maven-plugin ([see here](https://github.com/spotify/docker-maven-plugin/issues/233)): ```Shell -git clone https://github.com/WebGoat/WebGoat.git -git clone https://github.com/WebGoat/WebGoat-Lessons.git +sudo apt-get install build-essential +git clone https://github.com/jnr/jffi.git +cd jffi +ant jar +cd build/jni +sudo cp libjffi-1.2.so /usr/lib ``` -#### Now let's start by compiling the WebGoat Lessons server. +When you have done this you can build the Docker container using the following commands: ```Shell -cd WebGoat -git checkout develop -mvn clean compile install -cd .. +cd WebGoat/ +mvn install +cd webgoat-server +mvn docker:build -Drpi=true +docker tag webgoat/webgoat-8.0 webgoat/webgoat-8.0:8.0 +docker login +docker push webgoat/webgoat-8.0 ``` - -#### Before you can run the project, we need to compile the lessons and copy them over: -**If you don't run this step, you will not have any Lessons to work with!** - -```Shell -cd WebGoat-Lessons -git checkout develop -mvn package -(linux) cp target/plugins/*.jar ../WebGoat/webgoat-container/src/main/webapp/plugin_lessons/ -(windows) xcopy "target\plugins\*.jar" "..\WebGoat\webgoat-container\src\main\webapp\plugin_lessons\" -cd .. -``` - -#### Now we are ready to run the project. There are 3 options you can choose from to run the project: - -Then you can run the project with one of the steps below (From the WebGoat folder not WebGoat-Lessons): - -#### Option #1: Using the Maven-Tomcat Plugin -The __maven tomcat7:run-war__ goal runs the project in an embedded tomcat: - -```Shell -cd WebGoat -mvn -pl webgoat-container tomcat7:run-war -``` - -Browse to [http://localhost:8080/WebGoat](http://localhost:8080/WebGoat) and happy hacking ! - -#### Option #2: Java executable JAR -The __maven package__ goal generates an executable .jar file: - -```Shell -cd WebGoat -mvn package -cd webgoat-standalone/target -java -jar webgoat-standalone-7.1-SNAPSHOT-exec.jar [-p | --p ] [-a | --address
] -``` - -Browse to url shown in the console and happy hacking ! - -#### Option #3: Deploy the WebGoat WAR file in your local Tomcat or other Application Server: -The __maven package__ goal generates a .war file that can deployed into an Application Server, such as Tomcat - -```Shell -cd WebGoat -mvn package -cp webgoat-container/target/webgoat-container-7.1-SNAPSHOT.war /webapps/ -``` - -Browse to [http://localhost:8080/WebGoat](http://localhost:8080/WebGoat) and happy hacking ! - -# Debugging and Troubleshooting - -## Reloading plugins and lessons - -If you want to __reload all the plugin and lessons__, open a new browser tab and visit the following url: - -[http://localhost:8080/WebGoat/service/reloadplugins.mvc](http://localhost:8080/WebGoat/service/reloadplugins.mvc) - -After the plugin reload is complete, _reloading a message_ will appear and you can refresh the __main WebGoat browser tab__. - -## Debugging label properties - -To be able to see which labels are loaded through a property file, open a new browser tab and visit the following url: - -[http://localhost:8080/WebGoat/service/debug/labels.mvc](http://localhost:8080/WebGoat/service/debug/labels.mvc) - -Switch back to the main WebGoat broswer tab and __reload the main WebGoat browser tab__. - -After the reload is complete, all labels which where loaded from a property file will be __marked green__. diff --git a/buildspec.yml b/buildspec.yml new file mode 100644 index 000000000..477440e02 --- /dev/null +++ b/buildspec.yml @@ -0,0 +1,12 @@ +version: 0.1 + +phases: + build: + commands: + - mvn package + +artifacts: + files: + - webgoat-server/target/webgoat-server-8.0-SNAPSHOT.jar + discard-paths: yes + diff --git a/catalina.policy b/catalina.policy deleted file mode 100644 index facb61327..000000000 --- a/catalina.policy +++ /dev/null @@ -1,3 +0,0 @@ -grant { - permission java.security.AllPermission; -}; \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..9b0769407 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,15 @@ +version: '2.0' + +services: + webgoat: + build: webgoat-server/ + command: "sh /home/webgoat/start.sh" + ports: + - "8080:8080" + webwolf: + build: webwolf/ + command: "sh /home/webwolf/start.sh" + depends_on: + - webgoat + ports: + - "8081:8081" \ No newline at end of file diff --git a/platformQuickStarts/AWS/README.md b/platformQuickStarts/AWS/README.md new file mode 100644 index 000000000..762bdda12 --- /dev/null +++ b/platformQuickStarts/AWS/README.md @@ -0,0 +1,31 @@ +# AWS + +- This contains the various platform Quick Starts for Getting WebGoat Deployed into AWS. +- This IaaS quickstart uses AWS CloudFormation to perform most of the provisioning +- This IaaS quickstart is composed of three independent bundles + - Code pipeline and Build + - Deploying to EC2 + - Deploying to ECS + + +It is Assumed: +- You have an AWS Account +- You know what an S3 bucket is +- You have seen the IAM console and have permissions to create IAM Roles + + + + +## Code Pipeline and Build + +This Quickstart is for those that just want to perform builds with AWS. It Triggers off of Github to perform builds of `webgoat-server` + + + +## EC2 + +(WIP) This uses AWS CodePipeline, CodeBuild, and CodeDeploy to land WebGoat to Running EC2 instances + +## ECS + +(WIP) This uses AWS CodePipeline, CodeBuild, ECR, to land a container onto an ECS cluster \ No newline at end of file diff --git a/platformQuickStarts/AWS/codepipelinebuild/01_IAM_codebuild.json b/platformQuickStarts/AWS/codepipelinebuild/01_IAM_codebuild.json new file mode 100644 index 000000000..2fbf17f5a --- /dev/null +++ b/platformQuickStarts/AWS/codepipelinebuild/01_IAM_codebuild.json @@ -0,0 +1,101 @@ +{ + "AWSTemplateFormatVersion": "2010-09-09", + "Description": "IAM Roles for Code Build WebGoat IaaS Quickstart", + "Parameters": { + "qsS3BucketName": { + "Description": "Name of the S3 Bucket for artifacts", + "Type": "String", + "MinLength": "1" + }, + "qsRoleName": { + "Description": "Name of the IAM role that CodeBuild Will Use", + "Type": "String", + "Default": "SimpleCodeBuildRole", + "MinLength": "1" + } + }, + "Resources": { + "qsCodeBuildRole": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": { + "Service": [ + "codebuild.amazonaws.com" + ] + }, + "Action": [ + "sts:AssumeRole" + ] + } + ] + }, + "Path": "/webgoat/", + "RoleName": { + "Ref": "qsRoleName" + }, + "ManagedPolicyArns": [ + "arn:aws:iam::aws:policy/AWSCodeCommitFullAccess", + "arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess", + "arn:aws:iam::aws:policy/AWSCodeDeployDeployerAccess" + ], + "Policies": [ + { + "PolicyName": "CloudWatchLogs", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + {"Fn::Join": [ "",["arn:aws:logs:*:", { "Ref": "AWS::AccountId" }, ":log-group:/aws/codebuild*" ] ]} + ], + "Action": [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + } + ] + } + }, + { + "PolicyName": "S3buckets", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:aws:s3:::", + { + "Ref": "qsS3BucketName" + }, + "*" + ] + ] + }, + "arn:aws:s3:::codepipeline-*" + ], + "Action": [ + "s3:Put*", + "s3:Get*", + "s3:List*" + ] + } + ] + } + } + ] + } + } + } +} diff --git a/platformQuickStarts/AWS/codepipelinebuild/01_IAM_codepipeline.json b/platformQuickStarts/AWS/codepipelinebuild/01_IAM_codepipeline.json new file mode 100644 index 000000000..58fd9f1f4 --- /dev/null +++ b/platformQuickStarts/AWS/codepipelinebuild/01_IAM_codepipeline.json @@ -0,0 +1,127 @@ +{ + "AWSTemplateFormatVersion": "2010-09-09", + "Description": "IAM Role for Code Pipeline WebGoat IaaS Quickstart", + "Parameters": { + "qsS3BucketName": { + "Description": "Name of the S3 Bucket for artifacts", + "Type": "String", + "MinLength": "1" + }, + "qsRoleName": { + "Description": "Name of the IAM role that CodePipeline Will Use", + "Type": "String", + "Default": "SimpleCodePipelineRole", + "MinLength": "1" + } + }, + "Resources": { + "qsCodePipelineRole": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "", + "Effect": "Allow", + "Principal": { + "Service": "codepipeline.amazonaws.com" + }, + "Action": "sts:AssumeRole" + } + ] + }, + "Path": "/webgoat/", + "RoleName": { + "Ref": "qsRoleName" + }, + "ManagedPolicyArns": [ + "arn:aws:iam::aws:policy/AWSCodeCommitFullAccess", + "arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess", + "arn:aws:iam::aws:policy/AWSCodeDeployDeployerAccess" + ], + "Policies": [ + { + "PolicyName": "CloudWatchLogsPipeline", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + {"Fn::Join": [ "",["arn:aws:logs:*:", { "Ref": "AWS::AccountId" }, ":log-group:/aws/*" ] ]} + ], + "Action": [ + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:PutLogEvents" + ] + } + ] + } + }, + { + "PolicyName": "MiscComputeOpen", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": "*", + "Action": [ + "lambda:InvokeFunction", + "lambda:ListFunctions", + "elasticbeanstalk:*", + "ec2:*", + "elasticloadbalancing:*", + "autoscaling:*", + "cloudwatch:*", + "s3:*", + "sns:*", + "cloudformation:*", + "rds:*", + "sqs:*", + "ecs:*", + "iam:PassRole" + ] + } + ] + } + }, + { + "PolicyName": "S3buckets", + "PolicyDocument": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Resource": [ + { + "Fn::Join": [ + "", + [ + "arn:aws:s3:::", + { + "Ref": "qsS3BucketName" + }, + "*" + ] + ] + }, + "arn:aws:s3:::codepipeline-*", + "arn:aws:s3:::elasticbeanstalk*" + ], + "Action": [ + "s3:Put*", + "s3:Get*", + "s3:List*" + ] + } + ] + } + } + ] + } + } + } +} diff --git a/platformQuickStarts/AWS/codepipelinebuild/01_codepiplinebuild.yml b/platformQuickStarts/AWS/codepipelinebuild/01_codepiplinebuild.yml new file mode 100644 index 000000000..8aac7af2a --- /dev/null +++ b/platformQuickStarts/AWS/codepipelinebuild/01_codepiplinebuild.yml @@ -0,0 +1,123 @@ +AWSTemplateFormatVersion: "2010-09-09" + +Description: > + AWS Cloud Formation for creating an AWS CodePipeline that checks a git repo for changes and then performs a build using code build + + +Parameters: + qsPipelineName: + Description: The name of the AWS Code Pipeline + Type: String + Default: WG-pipeline + MinLength: 1 + qsPipelineRoleARN: + Description: The complete ARN to the IAM role that code pipeline should use + Type: String + MinLength: 1 + qsCodeRepo: + Description: The Repository + Type: String + MinLength: 1 + qsRepoBranch: + Description: The Branch in the Repository + Type: String + MinLength: 1 + qsGitHubUser: + Description: The GitHub User Id + Type: String + MinLength: 1 + qsGitHubAPIToken: + Description: The GitHub Personal Access token do not use password + NoEcho: true + Type: String + MinLength: 1 + qsS3PipelineArtifacts: + Description: Where Code Pipeline will state artifacts in S3 + Type: String + MinLength: 1 + qsS3CodeBuildArtifacts: + Description: Where Code Build will upload Artifacts can be same as codepipeline + Type: String + MinLength: 1 + qsCodeBuildName: + Description: Name of the AWS Code Build + Type: String + Default: WG-mvnBuilder + MinLength: 1 + qsKMSKeyARN: + Description: The KMS ARN that the IAM Role is allowed to use + Type: String + MinLength: 1 + qsCodeRoleArn: + Description: The IAM Role ARN for CodePipeline and CodeDeploy + Type: String + MinLength: 1 + + + +Resources: + + + + + stkcbrCodeBuild: + Type: AWS::CodeBuild::Project + Properties: + Artifacts: + Type: CODEPIPELINE + Description: Builds WebGoat Jar using build file in repo + EncryptionKey: !Ref 'qsKMSKeyARN' + Environment: + ComputeType: BUILD_GENERAL1_SMALL + Image: aws/codebuild/java:openjdk-8 + Type: LINUX_CONTAINER + Name: !Ref 'qsCodeBuildName' + ServiceRole: !Ref 'qsCodeRoleArn' + TimeoutInMinutes: 10 + Source: + Type: CODEPIPELINE + + + + stkcplPipeline: + Type: AWS::CodePipeline::Pipeline + Properties: + Name: !Ref 'qsPipelineName' + RoleArn: !Ref 'qsPipelineRoleARN' + ArtifactStore: + Location: !Ref 'qsS3PipelineArtifacts' + Type: S3 + Stages: + - Name: CodeRepo + Actions: + - Name: CodeSource + ActionTypeId: + Category: Source + Owner: ThirdParty + Provider: GitHub + Version: 1 + Configuration: + Branch: !Ref 'qsRepoBranch' + Repo: !Ref 'qsCodeRepo' + Owner: !Ref 'qsGitHubUser' + OAuthToken: !Ref 'qsGitHubAPIToken' + OutputArtifacts: + - Name: MySource + RunOrder: '1' + - Name: Build + Actions: + - Name: CodeBuild + ActionTypeId: + Category: Build + Owner: AWS + Provider: CodeBuild + Version: 1 + InputArtifacts: + - Name: MySource + Configuration: + ProjectName: !Ref stkcbrCodeBuild + OutputArtifacts: + - Name: MyBuild + RunOrder: '2' + + diff --git a/platformQuickStarts/AWS/codepipelinebuild/README.md b/platformQuickStarts/AWS/codepipelinebuild/README.md new file mode 100644 index 000000000..e8aea2d06 --- /dev/null +++ b/platformQuickStarts/AWS/codepipelinebuild/README.md @@ -0,0 +1,64 @@ +# Serverless MVN builds Featuring AWS + +This Quick Start forms the basis for the other AWS quickstarts. This only BUILDS the `webgoat-server` spring boot jar. If you want to also run it on AWS skip to the other AWS quickstarts + +Before you Begin +1. Do you have an AWS Account? +2. Can you create an S3 Bucket? +3. Can you create a KMS Key? +4. Do you know what Cloud Formation is? +5. Do you have enough permissions to do any real work in said AWS Account? + +If you said no to any of those...hop over to [docs](https://aws.amazon.com/documentation/) and learn (but don't do) how to create those. + + +You will also need: +1. A GitHub Account +2. Fork of WebGoat +3. Personal access Token with `Admin:repo_hook` and `repo` + + + +## Create Pre-requisites + +First pick an AWS region and stick with it for ALL the quickstarts. This one was mostly executed on US-east-1/2 but any region with KMS, CodePipeline, and CodeBuild will work. eu-Central-1, ap-southeast-1 and sa-east-1 have reported success also. + + +1. Create an S3 bucket and call it something meaningfull like `webgoat-stash-username` or something or use an existing bucket you have access to. +2. Create a KMS Key. Make sure you are a key administrator so you can add key users later. + +## Deploy IAM role Cloud Formation Stacks + +In this folder there are two json cloudformation templates: +-`01_IAM_codebuild.json` +-`01_IAM_codepipeline.json` + +You will use the CloudFormation templates to create two roles. One for CodePipeline and the Other for CodeBuild. You will use the name of the bucket you just created as a parameter. + +## Update KMS Key + +Access the KMS key you created earlier...add the two IAM roles you just created and Key Users + +## Finally the Pipeline + +You will use the yaml cloudformation template `01_codepiplinebuild.yml` to create the code building pipeline. + +Some of the parameters you will need to pass: +1. The S3 bucket (twice) +2. The Github Branch name (master? develop? yourbranchname?) +3. The Github user (if you forked it would be your username) +4. You personal access token for GitHub +5. The name or the repo (WebGoat! ...unless you renamed and did a whole bunch of fancy git magic) +6. The ARN of the KMS key +7. The ARN of the role for the codebuild for parameter qsCodeRoleArn +8. The ARN for codepipeline + +If this Stack successfully deploys a build will begin based on the latest commit automatically. You will have a funky named zip file (without the .zip ending) in a folder in the S3 bucket in a few minutes. + + + +Congratulations. You just Deployed a two step AWS Codepipeline that looks for codechanges and then performs a build. + +... ON to the next AWS Quickstart + + diff --git a/platformQuickStarts/GCP/GKE-Docker/README.md b/platformQuickStarts/GCP/GKE-Docker/README.md new file mode 100644 index 000000000..7b18993c1 --- /dev/null +++ b/platformQuickStarts/GCP/GKE-Docker/README.md @@ -0,0 +1,80 @@ +# GKE - DockerHub + +This Quickstart shows how to create a Kubernettes Cluster using Google Cloud Platform's [GKE](https://cloud.google.com/container-engine/) and WebGoat's Docker [Image](https://hub.docker.com/r/webgoat/webgoat-8.0/). + +To be Successfull with this Quickstart + +1. You have a Google Cloud Platform account and have enough access rights to create Compute Engine and Container Engine Resources +2. You know how to `git clone` +3. You have the gcloud SDK install and initialized somewhere ( do not use the google cloud shell) + + +Remeber to perform a 'gcloud auth login' before using the gcloud commands below. + + + +## Create Kubernettes Cluster + +You can create a cluster using the Google Cloud Console. The Default settings will suffice. For this QuickStart the cluster name used is `owaspbasiccluster`. The `PROJECTNAME` is whatever your project is. The `REGION` is a region/zone near you. + +If you want to use the gcloud sdk from a properly initialized gcloud commandline environment use the following command + + +``` +gcloud container --project "PROJECTNAME" clusters create "owaspbasiccluster" --zone "REGION" --machine-type "n1-standard-1" --image-type "COS" --disk-size "100" --scopes "https://www.googleapis.com/auth/compute","https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/servicecontrol","https://www.googleapis.com/auth/service.management.readonly","https://www.googleapis.com/auth/trace.append","https://www.googleapis.com/auth/source.read_only" --num-nodes "3" --network "default" --enable-cloud-logging --no-enable-cloud-monitoring + + +``` + +The command creates a similar cluster with more of the options set explicitly. + +## Set up Kubectl + +Using the commandline gcloud SDK environment you need to set-up 'kubectl' + +If you have not already installed 'Kubectl' you can do so with the following command using `gcloud` +- `gcloud components install kubectl` + +Then you just run: +- `gcloud container clusters get-credentials owaspbasiccluster --zone REGION --project PROJECTNAME` + + +## Deploy WebGoat Deployment + +Time to deploy the latest DockerImage for WebGoat! + + +Let's First Make a namespace for this: +- `kubectl create namespace webgoat` + +Now it is time to make the magic happen! + +- `kubectl create -f /where_you_git_cloned_webgoat/platformQuickStart/GCP/GKE-Docker/webgoat_noDNSnoTLS.yml` + +This should complete with no errors. + +Use the following command to see information/status about the deployment +- `kubectl describe deployment webgoat-dpl --namespace=webgoat` + +After a few minutes the service endpoint should be ready. You can check the status with +- `kubectl describe service webgoatsvc --namespace=webgoat` + +In the output you should see a message like "Created load..." after a "Creating load..." which means that the public facing loadbalancer (even thou there is just one container running!) is ready. + + +If you want to see the Kubernetes dashboard you can run `kubectl proxy` (in a new terminal window) and then navigate to http://localhost:8001/ui . + + + +## Test Deployment + +From the previous `describe service` command the `LoadBalancer Ingress:` line should have the external IP. The line below should give the port. + +So..... + +[IP]:[PORT]/WebGoat in your browser! + +DONE + + + diff --git a/platformQuickStarts/GCP/GKE-Docker/webgoat_deployment_noDNSnoTLS.yml b/platformQuickStarts/GCP/GKE-Docker/webgoat_deployment_noDNSnoTLS.yml new file mode 100644 index 000000000..228cf29ef --- /dev/null +++ b/platformQuickStarts/GCP/GKE-Docker/webgoat_deployment_noDNSnoTLS.yml @@ -0,0 +1,39 @@ +--- +apiVersion: v1 +kind: Service +metadata: + labels: + app: webgoatapp + name: webgoatsvc + namespace: webgoat +spec: + ports: + - + port: 8080 + protocol: TCP + selector: + app: webgoatapp + type: LoadBalancer +--- +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + name: webgoat-dpl + namespace: webgoat +spec: + replicas: 1 + template: + metadata: + name: webgoatapp + labels: + app: webgoatapp + spec: + containers: + - + image: webgoat/webgoat-8.0 + name: webgoat + ports: + - + containerPort: 8080 + + \ No newline at end of file diff --git a/platformQuickStarts/GCP/README.md b/platformQuickStarts/GCP/README.md new file mode 100644 index 000000000..1c4eb30cb --- /dev/null +++ b/platformQuickStarts/GCP/README.md @@ -0,0 +1,17 @@ +# WebGoat on GCP! + +This folder contains sub folders for the various ways you could deploy WebGoat on Google Cloud Platform + +It is assumed: +1. You have a Google Cloud Platform Account +2. You can use Git +3. You can use a Linux/Mac/Google Cloud Shell + + +## GKE Docker + +Uses GKE to run the latest DockerHub version of WebGoat8 + +## AppEngine + +WIP \ No newline at end of file diff --git a/platformQuickStarts/README.md b/platformQuickStarts/README.md new file mode 100644 index 000000000..f647f3273 --- /dev/null +++ b/platformQuickStarts/README.md @@ -0,0 +1,22 @@ +# OWASP WebGoat Platform Quick Starts + +Want to Run WebGoat? Want to run WebGoat in the Cloud? Don't want to be cloud Expert? + +Do we have a solution for you! + + +Additionally, Each IaaS/PaaS will have their deployment steps broken down giving the *app-guy-new-to-cloud* an opportunity to learn how said platform works. + + + +## AWS + +Multi-Part Quickstart. Starts with simple pipeline that just builds code to a deploying onto EC2 instances and then containers using ECS/ECR + +## GCP + +Get WebGoat Running on GKE and AppEngine + + + + diff --git a/pom.xml b/pom.xml index 50a2457b7..ed6151f87 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.owasp.webgoat webgoat-parent pom - 7.1 + 8.0.0.M3 WebGoat Parent Pom Parent Pom for the WebGoat Project. A deliberately insecure Web Application @@ -17,6 +17,12 @@ https://webgoat.github.io/ + + org.springframework.boot + spring-boot-starter-parent + 1.5.5.RELEASE + + GNU General Public License, version 2 @@ -35,14 +41,14 @@ nbaars Nanne Baars - nbaars@xebia.com + nanne.baars@owasp.org https://github.com/nbaars Europe/Amsterdam misfir3 - - + Jason White + jason.white@owasp.org jwayman @@ -86,7 +92,7 @@ https://github.com/WebGoat/WebGoat scm:git:git@github.com:WebGoat/WebGoat.git scm:git:git@github.com:WebGoat/WebGoat.git - 7.1 + HEAD @@ -100,6 +106,9 @@ + 1.8 + 1.8 + UTF-8 UTF-8 @@ -121,22 +130,20 @@ 1.3.1 2.4 3.4 - 1.2 4.0.0 - 1.4.2 + 2.2.5 + 2.2.4 18.0 1.4.190 - 1.8.0.10 + 2.3.2 1.3.1 2.6.3 2.6.3 6.0 1.2 1.7.12 - 1.2 1.3.1 4.12 - 1.2.17 1.5.4 3.3 2.19 @@ -146,13 +153,10 @@ 2.5.2 3.0.1 2.19 - 2.6 - 1.6.7 - 3.2.4.RELEASE + 1.6.6 + 2.11.7 2.1.20 2.48.2 - 1.7.12 - 1.7.12 3.2.4.RELEASE 1.1.2 3.0.5 @@ -164,7 +168,9 @@ webgoat-container - webgoat-standalone + webgoat-lessons + webgoat-server + webwolf @@ -285,6 +291,20 @@ + + + org.projectlombok + lombok + provided + true + + + org.apache.commons + commons-exec + 1.3 + + + diff --git a/scripts/deploy-webgoat.sh b/scripts/deploy-webgoat.sh new file mode 100644 index 000000000..c0374ad37 --- /dev/null +++ b/scripts/deploy-webgoat.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash + +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 + docker build --build-arg webgoat_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 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 . + docker push $REPO +else + echo "Skipping releasing to DockerHub because it is a build of branch ${BRANCH}" +fi \ No newline at end of file diff --git a/webgoat-container/pom.xml b/webgoat-container/pom.xml index 3f82404df..d9682cb57 100644 --- a/webgoat-container/pom.xml +++ b/webgoat-container/pom.xml @@ -1,92 +1,31 @@ - - + + org.owasp.webgoat webgoat-container 4.0.0 webgoat-container - war + jar org.owasp.webgoat webgoat-parent - 7.1 + 8.0.0.M3 - run-integration-tests - - false - - run-integration - true - - + performance - org.apache.tomcat.maven - tomcat7-maven-plugin - 2.3-SNAPSHOT - - local_tomcat - http://localhost:8080/manager - /WebGoat - exec - true - true - ${project.basedir}/src/main/webapp/WEB-INF/context.xml - - - - org.owasp.webgoat - webgoat-container - ${project.version} - - - - - tomcat-run - - exec-war-only - - package - - - tomcat-startup - pre-integration-test - - run-war-only - - - 8888 - true - - - - - tomcat-shutdown - post-integration-test - - shutdown - - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${maven-failsafe-plugin.version} - - - file:${project.basedir}/src/test/resources/log4j-silent.properties - - + io.gatling + gatling-maven-plugin + ${gatling-plugin.version} - integration-test - verify + execute @@ -94,178 +33,91 @@ + - ${basedir}/src/main/java + src/main/java - ${basedir}/src/main/resources + src/main/resources + true + + **/application.properties + + + + src/main/resources + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + + @ + + false + + org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin.version} - 1.7 - 1.7 + 1.8 + 1.8 ISO-8859-1 - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - create-jar - compile - - jar - - - - - - org.apache.maven.plugins - maven-war-plugin - ${maven-war-plugin.version} - - - false - - - true - - - ${project.name} - ${project.version} - ${build.number} - - - - - - org.codehaus.mojo - build-helper-maven-plugin - ${build-helper-maven-plugin.version} - - - attach-artifacts - package - - attach-artifact - - - - - ${project.build.directory}/webgoat-container-${project.version}.jar - - - - - - - - org.apache.tomcat.maven - tomcat7-maven-plugin - 2.3-SNAPSHOT - - local_tomcat - http://localhost:8080/manager/text - /WebGoat - exec - true - true - ${project.basedir}/src/main/webapp/WEB-INF/context.xml - - - - org.owasp.webgoat - webgoat-container - ${project.version} - - - - - tomcat-run - - exec-war-only - - package - - - org.apache.maven.plugins maven-surefire-plugin ${maven-surefire-plugin.version} - - **/*IT.java - + never - - - - - - - - - - - - - - - - - - - - - - + + org.apache.maven.plugins + maven-jar-plugin + 3.0.2 + + + + test-jar + + + + - javax.activation - activation - ${activation.version} + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 - com.h2database - h2 - ${h2.version} + org.springframework.boot + spring-boot-starter-web - axis - axis - ${axis.version} + org.springframework.boot + spring-boot-starter-actuator - axis - axis-saaj - ${axis-saaj.version} + org.asciidoctor + asciidoctorj + 1.5.4 - axis - axis-jaxrpc - ${axis-jaxrpc.version} - - - axis - axis-ant - ${axis-ant.version} + org.springframework.boot + spring-boot-starter-data-jpa org.apache.commons @@ -273,232 +125,76 @@ ${commons-lang3.version} - commons-io - commons-io - ${commons-io.version} + com.google.guava + guava + ${guava.version} + + + + + io.gatling.highcharts + gatling-charts-highcharts + ${gatling.version} + test - commons-collections - commons-collections - ${commons-collections.version} + org.springframework.boot + spring-boot-starter-security - commons-digester - commons-digester - ${commons-digester.version} - - - xml-apis - xml-apis - - + org.springframework.boot + spring-boot-starter-thymeleaf - commons-logging - commons-logging - ${commons-logging.version} + org.thymeleaf.extras + thymeleaf-extras-springsecurity4 + 2.1.2.RELEASE - org.slf4j - jcl-over-slf4j - ${jcl-over-slf4j.version} + javax.activation + activation + ${activation.version} - commons-discovery - commons-discovery - ${commons-discovery.version} - - - javax.mail - javax.mail-api - ${mail-api.version} - - - hsqldb + org.hsqldb hsqldb ${hsqldb.version} - - wsdl4j - wsdl4j - ${wsdl4j.version} - - - java2html - j2h - ${j2h.version} - - - ecs - ecs - ${ecs.version} - javax.transaction javax.transaction-api ${javax.transaction-api.version} - net.sourceforge.jtds - jtds - ${jtds.version} - - - org.apache.tomcat - tomcat-catalina - ${tomcat-catalina.version} - provided + org.scala-lang + scala-compiler + ${scala.version} + test - - - - - javax - javaee-api - ${javaee-api.version} - provided - - - - org.springframework - spring-core - ${org.springframework.version} - - - org.springframework - spring-aop - ${org.springframework.version} - - - - - com.fasterxml.jackson.core - jackson-core - ${jackson-core.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind.version} - - - - - org.springframework - spring-webmvc - ${org.springframework.version} - jar - - - - org.springframework.security - spring-security-core - ${spring.security.version} - - - - org.springframework.security - spring-security-config - ${spring.security.version} - - - - org.springframework.security - spring-security-web - ${spring.security.version} - - - - - commons-fileupload - commons-fileupload - ${commons-fileupload.version} - - - - com.google.guava - guava - ${guava.version} - - - - - javax.servlet - jstl - ${jstl.version} - - - - taglibs - standard - ${standard.version} - - - - log4j - log4j - ${log4j.version} - - - javax.jms - jms - - - com.sun.jdmk - jmxtools - - - com.sun.jmx - jmxri - - - - - org.apache.tiles - tiles-core - ${tiles.version} - jar - - - org.slf4j - slf4j-api - ${slf4j-api.version} - jar - - - org.slf4j - slf4j-log4j12 - ${slf4j-log4j12.version} - jar - + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + 4.1.3.RELEASE + test + junit junit ${junit.version} jar - - org.seleniumhq.selenium - selenium-java - ${selenium-java.version} - - - com.saucelabs - sauce_junit - ${sauce_junit.version} - test - - - - - - + diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/servlets/Controller.java b/webgoat-container/src/main/java/org/owasp/webgoat/AjaxAuthenticationEntryPoint.java similarity index 59% rename from webgoat-container/src/main/java/org/owasp/webgoat/servlets/Controller.java rename to webgoat-container/src/main/java/org/owasp/webgoat/AjaxAuthenticationEntryPoint.java index 9cd7f284e..f1af53ddc 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/servlets/Controller.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/AjaxAuthenticationEntryPoint.java @@ -1,71 +1,58 @@ -package org.owasp.webgoat.servlets; - -import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * ************************************************************************************************* - * - * + *

+ *

* This file is part of WebGoat, an Open Web Application Security Project * utility. For details, please see http://www.owasp.org/ - * + *

* Copyright (c) 2002 - 20014 Bruce Mayhew - * + *

* 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. - * + *

* 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. - * + *

* 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. - * + *

* Getting Source ============== - * + *

* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository * for free software projects. - * - * @version $Id: $Id - * @author dm */ -public class Controller extends HttpServlet { - private static final long serialVersionUID = 1L; +package org.owasp.webgoat; - /** {@inheritDoc} */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; - doPost(request, response); +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +/** + *

AjaxAuthenticationEntryPoint class.

+ * + * @author zupzup + */ + +public class AjaxAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { + public AjaxAuthenticationEntryPoint(String loginFormUrl) { + super(loginFormUrl); } - /** {@inheritDoc} */ - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, - IOException { - - String userAgent = request.getHeader("user-agent"); - - String clientBrowser = "Not known!"; - - if (userAgent != null) { - - clientBrowser = userAgent; - + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { + if(request.getHeader("x-requested-with") != null) { + response.sendError(401, authException.getMessage()); + } else { + super.commence(request, response, authException); } - - request.setAttribute("client.browser", clientBrowser); - - request.getRequestDispatcher("/view.jsp").forward(request, response); - } - } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/AsciiDoctorTemplateResolver.java b/webgoat-container/src/main/java/org/owasp/webgoat/AsciiDoctorTemplateResolver.java new file mode 100644 index 000000000..8510906f5 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/AsciiDoctorTemplateResolver.java @@ -0,0 +1,127 @@ + +/** + * ************************************************************************************************ + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 20014 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ * + * @author WebGoat + * @version $Id: $Id + * @since December 12, 2015 + */ +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.owasp.webgoat.i18n.Language; +import org.thymeleaf.TemplateProcessingParameters; +import org.thymeleaf.resourceresolver.IResourceResolver; +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; + +/** + * Thymeleaf resolver for AsciiDoc used in the lesson, can be used as follows inside a lesson file: + *

+ * + *

+ * + */ +@Slf4j +public class AsciiDoctorTemplateResolver extends TemplateResolver { + + private static final Asciidoctor asciidoctor = create(); + private static final String PREFIX = "doc:"; + private final Language language; + + public AsciiDoctorTemplateResolver(Language language) { + this.language = language; + + setResourceResolver(new AdocResourceResolver()); + setResolvablePatterns(Sets.newHashSet(PREFIX + "*")); + } + + @Override + protected String computeResourceName(TemplateProcessingParameters params) { + String templateName = params.getTemplateName(); + return templateName.substring(PREFIX.length()); + } + + private class AdocResourceResolver implements IResourceResolver { + + @Override + public InputStream getResourceAsStream(TemplateProcessingParameters params, String resourceName) { + 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(); + asciidoctor.convert(new InputStreamReader(is), writer, createAttributes()); + return new ByteArrayInputStream(writer.getBuffer().toString().getBytes(UTF_8)); + } + } catch (IOException e) { + //no html yet + return new ByteArrayInputStream(new byte[0]); + } + } + + /** + * The resource name is for example HttpBasics_content1.adoc. This is always located in the following directory: + * plugin/HttpBasics/lessonPlans/en/HttpBasics_content1.adoc + */ + private String computeResourceName(String resourceName, String language) { + return String.format("lessonPlans/%s/%s", language, resourceName); + } + + private InputStream readInputStreamOrFallbackToEnglish(String resourceName, Language language) { + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(computeResourceName(resourceName, language.getLocale().getLanguage())); + if (is == null) { + is = Thread.currentThread().getContextClassLoader().getResourceAsStream(computeResourceName(resourceName, "en")); + } + return is; + } + + private Map createAttributes() { + Map attributes = Maps.newHashMap(); + attributes.put("source-highlighter", "coderay"); + attributes.put("backend", "xhtml"); + + Map options = Maps.newHashMap(); + options.put("attributes", attributes); + + return options; + } + + @Override + public String getName() { + return "adocResourceResolver"; + } + } + +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/Catcher.java b/webgoat-container/src/main/java/org/owasp/webgoat/Catcher.java deleted file mode 100644 index 074c61c91..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/Catcher.java +++ /dev/null @@ -1,120 +0,0 @@ - -package org.owasp.webgoat; - -import java.io.IOException; -import java.util.Enumeration; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.owasp.webgoat.lessons.AbstractLesson; -import org.owasp.webgoat.session.Course; -import org.owasp.webgoat.session.WebSession; - - -/** - ************************************************************************************************* - * - * - * This file is part of WebGoat, an Open Web Application Security Project utility. For details, - * please see http://www.owasp.org/ - * - * Copyright (c) 2002 - 20014 Bruce Mayhew - * - * 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. - * - * 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. - * - * 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. - * - * Getting Source ============== - * - * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software - * projects. - * - * @author Bruce Mayhew WebGoat - * @since March 13, 2007 - * @version $Id: $Id - */ -public class Catcher extends HammerHead -{ - - /** - * - */ - private static final long serialVersionUID = 7441856110845727651L; - - /** - * Description of the Field - */ - public final static String START_SOURCE_SKIP = "START_OMIT_SOURCE"; - - /** Constant END_SOURCE_SKIP="END_OMIT_SOURCE" */ - public final static String END_SOURCE_SKIP = "END_OMIT_SOURCE"; - - /** Constant PROPERTY="PROPERTY" */ - public static final String PROPERTY = "PROPERTY"; - - /** Constant EMPTY_STRING="" */ - public static final String EMPTY_STRING = ""; - - /** - * {@inheritDoc} - * - * Description of the Method - * @exception IOException - * Description of the Exception - * @exception ServletException - * Description of the Exception - */ - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException - { - try - { - // System.out.println( "Entering doPost: " ); - // System.out.println( " - request " + request); - // System.out.println( " - principle: " + request.getUserPrincipal() ); - // setCacheHeaders(response, 0); - WebSession session = (WebSession) request.getSession(true).getAttribute(WebSession.SESSION); - session.update(request, response, this.getServletName()); // FIXME: Too much in this - // call. - - int scr = session.getCurrentScreen(); - Course course = session.getCourse(); - AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE); - - log(request, lesson.getClass().getName() + " | " + session.getParser().toString()); - - String property = new String(session.getParser().getStringParameter(PROPERTY, EMPTY_STRING)); - - // if the PROPERTY parameter is available - write all the parameters to the - // property file. No other control parameters are supported at this time. - if (!property.equals(EMPTY_STRING)) - { - Enumeration e = session.getParser().getParameterNames(); - - while (e.hasMoreElements()) - { - String name = (String) e.nextElement(); - String value = session.getParser().getParameterValues(name)[0]; - lesson.getLessonTracker(session).getLessonProperties().setProperty(name, value); - } - } - lesson.getLessonTracker(session).store(session, lesson); - - // BDM MC -// WEB-173 - removed for testing, as plugin architecture would not allow this -// if ( request.getParameter("Deleter") != null ){org.owasp.webgoat.lessons.BlindScript.StaticDeleter();} - - } catch (Throwable t) - { - t.printStackTrace(); - log("ERROR: " + t); - } - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/CleanupLocalProgressFiles.java b/webgoat-container/src/main/java/org/owasp/webgoat/CleanupLocalProgressFiles.java new file mode 100644 index 000000000..2048dbbd7 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/CleanupLocalProgressFiles.java @@ -0,0 +1,27 @@ +package org.owasp.webgoat; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.FileSystemUtils; + +import javax.annotation.PostConstruct; +import java.io.File; + +/** + * @author nbaars + * @since 4/15/17. + */ +@Slf4j +@Configuration +@ConditionalOnExpression("'${webgoat.clean}' == 'true'") +public class CleanupLocalProgressFiles { + + @Value("${webgoat.server.directory}") + private String webgoatHome; + + @PostConstruct + public void clean() { + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java b/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java index d870a8a49..0aa243993 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java @@ -1,442 +1,61 @@ package org.owasp.webgoat; -import org.owasp.webgoat.lessons.AbstractLesson; -import org.owasp.webgoat.lessons.WelcomeScreen; -import org.owasp.webgoat.lessons.admin.WelcomeAdminScreen; +import lombok.AllArgsConstructor; import org.owasp.webgoat.session.Course; -import org.owasp.webgoat.session.ErrorScreen; -import org.owasp.webgoat.session.Screen; -import org.owasp.webgoat.session.UserTracker; -import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.session.WebgoatContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URL; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; /** * ************************************************************************************************* - * - * + *

+ *

* This file is part of WebGoat, an Open Web Application Security Project * utility. For details, please see http://www.owasp.org/ - * + *

* Copyright (c) 2002 - 20014 Bruce Mayhew - * + *

* 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. - * + *

* 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. - * + *

* 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. - * + *

* Getting Source ============== - * + *

* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository * for free software projects. * - * @author Jeff Williams Aspect - * Security - * @author Bruce Mayhew WebGoat - * @since October 28, 2003 + * @author Jeff Williams + * @author Bruce Mayhew + * @author Nanne Baars * @version $Id: $Id + * @since October 28, 2003 */ -public class HammerHead extends HttpServlet { - - final Logger logger = LoggerFactory.getLogger(HammerHead.class); +@Controller +@AllArgsConstructor +public class HammerHead { + private final Course course; /** - * + * Entry point for WebGoat, redirects to the first lesson found within the course. */ - private static final long serialVersionUID = 645640331343188020L; - - /** - * Description of the Field - */ - protected static SimpleDateFormat httpDateFormat; - - /** - * Set the session timeout to be 2 days - */ - private final static int sessionTimeoutSeconds = 60 * 60 * 24 * 2; - - // private final static int sessionTimeoutSeconds = 1; - /** - * Properties file path - */ - public static String propertiesPath = null; - - /** - * provides convenience methods for getting setup information from the - * ServletContext - */ - private WebgoatContext webgoatContext = null; - - /** - * {@inheritDoc} - * - * Description of the Method - * @exception IOException Description of the Exception - * @exception ServletException Description of the Exception - */ - @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - doPost(request, response); - } - - /** - * {@inheritDoc} - * - * Description of the Method - * @exception IOException Description of the Exception - * @exception ServletException Description of the Exception - */ - @Override - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - Screen screen = null; - - WebSession mySession = null; - try { - logger.debug("Entering doPost"); - logger.debug("request: " + request); - logger.debug("principle: " + request.getUserPrincipal()); - // setCacheHeaders(response, 0); - ServletContext context = getServletContext(); - - // FIXME: If a response is written by updateSession(), do not - // call makeScreen() and writeScreen() - mySession = updateSession(request, response, context); - - if (response.isCommitted()) { - logger.debug("Response already committed, exiting"); - return; - } - - if ("true".equals(request.getParameter("start")) || request.getQueryString() == null) { - logger.warn("Redirecting to first lesson"); - response.sendRedirect("start.mvc" + mySession.getCourse().getFirstLesson().getLink()); - return; - } - - // Note: For the lesson to track the status, we need to update - // the lesson tracker object - // from the screen.createContent() method. The create content is - // the only point - // where the lesson "knows" what has happened. To track it at a - // latter point would - // require the lesson to have memory. - screen = makeScreen(mySession); - // This calls the lesson's - // handleRequest() - if (response.isCommitted()) { - return; - } - - // perform lesson-specific tracking activities - if (screen instanceof AbstractLesson) { - AbstractLesson lesson = (AbstractLesson) screen; - - // we do not count the initial display of the lesson screen as a visit - if ("GET".equals(request.getMethod())) { - String uri = request.getRequestURI() + "?" + request.getQueryString(); - if (!uri.endsWith(lesson.getLink())) { - screen.getLessonTracker(mySession).incrementNumVisits(); - } - } else if ("POST".equals(request.getMethod()) - && mySession.getPreviousScreen() == mySession.getCurrentScreen()) { - screen.getLessonTracker(mySession).incrementNumVisits(); - } - } - - // log the access to this screen for this user - UserTracker userTracker = UserTracker.instance(); - userTracker.update(mySession, screen); - log(request, screen.getClass().getName() + " | " + mySession.getParser().toString()); - - // Redirect the request to our View servlet - String userAgent = request.getHeader("user-agent"); - String clientBrowser = "Not known!"; - if (userAgent != null) { - clientBrowser = userAgent; - } - request.setAttribute("client.browser", clientBrowser); - // removed - this is being done in updateSession call - //request.getSession().setAttribute(WebSession.SESSION, mySession); - // not sure why this is being set in the session? - //request.getSession().setAttribute(WebSession.COURSE, mySession.getCourse()); - String viewPage = getViewPage(mySession); - logger.debug("Forwarding to view: " + viewPage); - logger.debug("Screen: " + screen); - request.getRequestDispatcher(viewPage).forward(request, response); - } catch (Throwable t) { - logger.error("Error handling request", t); screen = new ErrorScreen(mySession, t); - } finally { - try { - if (screen instanceof ErrorScreen) { - this.writeScreen(mySession, screen, response); - } - } catch (Throwable thr) { - logger.error("Could not write error screen", thr); - } - WebSession.returnConnection(mySession); - logger.debug("Leaving doPost: "); - } - } - - private String getViewPage(WebSession webSession) { - // now always display the lesson content - String page = "/lesson_content.jsp"; - //page = "/main.jsp"; - return page; - } - - /** - * Description of the Method - * - * @param date Description of the Parameter - * @return RFC 1123 http date format - */ - protected static String formatHttpDate(Date date) { - synchronized (httpDateFormat) { - return httpDateFormat.format(date); - } - } - - /** - * {@inheritDoc} - * - * Return information about this servlet - */ - @Override - public String getServletInfo() { - return "WebGoat is sponsored by Aspect Security."; - } - - /** - * {@inheritDoc} - * - * Return properties path - */ - @Override - public void init() throws ServletException { - logger.info("Initializing main webgoat servlet"); - httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyyy HH:mm:ss z", Locale.US); - httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); - propertiesPath = getServletContext().getRealPath("/WEB-INF/webgoat.properties"); - webgoatContext = new WebgoatContext(this); - URL runningStandalone = Thread.currentThread().getContextClassLoader().getResource("standalone.properties"); - if (runningStandalone == null) { - logger.info("Browse to http://localhost:8080/WebGoat and happy hacking!"); - } - } - - /** - * Description of the Method - * - * @param request Description of the Parameter - * @param message Description of the Parameter - */ - public void log(HttpServletRequest request, String message) { - String output = new Date() + " | " + request.getRemoteHost() + ":" + request.getRemoteAddr() + " | " + message; - log(output); - logger.debug(output); - } - - /* - * public List getLessons(Category category, String role) { Course course = - * mySession.getCourse(); // May need to clone the List before returning it. //return new - * ArrayList(course.getLessons(category, role)); return course.getLessons(category, role); } - */ - /** - * Description of the Method - * - * @param s Description of the Parameter - * @return Description of the Return Value - */ - protected Screen makeScreen(WebSession s) { - Screen screen = null; - int scr = s.getCurrentScreen(); - Course course = s.getCourse(); - - if (s.isUser() || s.isChallenge()) { - if (scr == WebSession.WELCOME) { - screen = new WelcomeScreen(s); - } else { - AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE); - if (lesson == null && s.isHackedAdmin()) { - // If admin was hacked, let the user see some of the - // admin screens - lesson = course.getLesson(s, scr, AbstractLesson.HACKED_ADMIN_ROLE); - } - - if (lesson != null) { - screen = lesson; - - // We need to do some bookkeeping for the hackable admin - // interface. - // This is the only place we can tell if the user - // successfully hacked the hackable - // admin and has actually accessed an admin screen. You - // need BOTH pieces of information - // in order to satisfy the remote admin lesson. - s.setHasHackableAdmin(screen.getRole()); - - lesson.handleRequest(s); - s.setCurrentMenu(lesson.getCategory().getRanking()); - } else { - screen = new ErrorScreen(s, "Invalid screen requested. Try: http://localhost/WebGoat/attack"); - } - } - } else if (s.isAdmin()) { - if (scr == WebSession.WELCOME) { - screen = new WelcomeAdminScreen(s); - } else { - // Admin can see all roles. - // FIXME: should be able to pass a list of roles. - AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.ADMIN_ROLE); - if (lesson == null) { - lesson = course.getLesson(s, scr, AbstractLesson.HACKED_ADMIN_ROLE); - } - if (lesson == null) { - lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE); - } - - if (lesson != null) { - screen = lesson; - - // We need to do some bookkeeping for the hackable admin - // interface. - // This is the only place we can tell if the user - // successfully hacked the hackable - // admin and has actually accessed an admin screen. You - // need BOTH pieces of information - // in order to satisfy the remote admin lesson. - s.setHasHackableAdmin(screen.getRole()); - - lesson.handleRequest(s); - s.setCurrentMenu(lesson.getCategory().getRanking()); - } else { - screen = new ErrorScreen(s, - "Invalid screen requested. Try Setting Admin to false or Try: http://localhost/WebGoat/attack"); - } - } - } - - return (screen); - } - - /** - * This method sets the required expiration headers in the response for a - * given RunData object. This method attempts to set all relevant headers, - * both for HTTP 1.0 and HTTP 1.1. - * - * @param response The new cacheHeaders value - * @param expiry The new cacheHeaders value - */ - protected static void setCacheHeaders(HttpServletResponse response, int expiry) { - if (expiry == 0) { - response.setHeader("Pragma", "no-cache"); - response.setHeader("Cache-Control", "no-cache"); - response.setHeader("Expires", formatHttpDate(new Date())); - } else { - Date expiryDate = new Date(System.currentTimeMillis() + expiry); - response.setHeader("Expires", formatHttpDate(expiryDate)); - } - } - - /** - * Description of the Method - * - * @param request Description of the Parameter - * @param response Description of the Parameter - * @param context Description of the Parameter - * @return Description of the Return Value - * @throws java.io.IOException if any. - */ - protected WebSession updateSession(HttpServletRequest request, HttpServletResponse response, ServletContext context) - throws IOException { - HttpSession hs; - // session should already be created by spring security - hs = request.getSession(false); - - logger.debug("HH Entering Session_id: " + hs.getId()); - // dumpSession( hs ); - // Get our session object out of the HTTP session - WebSession session = null; - Object o = hs.getAttribute(WebSession.SESSION); - - if ((o != null) && o instanceof WebSession) { - session = (WebSession) o; - hs.setAttribute(WebSession.COURSE, session.getCourse()); - } else { - // Create new custom session and save it in the HTTP session - logger.warn("HH Creating new WebSession"); - session = new WebSession(webgoatContext, context); - // Ensure splash screen shows on any restart - // rlawson - removed this since we show splash screen at login now - //hs.removeAttribute(WELCOMED); - hs.setAttribute(WebSession.SESSION, session); - // reset timeout - hs.setMaxInactiveInterval(sessionTimeoutSeconds); - } - - session.update(request, response, this.getServletName()); - // update last attack request info (cookies, parms) - // this is so the REST services can have access to them via the session - session.updateLastAttackRequestInfo(request); - - // to authenticate - logger.debug("HH Leaving Session_id: " + hs.getId()); - //dumpSession( hs ); - return (session); - } - - /** - * Description of the Method - * - * @param s Description of the Parameter - * @param screen a {@link org.owasp.webgoat.session.Screen} object. - * @param screen a {@link org.owasp.webgoat.session.Screen} object. - * @param response Description of the Parameter - * @exception IOException Description of the Exception - * @throws java.io.IOException if any. - */ - protected void writeScreen(WebSession s, Screen screen, HttpServletResponse response) throws IOException { - response.setContentType("text/html"); - - PrintWriter out = response.getWriter(); - - if (s == null) { - screen = new ErrorScreen(s, "Page to display was null"); - } - - // set the content-length of the response. - // Trying to avoid chunked-encoding. (Aspect required) - response.setContentLength(screen.getContentLength()); - response.setHeader("Content-Length", screen.getContentLength() + ""); - - screen.output(out); - out.flush(); - out.close(); + @RequestMapping(path = "/attack", method = {RequestMethod.GET, RequestMethod.POST}) + public ModelAndView attack(Authentication authentication, HttpServletRequest request, HttpServletResponse response) { + return new ModelAndView("redirect:" + "start.mvc" + course.getFirstLesson().getLink()); } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/LessonSource.java b/webgoat-container/src/main/java/org/owasp/webgoat/LessonSource.java deleted file mode 100644 index 0b03e30ba..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/LessonSource.java +++ /dev/null @@ -1,191 +0,0 @@ -package org.owasp.webgoat; - -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.owasp.webgoat.lessons.AbstractLesson; -import org.owasp.webgoat.session.Course; -import org.owasp.webgoat.session.WebSession; - -/** - * ************************************************************************************************* - * - * - * This file is part of WebGoat, an Open Web Application Security Project - * utility. For details, please see http://www.owasp.org/ - * - * Copyright (c) 2002 - 20014 Bruce Mayhew - * - * 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. - * - * 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. - * - * 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. - * - * Getting Source ============== - * - * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository - * for free software projects. - * - * @author Bruce Mayhew WebGoat - * @since October 28, 2003 - * @version $Id: $Id - */ -public class LessonSource extends HammerHead { - - /** - * - */ - private static final long serialVersionUID = 2588430536196446145L; - - /** - * Description of the Field - */ - public final static String START_SOURCE_SKIP = "START_OMIT_SOURCE"; - - /** Constant END_SOURCE_SKIP="END_OMIT_SOURCE" */ - public final static String END_SOURCE_SKIP = "END_OMIT_SOURCE"; - - /** - * {@inheritDoc} - * - * Description of the Method - * @exception IOException Description of the Exception - * @exception ServletException Description of the Exception - */ - public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - String source = null; - - try { - // System.out.println( "Entering doPost: " ); - // System.out.println( " - request " + request); - // System.out.println( " - principle: " + request.getUserPrincipal() - // ); - // setCacheHeaders(response, 0); - WebSession session = (WebSession) request.getSession(true).getAttribute(WebSession.SESSION); - // FIXME: Too much in this call. - session.update(request, response, this.getServletName()); - - boolean showSolution = session.getParser().getBooleanParameter("solution", false); - boolean showSource = session.getParser().getBooleanParameter("source", false); - if (showSolution) { - - // Get the Java solution of the lesson. - source = getSolution(session); - - int scr = session.getCurrentScreen(); - Course course = session.getCourse(); - AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE); - lesson.getLessonTracker(session).setViewedSolution(true); - - } else if (showSource) { - - // Get the Java source of the lesson. FIXME: Not needed - source = getSource(session); - - int scr = session.getCurrentScreen(); - Course course = session.getCourse(); - AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE); - lesson.getLessonTracker(session).setViewedSource(true); - } - } catch (Throwable t) { - t.printStackTrace(); - log("ERROR: " + t); - } finally { - try { - this.writeSource(source, response); - } catch (Throwable thr) { - thr.printStackTrace(); - log(request, "Could not write error screen: " + thr.getMessage()); - } - // System.out.println( "Leaving doPost: " ); - - } - } - - /** - * Description of the Method - * - * @param s Description of the Parameter - * @return Description of the Return Value - */ - protected String getSource(WebSession s) { - - String source = null; - int scr = s.getCurrentScreen(); - Course course = s.getCourse(); - - if (s.isUser() || s.isChallenge()) { - - AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE); - - if (lesson != null) { - source = lesson.getSource(s); - } - } - if (source == null) { - return "Source code is not available. Contact " - + s.getWebgoatContext().getFeedbackAddressHTML(); - } - return (source.replaceAll("(?s)" + START_SOURCE_SKIP + ".*" + END_SOURCE_SKIP, - "Code Section Deliberately Omitted")); - } - - /** - *

getSolution.

- * - * @param s a {@link org.owasp.webgoat.session.WebSession} object. - * @return a {@link java.lang.String} object. - */ - protected String getSolution(WebSession s) { - - String source = null; - int scr = s.getCurrentScreen(); - Course course = s.getCourse(); - - if (s.isUser() || s.isChallenge()) { - - AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE); - - if (lesson != null) { - source = lesson.getSolution(s); - } - } - if (source == null) { - return "Solution is not available. Contact " - + s.getWebgoatContext().getFeedbackAddressHTML(); - } - return (source); - } - - /** - * Description of the Method - * - * @param s Description of the Parameter - * @param response Description of the Parameter - * @exception IOException Description of the Exception - * @throws java.io.IOException if any. - */ - protected void writeSource(String s, HttpServletResponse response) throws IOException { - response.setContentType("text/html"); - - PrintWriter out = response.getWriter(); - - if (s == null) { - s = new String(); - } - - out.print(s); - out.close(); - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/LessonTemplateResolver.java b/webgoat-container/src/main/java/org/owasp/webgoat/LessonTemplateResolver.java new file mode 100644 index 000000000..14e983a81 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/LessonTemplateResolver.java @@ -0,0 +1,94 @@ +/** + ************************************************************************************************* + * + * + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * 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. + * + * 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. + * + * 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. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + * + * @author WebGoat + * @since October 28, 2003 + * @version $Id: $Id + */ +package org.owasp.webgoat; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.google.common.io.ByteStreams; +import lombok.SneakyThrows; +import org.springframework.core.io.ResourceLoader; +import org.thymeleaf.TemplateProcessingParameters; +import org.thymeleaf.resourceresolver.IResourceResolver; +import org.thymeleaf.templateresolver.TemplateResolver; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.util.Map; + +/** + * Dynamically resolve a lesson. In the html file this can be invoked as: + * + * + *
+ *
+ * + * Thymeleaf will invoke this resolver based on the prefix and this implementation will resolve the html in the plugins directory + */ +public class LessonTemplateResolver extends TemplateResolver { + + private final static String PREFIX = "lesson:"; + private final File pluginTargetDirectory; + private ResourceLoader resourceLoader; + private Map resources = Maps.newHashMap(); + + public LessonTemplateResolver(File pluginTargetDirectory, ResourceLoader resourceLoader) { + this.pluginTargetDirectory = pluginTargetDirectory; + this.resourceLoader = resourceLoader; + setResourceResolver(new LessonResourceResolver()); + setResolvablePatterns(Sets.newHashSet(PREFIX + "*")); + } + + @Override + protected String computeResourceName(TemplateProcessingParameters params) { + String templateName = params.getTemplateName(); + return templateName.substring(PREFIX.length()); + } + + private class LessonResourceResolver implements IResourceResolver { + + @Override + @SneakyThrows + public InputStream getResourceAsStream(TemplateProcessingParameters params, String resourceName) { + byte[] resource = resources.get(resourceName); + if (resource == null) { + resource = ByteStreams.toByteArray(resourceLoader.getResource("classpath:/html/" + resourceName + ".html").getInputStream()); + resources.put(resourceName, resource); + } + return new ByteArrayInputStream(resource); + } + + @Override + public String getName() { + return "lessonResourceResolver"; + } + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/MvcConfiguration.java b/webgoat-container/src/main/java/org/owasp/webgoat/MvcConfiguration.java new file mode 100644 index 000000000..e52cff71a --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/MvcConfiguration.java @@ -0,0 +1,160 @@ +/** + * ************************************************************************************************ + *

+ *

+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 20014 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + * + * @author WebGoat + * @version $Id: $Id + * @since October 28, 2003 + */ +package org.owasp.webgoat; + +import com.google.common.collect.Sets; +import org.owasp.webgoat.i18n.Language; +import org.owasp.webgoat.i18n.Messages; +import org.owasp.webgoat.i18n.PluginMessages; +import org.owasp.webgoat.session.Course; +import org.owasp.webgoat.session.LabelDebugger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ResourceLoader; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.i18n.SessionLocaleResolver; +import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.templateresolver.TemplateResolver; + +import java.io.File; + +/** + * Configuration for Spring MVC + */ +@Configuration +public class MvcConfiguration extends WebMvcConfigurerAdapter { + + @Autowired + @Qualifier("pluginTargetDirectory") + private File pluginTargetDirectory; + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/login").setViewName("login"); + registry.addViewController("/lesson_content").setViewName("lesson_content"); + registry.addViewController("/start.mvc").setViewName("main_new"); + registry.addViewController("/scoreboard").setViewName("scoreboard"); + //registry.addViewController("/list_users").setViewName("list_users"); + } + + + @Bean + public TemplateResolver springThymeleafTemplateResolver(ApplicationContext applicationContext) { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setPrefix("classpath:/templates/"); + resolver.setSuffix(".html"); + resolver.setOrder(1); + resolver.setCacheable(false); + resolver.setApplicationContext(applicationContext); + return resolver; + } + + @Bean + public LessonTemplateResolver lessonTemplateResolver(ResourceLoader resourceLoader) { + LessonTemplateResolver resolver = new LessonTemplateResolver(pluginTargetDirectory, resourceLoader); + resolver.setOrder(2); + resolver.setCacheable(false); + return resolver; + } + + @Bean + public AsciiDoctorTemplateResolver asciiDoctorTemplateResolver(Language language) { + AsciiDoctorTemplateResolver resolver = new AsciiDoctorTemplateResolver(language); + resolver.setCacheable(false); + resolver.setOrder(3); + return resolver; + } + + @Bean + public SpringTemplateEngine thymeleafTemplateEngine(TemplateResolver springThymeleafTemplateResolver, + LessonTemplateResolver lessonTemplateResolver, + AsciiDoctorTemplateResolver asciiDoctorTemplateResolver) { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.addDialect(new SpringSecurityDialect()); + engine.setTemplateResolvers( + Sets.newHashSet(springThymeleafTemplateResolver, lessonTemplateResolver, asciiDoctorTemplateResolver)); + return engine; + } + + /** + * This way we expose the plugins target directory as a resource within the web application. + * + * @param registry + */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/plugin_lessons/**").addResourceLocations("file:///" + pluginTargetDirectory.toString() + "/"); + registry.addResourceHandler("/images/**").addResourceLocations("classpath:/images/"); + registry.addResourceHandler("/lesson_js/**").addResourceLocations("classpath:/js/"); + registry.addResourceHandler("/lesson_css/**").addResourceLocations("classpath:/css/"); + registry.addResourceHandler("/video/**").addResourceLocations("classpath:/video/"); + super.addResourceHandlers(registry); + } + + @Bean + public PluginMessages pluginMessages(Messages messages, Language language) { + PluginMessages pluginMessages = new PluginMessages(messages, language); + pluginMessages.setBasenames("i18n/WebGoatLabels"); + return pluginMessages; + } + + @Bean + public Language language(LocaleResolver localeResolver) { + return new Language(localeResolver); + } + + @Bean + public Messages messageSource(Language language) { + Messages messages = new Messages(language); + messages.setBasename("classpath:i18n/messages"); + return messages; + } + + @Bean + public LocaleResolver localeResolver() { + SessionLocaleResolver slr = new SessionLocaleResolver(); + return slr; + } + + @Bean + public LabelDebugger labelDebugger() { + return new LabelDebugger(); + } + +} \ No newline at end of file diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/WebGoat.java b/webgoat-container/src/main/java/org/owasp/webgoat/WebGoat.java new file mode 100644 index 000000000..d78e248d7 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/WebGoat.java @@ -0,0 +1,118 @@ +/** + * ************************************************************************************************ + *

+ *

+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 20014 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + * + * @author WebGoat + * @version $Id: $Id + * @since October 28, 2003 + */ +package org.owasp.webgoat; + +import lombok.extern.slf4j.Slf4j; +import org.apache.catalina.Context; +import org.owasp.webgoat.plugins.PluginEndpointPublisher; +import org.owasp.webgoat.plugins.PluginsLoader; +import org.owasp.webgoat.session.Course; +import org.owasp.webgoat.session.UserSessionData; +import org.owasp.webgoat.session.WebSession; +import org.owasp.webgoat.session.WebgoatContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; +import org.springframework.boot.context.embedded.tomcat.TomcatContextCustomizer; +import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; +import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.web.client.RestTemplate; + +import java.io.File; +import java.util.Arrays; + +@SpringBootApplication +@Slf4j +public class WebGoat extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(WebGoat.class); + } + + public static void main(String[] args) throws Exception { + SpringApplication.run(WebGoat.class, args); + } + + @Bean(name = "pluginTargetDirectory") + public File pluginTargetDirectory(@Value("${webgoat.user.directory}") final String webgoatHome) { + return new File(webgoatHome); + } + + @Bean + @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) + public WebSession webSession(WebgoatContext webgoatContext) { + return new WebSession(webgoatContext); + } + + @Bean + @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) + public UserSessionData userSessionData() { + return new UserSessionData("test", "data"); + } + + @Bean + public PluginEndpointPublisher pluginEndpointPublisher(ApplicationContext applicationContext) { + return new PluginEndpointPublisher(applicationContext); + } + + @Bean + public Course course(PluginEndpointPublisher pluginEndpointPublisher) { + return new PluginsLoader(pluginEndpointPublisher).loadPlugins(); + } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + + @Bean + public EmbeddedServletContainerFactory servletContainer() { + TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory(); + factory.setTomcatContextCustomizers(Arrays.asList(new CustomCustomizer())); + return factory; + } + + static class CustomCustomizer implements TomcatContextCustomizer { + @Override + public void customize(Context context) { + context.setUseHttpOnly(false); + } + } + + +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/WebSecurityConfig.java b/webgoat-container/src/main/java/org/owasp/webgoat/WebSecurityConfig.java new file mode 100644 index 000000000..05f185927 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/WebSecurityConfig.java @@ -0,0 +1,95 @@ + +/** + * ************************************************************************************************ + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 20014 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ * + * @author WebGoat + * @version $Id: $Id + * @since December 12, 2015 + */ +package org.owasp.webgoat; + +import lombok.AllArgsConstructor; +import org.owasp.webgoat.users.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; +import org.springframework.security.core.userdetails.UserDetailsService; + +/** + * Security configuration for WebGoat. + */ +@Configuration +@AllArgsConstructor +@EnableWebSecurity +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + private final UserService userDetailsService; + + @Override + protected void configure(HttpSecurity http) throws Exception { + ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry security = http + .authorizeRequests() + .antMatchers("/css/**", "/images/**", "/js/**", "fonts/**", "/plugins/**", "/registration", "/register.mvc").permitAll() + .antMatchers("/servlet/AdminServlet/**").hasAnyRole("WEBGOAT_ADMIN", "SERVER_ADMIN") // + .antMatchers("/JavaSource/**").hasRole("SERVER_ADMIN") // + .anyRequest().authenticated(); + security.and() + .formLogin() + .loginPage("/login") + .defaultSuccessUrl("/welcome.mvc", true) + .usernameParameter("username") + .passwordParameter("password") + .permitAll(); + security.and() + .logout().deleteCookies("JSESSIONID").invalidateHttpSession(true); + security.and().csrf().disable(); + + http.headers().cacheControl().disable(); + http.exceptionHandling().authenticationEntryPoint(new AjaxAuthenticationEntryPoint("/login")); + } + + //// TODO: 11/18/2016 make this a little bit more configurabe last part at least + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/plugin_lessons/**", "/XXE/**"); + } + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService); //.passwordEncoder(bCryptPasswordEncoder()); + } + + @Bean + @Override + public UserDetailsService userDetailsServiceBean() throws Exception { + return userDetailsService; + } +} \ No newline at end of file diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/application/Application.java b/webgoat-container/src/main/java/org/owasp/webgoat/application/Application.java deleted file mode 100644 index 7ad64dbb5..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/application/Application.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.owasp.webgoat.application; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.ToStringBuilder; - -/** - * Singleton which is created on context startup - * - * @author rlawson - * @version $Id: $Id - */ -public class Application { - - private static final Application INSTANCE = new Application(); - - private Application() { - - } - - /** - *

getInstance.

- * - * @return a {@link org.owasp.webgoat.application.Application} object. - */ - public static final Application getInstance() { - return INSTANCE; - } - - private String version = "SNAPSHOT"; - private String build = "local"; - private String name = "WebGoat"; - - /** - *

Getter for the field version.

- * - * @return the version - */ - public String getVersion() { - return version; - } - - /** - *

Setter for the field version.

- * - * @param version the version to set - */ - public void setVersion(String version) { - if (StringUtils.isNotBlank(version)) { - this.version = version; - } - } - - /** - *

Getter for the field build.

- * - * @return the build - */ - public String getBuild() { - return build; - } - - /** - *

Setter for the field build.

- * - * @param build the build to set - */ - public void setBuild(String build) { - if (StringUtils.isNotBlank(build)) { - this.build = build; - } - } - - /** - *

Getter for the field name.

- * - * @return the name - */ - public String getName() { - return name; - } - - /** - *

Setter for the field name.

- * - * @param name the name to set - */ - public void setName(String name) { - if (StringUtils.isNotBlank(name)) { - this.name = name; - } - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return new ToStringBuilder(this). - append("name", name). - append("version", version). - append("build", build). - toString(); - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/application/WebGoatServletListener.java b/webgoat-container/src/main/java/org/owasp/webgoat/application/WebGoatServletListener.java deleted file mode 100644 index 7999387e0..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/application/WebGoatServletListener.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.owasp.webgoat.application; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Paths; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.Enumeration; -import java.util.Set; -import java.util.jar.Attributes; -import java.util.jar.Manifest; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.ServletRegistration; - -import org.owasp.webgoat.HammerHead; -import org.owasp.webgoat.lessons.LessonServletMapping; -import org.owasp.webgoat.plugins.PluginsLoader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; -import org.springframework.core.type.filter.AnnotationTypeFilter; - -/** - * Web application lifecycle listener. - * - * @author rlawson - * @version $Id: $Id - */ -public class WebGoatServletListener implements ServletContextListener { - - private static final Logger logger = LoggerFactory.getLogger(HammerHead.class); - - /** {@inheritDoc} */ - @Override - public void contextInitialized(ServletContextEvent sce) { - ServletContext context = sce.getServletContext(); - context.log("WebGoat is starting"); - setApplicationVariables(context); - context.log("Adding extra mappings for lessions"); - - loadPlugins(sce); - loadServlets(sce); - } - - private void loadServlets(ServletContextEvent sce) { - final ServletContext servletContext = sce.getServletContext(); - ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider( - false); - provider.addIncludeFilter(new AnnotationTypeFilter(LessonServletMapping.class)); - Set candidateComponents = provider.findCandidateComponents("org.owasp.webgoat"); - try { - for (BeanDefinition beanDefinition : candidateComponents) { - Class controllerClass = Class.forName(beanDefinition.getBeanClassName()); - LessonServletMapping pathAnnotation = (LessonServletMapping) controllerClass.getAnnotation(LessonServletMapping.class); - final ServletRegistration.Dynamic dynamic = servletContext.addServlet(controllerClass.getSimpleName(), controllerClass); - dynamic.addMapping(pathAnnotation.path()); - } - } catch (Exception e) { - logger.error("Error", e); - } - } - - private void loadPlugins(ServletContextEvent sce) { - String pluginPath = sce.getServletContext().getRealPath("plugin_lessons"); - String targetPath = sce.getServletContext().getRealPath("plugin_extracted"); - new PluginsLoader(Paths.get(pluginPath), Paths.get(targetPath)).loadPlugins(); - } - - /** {@inheritDoc} */ - @Override - public void contextDestroyed(ServletContextEvent sce) { - ServletContext context = sce.getServletContext(); - context.log("WebGoat is stopping"); - - // Unregister JDBC drivers in this context's ClassLoader: - // Get the webapp's ClassLoader - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - // Loop through all drivers - Enumeration drivers = DriverManager.getDrivers(); - while (drivers.hasMoreElements()) { - java.sql.Driver driver = drivers.nextElement(); - if (driver.getClass().getClassLoader() == cl) { - // This driver was registered by the webapp's ClassLoader, so deregister it: - try { - context.log("Unregister JDBC driver {}"); - DriverManager.deregisterDriver(driver); - } catch (SQLException ex) { - context.log("Error unregistering JDBC driver {}"); - } - } else { - // driver was not registered by the webapp's ClassLoader and may be in use elsewhere - context.log("Not unregistering JDBC driver {} as it does not belong to this webapp's ClassLoader"); - } - } - } - - private void setApplicationVariables(ServletContext context) { - Application app = Application.getInstance(); - try { - InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF"); - Manifest manifest = new Manifest(inputStream); - Attributes attr = manifest.getMainAttributes(); - String name = attr.getValue("Specification-Title"); - String version = attr.getValue("Specification-Version"); - String build = attr.getValue("Implementation-Version"); - app.setName(name); - app.setVersion(version); - app.setBuild(build); - } catch (IOException ioe) { - context.log("Error setting application variables", ioe); - } - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentEndpoint.java b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentEndpoint.java new file mode 100644 index 000000000..c4713a054 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentEndpoint.java @@ -0,0 +1,115 @@ +/* + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 2017 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ */ +package org.owasp.webgoat.assignments; + +import lombok.Getter; +import org.owasp.webgoat.i18n.PluginMessages; +import org.owasp.webgoat.session.UserSessionData; +import org.owasp.webgoat.users.UserTracker; +import org.owasp.webgoat.users.UserTrackerRepository; +import org.owasp.webgoat.session.WebSession; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * Each lesson can define an endpoint which can support the lesson. So for example if you create a lesson which uses JavaScript and + * needs to call out to the server to fetch data you can define an endpoint in that lesson. WebGoat will pick up this endpoint and + * Spring will publish it. + *

+ * Extend this class and implement the met + *

+ * Note: each subclass should declare this annotation otherwise the WebGoat framework cannot find your endpoint. + */ +public abstract class AssignmentEndpoint extends Endpoint { + + @Autowired + private UserTrackerRepository userTrackerRepository; + @Autowired + private WebSession webSession; + @Autowired + private UserSessionData userSessionData; + @Getter + @Autowired + private PluginMessages messages; + + //// TODO: 11/13/2016 events better fit? + protected AttackResult trackProgress(AttackResult attackResult) { + UserTracker userTracker = userTrackerRepository.findOne(webSession.getUserName()); + if (userTracker == null) { + userTracker = new UserTracker(webSession.getUserName()); + } + if (attackResult.assignmentSolved()) { + userTracker.assignmentSolved(webSession.getCurrentLesson(), this.getClass().getSimpleName()); + } else { + userTracker.assignmentFailed(webSession.getCurrentLesson()); + } + userTrackerRepository.save(userTracker); + return attackResult; + } + + protected WebSession getWebSession() { + return webSession; + } + + protected UserSessionData getUserSessionData() { + return userSessionData; + } + + @Override + public final String getPath() { + return this.getClass().getAnnotationsByType(AssignmentPath.class)[0].value(); + } + + /** + * Convenience method for create a successful result: + * + * - Assignment is set to solved + * - Feedback message is set to 'assignment.solved' + * + * Of course you can overwrite these values in a specific lesson + * + * @return a builder for creating a result from a lesson + */ + protected AttackResult.AttackResultBuilder success() { + return AttackResult.builder(messages).lessonCompleted(true).feedback("assignment.solved"); + } + + /** + * Convenience method for create a failed result: + * + * - Assignment is set to not solved + * - Feedback message is set to 'assignment.not.solved' + * + * Of course you can overwrite these values in a specific lesson + * + * @return a builder for creating a result from a lesson + */ + protected AttackResult.AttackResultBuilder failed() { + return AttackResult.builder(messages).lessonCompleted(false).feedback("assignment.not.solved"); + } + + protected AttackResult.AttackResultBuilder informationMessage() { + return AttackResult.builder(messages).lessonCompleted(false); + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentHints.java b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentHints.java new file mode 100644 index 000000000..6d29dbe6f --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentHints.java @@ -0,0 +1,16 @@ +package org.owasp.webgoat.assignments; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by nbaars on 1/14/17. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface AssignmentHints { + + String[] value() default {}; +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentPath.java b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentPath.java new file mode 100644 index 000000000..9147a1820 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentPath.java @@ -0,0 +1,16 @@ +package org.owasp.webgoat.assignments; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by nbaars on 1/14/17. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface AssignmentPath { + + String value(); +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AttackResult.java b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AttackResult.java new file mode 100644 index 000000000..e78d46338 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AttackResult.java @@ -0,0 +1,104 @@ +/* + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 2017 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ */ + +package org.owasp.webgoat.assignments; + +import lombok.Getter; +import org.apache.commons.lang3.StringEscapeUtils; +import org.owasp.webgoat.i18n.PluginMessages; + +public class AttackResult { + + public static class AttackResultBuilder { + + private boolean lessonCompleted; + private PluginMessages messages; + private Object[] feedbackArgs; + private String feedbackResourceBundleKey; + private String output; + private Object[] outputArgs; + + public AttackResultBuilder(PluginMessages messages) { + this.messages = messages; + } + + public AttackResultBuilder lessonCompleted(boolean lessonCompleted) { + this.lessonCompleted = lessonCompleted; + this.feedbackResourceBundleKey = "lesson.completed"; + return this; + } + + public AttackResultBuilder lessonCompleted(boolean lessonCompleted, String resourceBundleKey) { + this.lessonCompleted = lessonCompleted; + this.feedbackResourceBundleKey = resourceBundleKey; + return this; + } + + public AttackResultBuilder feedbackArgs(Object... args) { + this.feedbackArgs = args; + return this; + } + + public AttackResultBuilder feedback(String resourceBundleKey) { + this.feedbackResourceBundleKey = resourceBundleKey; + return this; + } + + public AttackResultBuilder output(String output) { + this.output = output; + return this; + } + + public AttackResultBuilder outputArgs(Object... args) { + this.outputArgs = args; + return this; + } + + public AttackResult build() { + return new AttackResult(lessonCompleted, messages.getMessage(feedbackResourceBundleKey, feedbackArgs), messages.getMessage(output, output, outputArgs)); + } + } + + @Getter + private boolean lessonCompleted; + @Getter + private String feedback; + @Getter + private String output; + + public AttackResult(boolean lessonCompleted, String feedback, String output) { + this.lessonCompleted = lessonCompleted; + this.feedback = StringEscapeUtils.escapeJson(feedback); + this.output = StringEscapeUtils.escapeJson(output); + } + + public static AttackResultBuilder builder(PluginMessages messages) { + return new AttackResultBuilder(messages); + } + + public boolean assignmentSolved() { + return lessonCompleted; + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/assignments/Endpoint.java b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/Endpoint.java new file mode 100644 index 000000000..746ac412d --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/Endpoint.java @@ -0,0 +1,41 @@ +/* + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 2017 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ */ + +package org.owasp.webgoat.assignments; + +import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; + +public abstract class Endpoint implements MvcEndpoint { + + @Override + public final boolean isSensitive() { + return false; + } + + @Override + public final Class getEndpointType() { + return null; + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/controller/About.java b/webgoat-container/src/main/java/org/owasp/webgoat/controller/About.java deleted file mode 100644 index 094d9285f..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/controller/About.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.owasp.webgoat.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -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.RequestParam; -import org.springframework.web.servlet.ModelAndView; - -/** - *

About class.

- * - * @author rlawson - * @version $Id: $Id - */ -@Controller -public class About { - - final Logger logger = LoggerFactory.getLogger(About.class); - private static final String WELCOMED = "welcomed"; - - /** - *

welcome.

- * - * @param request a {@link javax.servlet.http.HttpServletRequest} object. - * @param error a {@link java.lang.String} object. - * @param logout a {@link java.lang.String} object. - * @return a {@link org.springframework.web.servlet.ModelAndView} object. - */ - @RequestMapping(value = "about.mvc", method = RequestMethod.GET) - public ModelAndView welcome(HttpServletRequest request, - @RequestParam(value = "error", required = false) String error, - @RequestParam(value = "logout", required = false) String logout) { - - // set the welcome attribute - // this is so the attack servlet does not also - // send them to the welcome page - HttpSession session = request.getSession(); - if (session.getAttribute(WELCOMED) == null) { - session.setAttribute(WELCOMED, "true"); - } - - //go ahead and send them to webgoat (skip the welcome page) - ModelAndView model = new ModelAndView(); - //model.setViewName("welcome"); - //model.setViewName("main_new"); - model.setViewName("about"); - return model; - } - -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Login.java b/webgoat-container/src/main/java/org/owasp/webgoat/controller/Login.java deleted file mode 100644 index 6f9021f19..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Login.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.owasp.webgoat.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.servlet.ModelAndView; - -/** - *

Login class.

- * - * @author rlawson - * @version $Id: $Id - */ -@Controller -public class Login { - - /** - *

login.

- * - * @param error a {@link java.lang.String} object. - * @param logout a {@link java.lang.String} object. - * @return a {@link org.springframework.web.servlet.ModelAndView} object. - */ - @RequestMapping(value = "login.mvc", method = RequestMethod.GET) - public ModelAndView login( - @RequestParam(value = "error", required = false) String error, - @RequestParam(value = "logout", required = false) String logout) { - - ModelAndView model = new ModelAndView(); - if (error != null) { - model.addObject("error", "Invalid username and password!"); - } - - if (logout != null) { - model.addObject("msg", "You've been logged out successfully."); - } - model.setViewName("login"); - - return model; - - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Logout.java b/webgoat-container/src/main/java/org/owasp/webgoat/controller/Logout.java deleted file mode 100644 index 92e236a1c..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Logout.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.owasp.webgoat.controller; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -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.RequestParam; -import org.springframework.web.servlet.ModelAndView; - -/** - *

Logout class.

- * - * @author rlawson - * @version $Id: $Id - */ -@Controller -public class Logout { - - final Logger logger = LoggerFactory.getLogger(Logout.class); - - /** - *

logout.

- * - * @param error a {@link java.lang.String} object. - * @param logout a {@link java.lang.String} object. - * @return a {@link org.springframework.web.servlet.ModelAndView} object. - */ - @RequestMapping(value = "logout.mvc", method = RequestMethod.GET) - public ModelAndView logout( - @RequestParam(value = "error", required = false) String error, - @RequestParam(value = "logout", required = false) String logout) { - - logger.info("Logging user out"); - - ModelAndView model = new ModelAndView(); - if (error != null) { - model.addObject("error", "Invalid username and password!"); - } - - if (logout != null) { - model.addObject("msg", "You've been logged out successfully."); - } - model.setViewName("logout"); - - return model; - - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Start.java b/webgoat-container/src/main/java/org/owasp/webgoat/controller/Start.java deleted file mode 100644 index 300209a9d..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Start.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package org.owasp.webgoat.controller; - -import java.util.Collection; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import org.apache.commons.lang3.StringUtils; -import org.owasp.webgoat.application.Application; -import org.owasp.webgoat.session.WebSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -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.RequestParam; -import org.springframework.web.servlet.ModelAndView; - -/** - *

Start class.

- * - * @author rlawson - * @version $Id: $Id - */ -@Controller -public class Start { - - final Logger logger = LoggerFactory.getLogger(Start.class); - - private static final String WELCOMED = "welcomed"; - - @Autowired - private ServletContext servletContext; - - /** - *

start.

- * - * @param request a {@link javax.servlet.http.HttpServletRequest} object. - * @param error a {@link java.lang.String} object. - * @param logout a {@link java.lang.String} object. - * @return a {@link org.springframework.web.servlet.ModelAndView} object. - */ - @RequestMapping(value = "start.mvc", method = {RequestMethod.GET, RequestMethod.POST}) - public ModelAndView start(HttpServletRequest request, - @RequestParam(value = "error", required = false) String error, - @RequestParam(value = "logout", required = false) String logout) { - - ModelAndView model = new ModelAndView(); - // make sure session is set up correctly - // if not redirect user to login - if (checkWebSession(request.getSession()) == false) { - model.setViewName("redirect:/login.mvc"); - return model; - } - String role = getRole(); - String user = request.getUserPrincipal().getName(); - model.addObject("role", role); - model.addObject("user", user); - - String contactEmail = servletContext.getInitParameter("email"); - model.addObject("contactEmail", contactEmail); - String emailList = servletContext.getInitParameter("emaillist"); - model.addObject("emailList", emailList); - - Application app = Application.getInstance(); - logger.info("Setting application properties: " + app); - model.addObject("version", app.getVersion()); - model.addObject("build", app.getBuild()); - - // if everything ok then go to webgoat UI - model.setViewName("main_new"); - return model; - } - - private String getRole() { - Collection authorities = (Collection) SecurityContextHolder.getContext().getAuthentication().getAuthorities(); - String role = "N/A"; - for (GrantedAuthority authority : authorities) { - authority.getAuthority(); - role = authority.getAuthority(); - role = StringUtils.lowerCase(role); - role = StringUtils.remove(role, "role_"); - break; - } - return role; - } - - /** - *

checkWebSession.

- * - * @param session a {@link javax.servlet.http.HttpSession} object. - * @return a boolean. - */ - public boolean checkWebSession(HttpSession session) { - Object o = session.getAttribute(WebSession.SESSION); - if (o == null) { - logger.error("No valid WebSession object found, has session timed out? [" + session.getId() + "]"); - return false; - } - if (!(o instanceof WebSession)) { - logger.error("Invalid WebSession object found, this is probably a bug! [" + o.getClass() + " | " + session.getId() + "]"); - return false; - } - return true; - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/controller/StartLesson.java b/webgoat-container/src/main/java/org/owasp/webgoat/controller/StartLesson.java new file mode 100644 index 000000000..28d0524fb --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/controller/StartLesson.java @@ -0,0 +1,92 @@ +/** + * ************************************************************************************************ + *

+ *

+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 20014 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + * + * @author WebGoat + * @version $Id: $Id + * @since October 28, 2003 + */ +package org.owasp.webgoat.controller; + +import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.session.Course; +import org.owasp.webgoat.session.WebSession; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Optional; + + +@Controller +public class StartLesson { + + private final WebSession ws; + private final Course course; + + public StartLesson(final WebSession ws, final Course course) { + this.ws = ws; + this.course = course; + } + + /** + *

start.

+ * + * @return a {@link ModelAndView} object. + */ + @RequestMapping(path = "startlesson.mvc", method = {RequestMethod.GET, RequestMethod.POST}) + public ModelAndView start() { + ModelAndView model = new ModelAndView(); + + model.addObject("course", course); + model.addObject("lesson", ws.getCurrentLesson()); + model.setViewName("lesson_content"); + return model; + } + + @RequestMapping(value = {"*.lesson"}, produces = "text/html") + public ModelAndView lessonPage(HttpServletRequest request) { + // I will set here the thymeleaf fragment location based on the resource requested. + ModelAndView model = new ModelAndView(); + SecurityContext context = SecurityContextHolder.getContext(); //TODO this should work with the security roles of Spring + //GrantedAuthority authority = context.getAuthentication().getAuthorities().iterator().next(); + String path = request.getRequestURL().toString(); // we now got /a/b/c/AccessControlMatrix.lesson + String lessonName = path.substring(path.lastIndexOf('/') + 1, path.indexOf(".lesson")); + List lessons = course.getLessons(); + Optional lesson = lessons.stream() + .filter(l -> l.getId().equals(lessonName)) + .findFirst(); + ws.setCurrentLesson(lesson.get()); + model.setViewName("lesson_content"); + model.addObject("lesson", lesson.get()); + return model; + } + +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Welcome.java b/webgoat-container/src/main/java/org/owasp/webgoat/controller/Welcome.java index 050b0a79f..44fe432de 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/controller/Welcome.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/controller/Welcome.java @@ -1,20 +1,43 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. +/** + ************************************************************************************************* + * + * + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * 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. + * + * 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. + * + * 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. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + * + * @author WebGoat + * @since October 28, 2003 + * @version $Id: $Id */ package org.owasp.webgoat.controller; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; 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.RequestParam; import org.springframework.web.servlet.ModelAndView; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + /** *

Welcome class.

* @@ -23,22 +46,17 @@ import org.springframework.web.servlet.ModelAndView; */ @Controller public class Welcome { - - final Logger logger = LoggerFactory.getLogger(Welcome.class); + private static final String WELCOMED = "welcomed"; /** *

welcome.

* * @param request a {@link javax.servlet.http.HttpServletRequest} object. - * @param error a {@link java.lang.String} object. - * @param logout a {@link java.lang.String} object. * @return a {@link org.springframework.web.servlet.ModelAndView} object. */ - @RequestMapping(value = "welcome.mvc", method = RequestMethod.GET) - public ModelAndView welcome(HttpServletRequest request, - @RequestParam(value = "error", required = false) String error, - @RequestParam(value = "logout", required = false) String logout) { + @RequestMapping(path = {"welcome.mvc", "/"}, method = RequestMethod.GET) + public ModelAndView welcome(HttpServletRequest request) { // set the welcome attribute // this is so the attack servlet does not also diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Language.java b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Language.java new file mode 100644 index 000000000..d2fe5bd95 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Language.java @@ -0,0 +1,51 @@ +/* + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 2017 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ */ + +package org.owasp.webgoat.i18n; + +import lombok.AllArgsConstructor; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.LocaleResolver; + +import java.util.Locale; + +/** + * Wrapper around the LocaleResolver from Spring so we do not need to bother with passing the HttpRequest object + * when asking for a Locale. + * + * @author nbaars + * @date 2/7/17 + */ +@AllArgsConstructor +public class Language { + + private final LocaleResolver localeResolver; + + public Locale getLocale() { + return localeResolver.resolveLocale(((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()); + } + +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Messages.java b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Messages.java new file mode 100644 index 000000000..4f3312ddf --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Messages.java @@ -0,0 +1,59 @@ +/* + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 2017 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ */ +package org.owasp.webgoat.i18n; + +import lombok.AllArgsConstructor; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; + +import java.util.Properties; + +/** + *

ExposedReloadableResourceMessageBundleSource class.

+ * Extends the reloadable message source with a way to get all messages + * + * @author zupzup + */ +@AllArgsConstructor +public class Messages extends ReloadableResourceBundleMessageSource { + + private final Language language; + + /** + * Gets all messages for presented Locale. + * + * @return all messages + */ + public Properties getMessages() { + return getMergedProperties(language.getLocale()).getProperties(); + } + + public String getMessage(String code, Object... args) { + return getMessage(code, args, language.getLocale()); + } + + public String getMessage(String code, String defaultValue, Object... args) { + return super.getMessage(code, args, defaultValue, language.getLocale()); + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/i18n/PluginMessages.java b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/PluginMessages.java new file mode 100644 index 000000000..163909724 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/PluginMessages.java @@ -0,0 +1,80 @@ +/* + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + *

+ * Copyright (c) 2002 - 2017 Bruce Mayhew + *

+ * 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. + *

+ * 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. + *

+ * 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. + *

+ * Getting Source ============== + *

+ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software + * projects. + *

+ */ + +package org.owasp.webgoat.i18n; + +import lombok.SneakyThrows; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; + +import java.net.URL; +import java.util.Enumeration; +import java.util.Properties; + +/** + * Message resource bundle for plugins. + * + * @author nbaars + * @date 2/4/17 + */ +public class PluginMessages extends ReloadableResourceBundleMessageSource { + private static final String PROPERTIES_SUFFIX = ".properties"; + + private Language language; + + public PluginMessages(Messages messages, Language language) { + this.language = language; + this.setParentMessageSource(messages); + this.setBasename("WebGoatLabels"); + } + + @Override + @SneakyThrows + protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) { + Properties properties = new Properties(); + long lastModified = System.currentTimeMillis(); + + Enumeration resources = Thread.currentThread().getContextClassLoader().getResources(filename + PROPERTIES_SUFFIX); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + String sourcePath = resource.toURI().toString().replace(PROPERTIES_SUFFIX, ""); + PropertiesHolder holder = super.refreshProperties(sourcePath, propHolder); + properties.putAll(holder.getProperties()); + } + return new PropertiesHolder(properties, lastModified); + } + + + public Properties getMessages() { + return getMergedProperties(language.getLocale()).getProperties(); + } + + public String getMessage(String code, Object... args) { + return getMessage(code, args, language.getLocale()); + } + + public String getMessage(String code, String defaultValue, Object... args) { + return super.getMessage(code, args, defaultValue, language.getLocale()); + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java index b209a88cf..1336fa326 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java @@ -1,45 +1,15 @@ package org.owasp.webgoat.lessons; -import org.apache.ecs.Element; -import org.apache.ecs.ElementContainer; -import org.apache.ecs.StringElement; -import org.apache.ecs.html.Body; -import org.apache.ecs.html.Form; -import org.apache.ecs.html.Head; -import org.apache.ecs.html.Html; -import org.apache.ecs.html.IMG; -import org.apache.ecs.html.PRE; -import org.apache.ecs.html.Title; -import org.owasp.webgoat.session.ParameterNotFoundException; +import com.google.common.collect.Lists; +import lombok.Setter; import org.owasp.webgoat.session.Screen; -import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.session.WebgoatContext; -import org.owasp.webgoat.session.WebgoatProperties; -import org.owasp.webgoat.util.BeanProvider; -import org.owasp.webgoat.util.LabelManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.LinkedList; import java.util.List; -import java.util.Map; - -import static java.lang.Math.abs; /** * ************************************************************************************************ *

+ *

* This file is part of WebGoat, an Open Web Application Security Project utility. For details, * please see http://www.owasp.org/ *

@@ -68,66 +38,30 @@ import static java.lang.Math.abs; */ public abstract class AbstractLesson extends Screen implements Comparable { - private static final Logger logger = LoggerFactory.getLogger(AbstractLesson.class); - - /** - * Description of the Field - */ - public final static String ADMIN_ROLE = "admin"; - - /** - * Constant CHALLENGE_ROLE="challenge" - */ - public final static String CHALLENGE_ROLE = "challenge"; - - /** - * Description of the Field - */ - public final static String HACKED_ADMIN_ROLE = "hacked_admin"; - - /** - * Description of the Field - */ - public final static String USER_ROLE = "user"; - private static int count = 1; private Integer id = null; - final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next").setBorder(0).setHspace(0).setVspace(0); - - final static IMG previousGrey = new IMG("images/left14.gif").setAlt("Previous").setBorder(0).setHspace(0) - .setVspace(0); - private Integer ranking; - private Category category; + @Setter + private List assignments; - private boolean hidden; - - private String sourceFileName; - - private Map lessonPlanFileName = new HashMap(); - - private String lessonSolutionFileName; - - private WebgoatContext webgoatContext; - - private LinkedList availableLanguages = new LinkedList(); - - private String defaultLanguage = "en"; - - private LabelManager labelManager = null; + public List getAssignments() { + if (assignments == null) { + return Lists.newArrayList(); + } + return assignments; + } /** * Constructor for the Lesson object */ public AbstractLesson() { - //based on the class name derive an id so the screenId is fixed, should not give clashes based on - //the fact we use the classname and the size is limited - id = abs(this.getClass().getSimpleName().hashCode()); + id = new Integer(++count); } + /** *

getName.

* @@ -147,46 +81,6 @@ public abstract class AbstractLesson extends Screen implements ComparableSetter for the field hidden.

- * - * @param hidden a boolean. - */ - public void setHidden(boolean hidden) { - this.hidden = hidden; - } - - /** - *

update.

- * - * @param properties a {@link org.owasp.webgoat.session.WebgoatProperties} object. - */ - public void update(WebgoatProperties properties) { - String className = getClass().getName(); - className = className.substring(className.lastIndexOf(".") + 1); - setRanking(new Integer(properties.getIntProperty("lesson." + className + ".ranking", getDefaultRanking() - .intValue()))); - String categoryRankingKey = "category." + getDefaultCategory().getName() + ".ranking"; - // System.out.println("Category ranking key: " + categoryRankingKey); - Category tempCategory = Category.getCategory(getDefaultCategory().getName()); - tempCategory.setRanking(new Integer(properties.getIntProperty(categoryRankingKey, getDefaultCategory() - .getRanking().intValue()))); - category = tempCategory; - setHidden(properties.getBooleanProperty("lesson." + className + ".hidden", getDefaultHidden())); - // System.out.println(className + " in " + tempCategory.getName() + " - // (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking: - // " + getRanking() + ", hidden:" + hidden +")"); - } - - /** - *

isCompleted.

- * - * @param s a {@link org.owasp.webgoat.session.WebSession} object. - * @return a boolean. - */ - public boolean isCompleted(WebSession s) { - return getLessonTracker(s, this).getCompleted(); - } /** * {@inheritDoc} @@ -212,7 +106,7 @@ public abstract class AbstractLesson extends Screen implements ComparablegetSubmitMethod

- * - * @return a {@link java.lang.String} object. - */ - public abstract String getSubmitMethod(); - - - /** - * Gets the fileMethod attribute of the Lesson class - * - * @param reader Description of the Parameter - * @param methodName Description of the Parameter - * @param numbers Description of the Parameter - * @return The fileMethod value - */ - public static String getFileMethod(BufferedReader reader, String methodName, boolean numbers) { - int count = 0; - StringBuffer sb = new StringBuffer(); - boolean echo = false; - boolean startCount = false; - int parenCount = 0; - - try { - String line; - - while ((line = reader.readLine()) != null) { - if ((line.indexOf(methodName) != -1) - && ((line.indexOf("public") != -1) || (line.indexOf("protected") != -1) || (line - .indexOf("private") != -1))) { - echo = true; - startCount = true; - } - - if (echo && startCount) { - if (numbers) { - sb.append(pad(++count) + " "); - } - - sb.append(line + "\n"); - } - - if (echo && (line.indexOf("{") != -1)) { - parenCount++; - } - - if (echo && (line.indexOf("}") != -1)) { - parenCount--; - - if (parenCount == 0) { - startCount = false; - echo = false; - } - } - } - - reader.close(); - } catch (Exception e) { - System.out.println(e); - e.printStackTrace(); - } - - return (sb.toString()); - } - - /** - * Reads text from a file into an ElementContainer. Each line in the file is - * represented in the ElementContainer by a StringElement. Each - * StringElement is appended with a new-line character. - * - * @param reader Description of the Parameter - * @param numbers Description of the Parameter - * @return Description of the Return Value - */ - public static String readFromFile(BufferedReader reader, boolean numbers) { - return (getFileText(reader, numbers)); - } - - /** - * Gets the fileText attribute of the Screen class - * - * @param reader Description of the Parameter - * @param numbers Description of the Parameter - * @return The fileText value - */ - public static String getFileText(BufferedReader reader, boolean numbers) { - int count = 0; - StringBuffer sb = new StringBuffer(); - - try { - String line; - - while ((line = reader.readLine()) != null) { - if (numbers) { - sb.append(pad(++count) + " "); - } - sb.append(line + System.getProperty("line.separator")); - } - - reader.close(); - } catch (Exception e) { - System.out.println(e); - e.printStackTrace(); - } - - return (sb.toString()); - } - - /** - * Will this screen be included in an enterprise edition. - * - * @return The ranking value - */ - public boolean isEnterprise() { - return false; - } - /** * Gets the hintCount attribute of the Lesson object * - * @param s The user's WebSession * @return The hintCount value */ - public int getHintCount(WebSession s) { - return getHints(s).size(); + public int getHintCount() { + return getHints().size(); } /** *

getHints.

* - * @param s a {@link org.owasp.webgoat.session.WebSession} object. * @return a {@link java.util.List} object. */ - protected abstract List getHints(WebSession s); - - // @TODO we need to restrict access at the service layer - // rather than passing session object around - - /** - *

getHintsPublic.

- * - * @param s a {@link org.owasp.webgoat.session.WebSession} object. - * @return a {@link java.util.List} object. - */ - public List getHintsPublic(WebSession s) { - List hints = getHints(s); - return hints; - } - - /** - * Fill in a minor hint that will help people who basically get it, but are - * stuck on somthing silly. - * - * @param s The users WebSession - * @param hintNumber a int. - * @return The hint1 value - */ - public String getHint(WebSession s, int hintNumber) { - return "Hint: " + getHints(s).get(hintNumber); - } - - /** - * Gets the instructions attribute of the AbstractLesson object - * - * @param s a {@link org.owasp.webgoat.session.WebSession} object. - * @return The instructions value - */ - public abstract String getInstructions(WebSession s); - - /** - * Gets the lessonPlan attribute of the Lesson object - * - * @return The lessonPlan value - */ - public String getLessonName() { - return this.getClass().getSimpleName(); - } + public abstract List getHints(); /** * Gets the title attribute of the HelloScreen object @@ -421,36 +153,6 @@ public abstract class AbstractLesson extends Screen implements Comparable