Merge branch 'feature/spring-boot' into develop

* feature/spring-boot: (92 commits)
  XXE checkin
  XXE checkin
  XXE first attempt
  HTTP-Basics mark lesson complete issue fixed
  cleaning up some
  fixing the scroll 'sliver' problem. Likely need to check back on this when menu grows again
  lesson pagination fixes mainly, some other fixes included & clean up
  Incremental style changes
  refactor to help accomodate multiple attacks and output in one 'page'
  Updated some of the credits
  double-feedback fix on single page
  commenting out to stop redundant callbacks
  few cleanup items, added least privilege
  Fixed test for password
  First wave is complete; some rendering issues
  Trying to wire up the DB connection and fill out first sql stub
  Fixing hide/show of next/prev buttons
  another stub
  First round of sql injection with stubs
  Give focus to username when loading the login page
  ...

Signed-off-by: Doug Morato <dm@corp.io>

# Conflicts:
#	.travis.yml
#	README.MD
#	pom.xml
#	webgoat-container/pom.xml
#	webgoat-container/src/main/java/org/owasp/webgoat/HammerHead.java
#	webgoat-container/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java
#	webgoat-container/src/main/java/org/owasp/webgoat/lessons/LessonAdapter.java
#	webgoat-container/src/main/java/org/owasp/webgoat/plugins/PluginsLoader.java
#	webgoat-container/src/main/java/org/owasp/webgoat/service/RestartLessonService.java
#	webgoat-container/src/main/java/org/owasp/webgoat/session/WebgoatContext.java
#	webgoat-container/src/main/resources/static/js/goatApp/controller/LessonController.js
#	webgoat-container/src/main/resources/webgoat.properties
#	webgoat-container/src/main/webapp/META-INF/context.xml
#	webgoat-container/src/main/webapp/WEB-INF/context.xml
#	webgoat-container/src/main/webapp/js/goatApp/view/LessonContentView.js
#	webgoat-container/src/test/java/org/owasp/webgoat/plugins/WebGoatIT.java
#	webgoat-container/src/test/resources/log4j.properties
#	webgoat_developer_bootstrap.sh
This commit is contained in:
Doug Morato
2016-11-18 22:37:39 -05:00
371 changed files with 19523 additions and 29109 deletions

View File

@ -1,73 +0,0 @@
package org.owasp.webgoat.session;
import java.util.Hashtable;
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.
*
* * @version $Id: $Id
*
* @author dm
* @version $Id: $Id
*/
public class Authorization
{
Map<Integer, Integer> permissions = new Hashtable<Integer, Integer>();
/**
* <p>Constructor for Authorization.</p>
*/
public Authorization()
{
}
/**
* <p>setPermission.</p>
*
* @param userId a int.
* @param functionId a int.
*/
public void setPermission(int userId, int functionId)
{
permissions.put(new Integer(userId), new Integer(functionId));
}
/**
* <p>isAllowed.</p>
*
* @param userId a int.
* @param functionId a int.
* @return a boolean.
*/
public boolean isAllowed(int userId, int functionId)
{
return (permissions.get(new Integer(userId)) != null);
}
}

View File

