diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 000000000..c32394f14 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.5"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 717934671..9c96caffb 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1 +1,2 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.2.1/apache-maven-3.2.1-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar diff --git a/CREATE_RELEASE.MD b/CREATE_RELEASE.MD index b9250f807..b49c71b42 100644 --- a/CREATE_RELEASE.MD +++ b/CREATE_RELEASE.MD @@ -15,6 +15,10 @@ git flow release start mvn versions:set < git commit -am "New release, updating pom.xml" git flow release publish + +<> + +git flow release finish git push origin develop git push origin master git push --tags diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 000000000..573d2b4eb --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,19 @@ +This file is part of WebGoat, an Open Web Application Security Project utility. For details, please see http://www.owasp.org/ + +Copyright (c) 2002 - 2019 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. \ No newline at end of file diff --git a/README.MD b/README.MD index 099d49aef..654454fd3 100644 --- a/README.MD +++ b/README.MD @@ -97,27 +97,10 @@ To change IP address add the following variable to WebGoat/webgoat-container/src server.address=x.x.x.x ``` -# Vagrant - -We supply a complete environment using Vagrant, to run WebGoat with Vagrant you must first have Vagrant and Virtualbox installed. - -```shell - $ cd WebGoat/webgoat-images/vagrant-training - $ vagrant up -``` - -Once the provisioning is complete login to the Virtualbox with username vagrant and password vagrant. -WebGoat and WebWolf will automatically start when you login to this image. - - # Building a new Docker image NOTE: Travis will create a new Docker image automatically when making a new release. -WebGoat now has Docker support for x86 and ARM (raspberry pi). -### Docker on x86 -On x86 you can build a container with the following commands: - ```Shell cd WebGoat/ mvn install @@ -128,31 +111,6 @@ docker login docker push webgoat/webgoat-8.0 ``` -### 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 -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 -``` - -When you have done this you can build the Docker container using the following commands: - -```Shell -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 -``` - # Run Instructions: Once installed connect to http://localhost:8080/WebGoat and http://localhost:9090/WebWolf diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100755 index 000000000..8ba0622f5 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,259 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 000000000..6ce36f4e1 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/docker-compose-postgres.yml b/docker-compose-postgres.yml index 2ff77f0b5..3306c87a1 100644 --- a/docker-compose-postgres.yml +++ b/docker-compose-postgres.yml @@ -7,7 +7,7 @@ services: environment: - WEBWOLF_HOST=webwolf - WEBWOLF_PORT=9090 - - spring.datasource.url=jdbc:postgresql://webgoat_db:5432/webgoat + - spring.datasource.url=jdbc:postgresql://webgoat_db:5432/webgoat?user=webgoat&password=webgoat - spring.datasource.username=webgoat - spring.datasource.password=webgoat - spring.datasource.driver-class-name=org.postgresql.Driver @@ -19,7 +19,7 @@ services: webwolf: image: webgoat/webwolf environment: - - spring.datasource.url=jdbc:postgresql://webgoat_db:5432/webgoat + - spring.datasource.url=jdbc:postgresql://webgoat_db:5432/webgoat?user=webgoat&password=webgoat - spring.datasource.username=webgoat - spring.datasource.password=webgoat - spring.datasource.driver-class-name=org.postgresql.Driver diff --git a/mvnw b/mvnw index 5551fde8e..d2f0ea380 100755 --- a/mvnw +++ b/mvnw @@ -114,7 +114,6 @@ if $mingw ; then M2_HOME="`(cd "$M2_HOME"; pwd)`" [ -n "$JAVA_HOME" ] && JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? fi if [ -z "$JAVA_HOME" ]; then @@ -212,7 +211,11 @@ else if [ "$MVNW_VERBOSE" = true ]; then echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." fi - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + fi while IFS="=" read key value; do case "$key" in (wrapperUrl) jarUrl="$value"; break ;; esac @@ -221,22 +224,38 @@ else echo "Downloading from: $jarUrl" fi wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi if command -v wget > /dev/null; then if [ "$MVNW_VERBOSE" = true ]; then echo "Found wget ... using wget" fi - wget "$jarUrl" -O "$wrapperJarPath" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi elif command -v curl > /dev/null; then if [ "$MVNW_VERBOSE" = true ]; then echo "Found curl ... using curl" fi - curl -o "$wrapperJarPath" "$jarUrl" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + else if [ "$MVNW_VERBOSE" = true ]; then echo "Falling back to using Java to download" fi javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi if [ -e "$javaClass" ]; then if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then if [ "$MVNW_VERBOSE" = true ]; then @@ -277,6 +296,11 @@ if $cygwin; then MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` fi +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain exec "$JAVACMD" \ diff --git a/mvnw.cmd b/mvnw.cmd index e5cfb0ae9..b26ab24f0 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -37,7 +37,7 @@ @echo off @REM set title of command window title %0 -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% @REM set %HOME% to equivalent of $HOME @@ -120,23 +120,44 @@ SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" -FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B ) @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central @REM This allows using the maven wrapper in projects that prohibit checking in binary data. if exist %WRAPPER_JAR% ( - echo Found %WRAPPER_JAR% + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) ) else ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" - echo Finished downloading %WRAPPER_JAR% + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) ) @REM End of extension +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* if ERRORLEVEL 1 goto error goto end diff --git a/pom.xml b/pom.xml index 9e4fa1f03..83a87aecb 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.owasp.webgoat webgoat-parent pom - v8.0.0.M25 + v8.0.0.M26 WebGoat Parent Pom Parent Pom for the WebGoat Project. A deliberately insecure Web Application @@ -21,7 +21,7 @@ org.springframework.boot spring-boot-starter-parent - 1.5.18.RELEASE + 2.2.0.RELEASE @@ -51,6 +51,11 @@ Jason White jason.white@owasp.org + + zubcevic + René Zubcevic + rene.zubcevic@owasp.org + jwayman Jeff Wayman @@ -110,53 +115,27 @@ UTF-8 UTF-8 + 11 + 11 build 1.1.1 - 1.4 - 1.4 - 1.4 - 1.4 - 1.9.1 - 2.7 3.2.1 - 2.1 - 0.5 - 1.3.1 - 2.6 3.4 - 4.0.0 - 2.2.5 - 2.2.4 + 2.6 18.0 - 1.4.190 2.3.4 - 1.3.1 - 2.6.3 - 2.6.3 - 6.0 - 1.3 - 1.7.12 - 1.3.1 4.12 1.18.4 - 1.5.4 3.8.0 2.22.0 - 1.6 - 2.6 - 2.10.4 - 2.5.2 - 3.0.1 - 2.22.0 - 1.6.6 - 2.11.7 - 2.1.20 - 2.48.2 - 3.2.4.RELEASE + 3.1.2 + 3.1.1 + 3.1.0 + 2.22.2 @@ -164,34 +143,9 @@ webgoat-lessons webgoat-server webwolf + webgoat-integration-tests - - - ossrh - https://oss.sonatype.org/content/repositories/snapshots - - - ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - - - apache.snapshots - http://repository.apache.org/snapshots/ - - - daily - - - daily - - - - org.projectlombok @@ -226,37 +180,37 @@ org.apache.maven.plugins - maven-release-plugin - ${maven-release-plugin.version} + maven-checkstyle-plugin + 3.1.0 - true - false - release - @{project.version} - deploy - - - - org.eluder.coveralls - coveralls-maven-plugin - ${coveralls-maven-plugin.version} - - - - - - org.codehaus.mojo - cobertura-maven-plugin - ${cobertura-maven-plugin.version} - - - xml - 256m - - true + UTF-8 + true + true + config/checkstyle/checkstyle.xml + config/checkstyle/suppressions.xml + checkstyle.suppressions.file + + + central + https://repo.maven.apache.org/maven2 + + false + + + + + + central + https://repo.maven.apache.org/maven2 + + false + + + + diff --git a/webgoat-container/pom.xml b/webgoat-container/pom.xml index a07fc905e..4dd76271a 100644 --- a/webgoat-container/pom.xml +++ b/webgoat-container/pom.xml @@ -10,32 +10,9 @@ org.owasp.webgoat webgoat-parent - v8.0.0.M25 + v8.0.0.M26 - - - performance - - - - io.gatling - gatling-maven-plugin - ${gatling-plugin.version} - - - - execute - - - - - - - - - - @@ -69,7 +46,11 @@ maven-surefire-plugin ${maven-surefire-plugin.version} - never + 0 + true + + --illegal-access=permit + @@ -89,44 +70,52 @@ - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 + org.springframework.boot + spring-boot-starter-undertow org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + javax.activation + activation + ${activation.version} org.springframework.boot spring-boot-starter-actuator + + org.flywaydb + flyway-core + org.asciidoctor asciidoctorj - 1.5.4 + 1.5.8.1 org.springframework.boot spring-boot-starter-data-jpa + + + HikariCP + com.zaxxer + + org.apache.commons commons-lang3 ${commons-lang3.version} - - com.google.guava - guava - ${guava.version} - - - - - io.gatling.highcharts - gatling-charts-highcharts - ${gatling.version} - test - org.springframework.boot spring-boot-starter-security @@ -137,31 +126,13 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 - 2.1.2.RELEASE - - - javax.activation - activation - ${activation.version} + thymeleaf-extras-springsecurity5 org.hsqldb hsqldb ${hsqldb.version} - - javax.transaction - javax.transaction-api - ${javax.transaction-api.version} - - - org.scala-lang - scala-compiler - ${scala.version} - test - - diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/AjaxAuthenticationEntryPoint.java b/webgoat-container/src/main/java/org/owasp/webgoat/AjaxAuthenticationEntryPoint.java index f1af53ddc..ebd43fbf6 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/AjaxAuthenticationEntryPoint.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/AjaxAuthenticationEntryPoint.java @@ -49,7 +49,7 @@ public class AjaxAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoi } public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { - if(request.getHeader("x-requested-with") != null) { + if (request.getHeader("x-requested-with") != null) { response.sendError(401, authException.getMessage()); } else { super.commence(request, response, authException); diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/AsciiDoctorTemplateResolver.java b/webgoat-container/src/main/java/org/owasp/webgoat/AsciiDoctorTemplateResolver.java index df4c11e0b..cef65d29f 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/AsciiDoctorTemplateResolver.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/AsciiDoctorTemplateResolver.java @@ -28,25 +28,27 @@ * @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.asciidoctor.extension.JavaExtensionRegistry; -import org.owasp.webgoat.asciidoc.WebGoatVersionMacro; -import org.owasp.webgoat.asciidoc.WebWolfMacro; -import org.owasp.webgoat.asciidoc.WebWolfRootMacro; +import org.owasp.webgoat.asciidoc.*; import org.owasp.webgoat.i18n.Language; -import org.thymeleaf.TemplateProcessingParameters; -import org.thymeleaf.resourceresolver.IResourceResolver; -import org.thymeleaf.templateresolver.TemplateResolver; +import org.thymeleaf.IEngineConfiguration; +import org.thymeleaf.templateresolver.FileTemplateResolver; +import org.thymeleaf.templateresource.ITemplateResource; +import org.thymeleaf.templateresource.StringTemplateResource; -import java.io.*; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.HashMap; import java.util.Map; +import java.util.Set; -import static org.apache.commons.lang3.CharEncoding.UTF_8; import static org.asciidoctor.Asciidoctor.Factory.create; /** @@ -57,7 +59,7 @@ import static org.asciidoctor.Asciidoctor.Factory.create; * */ @Slf4j -public class AsciiDoctorTemplateResolver extends TemplateResolver { +public class AsciiDoctorTemplateResolver extends FileTemplateResolver { private static final Asciidoctor asciidoctor = create(); private static final String PREFIX = "doc:"; @@ -65,72 +67,58 @@ public class AsciiDoctorTemplateResolver extends TemplateResolver { public AsciiDoctorTemplateResolver(Language language) { this.language = language; - - setResourceResolver(new AdocResourceResolver()); - setResolvablePatterns(Sets.newHashSet(PREFIX + "*")); + setResolvablePatterns(Set.of(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(); - JavaExtensionRegistry extensionRegistry = asciidoctor.javaExtensionRegistry(); - extensionRegistry.inlineMacro("webWolfLink", WebWolfMacro.class); - extensionRegistry.inlineMacro("webWolfRootLink", WebWolfRootMacro.class); - extensionRegistry.inlineMacro("webGoatVersion", WebGoatVersionMacro.class); - - 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())); + protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, String resourceName, String characterEncoding, Map templateResolutionAttributes) { + var templateName = resourceName.substring(PREFIX.length()); + try (InputStream is = readInputStreamOrFallbackToEnglish(templateName, language)) { if (is == null) { - is = Thread.currentThread().getContextClassLoader().getResourceAsStream(computeResourceName(resourceName, "en")); + log.warn("Resource name: {} not found, did you add the adoc file?", templateName); + return new StringTemplateResource(""); + } else { + JavaExtensionRegistry extensionRegistry = asciidoctor.javaExtensionRegistry(); + extensionRegistry.inlineMacro("webWolfLink", WebWolfMacro.class); + extensionRegistry.inlineMacro("webWolfRootLink", WebWolfRootMacro.class); + extensionRegistry.inlineMacro("webGoatVersion", WebGoatVersionMacro.class); + extensionRegistry.inlineMacro("webGoatTempDir", WebGoatTmpDirMacro.class); + extensionRegistry.inlineMacro("operatingSystem", OperatingSystemMacro.class); + + StringWriter writer = new StringWriter(); + asciidoctor.convert(new InputStreamReader(is), writer, createAttributes()); + return new StringTemplateResource(writer.getBuffer().toString()); } - 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"; + } catch (IOException e) { + //no html yet + return new StringTemplateResource(""); } } + /** + * 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 = new HashMap<>(); + attributes.put("source-highlighter", "coderay"); + attributes.put("backend", "xhtml"); + + Map options = new HashMap<>(); + options.put("attributes", attributes); + + return options; + } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/DatabaseInitialization.java b/webgoat-container/src/main/java/org/owasp/webgoat/DatabaseInitialization.java new file mode 100644 index 000000000..4ed32e4e6 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/DatabaseInitialization.java @@ -0,0 +1,50 @@ +package org.owasp.webgoat; + +import org.flywaydb.core.Flyway; +import org.owasp.webgoat.service.RestartLessonService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; + +import javax.sql.DataSource; +import java.util.Map; + +/** + * Define 2 Flyway instances, 1 for WebGoat itself which it uses for internal storage like users and 1 for lesson + * specific tables we use. This way we clean the data in the lesson database quite easily see {@link RestartLessonService#restartLesson()} + * for how we clean the lesson related tables. + */ +@Configuration +public class DatabaseInitialization { + + private final DataSource dataSource; + private String driverClassName; + + public DatabaseInitialization(DataSource dataSource, + @Value("${spring.datasource.driver-class-name}") String driverClassName) { + this.dataSource = dataSource; + this.driverClassName = driverClassName; + } + + @Bean(initMethod = "migrate") + public Flyway flyWayContainer() { + return Flyway + .configure() + .configuration(Map.of("driver", driverClassName)) + .dataSource(dataSource) + .schemas("container") + .locations("db/container") + .load(); + } + + @Bean(initMethod = "migrate") + @DependsOn("flyWayContainer") + public Flyway flywayLessons() { + return Flyway + .configure() + .configuration(Map.of("driver", driverClassName)) + .dataSource(dataSource) + .load(); + } +} \ No newline at end of file diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/LessonTemplateResolver.java b/webgoat-container/src/main/java/org/owasp/webgoat/LessonTemplateResolver.java index 14e983a81..2fe020d56 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/LessonTemplateResolver.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/LessonTemplateResolver.java @@ -1,48 +1,47 @@ /** - ************************************************************************************************* - * - * + * ************************************************************************************************ + *

+ *

* 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 + * @since October 28, 2003 */ + 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 org.thymeleaf.IEngineConfiguration; +import org.thymeleaf.templateresolver.FileTemplateResolver; +import org.thymeleaf.templateresource.ITemplateResource; +import org.thymeleaf.templateresource.StringTemplateResource; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; import java.util.Map; +import java.util.Set; /** * Dynamically resolve a lesson. In the html file this can be invoked as: @@ -53,42 +52,29 @@ import java.util.Map; * * 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 { +public class LessonTemplateResolver extends FileTemplateResolver { - private final static String PREFIX = "lesson:"; - private final File pluginTargetDirectory; + private static final String PREFIX = "lesson:"; private ResourceLoader resourceLoader; - private Map resources = Maps.newHashMap(); + private Map resources = new HashMap<>(); - public LessonTemplateResolver(File pluginTargetDirectory, ResourceLoader resourceLoader) { - this.pluginTargetDirectory = pluginTargetDirectory; + public LessonTemplateResolver(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; - setResourceResolver(new LessonResourceResolver()); - setResolvablePatterns(Sets.newHashSet(PREFIX + "*")); + setResolvablePatterns(Set.of(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); + protected ITemplateResource computeTemplateResource(IEngineConfiguration configuration, String ownerTemplate, String template, String resourceName, String characterEncoding, Map templateResolutionAttributes) { + var templateName = resourceName.substring(PREFIX.length());; + byte[] resource = resources.get(templateName); + if (resource == null) { + try { + resource = resourceLoader.getResource("classpath:/html/" + templateName + ".html").getInputStream().readAllBytes(); + } catch (IOException e) { + e.printStackTrace(); } - return new ByteArrayInputStream(resource); - } - - @Override - public String getName() { - return "lessonResourceResolver"; + resources.put(resourceName, resource); } + return new StringTemplateResource(new String(resource, StandardCharsets.UTF_8)); } -} +} \ No newline at end of file diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/MvcConfiguration.java b/webgoat-container/src/main/java/org/owasp/webgoat/MvcConfiguration.java index fd2bf0333..ea39e3f0b 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/MvcConfiguration.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/MvcConfiguration.java @@ -28,40 +28,40 @@ * @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.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.ViewResolver; 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.config.annotation.WebMvcConfigurer; 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 org.thymeleaf.TemplateEngine; +import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect; +import org.thymeleaf.spring5.SpringTemplateEngine; +import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +import org.thymeleaf.spring5.view.ThymeleafViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ITemplateResolver; -import java.io.File; +import java.util.Set; /** * Configuration for Spring MVC */ @Configuration -public class MvcConfiguration extends WebMvcConfigurerAdapter { - - @Autowired - @Qualifier("pluginTargetDirectory") - private File pluginTargetDirectory; +public class MvcConfiguration implements WebMvcConfigurer { + + private static final String UTF8 = "UTF-8"; @Override public void addViewControllers(ViewControllerRegistry registry) { @@ -72,23 +72,33 @@ public class MvcConfiguration extends WebMvcConfigurerAdapter { //registry.addViewController("/list_users").setViewName("list_users"); } + @Bean + public ViewResolver viewResolver(SpringTemplateEngine thymeleafTemplateEngine) { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(thymeleafTemplateEngine); + resolver.setCharacterEncoding("UTF-8"); + return resolver; + } @Bean - public TemplateResolver springThymeleafTemplateResolver(ApplicationContext applicationContext) { + public ITemplateResolver springThymeleafTemplateResolver(ApplicationContext applicationContext) { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setPrefix("classpath:/templates/"); resolver.setSuffix(".html"); - resolver.setOrder(1); + resolver.setTemplateMode(TemplateMode.HTML); + resolver.setOrder(2); resolver.setCacheable(false); + resolver.setCharacterEncoding(UTF8); resolver.setApplicationContext(applicationContext); return resolver; } @Bean public LessonTemplateResolver lessonTemplateResolver(ResourceLoader resourceLoader) { - LessonTemplateResolver resolver = new LessonTemplateResolver(pluginTargetDirectory, resourceLoader); - resolver.setOrder(2); + LessonTemplateResolver resolver = new LessonTemplateResolver(resourceLoader); + resolver.setOrder(0); resolver.setCacheable(false); + resolver.setCharacterEncoding(UTF8); return resolver; } @@ -96,34 +106,29 @@ public class MvcConfiguration extends WebMvcConfigurerAdapter { public AsciiDoctorTemplateResolver asciiDoctorTemplateResolver(Language language) { AsciiDoctorTemplateResolver resolver = new AsciiDoctorTemplateResolver(language); resolver.setCacheable(false); - resolver.setOrder(3); + resolver.setOrder(1); + resolver.setCharacterEncoding(UTF8); return resolver; } @Bean - public SpringTemplateEngine thymeleafTemplateEngine(TemplateResolver springThymeleafTemplateResolver, + public SpringTemplateEngine thymeleafTemplateEngine(ITemplateResolver springThymeleafTemplateResolver, LessonTemplateResolver lessonTemplateResolver, AsciiDoctorTemplateResolver asciiDoctorTemplateResolver) { SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setEnableSpringELCompiler(true); engine.addDialect(new SpringSecurityDialect()); engine.setTemplateResolvers( - Sets.newHashSet(springThymeleafTemplateResolver, lessonTemplateResolver, asciiDoctorTemplateResolver)); + Set.of(lessonTemplateResolver, asciiDoctorTemplateResolver, springThymeleafTemplateResolver)); 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 diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/WebGoat.java b/webgoat-container/src/main/java/org/owasp/webgoat/WebGoat.java index d78e248d7..7b77b6dee 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/WebGoat.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/WebGoat.java @@ -28,45 +28,22 @@ * @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.Configuration; 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); - } +@Configuration +public class WebGoat { @Bean(name = "pluginTargetDirectory") public File pluginTargetDirectory(@Value("${webgoat.user.directory}") final String webgoatHome) { @@ -75,8 +52,8 @@ public class WebGoat extends SpringBootServletInitializer { @Bean @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) - public WebSession webSession(WebgoatContext webgoatContext) { - return new WebSession(webgoatContext); + public WebSession webSession() { + return new WebSession(); } @Bean @@ -85,34 +62,8 @@ public class WebGoat extends SpringBootServletInitializer { 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 index 05f185927..79a1b075b 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/WebSecurityConfig.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/WebSecurityConfig.java @@ -1,4 +1,3 @@ - /** * ************************************************************************************************ * This file is part of WebGoat, an Open Web Application Security Project utility. For details, @@ -28,6 +27,7 @@ * @version $Id: $Id * @since December 12, 2015 */ + package org.owasp.webgoat; import lombok.AllArgsConstructor; @@ -35,13 +35,14 @@ 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.authentication.AuthenticationManager; 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; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; /** * Security configuration for WebGoat. @@ -58,8 +59,6 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 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() @@ -76,12 +75,6 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 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()); @@ -92,4 +85,16 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public UserDetailsService userDetailsServiceBean() throws Exception { return userDetailsService; } + + @Override + @Bean + protected AuthenticationManager authenticationManager() throws Exception { + return super.authenticationManager(); + } + + @SuppressWarnings("deprecation") + @Bean + public NoOpPasswordEncoder passwordEncoder() { + return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance(); + } } \ No newline at end of file diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/OperatingSystemMacro.java b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/OperatingSystemMacro.java new file mode 100644 index 000000000..d965c2454 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/OperatingSystemMacro.java @@ -0,0 +1,18 @@ +package org.owasp.webgoat.asciidoc; + +import java.util.Map; + +import org.asciidoctor.ast.AbstractBlock; +import org.asciidoctor.extension.InlineMacroProcessor; + +public class OperatingSystemMacro extends InlineMacroProcessor { + + public OperatingSystemMacro(String macroName, Map config) { + super(macroName, config); + } + + @Override + public String process(AbstractBlock parent, String target, Map attributes) { + return System.getProperty("os.name"); + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebGoatTmpDirMacro.java b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebGoatTmpDirMacro.java new file mode 100644 index 000000000..845815d9f --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebGoatTmpDirMacro.java @@ -0,0 +1,17 @@ +package org.owasp.webgoat.asciidoc; + +import org.asciidoctor.ast.AbstractBlock; +import org.asciidoctor.extension.InlineMacroProcessor; +import java.util.Map; + +public class WebGoatTmpDirMacro extends InlineMacroProcessor { + + public WebGoatTmpDirMacro(String macroName, Map config) { + super(macroName, config); + } + + @Override + public String process(AbstractBlock parent, String target, Map attributes) { + return EnvironmentExposure.getEnv().getProperty("webgoat.server.directory"); + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebGoatVersionMacro.java b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebGoatVersionMacro.java index f33d06063..b736f4afe 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebGoatVersionMacro.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebGoatVersionMacro.java @@ -2,12 +2,6 @@ package org.owasp.webgoat.asciidoc; import org.asciidoctor.ast.AbstractBlock; import org.asciidoctor.extension.InlineMacroProcessor; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; import java.util.Map; public class WebGoatVersionMacro extends InlineMacroProcessor { @@ -17,7 +11,7 @@ public class WebGoatVersionMacro extends InlineMacroProcessor { } @Override - protected String process(AbstractBlock parent, String target, Map attributes) { + public String process(AbstractBlock parent, String target, Map attributes) { return EnvironmentExposure.getEnv().getProperty("webgoat.build.version"); } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebWolfMacro.java b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebWolfMacro.java index 2d655ce58..82ea258f4 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebWolfMacro.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/asciidoc/WebWolfMacro.java @@ -23,7 +23,7 @@ public class WebWolfMacro extends InlineMacroProcessor { } @Override - protected String process(AbstractBlock parent, String target, Map attributes) { + public String process(AbstractBlock parent, String target, Map attributes) { Environment env = EnvironmentExposure.getEnv(); String hostname = determineHost(env.getProperty("webwolf.host"), env.getProperty("webwolf.port")); 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 index 3b02b6129..1d1cbbb65 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentEndpoint.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentEndpoint.java @@ -22,38 +22,29 @@ * 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.session.WebSession; 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 { +public abstract class AssignmentEndpoint { @Autowired private UserTrackerRepository userTrackerRepository; @Autowired - private WebSession webSession; + 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.findByUser(webSession.getUserName()); if (userTracker == null) { @@ -67,26 +58,21 @@ public abstract class AssignmentEndpoint extends Endpoint { userTrackerRepository.save(userTracker); return attackResult; } - - protected WebSession getWebSession() { - return webSession; - } - protected UserSessionData getUserSessionData() { - return userSessionData; + protected WebSession getWebSession() { + return webSession; } - @Override - public final String getPath() { - return this.getClass().getAnnotationsByType(AssignmentPath.class)[0].value(); + protected UserSessionData getUserSessionData() { + return userSessionData; } /** * 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 @@ -97,10 +83,10 @@ public abstract class AssignmentEndpoint extends Endpoint { /** * 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 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 index 9147a1820..bb7f31a69 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentPath.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/assignments/AssignmentPath.java @@ -1,5 +1,7 @@ package org.owasp.webgoat.assignments; +import org.springframework.web.bind.annotation.RequestMethod; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -12,5 +14,9 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) public @interface AssignmentPath { - String value(); + String[] path() default {}; + + RequestMethod[] method() default {}; + + String value() default ""; } 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 index 28d0524fb..69e63c578 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/controller/StartLesson.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/controller/StartLesson.java @@ -28,9 +28,10 @@ * @version $Id: $Id * @since October 28, 2003 */ + package org.owasp.webgoat.controller; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.session.Course; import org.owasp.webgoat.session.WebSession; import org.springframework.security.core.context.SecurityContext; @@ -79,8 +80,8 @@ public class StartLesson { //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() + List lessons = course.getLessons(); + Optional lesson = lessons.stream() .filter(l -> l.getId().equals(lessonName)) .findFirst(); ws.setCurrentLesson(lesson.get()); 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 44fe432de..af80e2c82 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 @@ -28,6 +28,7 @@ * @since October 28, 2003 * @version $Id: $Id */ + package org.owasp.webgoat.controller; import org.springframework.stereotype.Controller; 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 index 4f3312ddf..e7758c43c 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Messages.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/Messages.java @@ -22,6 +22,7 @@ * projects. *

*/ + package org.owasp.webgoat.i18n; import lombok.AllArgsConstructor; 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 index 163909724..a2a046bf3 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/i18n/PluginMessages.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/i18n/PluginMessages.java @@ -25,9 +25,10 @@ package org.owasp.webgoat.i18n; -import lombok.SneakyThrows; import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import java.io.IOException; +import java.net.URISyntaxException; import java.net.URL; import java.util.Enumeration; import java.util.Properties; @@ -50,18 +51,23 @@ public class PluginMessages extends ReloadableResourceBundleMessageSource { } @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()); + Enumeration resources = null; + try { + resources = Thread.currentThread().getContextClassLoader().getResources(filename + PROPERTIES_SUFFIX); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + String sourcePath = resource.toURI().toString().replace(PROPERTIES_SUFFIX, ""); + PropertiesHolder holder = super.refreshProperties(sourcePath, propHolder); + properties.putAll(holder.getProperties()); + } + } catch (IOException | URISyntaxException e) { + logger.error("Unable to read plugin message", e); } + return new PropertiesHolder(properties, lastModified); } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Assignment.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Assignment.java index d9b1f3470..f4e8aaa31 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Assignment.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Assignment.java @@ -1,9 +1,9 @@ package org.owasp.webgoat.lessons; -import com.google.common.collect.Lists; import lombok.*; import javax.persistence.*; +import java.util.ArrayList; import java.util.List; /** @@ -45,6 +45,7 @@ public class Assignment { private Long id; private String name; private String path; + @Transient private List hints; @@ -52,13 +53,27 @@ public class Assignment { //Hibernate } - public Assignment(String name, String path) { - this(name, path, Lists.newArrayList()); + public Assignment(String name) { + this(name, name, new ArrayList<>()); } public Assignment(String name, String path, List hints) { + if (path.equals("") || path.equals("/") || path.equals("/WebGoat/")) { + throw new IllegalStateException("The path of assignment '" + name + "' overrides WebGoat endpoints, please choose a path within the scope of the lesson"); + } this.name = name; this.path = path; this.hints = hints; } + + /** + * Set path is here to overwrite stored paths. + * Since a stored path can no longer be used in a lesson while + * the lesson (name) itself is still part of the lesson. + * + * @param pathName the path + */ + public void setPath(String pathName) { + this.path = pathName; + } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Category.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Category.java index bdef4d39e..eaa4e3be7 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Category.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Category.java @@ -36,31 +36,40 @@ import lombok.Getter; */ public enum Category { - INTRODUCTION("Introduction", new Integer(5)), - GENERAL("General", new Integer(100)), - INJECTION("Injection Flaws", new Integer(200)), - AUTHENTICATION("Authentication Flaws", new Integer(300)), - XSS("Cross-Site Scripting (XSS)", new Integer(400)), - REQ_FORGERIES("Request Forgeries", new Integer(450)), - ACCESS_CONTROL("Access Control Flaws", new Integer(500)), - INSECURE_CONFIGURATION("Insecure Configuration", new Integer(600)), - INSECURE_COMMUNICATION("Insecure Communication", new Integer(700)), - INSECURE_STORAGE("Insecure Storage", new Integer(800)), - INSECURE_DESERIALIZATION("Insecure Deserialization", new Integer(850)), - REQUEST_FORGERIES("Request Forgeries", new Integer(900)), - VULNERABLE_COMPONENTS("Vulnerable Components - A9", new Integer(950)), - AJAX_SECURITY("AJAX Security", new Integer(1000)), - BUFFER_OVERFLOW("Buffer Overflows", new Integer(1100)), - CODE_QUALITY("Code Quality", new Integer(1200)), - CONCURRENCY("Concurrency", new Integer(1300)), - ERROR_HANDLING("Improper Error Handling", new Integer(1400)), - DOS("Denial of Service", new Integer(1500)), - MALICIOUS_EXECUTION("Malicious Execution", new Integer(1600)), - CLIENT_SIDE("Client side", new Integer(1700)), - SESSION_MANAGEMENT("Session Management Flaws", new Integer(1800)), - WEB_SERVICES("Web Services", new Integer(1900)), - ADMIN_FUNCTIONS("Admin Functions", new Integer(2000)), - CHALLENGE("Challenges", new Integer(3000)); + INTRODUCTION("Introduction", 5), + GENERAL("General", 100), + + INJECTION("(A1) Injection", 300), + AUTHENTICATION("(A2) Broken Authentication", 302), + INSECURE_COMMUNICATION("(A3) Sensitive Data Exposure", 303), + XXE("(A4) XML External Entities (XXE)", 304), + ACCESS_CONTROL("(A5) Broken Access Control", 305), + + XSS("(A7) Cross-Site Scripting (XSS)", 307), + INSECURE_DESERIALIZATION("(A8) Insecure Deserialization", 308), + VULNERABLE_COMPONENTS("(A9) Vulnerable Components", 309), + + REQUEST_FORGERIES("(A8:2013) Request Forgeries", 318), + + + REQ_FORGERIES("Request Forgeries", 450), + + INSECURE_CONFIGURATION("Insecure Configuration", 600), + INSECURE_STORAGE("Insecure Storage", 800), + + + AJAX_SECURITY("AJAX Security", 1000), + BUFFER_OVERFLOW("Buffer Overflows", 1100), + CODE_QUALITY("Code Quality", 1200), + CONCURRENCY("Concurrency", 1300), + ERROR_HANDLING("Improper Error Handling", 1400), + DOS("Denial of Service", 1500), + MALICIOUS_EXECUTION("Malicious Execution", 1600), + CLIENT_SIDE("Client side", 1700), + SESSION_MANAGEMENT("Session Management Flaws", 1800), + WEB_SERVICES("Web Services", 1900), + ADMIN_FUNCTIONS("Admin Functions", 2000), + CHALLENGE("Challenges", 3000); @Getter private String name; diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Hint.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Hint.java index 2f3363d9b..6b45b4d1d 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Hint.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Hint.java @@ -24,10 +24,10 @@ * projects. * */ + package org.owasp.webgoat.lessons; -import lombok.Getter; -import lombok.Setter; +import lombok.Value; /** *

Hint class.

@@ -35,12 +35,9 @@ import lombok.Setter; * @author rlawson * @version $Id: $Id */ -@Getter -@Setter +@Value public class Hint { private String hint; - private String lesson; private String assignmentPath; - private int number; } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Lesson.java similarity index 55% rename from webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java rename to webgoat-container/src/main/java/org/owasp/webgoat/lessons/Lesson.java index 1336fa326..80828deb8 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/Lesson.java @@ -1,64 +1,46 @@ -package org.owasp.webgoat.lessons; - -import com.google.common.collect.Lists; -import lombok.Setter; -import org.owasp.webgoat.session.Screen; - -import java.util.List; - -/** - * ************************************************************************************************ - *

- *

- * 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 file is part of WebGoat, an Open Web Application Security Project utility. For details, please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 2019 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 - * @version $Id: $Id - * @since October 28, 2003 + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software projects. */ -public abstract class AbstractLesson extends Screen implements Comparable { + +package org.owasp.webgoat.lessons; + +import lombok.Getter; +import lombok.Setter; +import lombok.Singular; + +import java.util.List; + +@Getter +@Setter +public abstract class Lesson { private static int count = 1; - private Integer id = null; - - private Integer ranking; - - @Setter private List assignments; - public List getAssignments() { - if (assignments == null) { - return Lists.newArrayList(); - } - return assignments; - } - /** * Constructor for the Lesson object */ - public AbstractLesson() { - id = new Integer(++count); + public Lesson() { + id = ++count; } @@ -72,34 +54,6 @@ public abstract class AbstractLesson extends Screen implements ComparableSetter for the field ranking.

- * - * @param ranking a {@link java.lang.Integer} object. - */ - public void setRanking(Integer ranking) { - this.ranking = ranking; - } - - - /** - * {@inheritDoc} - *

- * Description of the Method - */ - public int compareTo(Object obj) { - return this.getRanking().compareTo(((AbstractLesson) obj).getRanking()); - } - - /** - * {@inheritDoc} - *

- * Description of the Method - */ - public boolean equals(Object obj) { - return this.getScreenId() == ((AbstractLesson) obj).getScreenId(); - } - /** * Gets the category attribute of the Lesson object * @@ -109,13 +63,6 @@ public abstract class AbstractLesson extends Screen implements ComparablegetDefaultRanking.

- * - * @return a {@link java.lang.Integer} object. - */ - protected abstract Integer getDefaultRanking(); - /** *

getDefaultCategory.

* @@ -123,29 +70,6 @@ public abstract class AbstractLesson extends Screen implements ComparablegetDefaultHidden.

- * - * @return a boolean. - */ - protected abstract boolean getDefaultHidden(); - - /** - * Gets the hintCount attribute of the Lesson object - * - * @return The hintCount value - */ - public int getHintCount() { - return getHints().size(); - } - - /** - *

getHints.

- * - * @return a {@link java.util.List} object. - */ - public abstract List getHints(); - /** * Gets the title attribute of the HelloScreen object * @@ -153,28 +77,6 @@ public abstract class AbstractLesson extends Screen implements ComparableReturns the default "path" portion of a lesson's URL.

*

@@ -218,5 +120,4 @@ public abstract class AbstractLesson extends Screen implements ComparableWebGoat - * @since October 28, 2003 - * @version $Id: $Id - */ -package org.owasp.webgoat.lessons; - -//// TODO: 11/8/2016 remove -public abstract class LessonAdapter extends AbstractLesson { - - - /** - *

getDefaultHidden.

- * - * @return a boolean. - */ - protected boolean getDefaultHidden() { - return false; - } - - /** - * Initiates lesson restart functionality. Lessons should override this for - * lesson specific actions - */ - public void restartLesson() { - // Do Nothing - called when restart lesson is pressed. Each lesson can do something - } - - private final static Integer DEFAULT_RANKING = new Integer(1000); - - /** - *

getDefaultRanking.

- * - * @return a {@link java.lang.Integer} object. - */ - protected Integer getDefaultRanking() { - return DEFAULT_RANKING; - } - - /** - * provide a default submitMethod of lesson does not implement - * - * @return a {@link java.lang.String} object. - */ - public String getSubmitMethod() { - return "GET"; - } - - /** - * Fill in a descriptive title for this lesson. The title of the lesson. - * This will appear above the control area at the top of the page. This - * field will be rendered as html. - * - * @return The title value - */ - public String getTitle() { - return "Untitled Lesson " + getScreenId(); - } - - -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/LessonMenuItem.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/LessonMenuItem.java index 41c45a682..8aca79fcc 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/LessonMenuItem.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/LessonMenuItem.java @@ -1,32 +1,32 @@ /** * ************************************************************************************************* - * - * + *

+ *

* 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. - * */ + package org.owasp.webgoat.lessons; import java.util.ArrayList; @@ -46,8 +46,6 @@ public class LessonMenuItem { private boolean complete; private String link; private int ranking; -// private boolean showSource = true; -// private boolean showHints = true; /** *

Getter for the field name.

@@ -112,7 +110,6 @@ public class LessonMenuItem { children.add(child); } - /** {@inheritDoc} */ @Override public String toString() { StringBuilder bldr = new StringBuilder(); diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/RequestParameter.java b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/RequestParameter.java index 5d2716920..81c548fdf 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/lessons/RequestParameter.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/lessons/RequestParameter.java @@ -27,6 +27,7 @@ * for free software projects. * */ + package org.owasp.webgoat.lessons; /** @@ -69,7 +70,6 @@ public class RequestParameter implements Comparable { return value; } - /** {@inheritDoc} */ @Override public int compareTo(RequestParameter o) { return this.name.compareTo(o.getName()); diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/plugins/CourseConfiguration.java b/webgoat-container/src/main/java/org/owasp/webgoat/plugins/CourseConfiguration.java new file mode 100644 index 000000000..cb7269c04 --- /dev/null +++ b/webgoat-container/src/main/java/org/owasp/webgoat/plugins/CourseConfiguration.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 - 2019 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.plugins; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; +import org.owasp.webgoat.assignments.AssignmentEndpoint; +import org.owasp.webgoat.assignments.AssignmentHints; +import org.owasp.webgoat.assignments.AttackResult; +import org.owasp.webgoat.lessons.Lesson; +import org.owasp.webgoat.lessons.Assignment; +import org.owasp.webgoat.session.Course; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import java.lang.reflect.Method; +import java.util.*; + +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.toList; + +@Slf4j +@Configuration +public class CourseConfiguration { + + private final List lessons; + private final List assignments; + private final Map> assignmentsByPackage; + + public CourseConfiguration(List lessons, List assignments) { + this.lessons = lessons; + this.assignments = assignments; + assignmentsByPackage = this.assignments.stream().collect(groupingBy(a -> a.getClass().getPackageName())); + } + + @Bean + public Course course() { + lessons.stream().forEach(l -> l.setAssignments(createAssignment(l))); + return new Course(lessons); + } + + private List createAssignment(Lesson lesson) { + var endpoints = assignmentsByPackage.get(lesson.getClass().getPackageName()); + if (CollectionUtils.isEmpty(endpoints)) { + log.warn("Lesson: {} has no endpoints, is this intentionally?", lesson.getTitle()); + return new ArrayList(); + } + return endpoints.stream().map(e -> new Assignment(e.getClass().getSimpleName(), getPath(e.getClass()), getHints(e.getClass()))).collect(toList()); + } + + private String getPath(Class e) { + for (Method m : e.getMethods()) { + if (m.getReturnType() == AttackResult.class) { + var mapping = getMapping(m); + if (mapping == null) { + log.error("AttackResult method found without mapping in: {}", e.getSimpleName()); + } else { + return mapping; + } + } + } + return "none"; + } + + private String getMapping(Method m) { + String[] paths = null; + //Find the path, either it is @GetMapping("/attack") of GetMapping(path = "/attack") both are valid, we need to consider both + if (m.getAnnotation(RequestMapping.class) != null) { + paths = ArrayUtils.addAll(m.getAnnotation(RequestMapping.class).value(), m.getAnnotation(RequestMapping.class).path()); + } else if (m.getAnnotation(PostMapping.class) != null) { + paths = ArrayUtils.addAll(m.getAnnotation(PostMapping.class).value(), m.getAnnotation(PostMapping.class).path()); + } else if (m.getAnnotation(GetMapping.class) != null) { + paths = ArrayUtils.addAll(m.getAnnotation(GetMapping.class).value(), m.getAnnotation(GetMapping.class).path()); + } else if (m.getAnnotation(PutMapping.class) != null) { + paths = ArrayUtils.addAll(m.getAnnotation(PutMapping.class).value(), m.getAnnotation(PutMapping.class).path()); + } + if (paths == null) { + return ""; + } else { + return Arrays.stream(paths).filter(path -> !"".equals(path)).findFirst().orElseGet(() -> ""); + } + } + + private List getHints(Class e) { + if (e.isAnnotationPresent(AssignmentHints.class)) { + return List.of(e.getAnnotationsByType(AssignmentHints.class)[0].value()); + } + return Collections.emptyList(); + } +} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginEndpointPublisher.java b/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginEndpointPublisher.java deleted file mode 100644 index d3a2a333e..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginEndpointPublisher.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.owasp.webgoat.plugins; - -import lombok.extern.slf4j.Slf4j; -import org.owasp.webgoat.assignments.Endpoint; -import org.springframework.beans.factory.annotation.Autowire; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.AbstractApplicationContext; - -import java.util.List; - -/** - * ************************************************************************************************ - * 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 nbaars - * @version $Id: $Id - * @since October 16, 2016 - */ -@Slf4j -public class PluginEndpointPublisher { - - private AbstractApplicationContext applicationContext; - - public PluginEndpointPublisher(ApplicationContext applicationContext) { - this.applicationContext = (AbstractApplicationContext) applicationContext; - } - - public void publish(List> endpoints) { - endpoints.forEach(e -> publishEndpoint(e)); - } - - private void publishEndpoint(Class e) { - try { - BeanDefinition beanDefinition = new RootBeanDefinition(e, Autowire.BY_TYPE.value(), true); - DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getBeanFactory(); - beanFactory.registerBeanDefinition(beanDefinition.getBeanClassName(), beanDefinition); - } catch (Exception ex) { - log.error("Failed to register " + e.getSimpleName() + " as endpoint with Spring, skipping..."); - } - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginResource.java b/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginResource.java deleted file mode 100644 index 172b7b965..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginResource.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.owasp.webgoat.plugins; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import org.owasp.webgoat.assignments.AssignmentEndpoint; -import org.owasp.webgoat.assignments.Endpoint; -import org.owasp.webgoat.lessons.NewLesson; - -import java.net.URL; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Plugin resource - * - * @author nbaars - * @since 3/4/17. - */ -@AllArgsConstructor -@Getter -public class PluginResource { - - private final URL location; - private final List classes; - - public List getLessons() { - return classes.stream().filter(c -> c.getSuperclass() == NewLesson.class).collect(Collectors.toList()); - } - - public List> getEndpoints() { - return classes.stream(). - filter(c -> c.getSuperclass() == AssignmentEndpoint.class || c.getSuperclass() == Endpoint.class). - map(c -> (Class) c). - collect(Collectors.toList()); - } - - public List> getAssignments(Class lesson) { - return classes.stream(). - filter(c -> c.getSuperclass() == AssignmentEndpoint.class). - filter(c -> c.getPackage().equals(lesson.getPackage())). - map(c -> (Class) c). - collect(Collectors.toList()); - } - - -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginsLoader.java b/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginsLoader.java deleted file mode 100644 index 28437e786..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginsLoader.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.owasp.webgoat.plugins; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import lombok.AllArgsConstructor; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.owasp.webgoat.assignments.AssignmentEndpoint; -import org.owasp.webgoat.assignments.AssignmentHints; -import org.owasp.webgoat.assignments.AssignmentPath; -import org.owasp.webgoat.lessons.AbstractLesson; -import org.owasp.webgoat.lessons.Assignment; -import org.owasp.webgoat.lessons.NewLesson; -import org.owasp.webgoat.session.Course; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; -import org.springframework.core.type.filter.RegexPatternTypeFilter; - -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import static java.util.stream.Collectors.toList; - -/** - * ************************************************************************************************ - * 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 nbaars - * @version $Id: $Id - * @since November 25, 2016 - */ -@AllArgsConstructor -@Slf4j -public class PluginsLoader { - - private final PluginEndpointPublisher pluginEndpointPublisher; - - /** - *

createLessonsFromPlugins.

- */ - public Course loadPlugins() { - List lessons = Lists.newArrayList(); - for (PluginResource plugin : findPluginResources()) { - try { - plugin.getLessons().forEach(c -> { - NewLesson lesson = null; - try { - lesson = (NewLesson) c.newInstance(); - log.trace("Lesson loaded: {}", lesson.getId()); - } catch (Exception e) { - log.error("Error while loading:" + c, e); - } - List> assignments = plugin.getAssignments(c); - lesson.setAssignments(createAssignment(assignments)); - lessons.add(lesson); - pluginEndpointPublisher.publish(plugin.getEndpoints()); - }); - } catch (Exception e) { - log.error("Error in loadLessons: ", e); - } - } - if (lessons.isEmpty()) { - log.error("No lessons found if you downloaded an official release of WebGoat please take the time to"); - log.error("create a new issue at https://github.com/WebGoat/WebGoat/issues/new"); - log.error("For developers run 'mvn package' first from the root directory."); - } - return new Course(lessons); - } - - private List createAssignment(List> endpoints) { - return endpoints.stream().map(e -> new Assignment(e.getSimpleName(), getPath(e), getHints(e))).collect(toList()); - } - - private String getPath(Class e) { - return e.getAnnotationsByType(AssignmentPath.class)[0].value(); - } - - private List getHints(Class e) { - if (e.isAnnotationPresent(AssignmentHints.class)) { - return Lists.newArrayList(e.getAnnotationsByType(AssignmentHints.class)[0].value()); - } - return Lists.newArrayList(); - } - - - - @SneakyThrows - public List findPluginResources() { - final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false); - provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*"))); - final Set classes = provider.findCandidateComponents("org.owasp.webgoat.plugin"); - Map> pluginClasses = Maps.newHashMap(); - for (BeanDefinition bean : classes) { - Class clazz = Class.forName(bean.getBeanClassName()); - URL location = clazz.getProtectionDomain().getCodeSource().getLocation(); - List classFiles = pluginClasses.get(location); - if (classFiles == null) { - classFiles = Lists.newArrayList(clazz); - } else { - classFiles.add(clazz); - } - pluginClasses.put(location, classFiles); - } - return pluginClasses.entrySet().parallelStream() - .map(e -> new PluginResource(e.getKey(), e.getValue())) - .collect(Collectors.toList()); - } - -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/CookieService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/CookieService.java deleted file mode 100644 index fd9f55ae0..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/CookieService.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * ************************************************************************************************* - * - * - * 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. - * - */ -package org.owasp.webgoat.service; - -import com.google.common.collect.Lists; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpSession; -import java.util.List; - -/** - *

CookieService class.

- * - * @author rlawson - * @version $Id: $Id - */ -@Controller -public class CookieService { - - /** - * Returns cookies for last attack - * - * @param session a {@link javax.servlet.http.HttpSession} object. - * @return a {@link java.util.List} object. - */ - @RequestMapping(path = "/service/cookie.mvc", produces = "application/json") - public @ResponseBody - List showCookies() { - //// TODO: 11/6/2016 to be decided - List cookies = Lists.newArrayList(); - return cookies; - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/HintService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/HintService.java index f6d290aed..43dd88c57 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/HintService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/HintService.java @@ -3,12 +3,12 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ + package org.owasp.webgoat.service; -import com.google.common.collect.Lists; -import org.owasp.webgoat.lessons.AbstractLesson; import org.owasp.webgoat.lessons.Assignment; import org.owasp.webgoat.lessons.Hint; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.session.WebSession; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @@ -41,42 +41,22 @@ public class HintService { */ @GetMapping(path = URL_HINTS_MVC, produces = "application/json") @ResponseBody - public List showHint() { - AbstractLesson l = webSession.getCurrentLesson(); - List hints = createLessonHints(l); - hints.addAll(createAssignmentHints(l)); - return hints; - + public List getHints() { + Lesson l = webSession.getCurrentLesson(); + return createAssignmentHints(l); } - private List createLessonHints(AbstractLesson l) { - if ( l != null ) { - return l.getHints().stream().map(h -> createHint(h, l.getName(), null)).collect(toList()); + private List createAssignmentHints(Lesson l) { + if (l != null) { + return l.getAssignments().stream() + .map(a -> createHint(a)) + .flatMap(hints -> hints.stream()) + .collect(toList()); } - return Lists.newArrayList(); + return List.of(); } - private List createAssignmentHints(AbstractLesson l) { - List hints = Lists.newArrayList(); - if ( l != null) { - List assignments = l.getAssignments(); - assignments.stream().forEach(a -> { a.getHints(); createHints(a, hints);}); - } - return hints; - } - - private void createHints(Assignment a, List hints) { - hints.addAll(a.getHints().stream().map(h -> createHint(h, null, a.getPath())).collect(toList())); - } - - private Hint createHint(String hintText, String lesson, String assignmentName) { - Hint hint = new Hint(); - hint.setHint(hintText); - if (lesson != null) { - hint.setLesson(lesson); - } else { - hint.setAssignmentPath(assignmentName); - } - return hint; + private List createHint(Assignment a) { + return a.getHints().stream().map(h -> new Hint(h, a.getPath())).collect(toList()); } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelDebugService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelDebugService.java index b32832a88..d009e889c 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelDebugService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelDebugService.java @@ -1,32 +1,32 @@ /** * ************************************************************************************************* - * - * + *

+ *

* 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. - * */ + package org.owasp.webgoat.service; import lombok.AllArgsConstructor; @@ -73,20 +73,20 @@ public class LabelDebugService { return new ResponseEntity<>(result, HttpStatus.OK); } - /** - * Sets the enabled flag on the label debugger to the given parameter - * @param enabled {@link org.owasp.webgoat.session.LabelDebugger} object - * @throws Exception unhandled exception - * @return a {@link org.springframework.http.ResponseEntity} object. - */ - @RequestMapping(value = URL_DEBUG_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE, params = KEY_ENABLED) - public @ResponseBody - ResponseEntity> setDebuggingStatus(@RequestParam("enabled") Boolean enabled) throws Exception { - log.debug("Setting label debugging to {} ", labelDebugger.isEnabled()); - Map result = createResponse(enabled); - labelDebugger.setEnabled(enabled); - return new ResponseEntity<>(result, HttpStatus.OK); - } + /** + * Sets the enabled flag on the label debugger to the given parameter + * @param enabled {@link org.owasp.webgoat.session.LabelDebugger} object + * @throws Exception unhandled exception + * @return a {@link org.springframework.http.ResponseEntity} object. + */ + @RequestMapping(value = URL_DEBUG_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE, params = KEY_ENABLED) + public @ResponseBody + ResponseEntity> setDebuggingStatus(@RequestParam("enabled") Boolean enabled) throws Exception { + log.debug("Setting label debugging to {} ", labelDebugger.isEnabled()); + Map result = createResponse(enabled); + labelDebugger.setEnabled(enabled); + return new ResponseEntity<>(result, HttpStatus.OK); + } /** * @param enabled {@link org.owasp.webgoat.session.LabelDebugger} object diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelService.java index e42904b6a..c2b72957c 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/LabelService.java @@ -26,6 +26,7 @@ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository * for free software projects. */ + package org.owasp.webgoat.service; import lombok.AllArgsConstructor; @@ -67,21 +68,20 @@ public class LabelService { * We use Springs session locale resolver which also gives us the option to change the local later on. For * now it uses the accept-language from the HttpRequest. If this language is not found it will default back * to messages.properties. - * + *

* Note although it is possible to use Spring language interceptor we for now opt for this solution, the UI * will always need to fetch the labels with the new language set by the user. So we don't need to intercept each * and every request to see if the language param has been set in the request. * * @param lang the language to fetch labels for (optional) * @return a map of labels - * @throws Exception */ @GetMapping(path = URL_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody - public ResponseEntity fetchLabels(@RequestParam(value = "lang", required = false) String lang, HttpServletRequest request) { + public ResponseEntity fetchLabels(@RequestParam(value = "lang", required = false) String lang) { if (!StringUtils.isEmpty(lang)) { Locale locale = Locale.forLanguageTag(lang); - ((SessionLocaleResolver)localeResolver).setDefaultLocale(locale); + ((SessionLocaleResolver) localeResolver).setDefaultLocale(locale); log.debug("Language provided: {} leads to Locale: {}", lang, locale); } Properties allProperties = new Properties(); diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonInfoService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonInfoService.java index 927868f3e..9396e0225 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonInfoService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonInfoService.java @@ -1,7 +1,7 @@ package org.owasp.webgoat.service; import lombok.AllArgsConstructor; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.lessons.LessonInfoModel; import org.owasp.webgoat.session.WebSession; import org.springframework.web.bind.annotation.RequestMapping; @@ -29,7 +29,7 @@ public class LessonInfoService { @RequestMapping(path = "/service/lessoninfo.mvc", produces = "application/json") public @ResponseBody LessonInfoModel getLessonInfo() { - AbstractLesson lesson = webSession.getCurrentLesson(); + Lesson lesson = webSession.getCurrentLesson(); return new LessonInfoModel(lesson.getTitle(), false, false, false); } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonMenuService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonMenuService.java index 25b1e617e..d3e9cf7b1 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonMenuService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonMenuService.java @@ -26,10 +26,12 @@ * Source for this application is maintained at * https://github.com/WebGoat/WebGoat, a repository for free software projects. */ + package org.owasp.webgoat.service; import lombok.AllArgsConstructor; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; +import org.owasp.webgoat.lessons.Assignment; import org.owasp.webgoat.lessons.Category; import org.owasp.webgoat.lessons.LessonMenuItem; import org.owasp.webgoat.lessons.LessonMenuItemType; @@ -43,9 +45,9 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; -import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; /** @@ -81,16 +83,16 @@ public class LessonMenuService { categoryItem.setName(category.getName()); categoryItem.setType(LessonMenuItemType.CATEGORY); // check for any lessons for this category - List lessons = course.getLessons(category); + List lessons = course.getLessons(category); lessons = lessons.stream().sorted(Comparator.comparing(l -> l.getTitle())).collect(Collectors.toList()); - for (AbstractLesson lesson : lessons) { + for (Lesson lesson : lessons) { LessonMenuItem lessonItem = new LessonMenuItem(); lessonItem.setName(lesson.getTitle()); lessonItem.setLink(lesson.getLink()); - lessonItem.setRanking(lesson.getRanking()); lessonItem.setType(LessonMenuItemType.LESSON); LessonTracker lessonTracker = userTracker.getLessonTracker(lesson); - lessonItem.setComplete(lessonTracker.isLessonSolved()); + boolean lessonSolved = lessonCompleted(lessonTracker.getLessonOverview(), lesson); + lessonItem.setComplete(lessonSolved); categoryItem.addChild(lessonItem); } categoryItem.getChildren().sort((o1, o2) -> o1.getRanking() - o2.getRanking()); @@ -99,4 +101,19 @@ public class LessonMenuService { return menu; } + + private boolean lessonCompleted(Map map, Lesson currentLesson) { + boolean result = true; + for (Map.Entry entry : map.entrySet()) { + Assignment storedAssignment = entry.getKey(); + for (Assignment lessonAssignment: currentLesson.getAssignments()) { + if (lessonAssignment.getName().equals(storedAssignment.getName())) { + result = result && entry.getValue(); + break; + } + } + + } + return result; + } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonPlanService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonPlanService.java index c28a7bd83..976f583e4 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonPlanService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonPlanService.java @@ -27,6 +27,7 @@ * for free software projects. * */ + package org.owasp.webgoat.service; import org.owasp.webgoat.session.WebSession; diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonProgressService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonProgressService.java index 76e6187a5..17b9ae156 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonProgressService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonProgressService.java @@ -1,10 +1,8 @@ package org.owasp.webgoat.service; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import lombok.AllArgsConstructor; import lombok.Getter; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.lessons.Assignment; import org.owasp.webgoat.lessons.LessonInfoModel; import org.owasp.webgoat.session.WebSession; @@ -16,6 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -40,14 +39,14 @@ public class LessonProgressService { @RequestMapping(value = "/service/lessonprogress.mvc", produces = "application/json") @ResponseBody public Map getLessonInfo() { - Map json = Maps.newHashMap(); + Map json = new HashMap(); UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName()); if (webSession.getCurrentLesson() != null) { LessonTracker lessonTracker = userTracker.getLessonTracker(webSession.getCurrentLesson()); String successMessage = ""; boolean lessonCompleted = false; if (lessonTracker != null) { - lessonCompleted = lessonTracker.isLessonSolved(); + lessonCompleted = isLessonComplete(lessonTracker.getLessonOverview(), webSession.getCurrentLesson()); successMessage = "LessonCompleted"; //@todo we still use this?? } json.put("lessonCompleted", lessonCompleted); @@ -66,23 +65,53 @@ public class LessonProgressService { @ResponseBody public List lessonOverview() { UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName()); - AbstractLesson currentLesson = webSession.getCurrentLesson(); - List result = Lists.newArrayList(); - if ( currentLesson != null ) { + Lesson currentLesson = webSession.getCurrentLesson(); + List result = new ArrayList<>(); + if (currentLesson != null) { LessonTracker lessonTracker = userTracker.getLessonTracker(currentLesson); - result = toJson(lessonTracker.getLessonOverview()); + result = toJson(lessonTracker.getLessonOverview(), currentLesson); } return result; } - private List toJson(Map map) { - ArrayList result = Lists.newArrayList(); + private List toJson(Map map, Lesson currentLesson) { + List result = new ArrayList(); for (Map.Entry entry : map.entrySet()) { - result.add(new LessonOverview(entry.getKey(), entry.getValue())); + Assignment storedAssignment = entry.getKey(); + for (Assignment lessonAssignment : currentLesson.getAssignments()) { + if (lessonAssignment.getName().equals(storedAssignment.getName()) + && !lessonAssignment.getPath().equals(storedAssignment.getPath())) { + //here a stored path in the assignments table will be corrected for the JSON output + //with the value of the actual expected path + storedAssignment.setPath(lessonAssignment.getPath()); + result.add(new LessonOverview(storedAssignment, entry.getValue())); + break; + + } else if (lessonAssignment.getName().equals(storedAssignment.getName())) { + result.add(new LessonOverview(storedAssignment, entry.getValue())); + break; + } + } + //assignments not in the list will not be put in the lesson progress JSON output + } return result; } + private boolean isLessonComplete(Map map, Lesson currentLesson) { + boolean result = true; + for (Map.Entry entry : map.entrySet()) { + Assignment storedAssignment = entry.getKey(); + for (Assignment lessonAssignment : currentLesson.getAssignments()) { + if (lessonAssignment.getName().equals(storedAssignment.getName())) { + result = result && entry.getValue(); + break; + } + } + + } + return result; + } @AllArgsConstructor @Getter diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonTitleService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonTitleService.java index c3d7a82b5..40d4e9459 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonTitleService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/LessonTitleService.java @@ -1,6 +1,6 @@ package org.owasp.webgoat.service; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.session.WebSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -31,7 +31,7 @@ public class LessonTitleService { public @ResponseBody String showPlan() { - AbstractLesson lesson = webSession.getCurrentLesson(); + Lesson lesson = webSession.getCurrentLesson(); return lesson != null ? lesson.getTitle() : ""; } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/ParameterService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/ParameterService.java deleted file mode 100644 index 8ba3738af..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/ParameterService.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * ************************************************************************************************* - * - * - * 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. - * - */ -package org.owasp.webgoat.service; - -import com.google.common.collect.Lists; -import org.owasp.webgoat.lessons.RequestParameter; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.servlet.http.HttpSession; -import java.util.Collections; -import java.util.List; - -/** - *

ParameterService class.

- * - * @author rlawson - * @version $Id: $Id - */ -@Controller -public class ParameterService { - - /** - * Returns request parameters for last attack - * - * @param session a {@link javax.servlet.http.HttpSession} object. - * @return a {@link java.util.List} object. - */ - @RequestMapping(path = "/service/parameter.mvc", produces = "application/json") - public @ResponseBody - List showParameters(HttpSession session) { - //// TODO: 11/6/2016 to decide not sure about the role in WebGoat 8 - List listParms = Lists.newArrayList(); - Collections.sort(listParms); - return listParms; - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/PluginReloadService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/PluginReloadService.java index e9e494523..917920158 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/PluginReloadService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/PluginReloadService.java @@ -1,32 +1,32 @@ /** * ************************************************************************************************* - * - * + *

+ *

* 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. - * */ + package org.owasp.webgoat.service; import org.springframework.http.HttpStatus; @@ -46,6 +46,7 @@ import java.util.Map; * @author nbaars * @version $Id: $Id */ +//TODO REMOVE? @Controller public class PluginReloadService { @@ -58,15 +59,6 @@ public class PluginReloadService { @RequestMapping(path = "/service/reloadplugins.mvc", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody ResponseEntity> reloadPlugins(HttpSession session) { -// WebSession webSession = (WebSession) session.getAttribute(WebSession.SESSION); -// -// logger.debug("Loading plugins into cache"); -// String pluginPath = session.getServletContext().getRealPath("plugin_lessons"); -// String targetPath = session.getServletContext().getRealPath("plugin_extracted"); -// //TODO fix me -// //new PluginsLoader(Paths.get(pluginPath), Paths.get(targetPath)).copyJars(); -// //webSession.getCourse().createLessonsFromPlugins(); - Map result = new HashMap(); result.put("success", true); result.put("message", "Plugins reloaded"); diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/ReportCardService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/ReportCardService.java index 0337467b1..eac1cb5a7 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/ReportCardService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/ReportCardService.java @@ -26,14 +26,14 @@ * Source for this application is maintained at * https://github.com/WebGoat/WebGoat, a repository for free software projects. */ + package org.owasp.webgoat.service; -import com.google.common.collect.Lists; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import org.owasp.webgoat.i18n.PluginMessages; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.session.Course; import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.users.LessonTracker; @@ -43,6 +43,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; +import java.util.ArrayList; import java.util.List; /** @@ -66,14 +67,14 @@ public class ReportCardService { @GetMapping(path = "/service/reportcard.mvc", produces = "application/json") @ResponseBody public ReportCard reportCard() { - UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName()); - List lessons = course.getLessons(); ReportCard reportCard = new ReportCard(); reportCard.setTotalNumberOfLessons(course.getTotalOfLessons()); reportCard.setTotalNumberOfAssignments(course.getTotalOfAssignments()); + + UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName()); reportCard.setNumberOfAssignmentsSolved(userTracker.numberOfAssignmentsSolved()); reportCard.setNumberOfLessonsSolved(userTracker.numberOfLessonsSolved()); - for (AbstractLesson lesson : lessons) { + for (Lesson lesson : course.getLessons()) { LessonTracker lessonTracker = userTracker.getLessonTracker(lesson); LessonStatistics lessonStatistics = new LessonStatistics(); lessonStatistics.setName(pluginMessages.getMessage(lesson.getTitle())); @@ -93,7 +94,7 @@ public class ReportCardService { private int solvedLessons; private int numberOfAssignmentsSolved; private int numberOfLessonsSolved; - private List lessonStatistics = Lists.newArrayList(); + private List lessonStatistics = new ArrayList<>(); } @Setter diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/RestartLessonService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/RestartLessonService.java index b207b4ce1..4c17cbe0a 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/RestartLessonService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/RestartLessonService.java @@ -21,11 +21,13 @@ * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software * projects. */ + package org.owasp.webgoat.service; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.flywaydb.core.Flyway; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.users.UserTracker; import org.owasp.webgoat.users.UserTrackerRepository; @@ -34,33 +36,26 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; -/** - *

RestartLessonService class.

- * - * @author rlawson - * @version $Id: $Id - */ @Controller @AllArgsConstructor @Slf4j public class RestartLessonService { private final WebSession webSession; - private UserTrackerRepository userTrackerRepository; + private final UserTrackerRepository userTrackerRepository; + private final Flyway flywayLessons; - /** - * Returns current lesson - * - * @return a {@link java.lang.String} object. - */ @RequestMapping(path = "/service/restartlesson.mvc", produces = "text/text") @ResponseStatus(value = HttpStatus.OK) public void restartLesson() { - AbstractLesson al = webSession.getCurrentLesson(); + Lesson al = webSession.getCurrentLesson(); log.debug("Restarting lesson: " + al); UserTracker userTracker = userTrackerRepository.findByUser(webSession.getUserName()); userTracker.reset(al); userTrackerRepository.save(userTracker); + + flywayLessons.clean(); + flywayLessons.migrate(); } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/service/SessionService.java b/webgoat-container/src/main/java/org/owasp/webgoat/service/SessionService.java index 715f4e88f..5d0f4b3cc 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/service/SessionService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/service/SessionService.java @@ -3,6 +3,7 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ + package org.owasp.webgoat.service; import org.springframework.stereotype.Controller; diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/Course.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/Course.java index 1098f4a65..b4ede6ed3 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/Course.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/session/Course.java @@ -1,11 +1,9 @@ package org.owasp.webgoat.session; -import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.lessons.Category; -import java.util.LinkedList; import java.util.List; import static java.util.stream.Collectors.toList; @@ -41,10 +39,13 @@ import static java.util.stream.Collectors.toList; * @since October 28, 2003 */ @Slf4j -@AllArgsConstructor public class Course { - private List lessons = new LinkedList<>(); + private List lessons; + + public Course(List lessons) { + this.lessons = lessons; + } /** * Gets the categories attribute of the Course object @@ -60,7 +61,7 @@ public class Course { * * @return The firstLesson value */ - public AbstractLesson getFirstLesson() { + public Lesson getFirstLesson() { // Category 0 is the admin function. We want the first real category // to be returned. This is normally the General category and the Http Basics lesson return getLessons(getCategories().get(0)).get(0); @@ -71,7 +72,7 @@ public class Course { * * @return a {@link java.util.List} object. */ - public List getLessons() { + public List getLessons() { return this.lessons; } @@ -81,11 +82,11 @@ public class Course { * @param category a {@link org.owasp.webgoat.lessons.Category} object. * @return a {@link java.util.List} object. */ - public List getLessons(Category category) { - return this.lessons.stream().filter(l -> l.getCategory() == category).sorted().collect(toList()); + public List getLessons(Category category) { + return this.lessons.stream().filter(l -> l.getCategory() == category).collect(toList()); } - public void setLessons(List lessons) { + public void setLessons(List lessons) { this.lessons = lessons; } @@ -94,9 +95,6 @@ public class Course { } public int getTotalOfAssignments() { - final int[] total = {0}; - this.lessons.stream().forEach(l -> total[0] = total[0] + l.getAssignments().size()); - return total[0]; + return this.lessons.stream().reduce(0, (total, lesson) -> lesson.getAssignments().size() + total, Integer::sum); } - } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/CreateDB.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/CreateDB.java deleted file mode 100644 index a34e734db..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/CreateDB.java +++ /dev/null @@ -1,1073 +0,0 @@ - -package org.owasp.webgoat.session; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; - - -/** - * ************************************************************************************************ - *

- *

- * 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 - * @version $Id: $Id - */ -public class CreateDB { - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createServersTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Drop servers table - try { - String dropTable = "DROP TABLE servers"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop servers table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE servers" - + " (" + "id varchar(10)," - + "hostname varchar(20)," - + "ip varchar(20)," - + "mac varchar(20)," - + "status varchar(20)," - + "description varchar(40)" - + ")"; - statement.executeUpdate(createTableStatement); - - String insertData1 = "INSERT INTO servers VALUES ('1', 'webgoat-dev', '192.168.4.0', 'AA:BB:11:22:CC:DD', 'online', 'Development server')"; - String insertData2 = "INSERT INTO servers VALUES ('2', 'webgoat-tst', '192.168.2.1', 'EE:FF:33:44:AB:CD', 'online', 'Test server')"; - String insertData3 = "INSERT INTO servers VALUES ('3', 'webgoat-acc', '192.168.3.3', 'EF:12:FE:34:AA:CC', 'offline', 'Acceptance server')"; - String insertData4 = "INSERT INTO servers VALUES ('4', 'webgoat-pre-prod', '192.168.6.4', 'EF:12:FE:34:AA:CC', 'offline', 'Pre-production server')"; - String insertData5 = "INSERT INTO servers VALUES ('4', 'webgoat-prd', '104.130.219.202', 'FA:91:EB:82:DC:73', 'out of order', 'Production server')"; - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - } catch (SQLException e) { - System.out.println("Error creating product table " + e.getLocalizedMessage()); - } - } - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createJWTKeys(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Drop servers table - try { - String dropTable = "DROP TABLE jwt_keys"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop jwtkeys table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE jwt_keys" - + " (" + "id varchar(20)," - + "key varchar(20))"; - statement.executeUpdate(createTableStatement); - - String insertData1 = "INSERT INTO jwt_keys VALUES ('webgoat_key', 'qwertyqwerty1234')"; - String insertData2 = "INSERT INTO jwt_keys VALUES ('webwolf_key', 'doesnotreallymatter')"; - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - } catch (SQLException e) { - System.out.println("Error creating product table " + e.getLocalizedMessage()); - } - } - - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createMessageTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Drop admin user table - try { - String dropTable = "DROP TABLE messages"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop message database"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE messages (" + "num int not null," + "title varchar(50)," - + "message varchar(200)," + "user_name varchar(50) not null, " + "lesson_type varchar(50) not null" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating message database " + e.getLocalizedMessage()); - } - } - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createMFEImagesTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Drop mfe_images table - try { - String dropTable = "DROP TABLE mfe_images"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop mfe_images table from database"); - } - - // Create the new mfe_images table - try { - String createTableStatement = "CREATE TABLE mfe_images (" - + "user_name varchar(50) not null, " - + "image_relative_url varchar(50) not null" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating mfe_images table in database " + e.getLocalizedMessage()); - } - - } - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createProductTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Drop admin user table - try { - String dropTable = "DROP TABLE product_system_data"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop product table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE product_system_data (" - + "productid varchar(6) not null primary key," + "product_name varchar(20)," + "price varchar(10)" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating product table " + e.getLocalizedMessage()); - } - - // Populate - String insertData1 = "INSERT INTO product_system_data VALUES ('32226','Dog Bone','$1.99')"; - String insertData2 = "INSERT INTO product_system_data VALUES ('35632','DVD Player','$214.99')"; - String insertData3 = "INSERT INTO product_system_data VALUES ('24569','60 GB Hard Drive','$149.99')"; - String insertData4 = "INSERT INTO product_system_data VALUES ('56970','80 GB Hard Drive','$179.99')"; - String insertData5 = "INSERT INTO product_system_data VALUES ('14365','56 inch HDTV','$6999.99')"; - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - } - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createUserAdminTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Drop admin user table - try { - String dropTable = "DROP TABLE user_system_data"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop user admin table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE user_system_data (" + "userid int not null primary key," - + "user_name varchar(12)," + "password varchar(10)," + "cookie varchar(30)" + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating user admin table " + e.getLocalizedMessage()); - } - - // Populate - String insertData1 = "INSERT INTO user_system_data VALUES (101,'jsnow','passwd1', '')"; - String insertData2 = "INSERT INTO user_system_data VALUES (102,'jdoe','passwd2', '')"; - String insertData3 = "INSERT INTO user_system_data VALUES (103,'jplane','passwd3', '')"; - String insertData4 = "INSERT INTO user_system_data VALUES (104,'jeff','jeff', '')"; - String insertData5 = "INSERT INTO user_system_data VALUES (105,'dave','passW0rD', '')"; - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - } - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createUserDataTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Delete table if there is one - try { - String dropTable = "DROP TABLE user_data"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop user table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE user_data (" + "userid int not null," - + "first_name varchar(20)," + "last_name varchar(20)," + "cc_number varchar(30)," - + "cc_type varchar(10)," + "cookie varchar(20)," + "login_count int" + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating user table " + e.getLocalizedMessage()); - } - - // Populate it - String insertData1 = "INSERT INTO user_data VALUES (101,'Joe','Snow','987654321','VISA',' ',0)"; - String insertData2 = "INSERT INTO user_data VALUES (101,'Joe','Snow','2234200065411','MC',' ',0)"; - String insertData3 = "INSERT INTO user_data VALUES (102,'John','Smith','2435600002222','MC',' ',0)"; - String insertData4 = "INSERT INTO user_data VALUES (102,'John','Smith','4352209902222','AMEX',' ',0)"; - String insertData5 = "INSERT INTO user_data VALUES (103,'Jane','Plane','123456789','MC',' ',0)"; - String insertData6 = "INSERT INTO user_data VALUES (103,'Jane','Plane','333498703333','AMEX',' ',0)"; - String insertData7 = "INSERT INTO user_data VALUES (10312,'Jolly','Hershey','176896789','MC',' ',0)"; - String insertData8 = "INSERT INTO user_data VALUES (10312,'Jolly','Hershey','333300003333','AMEX',' ',0)"; - String insertData9 = "INSERT INTO user_data VALUES (10323,'Grumpy','youaretheweakestlink','673834489','MC',' ',0)"; - String insertData10 = "INSERT INTO user_data VALUES (10323,'Grumpy','youaretheweakestlink','33413003333','AMEX',' ',0)"; - String insertData11 = "INSERT INTO user_data VALUES (15603,'Peter','Sand','123609789','MC',' ',0)"; - String insertData12 = "INSERT INTO user_data VALUES (15603,'Peter','Sand','338893453333','AMEX',' ',0)"; - String insertData13 = "INSERT INTO user_data VALUES (15613,'Joesph','Something','33843453533','AMEX',' ',0)"; - String insertData14 = "INSERT INTO user_data VALUES (15837,'Chaos','Monkey','32849386533','CM',' ',0)"; - String insertData15 = "INSERT INTO user_data VALUES (19204,'Mr','Goat','33812953533','VISA',' ',0)"; - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - statement.executeUpdate(insertData6); - statement.executeUpdate(insertData7); - statement.executeUpdate(insertData8); - statement.executeUpdate(insertData9); - statement.executeUpdate(insertData10); - statement.executeUpdate(insertData11); - statement.executeUpdate(insertData12); - statement.executeUpdate(insertData13); - statement.executeUpdate(insertData14); - statement.executeUpdate(insertData15); - - } - - private void createLoginTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Delete table if there is one - try { - String dropTable = "DROP TABLE user_login"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop user_login table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE user_login (" + "userid varchar(5)," - + "webgoat_user varchar(20)" + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating user_login table " + e.getLocalizedMessage()); - } - - } - - // creates the table pins which is used in the blind sql injection lesson - private void createBlindSQLLessonTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Delete table if there is one - try { - String dropTable = "DROP TABLE pins"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop pins table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE pins (" - + "cc_number varchar(30)," - + "pin int," - + "name varchar(20)" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating pins table " + e.getLocalizedMessage()); - } - - // Populate it - String insertData1 = "INSERT INTO pins VALUES ('987654321098765', 1234, 'Joe')"; - String insertData2 = "INSERT INTO pins VALUES ('1234567890123456', 4567, 'Jack')"; - String insertData3 = "INSERT INTO pins VALUES ('4321432143214321', 4321, 'Jill')"; - String insertData4 = "INSERT INTO pins VALUES ('1111111111111111', 7777, 'Jim')"; - String insertData5 = "INSERT INTO pins VALUES ('1111222233334444', 2364, 'John')"; - - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - - } - - // creates the table salaries which is used in the lessons - // which add or modify data using sql injection - private void createModifyWithSQLLessonTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Delete table if there is one - try { - String dropTable = "DROP TABLE salaries"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop salaries table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE salaries (" - + "userid varchar(50)," - + "salary int" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating salaries table " + e.getLocalizedMessage()); - } - - // Populate it - String insertData1 = "INSERT INTO salaries VALUES ('jsmith', 20000)"; - String insertData2 = "INSERT INTO salaries VALUES ('lsmith', 45000)"; - String insertData3 = "INSERT INTO salaries VALUES ('wgoat', 100000)"; - String insertData4 = "INSERT INTO salaries VALUES ('rjones', 777777)"; - String insertData5 = "INSERT INTO salaries VALUES ('manderson', 65000)"; - - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - - } - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - */ - private void createWeatherDataTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Delete table if there is one - try { - String dropTable = "DROP TABLE weather_data"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop weather table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE weather_data (" + "station int not null," - + "name varchar(20) not null," + "state char(2) not null," + "min_temp int not null," - + "max_temp int not null" + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating weather table " + e.getLocalizedMessage()); - } - - // Populate it - String insertData1 = "INSERT INTO weather_data VALUES (101,'Columbia','MD',-10,102)"; - String insertData2 = "INSERT INTO weather_data VALUES (102,'Seattle','WA',-15,90)"; - String insertData3 = "INSERT INTO weather_data VALUES (103,'New York','NY',-10,110)"; - String insertData4 = "INSERT INTO weather_data VALUES (104,'Houston','TX',20,120)"; - String insertData5 = "INSERT INTO weather_data VALUES (10001,'Camp David','MD',-10,100)"; - String insertData6 = "INSERT INTO weather_data VALUES (11001,'Ice Station Zebra','NA',-60,30)"; - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - statement.executeUpdate(insertData6); - } - - /** - * Create users with tans - * - * @param connection - * @throws SQLException - */ - private void createTanUserDataTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Delete table if there is one - try { - String dropTable = "DROP TABLE user_data_tan"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop user_data_tan table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE user_data_tan (" + "userid int not null," - + "first_name varchar(20)," + "last_name varchar(20)," + "cc_number varchar(30)," - + "cc_type varchar(10)," + "cookie varchar(20)," + "login_count int," + "password varchar(20)" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating user_data_tan table " + e.getLocalizedMessage()); - } - - // Populate it - String insertData1 = "INSERT INTO user_data_tan VALUES (101,'Joe','Snow','987654321','VISA',' ',0, 'banana')"; - String insertData2 = "INSERT INTO user_data_tan VALUES (102,'Jane','Plane','74589864','MC',' ',0, 'tarzan')"; - String insertData3 = "INSERT INTO user_data_tan VALUES (103,'Jack','Sparrow','68659365','MC',' ',0, 'sniffy')"; - - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - } - - /** - * Create the Table for the tans - * - * @param connection - * @throws SQLException - */ - private void createTanTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Delete table if there is one - try { - String dropTable = "DROP TABLE tan"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop tan table"); - } - - // Create the new table - try { - String createTableStatement = "CREATE TABLE tan (" + "userid int not null," + "tanNr int," + "tanValue int" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating tan table " + e.getLocalizedMessage()); - } - - // Populate it - String insertData1 = "INSERT INTO tan VALUES (101,1,15161)"; - String insertData2 = "INSERT INTO tan VALUES (101,2,4894)"; - String insertData3 = "INSERT INTO tan VALUES (101,3,18794)"; - String insertData4 = "INSERT INTO tan VALUES (101,4,1564)"; - String insertData5 = "INSERT INTO tan VALUES (101,5,45751)"; - - String insertData6 = "INSERT INTO tan VALUES (102,1,15648)"; - String insertData7 = "INSERT INTO tan VALUES (102,2,92156)"; - String insertData8 = "INSERT INTO tan VALUES (102,3,4879)"; - String insertData9 = "INSERT INTO tan VALUES (102,4,9458)"; - String insertData10 = "INSERT INTO tan VALUES (102,5,4879)"; - - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - statement.executeUpdate(insertData6); - statement.executeUpdate(insertData7); - statement.executeUpdate(insertData8); - statement.executeUpdate(insertData9); - statement.executeUpdate(insertData10); - - } - - // -------------------------------------------------------------------------- - // -------------------------------------------------------------------------- - // - // The tables below are for WebGoat Financials - // - // DO NOT MODIFY THESE TABLES - unless you change the org chart - // and access control matrix documents - // - // -------------------------------------------------------------------------- - // -------------------------------------------------------------------------- - - private void createEmployeeTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - try { - String dropTable = "DROP TABLE employee"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop employee table"); - } - - // Create Table - try { - String createTable = "CREATE TABLE employee (" - // + "userid INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY," - + "userid INT NOT NULL PRIMARY KEY," + "first_name VARCHAR(20)," + "last_name VARCHAR(20)," - + "ssn VARCHAR(12)," + "password VARCHAR(10)," + "title VARCHAR(20)," + "phone VARCHAR(13)," - + "address1 VARCHAR(80)," + "address2 VARCHAR(80)," + "manager INT," + "start_date CHAR(8)," - + "salary INT," + "ccn VARCHAR(30)," + "ccn_limit INT," + "email VARCHAR(30)," // reason - // for the recent write-up - + "disciplined_date CHAR(8)," // date of write up, NA otherwise - + "disciplined_notes VARCHAR(60)," // reason for the recent write-up - + "personal_description VARCHAR(60)" // We can be rude here - // + ",CONSTRAINT fl UNIQUE NONCLUSTERED (first_name, last_name)" - + ")"; - - statement.executeUpdate(createTable); - } catch (SQLException e) { - System.out.println("Error: unable to create employee table " + e.getLocalizedMessage()); - } - - String insertData1 = "INSERT INTO employee VALUES (101, 'Larry', 'Stooge', '386-09-5451', 'larry'," - + "'Technician','443-689-0192','9175 Guilford Rd','New York, NY', 102, 01012000,55000,'2578546969853547'," - + "5000,'larry@stooges.com',010106,'Constantly harassing coworkers','Does not work well with others')"; - - String insertData2 = "INSERT INTO employee VALUES (102, 'Moe', 'Stooge', '936-18-4524','moe'," - + "'CSO','443-938-5301', '3013 AMD Ave', 'New York, NY', 112, 03082003, 140000, 'NA', 0, 'moe@stooges.com', 0101013, " - + "'Hit Curly over head', 'Very dominating over Larry and Curly')"; - - String insertData3 = "INSERT INTO employee VALUES (103, 'Curly', 'Stooge', '961-08-0047','curly'," - + "'Technician','410-667-6654', '1112 Crusoe Lane', 'New York, NY', 102, 02122001, 50000, 'NA', 0, 'curly@stooges.com', 0101014, " - + "'Hit Moe back', 'Owes three-thousand to company for fradulent purchases')"; - - String insertData4 = "INSERT INTO employee VALUES (104, 'Eric', 'Walker', '445-66-5565','eric'," - + "'Engineer','410-887-1193', '1160 Prescott Rd', 'New York, NY', 107, 12152005, 13000, 'NA', 0, 'eric@modelsrus.com',0101013, " - + "'Bothering Larry about webgoat problems', 'Late. Always needs help. Too intern-ish.')"; - - String insertData5 = "INSERT INTO employee VALUES (105, 'Tom', 'Cat', '792-14-6364','tom'," - + "'Engineer','443-599-0762', '2211 HyperThread Rd.', 'New York, NY', 106, 01011999, 80000, '5481360857968521', 30000, 'tom@wb.com', 0, " - + "'NA', 'Co-Owner.')"; - - String insertData6 = "INSERT INTO employee VALUES (106, 'Jerry', 'Mouse', '858-55-4452','jerry'," - + "'Human Resources','443-699-3366', '3011 Unix Drive', 'New York, NY', 102, 01011999, 70000, '6981754825013564', 20000, 'jerry@wb.com', 0, " - + "'NA', 'Co-Owner.')"; - - String insertData7 = "INSERT INTO employee VALUES (107, 'David', 'Giambi', '439-20-9405','david'," - + "'Human Resources','610-521-8413', '5132 DIMM Avenue', 'New York, NY', 102, 05011999, 100000, '6981754825018101', 10000, 'david@modelsrus.com', 061402, " - + "'Hacked into accounting server. Modified personal pay.', 'Strong work habbit. Questionable ethics.')"; - - String insertData8 = "INSERT INTO employee VALUES (108, 'Bruce', 'McGuirre', '707-95-9482','bruce'," - + "'Engineer','610-282-1103', '8899 FreeBSD Drive ', 'New York, NY', 107, 03012000, 110000, '6981754825854136', 30000, 'bruce@modelsrus.com', 061502, " - + "'Tortuous Boot Camp workout at 5am. Employees felt sick.', 'Enjoys watching others struggle in exercises.')"; - - String insertData9 = "INSERT INTO employee VALUES (109, 'Sean', 'Livingston', '136-55-1046','sean'," - + "'Engineer','610-878-9549', '6422 dFlyBSD Road', 'New York, NY', 107, 06012003, 130000, '6981754825014510', 5000, 'sean@modelsrus.com', 072804, " - + "'Late to work 30 days in row due to excessive Halo 2', 'Has some fascination with Steelers. Go Ravens.')"; - - String insertData10 = "INSERT INTO employee VALUES (110, 'Joanne', 'McDougal', '789-54-2413','joanne'," - + "'Human Resources','610-213-6341', '5567 Broadband Lane', 'New York, NY', 106, 01012001, 90000, '6981754825081054', 300, 'joanne@modelsrus.com', 112005, " - + "'Used company cc to purchase new car. Limit adjusted.', 'Finds it necessary to leave early every day.')"; - - String insertData11 = "INSERT INTO employee VALUES (111, 'John', 'Wayne', '129-69-4572', 'john'," - + "'CTO','610-213-1134', '129 Third St', 'New York, NY', 112, 01012001, 200000, '4437334565679921', 300, 'john@guns.com', 112005, " - + "'', '')"; - String insertData12 = "INSERT INTO employee VALUES (112, 'Neville', 'Bartholomew', '111-111-1111', 'socks'," - + "'CEO','408-587-0024', '1 Corporate Headquarters', 'San Jose, CA', 112, 03012000, 450000, '4803389267684109', 300000, 'neville@modelsrus.com', 112005, " - + "'', '')"; - - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - statement.executeUpdate(insertData6); - statement.executeUpdate(insertData7); - statement.executeUpdate(insertData8); - statement.executeUpdate(insertData9); - statement.executeUpdate(insertData10); - statement.executeUpdate(insertData11); - statement.executeUpdate(insertData12); - - } - - private void createRolesTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - try { - String dropTable = "DROP TABLE roles"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop roles table"); - } - - try { - String createTable = "CREATE TABLE roles (" + "userid INT NOT NULL," + "role VARCHAR(10) NOT NULL," - + "PRIMARY KEY (userid, role)" + ")"; - - statement.executeUpdate(createTable); - } catch (SQLException e) { - System.out.println("Error: Unable to create role table: " + e.getLocalizedMessage()); - } - - String insertData1 = "INSERT INTO roles VALUES (101, 'employee')"; - String insertData2 = "INSERT INTO roles VALUES (102, 'manager')"; - String insertData3 = "INSERT INTO roles VALUES (103, 'employee')"; - String insertData4 = "INSERT INTO roles VALUES (104, 'employee')"; - String insertData5 = "INSERT INTO roles VALUES (105, 'employee')"; - String insertData6 = "INSERT INTO roles VALUES (106, 'hr')"; - String insertData7 = "INSERT INTO roles VALUES (107, 'manager')"; - String insertData8 = "INSERT INTO roles VALUES (108, 'employee')"; - String insertData9 = "INSERT INTO roles VALUES (109, 'employee')"; - String insertData10 = "INSERT INTO roles VALUES (110, 'hr')"; - String insertData11 = "INSERT INTO roles VALUES (111, 'admin')"; - String insertData12 = "INSERT INTO roles VALUES (112, 'admin')"; - - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - statement.executeUpdate(insertData6); - statement.executeUpdate(insertData7); - statement.executeUpdate(insertData8); - statement.executeUpdate(insertData9); - statement.executeUpdate(insertData10); - statement.executeUpdate(insertData11); - statement.executeUpdate(insertData12); - } - - private void createAuthTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - try { - String dropTable = "DROP TABLE auth"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop auth table"); - } - - try { - String createTable = "CREATE TABLE auth (" + "role VARCHAR(10) NOT NULL," - + "functionid VARCHAR(20) NOT NULL," + "PRIMARY KEY (role, functionid)" + ")"; - - statement.executeUpdate(createTable); - } catch (SQLException e) { - System.out.println("Error: unable to create auth table: " + e.getLocalizedMessage()); - } - - String insertData1 = "INSERT INTO auth VALUES('employee', 'Logout')"; - String insertData2 = "INSERT INTO auth VALUES('employee', 'ListStaff')"; - String insertData3 = "INSERT INTO auth VALUES('employee', 'ViewProfile')"; - String insertData4 = "INSERT INTO auth VALUES('employee', 'EditProfile')"; - String insertData4_1 = "INSERT INTO auth VALUES('employee', 'SearchStaff')"; - String insertData4_2 = "INSERT INTO auth VALUES('employee', 'FindProfile')"; - String insertData5 = "INSERT INTO auth VALUES('manager', 'Logout')"; - String insertData6 = "INSERT INTO auth VALUES('manager', 'ListStaff')"; - String insertData7 = "INSERT INTO auth VALUES('manager', 'ViewProfile')"; - String insertData7_1 = "INSERT INTO auth VALUES('manager', 'SearchStaff')"; - String insertData7_2 = "INSERT INTO auth VALUES('manager', 'FindProfile')"; - // String insertData8 = "INSERT INTO auth VALUES('manager', 'EditProfile')"; - // String insertData9 = "INSERT INTO auth VALUES('manager', 'CreateProfile')"; - // String insertData10 = "INSERT INTO auth VALUES('manager', 'DeleteProfile')"; - // String insertData11 = "INSERT INTO auth VALUES('manager', 'UpdateProfile')"; - String insertData12 = "INSERT INTO auth VALUES('hr', 'Logout')"; - String insertData13 = "INSERT INTO auth VALUES('hr', 'ListStaff')"; - String insertData14 = "INSERT INTO auth VALUES('hr', 'ViewProfile')"; - String insertData15 = "INSERT INTO auth VALUES('hr', 'EditProfile')"; - String insertData16 = "INSERT INTO auth VALUES('hr', 'CreateProfile')"; - String insertData17 = "INSERT INTO auth VALUES('hr', 'DeleteProfile')"; - String insertData18 = "INSERT INTO auth VALUES('hr', 'UpdateProfile')"; - String insertData18_1 = "INSERT INTO auth VALUES('hr', 'SearchStaff')"; - String insertData18_2 = "INSERT INTO auth VALUES('hr', 'FindProfile')"; - String insertData19 = "INSERT INTO auth VALUES('admin', 'Logout')"; - String insertData20 = "INSERT INTO auth VALUES('admin', 'ListStaff')"; - String insertData21 = "INSERT INTO auth VALUES('admin', 'ViewProfile')"; - String insertData22 = "INSERT INTO auth VALUES('admin', 'EditProfile')"; - String insertData23 = "INSERT INTO auth VALUES('admin', 'CreateProfile')"; - String insertData24 = "INSERT INTO auth VALUES('admin', 'DeleteProfile')"; - String insertData25 = "INSERT INTO auth VALUES('admin', 'UpdateProfile')"; - String insertData25_1 = "INSERT INTO auth VALUES('admin', 'SearchStaff')"; - String insertData25_2 = "INSERT INTO auth VALUES('admin', 'FindProfile')"; - -// // Add a permission for the webgoat role to see the source. -// // The challenge(s) will change the default role to "challenge" -// String insertData26 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOURCE -// + "')"; -// String insertData27 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWHINTS -// + "')"; - // Add a permission for the webgoat role to see the solution. - // The challenge(s) will change the default role to "challenge" -// String insertData28 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOLUTION -// + "')"; - - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData4_1); - statement.executeUpdate(insertData4_2); - statement.executeUpdate(insertData5); - statement.executeUpdate(insertData6); - statement.executeUpdate(insertData7); - statement.executeUpdate(insertData7_1); - statement.executeUpdate(insertData7_2); - // statement.executeUpdate(insertData8); - // statement.executeUpdate(insertData9); - // statement.executeUpdate(insertData10); - // statement.executeUpdate(insertData11); - statement.executeUpdate(insertData12); - statement.executeUpdate(insertData13); - statement.executeUpdate(insertData14); - statement.executeUpdate(insertData15); - statement.executeUpdate(insertData16); - statement.executeUpdate(insertData17); - statement.executeUpdate(insertData18); - statement.executeUpdate(insertData18_1); - statement.executeUpdate(insertData18_2); - statement.executeUpdate(insertData19); - statement.executeUpdate(insertData20); - statement.executeUpdate(insertData21); - statement.executeUpdate(insertData22); - statement.executeUpdate(insertData23); - statement.executeUpdate(insertData24); - statement.executeUpdate(insertData25); - statement.executeUpdate(insertData25_1); - statement.executeUpdate(insertData25_2); - //statement.executeUpdate(insertData26); - //statement.executeUpdate(insertData27); - //statement.executeUpdate(insertData28); - } - - private void createOwnershipTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - try { - String dropTable = "DROP TABLE ownership"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop ownership table"); - } - - try { - String createTable = "CREATE TABLE ownership (" + "employer_id INT NOT NULL," + "employee_id INT NOT NULL," - + "PRIMARY KEY (employee_id, employer_id)" + ")"; - - statement.executeUpdate(createTable); - } catch (SQLException e) { - System.out.println("Error: unable to create ownership table: " + e.getLocalizedMessage()); - } - - String inputData = "INSERT INTO ownership VALUES (112, 101)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 102)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 103)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 104)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 105)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 106)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 107)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 108)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 109)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 110)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 111)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (112, 112)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (102, 101)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 102)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 103)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 104)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 105)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 106)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 107)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 108)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 109)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 110)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (102, 111)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (111, 101)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 102)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 103)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 104)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 105)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 106)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 107)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 108)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 109)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 110)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (111, 111)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (106, 105)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (106, 106)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (106, 110)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (101, 101)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (103, 103)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (107, 104)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (107, 108)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (107, 109)"; - statement.executeUpdate(inputData); - inputData = "INSERT INTO ownership VALUES (107, 107)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (105, 105)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (110, 110)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (104, 104)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (108, 108)"; - statement.executeUpdate(inputData); - - inputData = "INSERT INTO ownership VALUES (109, 109)"; - statement.executeUpdate(inputData); - - } - - // -------------------------------------------------------------------------- - // - // End of WebGoat Financials - // - // -------------------------------------------------------------------------- - - /** - * Start creation of data for WebServices labs - */ - - private void createTransactionTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - try { - String dropTable = "DROP TABLE transactions"; - statement.executeUpdate(dropTable); - } catch (SQLException e) { - System.out.println("Info - Could not drop transactions table"); - } - - try { - String createTable = "CREATE TABLE Transactions (" + "userName VARCHAR(16) NOT NULL, " - + "sequence INTEGER NOT NULL, " + "from_account VARCHAR(16) NOT NULL, " - + "to_account VARCHAR(16) NOT NULL, " + "transactionDate TIMESTAMP NOT NULL, " - + "description VARCHAR(255) NOT NULL, " + "amount INTEGER NOT NULL" + ")"; - - statement.executeUpdate(createTable); - } catch (SQLException e) { - System.out.println("Error: unable to create transactions table: " + e.getLocalizedMessage()); - throw e; - } - - String[] data = new String[]{ - "'dave', 0, '238-4723-4024', '324-7635-9867', '2008-02-06 21:40:00', 'Mortgage', '150'", - "'dave', 1, '238-4723-4024', '324-7635-9867', '2008-02-12 21:41:00', 'Car', '150'", - "'dave', 2, '238-4723-4024', '324-7635-9867', '2008-02-20 21:42:00', 'School fees', '150'", - "'CEO', 3, '348-6324-9872', '345-3490-8345', '2008-02-15 21:40:00', 'Rolls Royce', '-150000'", - "'CEO', 4, '348-6324-9872', '342-5893-4503', '2008-02-25 21:41:00', 'Mansion', '-150000'", - "'CEO', 5, '348-6324-9872', '980-2344-5492', '2008-02-27 21:42:00', 'Vacation', '-150000'", - "'jeff', 6, '934-2002-3485', '783-2409-8234', '2008-02-01 21:40:00', 'Vet', '250'", - "'jeff', 7, '934-2002-3485', '634-5879-0345', '2008-02-19 21:41:00', 'Doctor', '800'", - "'jeff', 8, '934-2002-3485', '435-4325-3358', '2008-02-20 21:42:00', 'X-rays', '200'",}; - try { - for (int i = 0; i < data.length; i++) { - statement.executeUpdate("INSERT INTO Transactions VALUES (" + data[i] + ");"); - } - } catch (SQLException sqle) { - System.out.println("Error: Unable to insert transactions: " + sqle.getLocalizedMessage()); - int errorCode = sqle.getErrorCode(); - System.out.println("Error Code: " + errorCode); - // ignore exceptions for Oracle and SQL Server - if (errorCode != 911 && errorCode != 273) { - throw sqle; - } - } - } - - /** - * Creates the table used in SQL-Injections (introduction) - */ - private void createEmployeesTable(Connection connection) throws SQLException { - Statement statement = connection.createStatement(); - - // Drop employees and access_log tables - try { - statement.executeUpdate("DROP TABLE employees"); - } catch (SQLException e) { - System.out.println("Info - Could not drop employees table"); - } - try { - statement.executeUpdate("DROP TABLE access_log"); - } catch (SQLException e) { - System.out.println("Info - Could not drop access_log table"); - } - - // Create the employees table - try { - String createTableStatement = "CREATE TABLE employees (" - + "userid varchar(6) not null primary key," - + "first_name varchar(20)," - + "last_name varchar(20)," - + "department varchar(20)," - + "salary int," - + "auth_tan varchar(6)" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating employees table " + e.getLocalizedMessage()); - } - - // Populate - String insertData1 = "INSERT INTO employees VALUES ('32147','Paulina', 'Travers', 'Accounting', 46000, 'P45JSI')"; - String insertData2 = "INSERT INTO employees VALUES ('89762','Tobi', 'Barnett', 'Development', 77000, 'TA9LL1')"; - String insertData3 = "INSERT INTO employees VALUES ('96134','Bob', 'Franco', 'Marketing', 83700, 'LO9S2V')"; - String insertData4 = "INSERT INTO employees VALUES ('34477','Abraham ', 'Holman', 'Development', 50000, 'UU2ALK')"; - String insertData5 = "INSERT INTO employees VALUES ('37648','John', 'Smith', 'Marketing', 64350, '3SL99A')"; - statement.executeUpdate(insertData1); - statement.executeUpdate(insertData2); - statement.executeUpdate(insertData3); - statement.executeUpdate(insertData4); - statement.executeUpdate(insertData5); - - // Create the logging table - try { - String createTableStatement = "CREATE TABLE access_log (" - + "id int not null primary key identity," - + "time varchar(50)," - + "action varchar(200)" - + ")"; - statement.executeUpdate(createTableStatement); - } catch (SQLException e) { - System.out.println("Error creating access_log table " + e.getLocalizedMessage()); - } - } - - /** - * Description of the Method - * - * @param connection Description of the Parameter - * @throws SQLException Description of the Exception - * @throws java.sql.SQLException if any. - */ - public void makeDB(Connection connection) throws SQLException { - System.out.println("Successful connection to database"); - createServersTable(connection); - createUserDataTable(connection); - createLoginTable(connection); - createBlindSQLLessonTable(connection); - createUserAdminTable(connection); - createProductTable(connection); - createMessageTable(connection); - createEmployeeTable(connection); - createRolesTable(connection); - createAuthTable(connection); - createOwnershipTable(connection); - createWeatherDataTable(connection); - createTransactionTable(connection); - createTanUserDataTable(connection); - createTanTable(connection); - createMFEImagesTable(connection); - createModifyWithSQLLessonTable(connection); - createJWTKeys(connection); - createEmployeesTable(connection); - System.out.println("Success: creating tables."); - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/DatabaseUtilities.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/DatabaseUtilities.java deleted file mode 100644 index 1d015ff3d..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/DatabaseUtilities.java +++ /dev/null @@ -1,129 +0,0 @@ - -package org.owasp.webgoat.session; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.Map; - - -/** - ************************************************************************************************* - * - * - * 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 - * @version $Id: $Id - */ -//TODO: class we need to refactor to new structure, we can put the connection in the current session of the user - // start using jdbc template -public class DatabaseUtilities -{ - - private static Map connections = new HashMap(); - private static Map dbBuilt = new HashMap(); - - /** - *

getConnection.

- * - * @param s a {@link org.owasp.webgoat.session.WebSession} object. - * @return a {@link java.sql.Connection} object. - * @throws java.sql.SQLException if any. - */ - public static Connection getConnection(WebSession s) throws SQLException - { - return getConnection(s.getUserName(), s.getWebgoatContext()); - } - - /** - *

getConnection.

- * - * @param user a {@link java.lang.String} object. - * @param context a {@link org.owasp.webgoat.session.WebgoatContext} object. - * @return a {@link java.sql.Connection} object. - * @throws java.sql.SQLException if any. - */ - public static synchronized Connection getConnection(String user, WebgoatContext context) throws SQLException - { - Connection conn = connections.get(user); - if (conn != null && !conn.isClosed()) return conn; - conn = makeConnection(user, context); - connections.put(user, conn); - - if (dbBuilt.get(user) == null) - { - new CreateDB().makeDB(conn); - dbBuilt.put(user, Boolean.TRUE); - } - - return conn; - } - - /** - *

returnConnection.

- * - * @param user a {@link java.lang.String} object. - */ - public static synchronized void returnConnection(String user) - { - try - { - Connection connection = connections.get(user); - if (connection == null || connection.isClosed()) return; - - if (connection.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle")) connection.close(); - } catch (SQLException sqle) - { - sqle.printStackTrace(); - } - } - - private static Connection makeConnection(String user, WebgoatContext context) throws SQLException - { - try - { - Class.forName(context.getDatabaseDriver()); - - if (context.getDatabaseConnectionString().contains("hsqldb")) return getHsqldbConnection(user, context); - - String userPrefix = context.getDatabaseUser(); - String password = context.getDatabasePassword(); - String url = context.getDatabaseConnectionString(); - return DriverManager.getConnection(url, userPrefix + "_" + user, password); - } catch (ClassNotFoundException cnfe) - { - cnfe.printStackTrace(); - throw new SQLException("Couldn't load the database driver: " + cnfe.getLocalizedMessage()); - } - } - - private static Connection getHsqldbConnection(String user, WebgoatContext context) throws ClassNotFoundException, - SQLException - { - String url = context.getDatabaseConnectionString().replace("{USER}", user); - return DriverManager.getConnection(url, "sa", ""); - } - -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/Screen.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/Screen.java deleted file mode 100644 index fae5c7fe7..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/Screen.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.owasp.webgoat.session; - -/** - * ************************************************************************************************* - * - * - * 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 - * @since October 28, 2003 - * @version $Id: $Id - */ -public abstract class Screen { - - /** - * Constructor for the Screen object - */ - public Screen() { - } - - - /** - * Fill in a descriptive title for this lesson - * - * @return The title value - */ - public abstract String getTitle(); - - -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/WebSession.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/WebSession.java index 33196575a..f59bdbaf5 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/WebSession.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/session/WebSession.java @@ -1,10 +1,10 @@ package org.owasp.webgoat.session; -import lombok.extern.slf4j.Slf4j; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.users.WebGoatUser; import org.springframework.security.core.context.SecurityContextHolder; +import java.io.Serializable; import java.sql.Connection; import java.sql.SQLException; @@ -37,58 +37,31 @@ import java.sql.SQLException; * @version $Id: $Id * @since October 28, 2003 */ -@Slf4j -public class WebSession { +public class WebSession implements Serializable { - private final WebGoatUser currentUser; - private final WebgoatContext webgoatContext; - private AbstractLesson currentLesson; + private static final long serialVersionUID = -4270066103101711560L; + private final WebGoatUser currentUser; + private Lesson currentLesson; - /** - * Constructor for the WebSession object - * - * @param webgoatContext a {@link org.owasp.webgoat.session.WebgoatContext} object. - */ - public WebSession(WebgoatContext webgoatContext) { - this.webgoatContext = webgoatContext; + public WebSession() { this.currentUser = (WebGoatUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } - /** - *

getConnection.

- * - * @param s a {@link org.owasp.webgoat.session.WebSession} object. - * @return a {@link java.sql.Connection} object. - * @throws java.sql.SQLException if any. - */ - public static synchronized Connection getConnection(WebSession s) throws SQLException { - return DatabaseUtilities.getConnection(s); - } - - /** - *

returnConnection.

- * - * @param s a {@link org.owasp.webgoat.session.WebSession} object. - */ - public static void returnConnection(WebSession s) { - DatabaseUtilities.returnConnection(s.getUserName()); - } - /** *

Setter for the field currentScreen.

* * @param lesson current lesson */ - public void setCurrentLesson(AbstractLesson lesson) { + public void setCurrentLesson(Lesson lesson) { this.currentLesson = lesson; } /** *

getCurrentLesson.

* - * @return a {@link org.owasp.webgoat.lessons.AbstractLesson} object. + * @return a {@link Lesson} object. */ - public AbstractLesson getCurrentLesson() { + public Lesson getCurrentLesson() { return this.currentLesson; } @@ -100,13 +73,4 @@ public class WebSession { public String getUserName() { return currentUser.getUsername(); } - - /** - *

Getter for the field webgoatContext.

- * - * @return a {@link org.owasp.webgoat.session.WebgoatContext} object. - */ - public WebgoatContext getWebgoatContext() { - return webgoatContext; - } } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/session/WebgoatContext.java b/webgoat-container/src/main/java/org/owasp/webgoat/session/WebgoatContext.java deleted file mode 100644 index c2e0c7e12..000000000 --- a/webgoat-container/src/main/java/org/owasp/webgoat/session/WebgoatContext.java +++ /dev/null @@ -1,187 +0,0 @@ -package org.owasp.webgoat.session; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; - -/** - *

WebgoatContext class.

- * - * @version $Id: $Id - * @author dm - */ -@Configuration -public class WebgoatContext { - - @Value("${webgoat.database.connection.string}") - private String databaseConnectionString; - - private String realConnectionString = null; - - @Value("${webgoat.database.driver}") - private String databaseDriver; - - private String databaseUser; - - private String databasePassword; - - private boolean showCookies = false; - - private boolean showParams = false; - - private boolean showRequest = false; - - private boolean showSource = false; - - private boolean showSolution = false; - - private boolean enterprise = false; - - private boolean codingExercises = false; - - @Value("${webgoat.feedback.address}") - private String feedbackAddress; - - @Value("${webgoat.feedback.address.html}") - private String feedbackAddressHTML = ""; - - private boolean isDebug = false; - - @Value("${webgoat.default.language}") - private String defaultLanguage; - - /** - * returns the connection string with the real path to the database - * directory inserted at the word PATH - * - * @return The databaseConnectionString value - */ - public String getDatabaseConnectionString() { - return this.databaseConnectionString; - } - - /** - * Gets the databaseDriver attribute of the WebSession object - * - * @return The databaseDriver value - */ - public String getDatabaseDriver() { - return (databaseDriver); - } - - /** - * Gets the databaseUser attribute of the WebSession object - * - * @return The databaseUser value - */ - public String getDatabaseUser() { - return (databaseUser); - } - - /** - * Gets the databasePassword attribute of the WebSession object - * - * @return The databasePassword value - */ - public String getDatabasePassword() { - return (databasePassword); - } - - /** - *

isEnterprise.

- * - * @return a boolean. - */ - public boolean isEnterprise() { - return enterprise; - } - - /** - *

isCodingExercises.

- * - * @return a boolean. - */ - public boolean isCodingExercises() { - return codingExercises; - } - - /** - *

Getter for the field feedbackAddress.

- * - * @return a {@link java.lang.String} object. - */ - public String getFeedbackAddress() { - return feedbackAddress; - } - - /** - *

Getter for the field feedbackAddressHTML.

- * - * @return a {@link java.lang.String} object. - */ - public String getFeedbackAddressHTML() { - return feedbackAddressHTML; - } - - /** - *

isDebug.

- * - * @return a boolean. - */ - public boolean isDebug() { - return isDebug; - } - - /** - *

isShowCookies.

- * - * @return a boolean. - */ - public boolean isShowCookies() { - return showCookies; - } - - /** - *

isShowParams.

- * - * @return a boolean. - */ - public boolean isShowParams() { - return showParams; - } - - /** - *

isShowRequest.

- * - * @return a boolean. - */ - public boolean isShowRequest() { - return showRequest; - } - - /** - *

isShowSource.

- * - * @return a boolean. - */ - public boolean isShowSource() { - return showSource; - } - - /** - *

isShowSolution.

- * - * @return a boolean. - */ - public boolean isShowSolution() { - return showSolution; - } - - /** - *

Getter for the field defaultLanguage.

- * - * @return a {@link java.lang.String} object. - */ - public String getDefaultLanguage() { - return defaultLanguage; - } -} diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/users/LessonTracker.java b/webgoat-container/src/main/java/org/owasp/webgoat/users/LessonTracker.java index 7d1d5d859..31f9be00a 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/users/LessonTracker.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/users/LessonTracker.java @@ -1,17 +1,12 @@ package org.owasp.webgoat.users; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import lombok.Getter; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.lessons.Assignment; import javax.persistence.*; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; @@ -54,19 +49,21 @@ public class LessonTracker { @Getter private String lessonName; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private final Set solvedAssignments = Sets.newHashSet(); + private final Set solvedAssignments = new HashSet<>(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private final Set allAssignments = Sets.newHashSet(); + private final Set allAssignments = new HashSet<>(); @Getter private int numberOfAttempts = 0; + @Version + private Integer version; private LessonTracker() { //JPA } - public LessonTracker(AbstractLesson lesson) { + public LessonTracker(Lesson lesson) { lessonName = lesson.getId(); - allAssignments.addAll(lesson.getAssignments()); + allAssignments.addAll(lesson.getAssignments() == null ? List.of() : lesson.getAssignments()); } public Optional getAssignment(String name) { diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/users/RegistrationController.java b/webgoat-container/src/main/java/org/owasp/webgoat/users/RegistrationController.java index 41eda0bda..754046f4c 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/users/RegistrationController.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/users/RegistrationController.java @@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; +import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; @@ -32,8 +33,7 @@ public class RegistrationController { } @PostMapping("/register.mvc") - @SneakyThrows - public String registration(@ModelAttribute("userForm") @Valid UserForm userForm, BindingResult bindingResult, HttpServletRequest request) { + public String registration(@ModelAttribute("userForm") @Valid UserForm userForm, BindingResult bindingResult, HttpServletRequest request) throws ServletException { userValidator.validate(userForm, bindingResult); if (bindingResult.hasErrors()) { diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/users/Scoreboard.java b/webgoat-container/src/main/java/org/owasp/webgoat/users/Scoreboard.java index 0b77b89c6..43801e2db 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/users/Scoreboard.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/users/Scoreboard.java @@ -1,6 +1,5 @@ package org.owasp.webgoat.users; -import com.google.common.collect.Lists; import lombok.AllArgsConstructor; import lombok.Getter; import org.owasp.webgoat.i18n.PluginMessages; @@ -8,6 +7,7 @@ import org.owasp.webgoat.session.Course; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -36,7 +36,7 @@ public class Scoreboard { @GetMapping("/scoreboard-data") public List getRankings() { List allUsers = userRepository.findAll(); - List rankings = Lists.newArrayList(); + List rankings = new ArrayList<>(); for (WebGoatUser user : allUsers) { UserTracker userTracker = userTrackerRepository.findByUser(user.getUsername()); rankings.add(new Ranking(user.getUsername(), challengesSolved(userTracker))); @@ -45,7 +45,7 @@ public class Scoreboard { } private List challengesSolved(UserTracker userTracker) { - List challenges = Lists.newArrayList("Challenge1", "Challenge2", "Challenge3", "Challenge4", "Challenge5", "Challenge6", "Challenge7", "Challenge8", "Challenge9"); + List challenges = List.of("Challenge1", "Challenge2", "Challenge3", "Challenge4", "Challenge5", "Challenge6", "Challenge7", "Challenge8", "Challenge9"); return challenges.stream() .map(c -> userTracker.getLessonTracker(c)) .filter(l -> l.isPresent()).map(l -> l.get()) diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserForm.java b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserForm.java index e2062cbdd..e88ea5c47 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserForm.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserForm.java @@ -16,14 +16,14 @@ import javax.validation.constraints.Size; public class UserForm { @NotNull - @Size(min=6, max=20) - @Pattern(regexp = "[a-zA-Z0-9-]*", message = "can only contain letters, digits, and -") + @Size(min = 6, max = 45) + @Pattern(regexp = "[a-z0-9-]*", message = "can only contain lowercase letters, digits, and -") private String username; @NotNull - @Size(min=6, max=10) + @Size(min = 6, max = 10) private String password; @NotNull - @Size(min=6, max=10) + @Size(min = 6, max = 10) private String matchingPassword; @NotNull private String agree; diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserService.java b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserService.java index 932dc6e98..3b7825dce 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserService.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserService.java @@ -30,16 +30,28 @@ public class UserService implements UserDetailsService { } public void addUser(String username, String password) { + //get user if there exists one by the name + WebGoatUser webGoatUser = userRepository.findByUsername(username); + //if user exists it will be updated, otherwise created userRepository.save(new WebGoatUser(username, password)); - userTrackerRepository.save(new UserTracker(username)); + //if user previously existed it will not get another tracker + if (webGoatUser == null) { + userTrackerRepository.save(new UserTracker(username)); + } } public void addUser(String username, String password, String role) { - userRepository.save(new WebGoatUser(username,password,role)); - userTrackerRepository.save(new UserTracker(username)); + //get user if there exists one by the name + WebGoatUser webGoatUser = userRepository.findByUsername(username); + //if user exists it will be updated, otherwise created + userRepository.save(new WebGoatUser(username, password, role)); + //if user previously existed it will not get another tracker + if (webGoatUser == null) { + userTrackerRepository.save(new UserTracker(username)); + } } - public List getAllUsers () { + public List getAllUsers() { return userRepository.findAll(); } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserTracker.java b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserTracker.java index 1cc4920ea..eabc9fa68 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserTracker.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserTracker.java @@ -1,14 +1,12 @@ package org.owasp.webgoat.users; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import lombok.extern.slf4j.Slf4j; -import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Lesson; import org.owasp.webgoat.lessons.Assignment; import javax.persistence.*; -import java.util.List; +import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -55,7 +53,7 @@ public class UserTracker { @Column(name = "username") private String user; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - private Set lessonTrackers = Sets.newHashSet(); + private Set lessonTrackers = new HashSet<>(); private UserTracker() {} @@ -69,7 +67,7 @@ public class UserTracker { * @param lesson the lesson * @return a lesson tracker created if not already present */ - public LessonTracker getLessonTracker(AbstractLesson lesson) { + public LessonTracker getLessonTracker(Lesson lesson) { Optional lessonTracker = lessonTrackers .stream().filter(l -> l.getLessonName().equals(lesson.getId())).findFirst(); if (!lessonTracker.isPresent()) { @@ -91,18 +89,18 @@ public class UserTracker { return lessonTrackers.stream().filter(l -> l.getLessonName().equals(id)).findFirst(); } - public void assignmentSolved(AbstractLesson lesson, String assignmentName) { + public void assignmentSolved(Lesson lesson, String assignmentName) { LessonTracker lessonTracker = getLessonTracker(lesson); lessonTracker.incrementAttempts(); lessonTracker.assignmentSolved(assignmentName); } - public void assignmentFailed(AbstractLesson lesson) { + public void assignmentFailed(Lesson lesson) { LessonTracker lessonTracker = getLessonTracker(lesson); lessonTracker.incrementAttempts(); } - public void reset(AbstractLesson al) { + public void reset(Lesson al) { LessonTracker lessonTracker = getLessonTracker(al); lessonTracker.reset(); } diff --git a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserValidator.java b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserValidator.java index b0a46b4d6..ce63a3ef7 100644 --- a/webgoat-container/src/main/java/org/owasp/webgoat/users/UserValidator.java +++ b/webgoat-container/src/main/java/org/owasp/webgoat/users/UserValidator.java @@ -16,8 +16,8 @@ public class UserValidator implements Validator { private final UserRepository userRepository; @Override - public boolean supports(Class aClass) { - return UserForm.class.equals(aClass); + public boolean supports(Class clazz) { + return UserForm.class.equals(clazz); } @Override diff --git a/webgoat-container/src/main/resources/application.properties b/webgoat-container/src/main/resources/application-webgoat.properties similarity index 59% rename from webgoat-container/src/main/resources/application.properties rename to webgoat-container/src/main/resources/application-webgoat.properties index ba8b75afc..7b6acee6e 100644 --- a/webgoat-container/src/main/resources/application.properties +++ b/webgoat-container/src/main/resources/application-webgoat.properties @@ -1,26 +1,32 @@ server.error.include-stacktrace=always server.error.path=/error.html -server.session.timeout=600 -server.contextPath=/WebGoat -server.port=8080 -server.address=127.0.0.1 +server.servlet.context-path=/WebGoat +server.servlet.session.persistent=false +server.port=${WEBGOAT_PORT:8080} +server.address=${WEBGOAT_HOST:127.0.0.1} -spring.datasource.url=jdbc:hsqldb:hsql://localhost:9001/webgoat -spring.jpa.hibernate.ddl-auto=update + +server.ssl.key-store-type=${WEBGOAT_KEYSTORE_TYPE:PKCS12} +server.ssl.key-store=${WEBGOAT_KEYSTORE:classpath:goatkeystore.pkcs12} +server.ssl.key-store-password=${WEBGOAT_KEYSTORE_PASSWORD:password} +server.ssl.key-alias=${WEBGOAT_KEY_ALIAS:goat} +server.ssl.enabled=${WEBGOAT_SSLENABLED:false} + +hsqldb.port=${WEBGOAT_HSQLPORT:9001} +spring.datasource.url=jdbc:hsqldb:hsql://${server.address}:${hsqldb.port}/webgoat spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.HSQLDialect spring.datasource.driver-class-name=org.hsqldb.jdbc.JDBCDriver +spring.jpa.properties.hibernate.default_schema=CONTAINER - +logging.level.org.thymeleaf=INFO +logging.level.org.thymeleaf.TemplateEngine.CONFIG=INFO +logging.level.org.thymeleaf.TemplateEngine.TIMER=INFO +logging.level.org.thymeleaf.TemplateEngine.cache.TEMPLATE_CACHE=INFO +logging.level.org.springframework.web=INFO logging.level.org.springframework=INFO logging.level.org.springframework.boot.devtools=INFO logging.level.org.owasp=DEBUG -logging.level.org.owasp.webgoat=TRACE - -# Needed for creating a vulnerable web application -security.enable-csrf=false - -spring.resources.cache-period=0 -spring.thymeleaf.cache=false +logging.level.org.owasp.webgoat=DEBUG webgoat.start.hsqldb=true webgoat.clean=false @@ -32,11 +38,10 @@ webgoat.email=webgoat@owasp.org webgoat.emaillist=owasp-webgoat@lists.owasp.org webgoat.feedback.address=webgoat@owasp.org webgoat.feedback.address.html=webgoat@owasp.org -webgoat.database.driver=org.hsqldb.jdbcDriver webgoat.database.connection.string=jdbc:hsqldb:mem:{USER} webgoat.default.language=en -webwolf.host=${WEBWOLF_HOST:localhost} +webwolf.host=${WEBWOLF_HOST:127.0.0.1} webwolf.port=${WEBWOLF_PORT:9090} webwolf.url=http://${webwolf.host}:${webwolf.port}/WebWolf webwolf.url.landingpage=http://${webwolf.host}:${webwolf.port}/landing diff --git a/webgoat-container/src/main/resources/db/container/V1__init.sql b/webgoat-container/src/main/resources/db/container/V1__init.sql new file mode 100644 index 000000000..176eef387 --- /dev/null +++ b/webgoat-container/src/main/resources/db/container/V1__init.sql @@ -0,0 +1,64 @@ +CREATE SCHEMA CONTAINER; + +CREATE SEQUENCE CONTAINER.HIBERNATE_SEQUENCE AS INTEGER START WITH 1; + +CREATE TABLE CONTAINER.ASSIGNMENT ( + ID BIGINT NOT NULL PRIMARY KEY, + NAME VARCHAR(255), + PATH VARCHAR(255) +); + +CREATE TABLE CONTAINER.LESSON_TRACKER( + ID BIGINT NOT NULL PRIMARY KEY, + LESSON_NAME VARCHAR(255), + NUMBER_OF_ATTEMPTS INTEGER NOT NULL +); + +CREATE TABLE CONTAINER.LESSON_TRACKER_ALL_ASSIGNMENTS( + LESSON_TRACKER_ID BIGINT NOT NULL, + ALL_ASSIGNMENTS_ID BIGINT NOT NULL, + PRIMARY KEY(LESSON_TRACKER_ID,ALL_ASSIGNMENTS_ID), + CONSTRAINT FKNHIDKE27BCJHI8C7WJ9QW6Y3Q FOREIGN KEY(ALL_ASSIGNMENTS_ID) REFERENCES CONTAINER.ASSIGNMENT(ID), + CONSTRAINT FKBM51QSDJ7N17O2DNATGAMW7D FOREIGN KEY(LESSON_TRACKER_ID) REFERENCES CONTAINER.LESSON_TRACKER(ID), + CONSTRAINT UK_SYGJY2S8O8DDGA2K5YHBMUVEA UNIQUE(ALL_ASSIGNMENTS_ID) +); + +CREATE TABLE CONTAINER.LESSON_TRACKER_SOLVED_ASSIGNMENTS( + LESSON_TRACKER_ID BIGINT NOT NULL, + SOLVED_ASSIGNMENTS_ID BIGINT NOT NULL, + PRIMARY KEY(LESSON_TRACKER_ID,SOLVED_ASSIGNMENTS_ID), + CONSTRAINT FKPP850U1MG09YKKL2EQGM0TRJK FOREIGN KEY(SOLVED_ASSIGNMENTS_ID) REFERENCES CONTAINER.ASSIGNMENT(ID), + CONSTRAINT FKNKRWGA1UHLOQ6732SQXHXXSCR FOREIGN KEY(LESSON_TRACKER_ID) REFERENCES CONTAINER.LESSON_TRACKER(ID), + CONSTRAINT UK_9WFYDUY3TVE1XD05LWOUEG0C1 UNIQUE(SOLVED_ASSIGNMENTS_ID) +); + +CREATE TABLE CONTAINER.USER_TRACKER( + ID BIGINT NOT NULL PRIMARY KEY, + USERNAME VARCHAR(255) +); + +CREATE TABLE CONTAINER.USER_TRACKER_LESSON_TRACKERS( + USER_TRACKER_ID BIGINT NOT NULL, + LESSON_TRACKERS_ID BIGINT NOT NULL, + PRIMARY KEY(USER_TRACKER_ID,LESSON_TRACKERS_ID), + CONSTRAINT FKQJSTCA3YND3OHP35D50PNUH3H FOREIGN KEY(LESSON_TRACKERS_ID) REFERENCES CONTAINER.LESSON_TRACKER(ID), + CONSTRAINT FKC9GX8INK7LRC79XC77O2MN9KE FOREIGN KEY(USER_TRACKER_ID) REFERENCES CONTAINER.USER_TRACKER(ID), + CONSTRAINT UK_5D8N5I3IC26CVF7DF7N95DOJB UNIQUE(LESSON_TRACKERS_ID) +); + +CREATE TABLE CONTAINER.WEB_GOAT_USER( + USERNAME VARCHAR(255) NOT NULL PRIMARY KEY, + PASSWORD VARCHAR(255), + ROLE VARCHAR(255) +); + +CREATE TABLE CONTAINER.EMAIL( + ID BIGINT GENERATED BY DEFAULT AS IDENTITY(START WITH 1) NOT NULL PRIMARY KEY, + CONTENTS VARCHAR(1024), + RECIPIENT VARCHAR(255), + SENDER VARCHAR(255), + TIME TIMESTAMP, + TITLE VARCHAR(255) +); + +ALTER TABLE CONTAINER.EMAIL ALTER COLUMN ID RESTART WITH 2; \ No newline at end of file diff --git a/webgoat-container/src/main/resources/db/container/V2__version.sql b/webgoat-container/src/main/resources/db/container/V2__version.sql new file mode 100644 index 000000000..3d7a8908a --- /dev/null +++ b/webgoat-container/src/main/resources/db/container/V2__version.sql @@ -0,0 +1 @@ +ALTER TABLE CONTAINER.LESSON_TRACKER ADD VERSION INTEGER; diff --git a/webgoat-container/src/main/resources/goatkeystore.pkcs12 b/webgoat-container/src/main/resources/goatkeystore.pkcs12 new file mode 100644 index 000000000..c7e335790 Binary files /dev/null and b/webgoat-container/src/main/resources/goatkeystore.pkcs12 differ diff --git a/webgoat-container/src/main/resources/static/css/main.css b/webgoat-container/src/main/resources/static/css/main.css index 59f674616..27a4e6d83 100644 --- a/webgoat-container/src/main/resources/static/css/main.css +++ b/webgoat-container/src/main/resources/static/css/main.css @@ -1001,9 +1001,15 @@ cookie-container { margin: 3px; } +@keyframes blink { + 50% { border-color: white; } +} + .cur-page { - border-bottom: 2px solid #000; + animation: blink 1.5s 2 forwards; + border: 3px solid blue; color:#aaa; + background-color: lightsalmon; } span.show-next-page, span.show-prev-page { diff --git a/webgoat-container/src/main/resources/templates/main_new.html b/webgoat-container/src/main/resources/templates/main_new.html index eadb722c3..edde993ab 100644 --- a/webgoat-container/src/main/resources/templates/main_new.html +++ b/webgoat-container/src/main/resources/templates/main_new.html @@ -28,15 +28,15 @@ - - WebGoat @@ -67,8 +67,7 @@
  • Logout
  • -