@ -1,175 +1,58 @@
package org.owasp.webgoat.session;
import org.owasp.webgoat.HammerHead;
import lombok.extern.slf4j.Slf4j;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.NewLesson;
import org.owasp.webgoat.plugins.Plugin;
import org.owasp.webgoat.plugins.PluginsLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.owasp.webgoat.HammerHead;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.plugins.LegacyLoader;
import org.owasp.webgoat.plugins.Plugin;
import org.owasp.webgoat.plugins.PluginsLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.stream.Collectors.toList;
/**
*************************************************************************************************
*
*
* ************************************************************************************************
* <p>
* <p>
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* <p>
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* <p>
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* <p>
* Getting Source ==============
*
* <p>
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @since October 28, 2003
* @version $Id: $Id
* @since October 28, 2003
*/
@Slf4j
public class Course {
final Logger logger = LoggerFactory.getLogger(Course.class);
private final List<AbstractLesson> lessons = new LinkedList<AbstractLesson>();
private final static String PROPERTIES_FILENAME = HammerHead.propertiesPath;
private WebgoatProperties properties = null;
private WebgoatContext webgoatContext;
/**
* <p>Constructor for Course.</p>
*/
public Course() {
try {
properties = new WebgoatProperties(PROPERTIES_FILENAME);
} catch (IOException e) {
logger.error("Error loading webgoat properties", e);
}
}
/**
* Take an absolute file and return the filename.
*
* Ex. /etc/password becomes password
*
* @param s
* @return the file name
*/
private static String getFileName(String s) {
String fileName = new File(s).getName();
if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf("/"), fileName.length());
}
if (fileName.contains(".")) {
fileName = fileName.substring(0, fileName.indexOf("."));
}
return fileName;
}
/**
* Take a class name and return the equivalent file name
*
* Ex. org.owasp.webgoat becomes org/owasp/webgoat.java
*
* @param className
* @return
*/
private static String getSourceFile(String className) {
StringBuilder sb = new StringBuilder();
sb.append(className.replace(".", "/"));
sb.append(".java");
return sb.toString();
}
/**
* Takes a file name and builds the class file name
*
* @param fileName Description of the Parameter
* @param path Description of the Parameter
* @return Description of the Return Value
*/
private static String getClassFile(String fileName, String path) {
String ext = ".class";
fileName = fileName.trim();
/**
* We do not handle directories. We do not handle files with different
* extensions
*/
if (fileName.endsWith("/") || !fileName.endsWith(ext)) {
return null;
}
// if the file is in /WEB-INF/classes strip the dir info off
int index = fileName.indexOf("/WEB-INF/classes/");
if (index != -1) {
fileName = fileName.substring(index + "/WEB-INF/classes/".length(), fileName.length() - ext.length());
fileName = fileName.replace('/', '.');
fileName = fileName.replace('\\', '.');
} else {
// Strip off the leading path info
fileName = fileName.substring(path.length(), fileName.length() - ext.length());
}
return fileName;
}
private List<AbstractLesson> lessons = new LinkedList<>();
/**
* Gets the categories attribute of the Course object
*
* @return The categories value
*/
public List getCategories() {
List<Category> categories = new ArrayList<Category>();
for (AbstractLesson lesson : lessons) {
if (!categories.contains(lesson.getCategory())) {
categories.add(lesson.getCategory());
}
}
Collections.sort(categories);
return categories;
public List<Category> getCategories() {
return lessons.parallelStream().map(l -> l.getCategory()).distinct().sorted().collect(toList());
}
/**
@ -178,202 +61,46 @@ public class Course {
* @return The firstLesson value
*/
public AbstractLesson getFirstLesson() {
List<String> roles = new ArrayList<String>();
roles.add(AbstractLesson.USER_ROLE);
// 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 ((AbstractLesson) getLessons((Category) getCategories().get(0), roles).get(0));
}
/**
* Gets the lesson attribute of the Course object
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param lessonId Description of the Parameter
* @param roles a {@link java.util.List} object.
* @return The lesson value
*/
public AbstractLesson getLesson(WebSession s, int lessonId, List<String> roles) {
if (s.isHackedAdmin()) {
roles.add(AbstractLesson.HACKED_ADMIN_ROLE);
}
// System.out.println("getLesson() with roles: " + roles);
Iterator<AbstractLesson> iter = lessons.iterator();
while (iter.hasNext()) {
AbstractLesson lesson = iter.next();
if (lesson.getScreenId() == lessonId && roles.contains(lesson.getRole())) {
return lesson;
}
}
return null;
}
/**
* <p>getLesson.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param lessonId a int.
* @param role a {@link java.lang.String} object.
* @return a {@link org.owasp.webgoat.lessons.AbstractLesson} object.
*/
public AbstractLesson getLesson(WebSession s, int lessonId, String role) {
List<String> roles = new ArrayList<String>();
roles.add(role);
return getLesson(s, lessonId, roles);
return getLessons(getCategories().get(0)).get(0);
}
/**
* <p>Getter for the field <code>lessons</code>.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param role a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
*/
public List<AbstractLesson> getLessons(WebSession s, String role) {
List<String> roles = new ArrayList<String>();
roles.add(role);
return getLessons(s, roles);
}
/**
* Gets the lessons attribute of the Course object
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param roles a {@link java.util.List} object.
* @return The lessons value
*/
public List<AbstractLesson> getLessons(WebSession s, List<String> roles) {
if (s.isHackedAdmin()) {
roles.add(AbstractLesson.HACKED_ADMIN_ROLE);
}
List<AbstractLesson> lessonList = new ArrayList<AbstractLesson>();
Iterator categoryIter = getCategories().iterator();
while (categoryIter.hasNext()) {
lessonList.addAll(getLessons(s, (Category) categoryIter.next(), roles));
}
return lessonList;
}
/**
* Gets the lessons attribute of the Course object
*
* @param category Description of the Parameter
* @param role Description of the Parameter
* @return The lessons value
*/
private List<AbstractLesson> getLessons(Category category, List roles) {
List<AbstractLesson> lessonList = new ArrayList<AbstractLesson>();
for (AbstractLesson lesson : lessons) {
if (lesson.getCategory().equals(category) && roles.contains(lesson.getRole())) {
lessonList.add(lesson);
}
}
Collections.sort(lessonList);
return lessonList;
public List<AbstractLesson> getLessons() {
return this.lessons;
}
/**
* <p>Getter for the field <code>lessons</code>.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param category a {@link org.owasp.webgoat.lessons.Category} object.
* @param role a {@link java.lang.String} object.
* @return a {@link java.util.List} object.
*/
public List getLessons(WebSession s, Category category, String role) {
List<String> roles = new ArrayList<String>();
roles.add(role);
return getLessons(s, category, roles);
public List<AbstractLesson> getLessons(Category category) {
return this.lessons.stream().filter(l -> l.getCategory() == category).collect(toList());
}
public void setLessons(List<AbstractLesson> lessons) {
this.lessons = lessons;
}
/**
* <p>Getter for the field <code>lessons</code>.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param category a {@link org.owasp.webgoat.lessons.Category} object.
* @param roles a {@link java.util.List} object.
* @return a {@link java.util.List} object.
* <p>createLessonsFromPlugins.</p>
*/
public List<AbstractLesson> getLessons(WebSession s, Category category, List<String> roles) {
if (s.isHackedAdmin()) {
roles.add(AbstractLesson.HACKED_ADMIN_ROLE);
}
return getLessons(category, roles);
}
/**
* <p>getLesson.</p>
*
* @param lessonId a int.
* @return a {@link org.owasp.webgoat.lessons.AbstractLesson} object.
*/
public AbstractLesson getLesson(int lessonId) {
for (AbstractLesson l : lessons) {
if (l.getScreenId() == lessonId) {
return l;
}
}
return null;
}
/**
* <p>loadLessonFromPlugin.</p>
*
* @param context a {@link javax.servlet.ServletContext} object.
*/
public void loadLessonFromPlugin(ServletContext context) {
logger.debug("Loading plugins into cache");
String pluginPath = context.getRealPath("plugin_lessons");
String targetPath = context.getRealPath("plugin_extracted");
if (pluginPath == null) {
logger.error("Plugins directory {} not found", pluginPath);
return;
}
lessons.clear();
List<Plugin> plugins = new PluginsLoader(Paths.get(pluginPath), Paths.get(targetPath)).loadPlugins();
public void createLessonsFromPlugins(List<Plugin> plugins) {
for (Plugin plugin : plugins) {
try {
AbstractLesson lesson = plugin.getLesson().get();
lesson.setWebgoatContext(webgoatContext);
lesson.update(properties);
if (!lesson.getHidden()) {
lessons.add(lesson);
}
for(Map.Entry<String, File> lessonPlan : plugin.getLessonPlans().entrySet()) {
lesson.setLessonPlanFileName(lessonPlan.getKey(), lessonPlan.getValue().toString());
}
if (plugin.getLessonSolution("en").isPresent()) {
lesson.setLessonSolutionFileName(plugin.getLessonSolution("en").get().toString());
}
if (plugin.getLessonSource().isPresent()) {
lesson.setSourceFileName(plugin.getLessonSource().get().toString());
}
NewLesson lesson = (NewLesson) plugin.getLesson().get();
lesson.setAssignments(plugin.getAssignments());
lessons.add(lesson);
} catch (Exception e) {
logger.error("Error in loadLessons: ", e);
log.error("Error in loadLessons: ", e);
}
}
}
/**
* Description of the Method
*
* @param webgoatContext a {@link org.owasp.webgoat.session.WebgoatContext} object.
* @param path Description of the Parameter
* @param context Description of the Parameter
*/
public void loadCourses(WebgoatContext webgoatContext, ServletContext context, String path) {
logger.info("Loading courses: " + path);
this.webgoatContext = webgoatContext;
loadLessonFromPlugin(context);
LegacyLoader loader = new LegacyLoader();
lessons.addAll(loader.loadLessons(webgoatContext, context, path, properties));
}
}

View File

@ -4,7 +4,6 @@ package org.owasp.webgoat.session;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.AbstractLesson;
/**
@ -759,16 +758,16 @@ public class CreateDB
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 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
+ "')";
// String insertData28 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOLUTION
// + "')";
statement.executeUpdate(insertData1);
statement.executeUpdate(insertData2);
@ -803,9 +802,9 @@ public class CreateDB
statement.executeUpdate(insertData25);
statement.executeUpdate(insertData25_1);
statement.executeUpdate(insertData25_2);
statement.executeUpdate(insertData26);
statement.executeUpdate(insertData27);
statement.executeUpdate(insertData28);
//statement.executeUpdate(insertData26);
//statement.executeUpdate(insertData27);
//statement.executeUpdate(insertData28);
}
private void createOwnershipTable(Connection connection) throws SQLException

View File

@ -1,19 +1,13 @@
package org.owasp.webgoat.session;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.ecs.MultiPartElement;
import org.apache.ecs.html.B;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.springframework.beans.factory.annotation.Autowired;
/**
@ -131,73 +125,5 @@ public class DatabaseUtilities
String url = context.getDatabaseConnectionString().replaceAll("\\$\\{USER\\}", user);
return DriverManager.getConnection(url, "sa", "");
}
/**
* Description of the Method
*
* @param results
* Description of the Parameter
* @param resultsMetaData
* Description of the Parameter
* @param resultsMetaData
* Description of the Parameter
* @param resultsMetaData
* Description of the Parameter
* @param resultsMetaData
* Description of the Parameter
* @param resultsMetaData
* Description of the Parameter
* @param resultsMetaData
* Description of the Parameter
* @return Description of the Return Value
* @exception IOException
* Description of the Exception
* @exception SQLException
* Description of the Exception
* @throws java.io.IOException if any.
* @throws java.sql.SQLException if any.
*/
public static MultiPartElement writeTable(ResultSet results, ResultSetMetaData resultsMetaData) throws IOException,
SQLException
{
int numColumns = resultsMetaData.getColumnCount();
results.beforeFirst();
if (results.next())
{
Table t = new Table(1); // 1 = with border
t.setCellPadding(1);
TR tr = new TR();
for (int i = 1; i < (numColumns + 1); i++)
{
tr.addElement(new TD(new B(resultsMetaData.getColumnName(i))));
}
t.addElement(tr);
results.beforeFirst();
while (results.next())
{
TR row = new TR();
for (int i = 1; i < (numColumns + 1); i++)
{
String str = results.getString(i);
if (str == null) str = "";
row.addElement(new TD(str.replaceAll(" ", "&nbsp;")));
}
t.addElement(row);
}
return (t);
}
else
{
return (new B("Query Successful; however no data was returned from this query."));
}
}
}

View File

@ -1,754 +0,0 @@
package org.owasp.webgoat.session;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.A;
import org.apache.ecs.html.BR;
import org.apache.ecs.html.H3;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.Label;
import org.apache.ecs.html.Option;
import org.apache.ecs.html.P;
import org.apache.ecs.html.Select;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.U;
/**
*************************************************************************************************
*
*
* 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 (jeff.williams@aspectsecurity.com)
* @since October 29, 2003
* @version $Id: $Id
*/
public class ECSFactory
{
/**
* Description of the Field
*/
public final static String ON = "On";
/**
* Description of the Field
*/
public final static String PASSWORD = "Password";
/**
* Don't let anyone instantiate this class
*/
private ECSFactory()
{
}
/**
* Description of the Method
*
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeBox(String name, String value)
{
Input i = new Input(Input.CHECKBOX, name, ON);
i.setChecked(value.equals(ON));
return (i);
}
/**
* Description of the Method
*
* @param text
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeButton(String text)
{
Input b = new Input();
b.setType(Input.SUBMIT);
b.setValue(text);
b.setName(Input.SUBMIT);
return (b);
}
/**
* <p>makeButton.</p>
*
* @param text a {@link java.lang.String} object.
* @param onClickFunction a {@link java.lang.String} object.
* @return a {@link org.apache.ecs.Element} object.
*/
public static Element makeButton(String text, String onClickFunction)
{
Input b = (Input) makeButton(text);
b.setOnClick(onClickFunction);
return (b);
}
/**
* Description of the Method
*
* @param labeltext
* Description of the Parameter
* @param value
* Description of the Parameter
* @param e
* Description of the Parameter
* @return Description of the Return Value
*/
public static TR makeField(String labeltext, String value, Element e)
{
TD left = new TD().setAlign("right");
Label label = new Label().addElement(labeltext);
left.addElement(label);
TD right = new TD().setAlign("left");
right.addElement(e);
TR row = new TR();
row.addElement(left);
row.addElement(right);
return (row);
}
/**
* Description of the Method
*
* @param labeltext
* Description of the Parameter
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @param size
* Description of the Parameter
* @return Description of the Return Value
*/
public static TR makeField(String labeltext, String name, String value, int size)
{
Input field = new Input().setName(name).setValue(value).setSize(size).setMaxlength(size);
// double check in case someone means to make a * starred out password field
if (name.equals(PASSWORD))
{
field.setType(Input.PASSWORD);
}
return (makeField(labeltext, value, field));
}
/**
* Description of the Method
*
* @param label
* Description of the Parameter
* @param type
* Description of the Parameter
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @param alignment
* Description of the Parameter
* @param selected
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeInput(String label, String type, String name, boolean value, boolean selected,
String alignment)
{
return makeInput(label, type, name, new Boolean(value).toString(), selected, alignment);
}
/**
* Description of the Method
*
* @param label
* Description of the Parameter
* @param type
* Description of the Parameter
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeInput(String label, String type, String name, String value)
{
return makeInput(label, type, name, value, new Boolean(value).booleanValue(), "RIGHT");
}
/**
* Description of the Method
*
* @param label
* Description of the Parameter
* @param type
* Description of the Parameter
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @param alignment
* Description of the Parameter
* @param selected
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeInput(String label, String type, String name, String value, boolean selected,
String alignment)
{
ElementContainer ec = new ElementContainer();
if (!alignment.equalsIgnoreCase("LEFT"))
{
ec.addElement(new StringElement(label));
}
Input input = new Input(type, name, value);
ec.addElement(input);
if (alignment.equalsIgnoreCase("LEFT"))
{
ec.addElement(new StringElement(label));
}
if (type.equalsIgnoreCase("CHECKBOX"))
{
input.setChecked(selected);
}
return (ec);
}
/**
* Description of the Method
*
* @param text
* Description of the Parameter
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public static A makeLink(String text, String name, String value)
{
String href = "attack?" + name;
if (value.length() > 0)
{
href = href + "=" + value;
}
A a = new A(href);
a.addElement(new U().addElement(text));
a.addAttribute("style", "cursor:hand");
return (a);
}
/**
* Description of the Method
*
* @param text
* Description of the Parameter
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public static A makeLink(String text, String name, int value)
{
return (makeLink(text, name, Integer.toString(value)));
}
/**
* Description of the Method
*
* @param text
* Description of the Parameter
* @param name
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public static A makeLink(String text, String name, boolean value)
{
return (makeLink(text, name, new Boolean(value).toString()));
}
/**
* Description of the Method
*
* @param text
* Description of the Parameter
* @param clickAction
* Description of the Parameter
* @param type
* Description of the Parameter
* @return Description of the Return Value
*/
public static Input makeOnClickInput(String text, String clickAction, String type)
{
Input b = new Input();
b.setType(type);
b.setValue(text);
b.setOnClick(clickAction);
return (b);
}
/**
* Description of the Method
*
* @param labeltext
* Description of the Parameter
* @param value
* Description of the Parameter
* @param e
* Description of the Parameter
* @return Description of the Return Value
*/
public static TR makeOption(String labeltext, String value, Element e)
{
TD left = new TD().setAlign("left").setWidth("10%");
left.addElement(e);
TD right = new TD().setAlign("right");
Label label = new Label().addElement(labeltext);
right.addElement(label);
TR row = new TR();
row.addElement(right);
row.addElement(left);
return (row);
}
/**
* Description of the Method
*
* @param label
* Description of the Parameter
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public static Option makeOption(String label, boolean value)
{
Option option = new Option(label, new Boolean(value).toString());
option.setSelected(value);
return option;
}
/**
* Description of the Method
*
* @param line
* Description of the Parameter
* @return Description of the Return Value
*/
private static org.apache.ecs.html.Option makeOption(String line)
{
StringTokenizer st = new StringTokenizer(line, "|");
org.apache.ecs.html.Option o = new org.apache.ecs.html.Option();
String token = "";
if (st.hasMoreTokens())
{
token = st.nextToken();
}
o.addElement(token);
return (o);
}
/**
* Description of the Method
*
* @param name
* Description of the Parameter
* @param options
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makePulldown(String name, List<String> options)
{
Select s = new Select(name);
s.addElement(options.toArray(new String[options.size()]));
return (s);
}
/**
* Description of the Method
*
* @param results
* Description of the Parameter
* @return Description of the Return Value
* @param name a {@link java.lang.String} object.
*/
public static Element makePulldown(String name, String results)
{
Select select = new Select(name);
StringTokenizer st = new StringTokenizer(results, "\n");
if (!st.hasMoreTokens()) {
return (new StringElement("")); }
while (st.hasMoreTokens())
{
String line = st.nextToken();
select.addElement(makeOption(line));
}
select.addElement("-------------------------");
return (select);
}
/**
* Description of the Method
*
* @param name
* Description of the Parameter
* @param list
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param rowsShowing
* Description of the Parameter
* @return Description of the Return Value
*/
public static Select makePulldown(String name, Object[] list, String selected, int rowsShowing)
{
Select select = new Select(name);
for (int loop = 0; loop < list.length; loop++)
{
String value = list[loop].toString();
org.apache.ecs.html.Option o = new org.apache.ecs.html.Option(value, value, value);
if (value.equals(selected))
{
o.setSelected(true);
}
select.addElement(o);
}
select.setSize(rowsShowing);
return select;
}
/**
* Default size of 1 for rows showing in select box.
*
* @param diffNames
* Description of the Parameter
* @param select
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param name
* Description of the Parameter
* @param options
* Description of the Parameter
* @param list
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeSelect(boolean diffNames, Select select, String name, Vector<Option> options,
String[] list, String selected)
{
return makeSelect(diffNames, select, name, options, list, selected, 1);
}
/**
* Description of the Method
*
* @param diffNames
* Description of the Parameter
* @param select
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param name
* Description of the Parameter
* @param options
* Description of the Parameter
* @param list
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param selected
* Description of the Parameter
* @param rowsShowing
* Description of the Parameter
* @return Description of the Return Value
*/
public static Select makeSelect(boolean diffNames, Select select, String name, Vector<Option> options,
String[] list, String selected, int rowsShowing)
{
if (select == null)
{
select = new Select(name);
if (diffNames)
{
for (int loop = 0; loop < list.length; loop += 2)
{
String value = list[loop];
String label = list[loop + 1];
Option o = new Option(value);
if (loop == 0)
{
o.setSelected(true);
}
options.addElement(o);// add to Vector containing all options
select.addElement(o);
select.addElement(label);
}
}
else
{
for (int loop = 0; loop < list.length; loop++)
{
String value = list[loop];
org.apache.ecs.html.Option o = new org.apache.ecs.html.Option(value);
if (loop == 0)
{
o.setSelected(true);
}
options.addElement(o);// add to Vector containing all options
select.addElement(o);
select.addElement(value);
}
}
}
// find selected option and set selected
Iterator i = options.iterator();
while (i.hasNext())
{
org.apache.ecs.html.Option o = (org.apache.ecs.html.Option) i.next();
if (selected.equalsIgnoreCase(o.getAttribute("value")))
{
o.setSelected(true);
}
}
select.setSize(rowsShowing);
return (select);
}
/**
* Description of the Method
*
* @param title
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeTallHeader(String title)
{
StringBuffer buff = new StringBuffer();
for (int i = 0; i < title.length(); i++)
{
buff.append(title.charAt(i));
buff.append("<BR>");
}
return new TH(buff.toString());
}
/**
* Description of the Method
*
* @param title
* Description of the Parameter
* @param text
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeTextArea(String title, String text)
{
ElementContainer ec = new ElementContainer();
ec.addElement(new BR());
ec.addElement(new H3().addElement(title));
ec.addElement(new P());
ec.addElement("<CENTER><TEXTAREA ROWS=10 COLS=90 READONLY>" + text + "</TEXTAREA></CENTER>");
ec.addElement(new BR());
ec.addElement(new BR());
return (ec);
}
}

View File

@ -1,283 +0,0 @@
package org.owasp.webgoat.session;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.HtmlColor;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.Div;
import org.apache.ecs.html.Form;
import org.apache.ecs.html.H2;
import org.apache.ecs.html.Small;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
/**
*************************************************************************************************
*
*
* 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 <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @since November 4, 2003
* @version $Id: $Id
*/
public class ErrorScreen extends Screen
{
/**
* Description of the Field
*/
protected Throwable error;
/**
* Description of the Field
*/
protected String message;
/**
* Constructor for the ErrorScreen object
*
* @param s
* Description of the Parameter
* @param t
* Description of the Parameter
*/
public ErrorScreen(WebSession s, Throwable t)
{
this.error = t;
fixCurrentScreen(s);
setup(s);
}
/**
* Constructor for the ErrorScreen object
*
* @param s
* Description of the Parameter
* @param msg
* Description of the Parameter
*/
public ErrorScreen(WebSession s, String msg)
{
this.message = msg;
fixCurrentScreen(s);
setup(s);
}
/**
* <p>fixCurrentScreen.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
*/
public void fixCurrentScreen(WebSession s)
{
// So the user can't get stuck on the error screen, reset the
// current screen to something known
if (s != null)
{
try
{
s.setCurrentScreen(s.getCourse().getFirstLesson().getScreenId());
} catch (Throwable t)
{
s.setCurrentScreen(WebSession.WELCOME);
}
}
}
/**
* <p>setup.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
*/
public void setup(WebSession s)
{
// call createContent first so messages will go somewhere
Form form = new Form("attack", Form.POST).setName("form").setEncType("");
form.addElement(wrapForm(s));
TD lowerright = new TD().setHeight("100%").setVAlign("top").setAlign("left").addElement(form);
TR row = new TR().addElement(lowerright);
Table layout = new Table().setBgColor(HtmlColor.WHITE).setCellSpacing(0).setCellPadding(0).setBorder(0);
layout.addElement(row);
setContent(layout);
}
/**
* <p>wrapForm.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link org.apache.ecs.Element} object.
*/
protected Element wrapForm(WebSession s)
{
if (s == null) { return new StringElement("Invalid Session"); }
Table container = new Table().setWidth("100%").setCellSpacing(10).setCellPadding(0).setBorder(0);
// CreateContent can generate error messages so you MUST call it before makeMessages()
Element content = createContent(s);
container.addElement(new TR().addElement(new TD().setColSpan(2).setVAlign("TOP").addElement(makeMessages(s))));
container.addElement(new TR().addElement(new TD().setColSpan(2).addElement(content)));
container.addElement(new TR());
return (container);
}
/**
* {@inheritDoc}
*
* Description of the Method
*/
protected Element createContent(WebSession s)
{
System.out.println("errorscreen createContent Error:" + this.error + " message:" + this.message);
Element content;
if (this.error != null)
{
content = createContent(this.error);
}
else if (this.message != null)
{
content = createContent(this.message);
}
else
{
content = new StringElement("An unknown error occurred.");
}
return content;
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(String s)
{
StringElement list = new StringElement(s);
return (list);
}
/**
* Description of the Method
*
* @param t
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(Throwable t)
{
StringElement list = new StringElement();
list.addElement(new H2().addElement(new StringElement("Error Message: " + t.getMessage())));
list.addElement(formatStackTrace(t));
if (t instanceof ServletException)
{
Throwable root = ((ServletException) t).getRootCause();
if (root != null)
{
list.addElement(new H2().addElement(new StringElement("Root Message: " + root.getMessage())));
list.addElement(formatStackTrace(root));
}
}
return (new Small().addElement(list));
}
/**
* Description of the Method
*
* @param t
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element formatStackTrace(Throwable t)
{
String trace = getStackTrace(t);
StringElement list = new StringElement();
StringTokenizer st = new StringTokenizer(trace, "\r\n\t");
while (st.hasMoreTokens())
{
String line = st.nextToken();
list.addElement(new Div(line));
}
return (list);
}
/**
* Gets the stackTrace attribute of the ErrorScreen class
*
* @param t
* Description of the Parameter
* @return The stackTrace value
*/
public static String getStackTrace(Throwable t)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(bytes, true);
t.printStackTrace(writer);
return (bytes.toString());
}
/**
* Gets the title attribute of the ErrorScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Error");
}
/**
* <p>getRole.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getRole()
{
return AbstractLesson.USER_ROLE;
}
}

View File

@ -1,83 +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.
*
* Represents a virtual session for a lesson. Lesson-specific session data may be stored here.
*
* @author David Anderson <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @since January 19, 2006
* @version $Id: $Id
*/
public class LessonSession
{
private boolean isAuthenticated = false;
private String currentLessonScreen;
/**
* <p>setAuthenticated.</p>
*
* @param isAuthenticated a boolean.
*/
public void setAuthenticated(boolean isAuthenticated)
{
this.isAuthenticated = isAuthenticated;
}
/**
* <p>isAuthenticated.</p>
*
* @return a boolean.
*/
public boolean isAuthenticated()
{
return this.isAuthenticated;
}
/**
* <p>Setter for the field <code>currentLessonScreen</code>.</p>
*
* @param currentLessonScreen a {@link java.lang.String} object.
*/
public void setCurrentLessonScreen(String currentLessonScreen)
{
this.currentLessonScreen = currentLessonScreen;
}
/**
* <p>Getter for the field <code>currentLessonScreen</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getCurrentLessonScreen()
{
return this.currentLessonScreen;
}
}

View File

@ -1,435 +1,82 @@
package org.owasp.webgoat.session;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Properties;
import com.google.common.collect.Sets;
import org.owasp.webgoat.lessons.AbstractLesson;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
*************************************************************************************************
*
*
* ************************************************************************************************
* <p>
* <p>
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* <p>
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* <p>
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* <p>
* Getting Source ==============
*
* <p>
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @since October 29, 2003
* @version $Id: $Id
* @since October 29, 2003
*/
public class LessonTracker
{
public class LessonTracker implements Serializable {
private static final long serialVersionUID = 5410058267505412928L;
private final List<String> assignments;
private final Set<String> solvedAssignments = Sets.newHashSet();
private int numberOfAttempts = 0;
private boolean completed = false;
public LessonTracker(AbstractLesson lesson) {
this.assignments = lesson.getAssignments().stream().map(a -> a.getSimpleName()).collect(Collectors.toList());
}
private int maxHintLevel = 0;
/**
* Mark an assingment as solved
*
* @param solvedAssignment the assignment which the user solved
*/
public void assignmentSolved(String solvedAssignment) {
solvedAssignments.add(solvedAssignment);
}
private int numVisits = 0;
/**
* @return did they user solved all assignments for the lesson?
*/
public boolean isLessonSolved() {
return solvedAssignments.size() == assignments.size();
}
private boolean viewedCookies = false;
/**
* Increase the number attempts to solve the lesson
*/
public void incrementAttempts() {
numberOfAttempts++;
}
private boolean viewedHtml = false;
private boolean viewedLessonPlan = false;
private boolean viewedParameters = false;
private boolean viewedSource = false;
private boolean viewedSolution = false;
Properties lessonProperties = new Properties();
/**
* Gets the completed attribute of the LessonTracker object
*
* @return The completed value
*/
public boolean getCompleted()
{
return completed;
}
/**
* Gets the maxHintLevel attribute of the LessonTracker object
*
* @return The maxHintLevel value
*/
public int getMaxHintLevel()
{
return maxHintLevel;
}
/**
* Gets the numVisits attribute of the LessonTracker object
*
* @return The numVisits value
*/
public int getNumVisits()
{
return numVisits;
}
/**
* Gets the viewedCookies attribute of the LessonTracker object
*
* @return The viewedCookies value
*/
public boolean getViewedCookies()
{
return viewedCookies;
}
/**
* Gets the viewedHtml attribute of the LessonTracker object
*
* @return The viewedHtml value
*/
public boolean getViewedHtml()
{
return viewedHtml;
}
/**
* Gets the viewedLessonPlan attribute of the LessonTracker object
*
* @return The viewedLessonPlan value
*/
public boolean getViewedLessonPlan()
{
return viewedLessonPlan;
}
/**
* Gets the viewedParameters attribute of the LessonTracker object
*
* @return The viewedParameters value
*/
public boolean getViewedParameters()
{
return viewedParameters;
}
/**
* Gets the viewedSource attribute of the LessonTracker object
*
* @return The viewedSource value
*/
public boolean getViewedSource()
{
return viewedSource;
}
/**
* <p>Getter for the field <code>viewedSolution</code>.</p>
*
* @return a boolean.
*/
public boolean getViewedSolution()
{
return viewedSource;
}
/**
* Description of the Method
*/
public void incrementNumVisits()
{
numVisits++;
}
/**
* Sets the properties attribute of the LessonTracker object
*
* @param props
* The new properties value
* @param screen a {@link org.owasp.webgoat.session.Screen} object.
*/
protected void setProperties(Properties props, Screen screen)
{
completed = Boolean.valueOf(props.getProperty(screen.getTitle() + ".completed")).booleanValue();
maxHintLevel = Integer.parseInt(props.getProperty(screen.getTitle() + ".maxHintLevel", "0"));
numVisits = Integer.parseInt(props.getProperty(screen.getTitle() + ".numVisits", "0"));
viewedCookies = Boolean.valueOf(props.getProperty(screen.getTitle() + ".viewedCookies", "false")).booleanValue();
viewedHtml = Boolean.valueOf(props.getProperty(screen.getTitle() + ".viewedHtml", "false")).booleanValue();
viewedLessonPlan = Boolean.valueOf(props.getProperty(screen.getTitle() + ".viewedLessonPlan", "false")).booleanValue();
viewedParameters = Boolean.valueOf(props.getProperty(screen.getTitle() + ".viewedParameters", "false")).booleanValue();
viewedSource = Boolean.valueOf(props.getProperty(screen.getTitle() + ".viewedSource", "false")).booleanValue();
}
/**
* <p>getUserDir.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public static String getUserDir(WebSession s)
{
return s.getContext().getRealPath("users") + "/";
}
private static String getTrackerFile(WebSession s, String user, Screen screen)
{
return getUserDir(s) + user + "." + screen.getClass().getName() + ".props";
}
/**
* Description of the Method
*
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
* @param user a {@link java.lang.String} object.
*/
public static LessonTracker load(WebSession s, String user, Screen screen)
{
FileInputStream in = null;
try
{
String fileName = getTrackerFile(s, user, screen);
if (fileName != null)
{
Properties tempProps = new Properties();
// System.out.println("Loading lesson state from: " + fileName);
in = new FileInputStream(fileName);
tempProps.load(in);
// allow the screen to use any custom properties it may have set
LessonTracker tempLessonTracker = screen.createLessonTracker(tempProps);
tempLessonTracker.setProperties(tempProps, screen);
return tempLessonTracker;
}
} catch (FileNotFoundException e)
{
// Normal if the lesson has not been accessed yet.
} catch (Exception e)
{
System.out.println("Failed to load lesson state for " + screen);
e.printStackTrace();
} finally
{
try
{
in.close();
} catch (Exception e)
{
}
}
return screen.createLessonTracker();
}
/**
* Sets the completed attribute of the LessonTracker object
*
* @param completed
* The new completed value
*/
public void setCompleted(boolean completed)
{
this.completed = completed;
}
/**
* Sets the maxHintLevel attribute of the LessonTracker object
*
* @param maxHintLevel
* The new maxHintLevel value
*/
public void setMaxHintLevel(int maxHintLevel)
{
this.maxHintLevel = Math.max(this.maxHintLevel, maxHintLevel);
}
/**
* Sets the viewedCookies attribute of the LessonTracker object
*
* @param viewedCookies
* The new viewedCookies value
*/
public void setViewedCookies(boolean viewedCookies)
{
this.viewedCookies = viewedCookies;
}
/**
* Sets the viewedHtml attribute of the LessonTracker object
*
* @param viewedHtml
* The new viewedHtml value
*/
public void setViewedHtml(boolean viewedHtml)
{
this.viewedHtml = viewedHtml;
}
/**
* Sets the viewedLessonPlan attribute of the LessonTracker object
*
* @param viewedLessonPlan
* The new viewedLessonPlan value
*/
public void setViewedLessonPlan(boolean viewedLessonPlan)
{
this.viewedLessonPlan = viewedLessonPlan;
}
/**
* Sets the viewedParameters attribute of the LessonTracker object
*
* @param viewedParameters
* The new viewedParameters value
*/
public void setViewedParameters(boolean viewedParameters)
{
this.viewedParameters = viewedParameters;
}
/**
* Sets the viewedSource attribute of the LessonTracker object
*
* @param viewedSource
* The new viewedSource value
*/
public void setViewedSource(boolean viewedSource)
{
this.viewedSource = viewedSource;
}
/**
* Sets the viewedSource attribute of the LessonTracker object
*
* @param viewedSolution a boolean.
*/
public void setViewedSolution(boolean viewedSolution)
{
this.viewedSolution = viewedSolution;
}
/**
* Allows the storing of properties for the logged in and a screen.
*
* @param s
* Description of the Parameter
* @param screen a {@link org.owasp.webgoat.session.Screen} object.
* @param screen a {@link org.owasp.webgoat.session.Screen} object.
*/
public void store(WebSession s, Screen screen)
{
store(s, screen, s.getUserName());
}
/**
* Allows the storing of properties for a user and a screen.
*
* @param s
* Description of the Parameter
* @param screen a {@link org.owasp.webgoat.session.Screen} object.
* @param screen a {@link org.owasp.webgoat.session.Screen} object.
* @param user a {@link java.lang.String} object.
*/
public void store(WebSession s, Screen screen, String user)
{
FileOutputStream out = null;
String fileName = getTrackerFile(s, user, screen);
// System.out.println( "Storing data to" + fileName );
lessonProperties.setProperty(screen.getTitle() + ".completed", Boolean.toString(completed));
lessonProperties.setProperty(screen.getTitle() + ".maxHintLevel", Integer.toString(maxHintLevel));
lessonProperties.setProperty(screen.getTitle() + ".numVisits", Integer.toString(numVisits));
lessonProperties.setProperty(screen.getTitle() + ".viewedCookies", Boolean.toString(viewedCookies));
lessonProperties.setProperty(screen.getTitle() + ".viewedHtml", Boolean.toString(viewedHtml));
lessonProperties.setProperty(screen.getTitle() + ".viewedLessonPlan", Boolean.toString(viewedLessonPlan));
lessonProperties.setProperty(screen.getTitle() + ".viewedParameters", Boolean.toString(viewedParameters));
lessonProperties.setProperty(screen.getTitle() + ".viewedSource", Boolean.toString(viewedSource));
try
{
out = new FileOutputStream(fileName);
lessonProperties.store(out, s.getUserName());
} catch (Exception e)
{
// what do we want to do, I think nothing.
System.out.println("Warning User data for " + s.getUserName() + " will not persist");
} finally
{
try
{
out.close();
} catch (Exception e)
{
}
}
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public String toString()
{
StringBuffer buff = new StringBuffer();
buff.append("LessonTracker:" + "\n");
buff.append(" - completed:.......... " + completed + "\n");
buff.append(" - maxHintLevel:....... " + maxHintLevel + "\n");
buff.append(" - numVisits:.......... " + numVisits + "\n");
buff.append(" - viewedCookies:...... " + viewedCookies + "\n");
buff.append(" - viewedHtml:......... " + viewedHtml + "\n");
buff.append(" - viewedLessonPlan:... " + viewedLessonPlan + "\n");
buff.append(" - viewedParameters:... " + viewedParameters + "\n");
buff.append(" - viewedSource:....... " + viewedSource + "\n" + "\n");
return buff.toString();
}
/**
* <p>Getter for the field <code>lessonProperties</code>.</p>
*
* @return Returns the lessonProperties.
*/
public Properties getLessonProperties()
{
return lessonProperties;
}
/**
* <p>Setter for the field <code>lessonProperties</code>.</p>
*
* @param lessonProperties
* The lessonProperties to set.
*/
public void setLessonProperties(Properties lessonProperties)
{
this.lessonProperties = lessonProperties;
}
/**
* Reset the tracker. We do not reset the number of attempts here!
*/
void reset() {
solvedAssignments.clear();
}
}

View File

@ -1,111 +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.
*
* @version $Id: $Id
* @author dm
*/
public class Parameter implements Comparable
{
String name;
String value;
/**
* <p>Constructor for Parameter.</p>
*
* @param name a {@link java.lang.String} object.
* @param value a {@link java.lang.String} object.
*/
public Parameter(String name, String value)
{
this.name = name;
this.value = value;
}
/**
* <p>Getter for the field <code>name</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getName()
{
return name;
}
/**
* <p>Getter for the field <code>value</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getValue()
{
return value;
}
// @Override
/** {@inheritDoc} */
public boolean equals(Object obj)
{
if (obj instanceof Parameter)
{
Parameter other = (Parameter) obj;
return (name.equals(other.getName()) && value.equals(other.getValue()));
}
return false;
}
// @Override
/**
* <p>hashCode.</p>
*
* @return a int.
*/
public int hashCode()
{
return toString().hashCode();
}
// @Override
/**
* <p>toString.</p>
*
* @return a {@link java.lang.String} object.
*/
public String toString()
{
return (name + "=" + value);
}
/** {@inheritDoc} */
public int compareTo(Object o)
{
return toString().compareTo(o.toString());
}
}

View File

@ -1,59 +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 <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @version $Id: $Id
*/
public class ParameterNotFoundException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 3286112913299408382L;
/**
* Constructs a new ParameterNotFoundException with no detail message.
*/
public ParameterNotFoundException()
{
super();
}
/**
* Constructs a new ParameterNotFoundException with the specified detail message.
*
* @param s
* the detail message
*/
public ParameterNotFoundException(String s)
{
super(s);
}
}

View File

@ -1,165 +0,0 @@
package org.owasp.webgoat.session;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* <p>RandomLessonTracker class.</p>
*
* @version $Id: $Id
* @author dm
*/
public class RandomLessonTracker extends LessonTracker
{
private String[] stages;
private String stage;
private Map<String, Boolean> completed = new HashMap<String, Boolean>();
/**
* <p>Constructor for RandomLessonTracker.</p>
*
* @param stages an array of {@link java.lang.String} objects.
*/
public RandomLessonTracker(String[] stages)
{
if (stages == null) stages = new String[0];
this.stages = stages;
}
/**
* <p>Setter for the field <code>stage</code>.</p>
*
* @param stage a {@link java.lang.String} object.
*/
public void setStage(String stage)
{
this.stage = stage;
}
/**
* <p>Getter for the field <code>stage</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getStage()
{
if (this.stage == null && stages.length > 0) return stages[0];
return this.stage;
}
/**
* <p>setStageComplete.</p>
*
* @param stage a {@link java.lang.String} object.
* @param complete a boolean.
*/
public void setStageComplete(String stage, boolean complete)
{
completed.put(stage, Boolean.valueOf(complete));
if (!complete) return;
int i = getStageNumber(stage);
if (i < stages.length - 1) setStage(stages[i + 1]);
}
/**
* <p>getStageNumber.</p>
*
* @param stage a {@link java.lang.String} object.
* @return a int.
*/
public int getStageNumber(String stage)
{
for (int i = 0; i < stages.length; i++)
if (stages[i].equals(stage)) return i;
return -1;
}
/**
* <p>hasCompleted.</p>
*
* @param stage a {@link java.lang.String} object.
* @return a boolean.
*/
public boolean hasCompleted(String stage)
{
Boolean complete = completed.get(stage);
return complete == null ? false : complete.booleanValue();
}
/** {@inheritDoc} */
@Override
public boolean getCompleted()
{
for (int i = 0; i < stages.length; i++)
if (!hasCompleted(stages[i])) return false;
return true;
}
/** {@inheritDoc} */
@Override
public void setCompleted(boolean complete)
{
if (complete == true) throw new UnsupportedOperationException("Use individual stage completion instead");
for (int i = 0; i < stages.length; i++)
setStageComplete(stages[i], false);
setStage(stages[0]);
}
/** {@inheritDoc} */
protected void setProperties(Properties props, Screen screen)
{
super.setProperties(props, screen);
for (int i = 0; i < stages.length; i++)
{
String p = props.getProperty(screen.getTitle() + "." + stages[i] + ".completed");
if (p != null)
{
setStageComplete(stages[i], Boolean.valueOf(p));
}
}
setStage(props.getProperty(screen.getTitle() + ".stage"));
}
/** {@inheritDoc} */
public void store(WebSession s, Screen screen, String user)
{
for (int i = 0; i < stages.length; i++)
{
if (hasCompleted(stages[i]))
{
lessonProperties.setProperty(screen.getTitle() + "." + stages[i] + ".completed", Boolean.TRUE
.toString());
}
else
{
lessonProperties.remove(screen.getTitle() + "." + stages[i] + ".completed");
}
}
lessonProperties.setProperty(screen.getTitle() + ".stage", getStage());
super.store(s, screen, user);
}
/**
* <p>toString.</p>
*
* @return a {@link java.lang.String} object.
*/
public String toString()
{
StringBuffer buff = new StringBuffer();
buff.append(super.toString());
for (int i = 0; i < stages.length; i++)
{
buff.append(" - completed " + stages[i] + " :....... " + hasCompleted(stages[i]) + "\n");
}
buff.append(" - currentStage:....... " + getStage() + "\n");
return buff.toString();
}
}

View File

@ -1,29 +0,0 @@
package org.owasp.webgoat.session;
/**
* <p>Role class.</p>
*
* @version $Id: $Id
* @author dm
*/
public class Role {
private String rolename;
/**
* <p>Constructor for Role.</p>
*
* @param rolename a {@link java.lang.String} object.
*/
public Role(String rolename) {
this.rolename = rolename;
}
/**
* <p>Getter for the field <code>rolename</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getRolename() {
return this.rolename;
}
}

View File

@ -1,15 +1,5 @@
package org.owasp.webgoat.session;
import java.io.PrintWriter;
import java.util.Properties;
import org.apache.ecs.Element;
import org.apache.ecs.HtmlColor;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.A;
import org.apache.ecs.html.Font;
import org.apache.ecs.html.IMG;
import org.owasp.webgoat.lessons.AbstractLesson;
/**
* *************************************************************************************************
*
@ -45,102 +35,12 @@ import org.owasp.webgoat.lessons.AbstractLesson;
*/
public abstract class Screen {
/**
* Description of the Field
*/
public static int MAIN_SIZE = 375;
// private Head head;
private Element content;
final static IMG logo = new IMG("images/aspectlogo-horizontal-small.jpg").setAlt("Aspect Security").setBorder(0)
.setHspace(0).setVspace(0);
/**
* Constructor for the Screen object
*/
public Screen() {
}
// FIXME: Each lesson should have a role assigned to it. Each user/student
// should also have a role(s) assigned. The user would only be allowed
// to see lessons that correspond to their role. Eventually these roles
// will be stored in the internal database. The user will be able to hack
// into the database and change their role. This will allow the user to
// see the admin screens, once they figure out how to turn the admin switch on.
/**
* <p>getRole.</p>
*
* @return a {@link java.lang.String} object.
*/
public abstract String getRole();
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected abstract Element createContent(WebSession s);
/**
* Creates a new lessonTracker object.
*
* @param props The properties file that was used to persist the user data.
* @return Description of the Return Value
*/
public LessonTracker createLessonTracker(Properties props) {
// If the lesson had any specialized properties in the user persisted properties,
// now would be the time to pull them out.
return createLessonTracker();
}
/**
* This allows the screens to provide a custom LessonTracker object if
* needed.
*
* @return Description of the Return Value
*/
public LessonTracker createLessonTracker() {
return new LessonTracker();
}
/**
* Gets the lessonTracker attribute of the AbstractLesson object
*
* @return The lessonTracker value
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
*/
public LessonTracker getLessonTracker(WebSession s) {
UserTracker userTracker = UserTracker.instance();
return userTracker.getLessonTracker(s, this);
}
/**
* <p>getLessonTracker.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param userNameOverride a {@link java.lang.String} object.
* @return a {@link org.owasp.webgoat.session.LessonTracker} object.
*/
public LessonTracker getLessonTracker(WebSession s, String userNameOverride) {
UserTracker userTracker = UserTracker.instance();
return userTracker.getLessonTracker(s, userNameOverride, this);
}
/**
* <p>getLessonTracker.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param lesson a {@link org.owasp.webgoat.lessons.AbstractLesson} object.
* @return a {@link org.owasp.webgoat.session.LessonTracker} object.
*/
public LessonTracker getLessonTracker(WebSession s, AbstractLesson lesson) {
UserTracker userTracker = UserTracker.instance();
return userTracker.getLessonTracker(s, lesson);
}
/**
* Fill in a descriptive title for this lesson
@ -149,168 +49,5 @@ public abstract class Screen {
*/
public abstract String getTitle();
/**
* <p>Setter for the field <code>content</code>.</p>
*
* @param content a {@link org.apache.ecs.Element} object.
*/
protected void setContent(Element content) {
this.content = content;
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
protected Element makeLogo() {
return new A("http://www.aspectsecurity.com/webgoat.html", logo);
}
/**
* <p>getSponsor.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getSponsor() {
return "Aspect Security";
}
/**
* <p>getSponsorLogoResource.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getSponsorLogoResource() {
return "images/aspectlogo-horizontal-small.jpg";
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeMessages(WebSession s) {
if (s == null) {
return (new StringElement(""));
}
Font f = new Font().setColor(HtmlColor.RED);
String message = s.getMessage();
f.addElement(message);
return (f);
}
/**
* Returns the content length of the the html.
*
* @return a int.
*/
public int getContentLength() {
return getContent().length();
}
/**
* Description of the Method
*
* @param out Description of the Parameter
*/
public void output(PrintWriter out) {
// format output -- then send to printwriter
// otherwise we're doing way too much SSL encryption work
out.print(getContent());
}
// hook all the links
/**
* <p>Getter for the field <code>content</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getContent() {
//String makeAllAjax = "<script>goat.utils.makeFormsAjax();goat.utils.ajaxifyAttackHref();</script>";
// need to do this here as some of the lessons render forms after submission of an ajax form
return (content == null) ? "" : content.toString();// + makeAllAjax;
}
/**
* Description of the Method
*
* @param x Description of the Parameter
* @return Description of the Return Value
*/
protected static String pad(int x) {
StringBuilder sb = new StringBuilder();
if (x < 10) {
sb.append(" ");
}
if (x < 100) {
sb.append(" ");
}
sb.append(x);
return (sb.toString());
}
/**
* Description of the Method
*
* @param token Description of the Parameter
* @return Description of the Return Value
*/
protected static String convertMetachars(String token) {
int mci = 0;
/*
* meta char array FIXME: Removed the conversion of whitespace " " to "&nbsp" in order for
* the html to be automatically wrapped in client browser. It is better to add line length
* checking and only do "&nbsp" conversion in lines that won't exceed screen size, say less
* than 80 characters.
*/
String[] metaChar = {"&", "<", ">", "\"", "\t", System.getProperty("line.separator")};
String[] htmlCode = {"&amp;", "&lt;", "&gt;", "&quot;", " ", "<br>"};
String replacedString = token;
for (; mci < metaChar.length; mci += 1) {
replacedString = replacedString.replaceAll(metaChar[mci], htmlCode[mci]);
}
return (replacedString);
}
/**
* Description of the Method
*
* @param token Description of the Parameter
* @return Description of the Return Value
*/
protected static String convertMetacharsJavaCode(String token) {
return (convertMetachars(token).replaceAll(" ", "&nbsp;"));
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
// protected abstract Element wrapForm( WebSession s );
}

View File

@ -1,61 +0,0 @@
package org.owasp.webgoat.session;
import java.util.Properties;
/**
* <p>SequentialLessonTracker class.</p>
*
* @version $Id: $Id
* @author dm
*/
public class SequentialLessonTracker extends LessonTracker
{
private int currentStage = 1;
/**
* <p>getStage.</p>
*
* @return a int.
*/
public int getStage()
{
return currentStage;
}
/**
* <p>setStage.</p>
*
* @param stage a int.
*/
public void setStage(int stage)
{
currentStage = stage;
}
/** {@inheritDoc} */
protected void setProperties(Properties props, Screen screen)
{
super.setProperties(props, screen);
currentStage = Integer.parseInt(props.getProperty(screen.getTitle() + ".currentStage"));
}
/** {@inheritDoc} */
public void store(WebSession s, Screen screen, String user)
{
lessonProperties.setProperty(screen.getTitle() + ".currentStage", Integer.toString(currentStage));
super.store(s, screen, user);
}
/**
* <p>toString.</p>
*
* @return a {@link java.lang.String} object.
*/
public String toString()
{
return super.toString() + " - currentStage:....... " + currentStage + "\n";
}
}

View File

@ -1,41 +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.
*
* @version $Id: $Id
* @author dm
*/
public class UnauthenticatedException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 97865025446819061L;
}

View File

@ -1,41 +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.
*
* @version $Id: $Id
* @author dm
*/
public class UnauthorizedException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 5245519486798464814L;
}

View File

@ -1,52 +0,0 @@
package org.owasp.webgoat.session;
import java.util.ArrayList;
import java.util.Iterator;
/**
* <p>User class.</p>
*
* @version $Id: $Id
* @author dm
*/
public class User {
private String username;
private ArrayList<Role> roles;
/**
* <p>Constructor for User.</p>
*
* @param username a {@link java.lang.String} object.
*/
public User(String username) {
this.username = username;
this.roles = new ArrayList<Role>();
}
/**
* <p>Getter for the field <code>username</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getUsername() {
return username;
}
/**
* <p>Getter for the field <code>roles</code>.</p>
*
* @return a {@link java.util.Iterator} object.
*/
public Iterator<Role> getRoles() {
return roles.iterator();
}
/**
* <p>addRole.</p>
*
* @param rolename a {@link java.lang.String} object.
*/
public void addRole(String rolename) {
roles.add(new Role(rolename));
}
}

View File

@ -1,9 +1,12 @@
package org.owasp.webgoat.session;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class UserDatabase {
private Connection userDB;
@ -20,9 +23,6 @@ class UserDatabase {
private final String QUERY_ALL_ROLES_FOR_USERNAME = "SELECT rolename FROM roles, user_roles, users WHERE roles.id = user_roles.role_id AND user_roles.user_id = users.id AND users.username = ?;";
private final String QUERY_TABLE_COUNT = "SELECT count(id) AS count FROM table;";
private final String DELETE_ALL_ROLES_FOR_USER = "DELETE FROM user_roles WHERE user_id IN (SELECT id FROM users WHERE username = ?);";
private final String DELETE_USER = "DELETE FROM users WHERE username = ?;";
/**
* <p>Constructor for UserDatabase.</p>
*/
@ -101,42 +101,6 @@ class UserDatabase {
return count;
}
/**
* <p>getUsers.</p>
*
* @return a {@link java.util.Iterator} object.
*/
public Iterator<User> getUsers() {
ArrayList<User> users = new ArrayList<User>();
User currentUser;
ResultSet userResults, roleResults;
try {
open();
Statement statement = userDB.createStatement();
PreparedStatement rolesForUsers = userDB.prepareStatement(QUERY_ALL_ROLES_FOR_USERNAME);
userResults = statement.executeQuery(QUERY_ALL_USERS);
while (userResults.next()) {
currentUser = new User(userResults.getString("username"));
rolesForUsers.setString(1, currentUser.getUsername());
roleResults = rolesForUsers.executeQuery();
while (roleResults.next()) {
currentUser.addRole(roleResults.getString("rolename"));
}
roleResults.close();
}
rolesForUsers.close();
userResults.close();
close();
} catch (SQLException e) {
e.printStackTrace();
users = new ArrayList<User>();
}
return users.iterator();
}
/**
* <p>addRoleToUser.</p>
*
@ -160,46 +124,6 @@ class UserDatabase {
return true;
}
/**
* <p>removeUser.</p>
*
* @param user a {@link org.owasp.webgoat.session.User} object.
* @return a boolean.
*/
public boolean removeUser(User user) {
return removeUser(user.getUsername());
}
/**
* <p>removeUser.</p>
*
* @param username a {@link java.lang.String} object.
* @return a boolean.
*/
public boolean removeUser(String username) {
try {
open();
PreparedStatement deleteUserRoles = userDB.prepareStatement(DELETE_ALL_ROLES_FOR_USER);
PreparedStatement deleteUser = userDB.prepareStatement(DELETE_USER);
deleteUserRoles.setString(1, username);
deleteUser.setString(1, username);
deleteUserRoles.execute();
deleteUser.execute();
deleteUserRoles.close();
deleteUser.close();
close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
/*
* Methods to initialise the default state of the database.
*/

View File

@ -1,300 +1,104 @@
package org.owasp.webgoat.session;
import java.util.ArrayList;
import java.util.Collection;
import lombok.SneakyThrows;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Assignment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.SerializationUtils;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
*************************************************************************************************
*
*
* ************************************************************************************************
* <p>
* <p>
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* <p>
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* <p>
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* <p>
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* <p>
* Getting Source ==============
*
* <p>
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @since October 29, 2003
* @version $Id: $Id
* @since October 29, 2003
*/
public class UserTracker
{
public class UserTracker {
private static UserTracker instance;
private final String webgoatHome;
private final String user;
private Map<String, LessonTracker> storage = new HashMap<>();
// FIXME: persist this somehow!
public UserTracker(@Value("${webgoat.user.directory}") final String webgoatHome, final String user) {
this.webgoatHome = webgoatHome;
this.user = user;
}
private static HashMap<String, HashMap<String, LessonTracker>> storage = new HashMap<String, HashMap<String, LessonTracker>>();
/**
* Returns the lesson tracker for a specific lesson if available.
*
* @param lesson the lesson
* @return the optional lesson tracker
*/
public LessonTracker getLessonTracker(AbstractLesson lesson) {
LessonTracker lessonTracker = storage.get(lesson.getTitle());
if (lessonTracker == null) {
lessonTracker = new LessonTracker(lesson);
storage.put(lesson.getTitle(), lessonTracker);
}
return lessonTracker;
}
private static UserDatabase usersDB = new UserDatabase();
public void assignmentSolved(AbstractLesson lesson, Assignment assignment) {
LessonTracker lessonTracker = getLessonTracker(lesson);
lessonTracker.incrementAttempts();
lessonTracker.assignmentSolved(assignment.getClass().getSimpleName());
save();
}
/**
* Constructor for the UserTracker object
*/
private UserTracker()
{
}
public void assignmentFailed(AbstractLesson lesson) {
LessonTracker lessonTracker = getLessonTracker(lesson);
lessonTracker.incrementAttempts();
save();
}
/**
* Gets the completed attribute of the UserTracker object
*
* @param userName
* Description of the Parameter
* @return The completed value
*/
public int getCompleted(String userName)
{
@SneakyThrows
public void load() {
File file = new File(webgoatHome, user + ".progress");
if (file.exists() && file.isFile()) {
this.storage = (Map<String, LessonTracker>) SerializationUtils.deserialize(FileCopyUtils.copyToByteArray(file));
}
}
HashMap usermap = getUserMap(userName);
@SneakyThrows
private void save() {
File file = new File(webgoatHome, user + ".progress");
FileCopyUtils.copy(SerializationUtils.serialize(this.storage), file);
}
Iterator i = usermap.entrySet().iterator();
int count = 0;
while (i.hasNext())
{
Map.Entry entry = (Map.Entry) i.next();
int value = ((Integer) entry.getValue()).intValue();
if (value > 5)
{
count++;
}
}
return count;
}
/**
* Gets the users attribute of the UserTracker object
*
* @return The users value
*/
public Collection getUsers()
{
return storage.keySet();
}
/**
* <p>getAllUsers.</p>
*
* @param roleName a {@link java.lang.String} object.
* @return a {@link java.util.Collection} object.
*/
public Collection<String> getAllUsers(String roleName)
{
synchronized (usersDB)
{
Collection<String> allUsers = new ArrayList<String>();
try
{
usersDB.open();
Iterator users = usersDB.getUsers();
while (users.hasNext())
{
User user = (User) users.next();
Iterator roles = user.getRoles();
while (roles.hasNext())
{
Role role = (Role) roles.next();
if (role.getRolename().trim().equals(roleName))
{
allUsers.add(user.getUsername());
}
}
}
usersDB.close();
} catch (Exception e)
{
}
return allUsers;
}
}
/**
* <p>deleteUser.</p>
*
* @param user a {@link java.lang.String} object.
*/
public void deleteUser(String user)
{
synchronized (usersDB)
{
try
{
usersDB.open();
Iterator users = usersDB.getUsers();
while (users.hasNext())
{
User tomcatUser = (User) users.next();
if (tomcatUser.getUsername().equals(user))
{
usersDB.removeUser(tomcatUser);
// FIXME: delete all the lesson tracking property files
break;
}
}
usersDB.close();
} catch (Exception e)
{
}
}
}
/**
* Gets the lessonTracker attribute of the UserTracker object
*
* @param screen
* Description of the Parameter
* @return The lessonTracker value
* @param screen
* Description of the Parameter
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
*/
public LessonTracker getLessonTracker(WebSession s, Screen screen)
{
return getLessonTracker(s, s.getUserName(), screen);
}
/**
* <p>getLessonTracker.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param screen a {@link org.owasp.webgoat.session.Screen} object.
* @param user a {@link java.lang.String} object.
* @param screen a {@link org.owasp.webgoat.session.Screen} object.
* @return a {@link org.owasp.webgoat.session.LessonTracker} object.
*/
public LessonTracker getLessonTracker(WebSession s, String user, Screen screen)
{
HashMap<String, LessonTracker> usermap = getUserMap(user);
LessonTracker tracker = (LessonTracker) usermap.get(screen.getTitle());
if (tracker == null)
{
// Creates a new lesson tracker, if one does not exist on disk.
tracker = LessonTracker.load(s, user, screen);
usermap.put(screen.getTitle(), tracker);
}
// System.out.println( "User: [" + userName + "] UserTracker:getLessonTracker() LTH " +
// tracker.hashCode() + " for " + screen );
return tracker;
}
/**
* Gets the status attribute of the UserTracker object
*
* @param screen
* Description of the Parameter
* @return The status value
* @param screen
* Description of the Parameter
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
*/
public String getStatus(WebSession s, Screen screen)
{
return ("User [" + s.getUserName() + "] has accessed " + screen + " UserTracker:getStatus()LTH = " + getLessonTracker(
s,
screen)
.hashCode());
}
/**
* Gets the userMap attribute of the UserTracker object
*
* @param userName
* Description of the Parameter
* @return The userMap value
*/
private HashMap<String, LessonTracker> getUserMap(String userName)
{
HashMap<String, LessonTracker> usermap = storage.get(userName);
if (usermap == null)
{
usermap = new HashMap<String, LessonTracker>();
storage.put(userName, usermap);
}
return (usermap);
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public static synchronized UserTracker instance()
{
if (instance == null)
{
instance = new UserTracker();
}
return instance;
}
/**
* Description of the Method
*
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param screen
* Description of the Parameter
* @param s
* Description of the Parameter
*/
public void update(WebSession s, Screen screen)
{
LessonTracker tracker = getLessonTracker(s, screen);
// System.out.println( "User [" + s.getUserName() + "] TRACKER: updating " + screen +
// " LTH " + tracker.hashCode() );
tracker.store(s, screen);
HashMap<String, LessonTracker> usermap = getUserMap(s.getUserName());
usermap.put(screen.getTitle(), tracker);
}
public void reset(AbstractLesson al) {
getLessonTracker(al).reset();
save();
}
}

View File

@ -1,58 +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.
*
* @version $Id: $Id
* @author dm
*/
public class ValidationException extends Exception
{
/**
*
*/
private static final long serialVersionUID = -8358754606830400708L;
/**
* <p>Constructor for ValidationException.</p>
*/
public ValidationException()
{
super();
}
/**
* <p>Constructor for ValidationException.</p>
*
* @param message a {@link java.lang.String} object.
*/
public ValidationException(String message)
{
super(message);
}
}

View File

@ -1,9 +1,7 @@
package org.owasp.webgoat.session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServlet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* <p>WebgoatContext class.</p>
@ -11,62 +9,15 @@ import javax.servlet.http.HttpServlet;
* @version $Id: $Id
* @author dm
*/
@Configuration
public class WebgoatContext {
final Logger logger = LoggerFactory.getLogger(WebgoatContext.class);
/** Constant <code>DATABASE_CONNECTION_STRING="DatabaseConnectionString"</code> */
public final static String DATABASE_CONNECTION_STRING = "DatabaseConnectionString";
/** Constant <code>DATABASE_DRIVER="DatabaseDriver"</code> */
public final static String DATABASE_DRIVER = "DatabaseDriver";
/** Constant <code>DATABASE_USER="DatabaseUser"</code> */
public final static String DATABASE_USER = "DatabaseUser";
/** Constant <code>DATABASE_PASSWORD="DatabasePassword"</code> */
public final static String DATABASE_PASSWORD = "DatabasePassword";
/** Constant <code>ENTERPRISE="Enterprise"</code> */
public final static String ENTERPRISE = "Enterprise";
/** Constant <code>CODING_EXERCISES="CodingExercises"</code> */
public final static String CODING_EXERCISES = "CodingExercises";
/** Constant <code>SHOWCOOKIES="ShowCookies"</code> */
public final static String SHOWCOOKIES = "ShowCookies";
/** Constant <code>SHOWPARAMS="ShowParams"</code> */
public final static String SHOWPARAMS = "ShowParams";
/** Constant <code>SHOWREQUEST="ShowRequest"</code> */
public final static String SHOWREQUEST = "ShowRequest";
/** Constant <code>SHOWSOURCE="ShowSource"</code> */
public final static String SHOWSOURCE = "ShowSource";
/** Constant <code>SHOWSOLUTION="ShowSolution"</code> */
public final static String SHOWSOLUTION = "ShowSolution";
/** Constant <code>SHOWHINTS="ShowHints"</code> */
public final static String SHOWHINTS = "ShowHints";
/** Constant <code>FEEDBACK_ADDRESS_HTML="FeedbackAddressHTML"</code> */
public final static String FEEDBACK_ADDRESS_HTML = "FeedbackAddressHTML";
/** Constant <code>FEEDBACK_ADDRESS="email"</code> */
public final static String FEEDBACK_ADDRESS = "email";
/** Constant <code>DEBUG="debug"</code> */
public final static String DEBUG = "debug";
/** Constant <code>DEFAULTLANGUAGE="DefaultLanguage"</code> */
public final static String DEFAULTLANGUAGE = "DefaultLanguage";
@Value("${webgoat.database.connection.string}")
private String databaseConnectionString;
private String realConnectionString = null;
@Value("${webgoat.database.driver}")
private String databaseDriver;
private String databaseUser;
@ -87,58 +38,17 @@ public class WebgoatContext {
private boolean codingExercises = false;
private String feedbackAddress = "owasp-webgoat@list.owasp.org";
@Value("${webgoat.feedback.address}")
private String feedbackAddress;
private String feedbackAddressHTML = "<A HREF=mailto:owasp-webgoat@list.owasp.org>owasp-webgoat@list.owasp.org</A>";
@Value("${webgoat.feedback.address.html}")
private String feedbackAddressHTML = "";
private boolean isDebug = false;
private String servletName;
private HttpServlet servlet;
@Value("${webgoat.default.language}")
private String defaultLanguage;
private java.nio.file.Path pluginDirectory;
/**
* <p>Constructor for WebgoatContext.</p>
*
* @param servlet a {@link javax.servlet.http.HttpServlet} object.
*/
public WebgoatContext(HttpServlet servlet) {
this.servlet = servlet;
databaseConnectionString = getParameter(servlet, DATABASE_CONNECTION_STRING);
databaseDriver = getParameter(servlet, DATABASE_DRIVER);
databaseUser = getParameter(servlet, DATABASE_USER);
databasePassword = getParameter(servlet, DATABASE_PASSWORD);
// initialize from web.xml
showParams = "true".equals(getParameter(servlet, SHOWPARAMS));
showCookies = "true".equals(getParameter(servlet, SHOWCOOKIES));
showSource = "true".equals(getParameter(servlet, SHOWSOURCE));
showSolution = "true".equals(getParameter(servlet, SHOWSOLUTION));
enterprise = "true".equals(getParameter(servlet, ENTERPRISE));
codingExercises = "true".equals(getParameter(servlet, CODING_EXERCISES));
feedbackAddressHTML = getParameter(servlet, FEEDBACK_ADDRESS_HTML) != null ? getParameter(servlet,
FEEDBACK_ADDRESS_HTML)
: feedbackAddressHTML;
feedbackAddress = getParameter(servlet, FEEDBACK_ADDRESS) != null ? getParameter(servlet, FEEDBACK_ADDRESS)
: feedbackAddress;
showRequest = "true".equals(getParameter(servlet, SHOWREQUEST));
isDebug = "true".equals(getParameter(servlet, DEBUG));
servletName = servlet.getServletName();
defaultLanguage = getParameter(servlet, DEFAULTLANGUAGE) != null ? new String(getParameter(servlet, DEFAULTLANGUAGE)) : new String("en");
}
private String getParameter(HttpServlet servlet, String key) {
String value = System.getenv().get(key);
if (value == null) {
value = servlet.getInitParameter(key);
}
return value;
}
/**
* returns the connection string with the real path to the database
* directory inserted at the word PATH
@ -146,17 +56,7 @@ public class WebgoatContext {
* @return The databaseConnectionString value
*/
public String getDatabaseConnectionString() {
if (realConnectionString == null) {
try {
String path = servlet.getServletContext().getRealPath("/database").replace('\\', '/');
System.out.println("PATH: " + path);
realConnectionString = databaseConnectionString.replaceAll("PATH", path);
System.out.println("Database Connection String: " + realConnectionString);
} catch (Exception e) {
logger.error("Couldn't open database: check web.xml database parameters", e);
}
}
return realConnectionString;
return this.databaseConnectionString;
}
/**
@ -185,7 +85,7 @@ public class WebgoatContext {
public String getDatabasePassword() {
return (databasePassword);
}
/**
* <p>isEnterprise.</p>
*
@ -231,15 +131,6 @@ public class WebgoatContext {
return isDebug;
}
/**
* <p>Getter for the field <code>servletName</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getServletName() {
return servletName;
}
/**
* <p>isShowCookies.</p>
*

View File

@ -1,145 +0,0 @@
package org.owasp.webgoat.session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* @version $Id: $Id
* @author dm
*/
public class WebgoatProperties extends Properties {
/**
*
*/
private static final long serialVersionUID = 4351681705558227918L;
final Logger logger = LoggerFactory.getLogger(WebgoatProperties.class);
/**
* <p>Constructor for WebgoatProperties.</p>
*
* @param propertiesFileName a {@link java.lang.String} object.
* @throws java.io.IOException if any.
*/
public WebgoatProperties(String propertiesFileName) throws IOException {
if (propertiesFileName == null) {
throw new IOException("Path to webgoat.properties is null, initialization must have failed");
}
File propertiesFile = new File(propertiesFileName);
if (propertiesFile.exists() == false) {
throw new IOException("Unable to locate webgoat.properties at: " + propertiesFileName);
}
FileInputStream in = new FileInputStream(propertiesFile);
load(in);
}
/**
* <p>getIntProperty.</p>
*
* @param key a {@link java.lang.String} object.
* @param defaultValue a int.
* @return a int.
*/
public int getIntProperty(String key, int defaultValue) {
int value = defaultValue;
String s = getProperty(key);
if (s != null) {
value = Integer.parseInt(s);
}
return value;
}
/**
* <p>getBooleanProperty.</p>
*
* @param key a {@link java.lang.String} object.
* @param defaultValue a boolean.
* @return a boolean.
*/
public boolean getBooleanProperty(String key, boolean defaultValue) {
boolean value = defaultValue;
key = this.trimLesson(key);
String s = getProperty(key);
if (s != null) {
if (s.equalsIgnoreCase("true")) {
value = true;
} else if (s.equalsIgnoreCase("yes")) {
value = true;
} else if (s.equalsIgnoreCase("on")) {
value = true;
} else if (s.equalsIgnoreCase("false")) {
value = false;
} else if (s.equalsIgnoreCase("no")) {
value = false;
} else if (s.equalsIgnoreCase("off")) {
value = false;
}
}
return value;
}
private String trimLesson(String lesson) {
String result = "";
if (lesson.startsWith("org.owasp.webgoat.lessons.")) {
result = lesson.substring("org.owasp.webgoat.lessons.".length(), lesson.length());
} else {
result = lesson;
}
return result;
}
/**
* <p>main.</p>
*
* @param args an array of {@link java.lang.String} objects.
*/
public static void main(String[] args) {
WebgoatProperties properties = null;
try {
properties = new WebgoatProperties("C:\\webgoat.properties");
} catch (IOException e) {
System.out.println("Error loading properties");
e.printStackTrace();
}
System.out.println(properties.getProperty("CommandInjection.category"));
}
}