Moved Maven multiproject setup

This commit is contained in:
Nanne Baars
2015-08-11 21:57:12 +02:00
parent 28a2d01ba3
commit 42f373d66a
578 changed files with 455 additions and 435 deletions

View File

@ -1,120 +0,0 @@
package org.owasp.webgoat;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created March 13, 2007
*/
public class Catcher extends HammerHead
{
/**
*
*/
private static final long serialVersionUID = 7441856110845727651L;
/**
* Description of the Field
*/
public final static String START_SOURCE_SKIP = "START_OMIT_SOURCE";
public final static String END_SOURCE_SKIP = "END_OMIT_SOURCE";
public static final String PROPERTY = "PROPERTY";
public static final String EMPTY_STRING = "";
/**
* Description of the Method
*
* @param request
* Description of the Parameter
* @param response
* Description of the Parameter
* @exception IOException
* Description of the Exception
* @exception ServletException
* Description of the Exception
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try
{
// System.out.println( "Entering doPost: " );
// System.out.println( " - request " + request);
// System.out.println( " - principle: " + request.getUserPrincipal() );
// setCacheHeaders(response, 0);
WebSession session = (WebSession) request.getSession(true).getAttribute(WebSession.SESSION);
session.update(request, response, this.getServletName()); // FIXME: Too much in this
// call.
int scr = session.getCurrentScreen();
Course course = session.getCourse();
AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
log(request, lesson.getClass().getName() + " | " + session.getParser().toString());
String property = new String(session.getParser().getStringParameter(PROPERTY, EMPTY_STRING));
// if the PROPERTY parameter is available - write all the parameters to the
// property file. No other control parameters are supported at this time.
if (!property.equals(EMPTY_STRING))
{
Enumeration e = session.getParser().getParameterNames();
while (e.hasMoreElements())
{
String name = (String) e.nextElement();
String value = session.getParser().getParameterValues(name)[0];
lesson.getLessonTracker(session).getLessonProperties().setProperty(name, value);
}
}
lesson.getLessonTracker(session).store(session, lesson);
// BDM MC
// WEB-173 - removed for testing, as plugin architecture would not allow this
// if ( request.getParameter("Deleter") != null ){org.owasp.webgoat.lessons.BlindScript.StaticDeleter();}
} catch (Throwable t)
{
t.printStackTrace();
log("ERROR: " + t);
}
}
}

View File

@ -1,440 +0,0 @@
package org.owasp.webgoat;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.WelcomeScreen;
import org.owasp.webgoat.lessons.admin.WelcomeAdminScreen;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.ErrorScreen;
import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect
* Security</a>
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public class HammerHead extends HttpServlet {
final Logger logger = LoggerFactory.getLogger(HammerHead.class);
private static final String WELCOMED = "welcomed";
/**
*
*/
private static final long serialVersionUID = 645640331343188020L;
/**
* Description of the Field
*/
protected static SimpleDateFormat httpDateFormat;
/**
* Set the session timeout to be 2 days
*/
private final static int sessionTimeoutSeconds = 60 * 60 * 24 * 2;
// private final static int sessionTimeoutSeconds = 1;
/**
* Properties file path
*/
public static String propertiesPath = null;
/**
* provides convenience methods for getting setup information from the
* ServletContext
*/
private WebgoatContext webgoatContext = null;
/**
* Description of the Method
*
* @param request Description of the Parameter
* @param response Description of the Parameter
* @exception IOException Description of the Exception
* @exception ServletException Description of the Exception
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}
/**
* Description of the Method
*
* @param request Description of the Parameter
* @param response Description of the Parameter
* @exception IOException Description of the Exception
* @exception ServletException Description of the Exception
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Screen screen = null;
WebSession mySession = null;
try {
logger.debug("Entering doPost");
logger.debug("request: " + request);
logger.debug("principle: " + request.getUserPrincipal());
// setCacheHeaders(response, 0);
ServletContext context = getServletContext();
// FIXME: If a response is written by updateSession(), do not
// call makeScreen() and writeScreen()
mySession = updateSession(request, response, context);
if (response.isCommitted()) {
logger.debug("Response already committed, exiting");
return;
}
if ("true".equals(request.getParameter("start")) || request.getQueryString() == null) {
logger.warn("Redirecting to start controller");
response.sendRedirect("start.mvc");
return;
}
// Note: For the lesson to track the status, we need to update
// the lesson tracker object
// from the screen.createContent() method. The create content is
// the only point
// where the lesson "knows" what has happened. To track it at a
// latter point would
// require the lesson to have memory.
screen = makeScreen(mySession);
// This calls the lesson's
// handleRequest()
if (response.isCommitted()) {
return;
}
// perform lesson-specific tracking activities
if (screen instanceof AbstractLesson) {
AbstractLesson lesson = (AbstractLesson) screen;
// we do not count the initial display of the lesson screen as a visit
if ("GET".equals(request.getMethod())) {
String uri = request.getRequestURI() + "?" + request.getQueryString();
if (!uri.endsWith(lesson.getLink())) {
screen.getLessonTracker(mySession).incrementNumVisits();
}
} else if ("POST".equals(request.getMethod())
&& mySession.getPreviousScreen() == mySession.getCurrentScreen()) {
screen.getLessonTracker(mySession).incrementNumVisits();
}
}
// log the access to this screen for this user
UserTracker userTracker = UserTracker.instance();
userTracker.update(mySession, screen);
log(request, screen.getClass().getName() + " | " + mySession.getParser().toString());
// Redirect the request to our View servlet
String userAgent = request.getHeader("user-agent");
String clientBrowser = "Not known!";
if (userAgent != null) {
clientBrowser = userAgent;
}
request.setAttribute("client.browser", clientBrowser);
// removed - this is being done in updateSession call
//request.getSession().setAttribute(WebSession.SESSION, mySession);
// not sure why this is being set in the session?
//request.getSession().setAttribute(WebSession.COURSE, mySession.getCourse());
String viewPage = getViewPage(mySession);
logger.debug("Forwarding to view: " + viewPage);
logger.debug("Screen: " + screen);
request.getRequestDispatcher(viewPage).forward(request, response);
} catch (Throwable t) {
logger.error("Error handling request", t); screen = new ErrorScreen(mySession, t);
} finally {
try {
if (screen instanceof ErrorScreen) {
this.writeScreen(mySession, screen, response);
}
} catch (Throwable thr) {
logger.error("Could not write error screen", thr);
}
WebSession.returnConnection(mySession);
logger.debug("Leaving doPost: ");
}
}
private String getViewPage(WebSession webSession) {
// now always display the lesson content
String page = "/lesson_content.jsp";
//page = "/main.jsp";
return page;
}
/**
* Description of the Method
*
* @param date Description of the Parameter
* @return RFC 1123 http date format
*/
protected static String formatHttpDate(Date date) {
synchronized (httpDateFormat) {
return httpDateFormat.format(date);
}
}
/**
* Return information about this servlet
*
* @return The servletInfo value
*/
@Override
public String getServletInfo() {
return "WebGoat is sponsored by Aspect Security.";
}
/**
* Return properties path
*
* @throws javax.servlet.ServletException
*/
@Override
public void init() throws ServletException {
logger.info("Initializing main webgoat servlet");
httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyyy HH:mm:ss z", Locale.US);
httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
propertiesPath = getServletContext().getRealPath("/WEB-INF/webgoat.properties");
webgoatContext = new WebgoatContext(this);
}
/**
* Description of the Method
*
* @param request Description of the Parameter
* @param message Description of the Parameter
*/
public void log(HttpServletRequest request, String message) {
String output = new Date() + " | " + request.getRemoteHost() + ":" + request.getRemoteAddr() + " | " + message;
log(output);
logger.debug(output);
}
/*
* public List getLessons(Category category, String role) { Course course =
* mySession.getCourse(); // May need to clone the List before returning it. //return new
* ArrayList(course.getLessons(category, role)); return course.getLessons(category, role); }
*/
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected Screen makeScreen(WebSession s) {
Screen screen = null;
int scr = s.getCurrentScreen();
Course course = s.getCourse();
if (s.isUser() || s.isChallenge()) {
if (scr == WebSession.WELCOME) {
screen = new WelcomeScreen(s);
} else {
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
if (lesson == null && s.isHackedAdmin()) {
// If admin was hacked, let the user see some of the
// admin screens
lesson = course.getLesson(s, scr, AbstractLesson.HACKED_ADMIN_ROLE);
}
if (lesson != null) {
screen = lesson;
// We need to do some bookkeeping for the hackable admin
// interface.
// This is the only place we can tell if the user
// successfully hacked the hackable
// admin and has actually accessed an admin screen. You
// need BOTH pieces of information
// in order to satisfy the remote admin lesson.
s.setHasHackableAdmin(screen.getRole());
lesson.handleRequest(s);
s.setCurrentMenu(lesson.getCategory().getRanking());
} else {
screen = new ErrorScreen(s, "Invalid screen requested. Try: http://localhost/WebGoat/attack");
}
}
} else if (s.isAdmin()) {
if (scr == WebSession.WELCOME) {
screen = new WelcomeAdminScreen(s);
} else {
// Admin can see all roles.
// FIXME: should be able to pass a list of roles.
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.ADMIN_ROLE);
if (lesson == null) {
lesson = course.getLesson(s, scr, AbstractLesson.HACKED_ADMIN_ROLE);
}
if (lesson == null) {
lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
}
if (lesson != null) {
screen = lesson;
// We need to do some bookkeeping for the hackable admin
// interface.
// This is the only place we can tell if the user
// successfully hacked the hackable
// admin and has actually accessed an admin screen. You
// need BOTH pieces of information
// in order to satisfy the remote admin lesson.
s.setHasHackableAdmin(screen.getRole());
lesson.handleRequest(s);
s.setCurrentMenu(lesson.getCategory().getRanking());
} else {
screen = new ErrorScreen(s,
"Invalid screen requested. Try Setting Admin to false or Try: http://localhost/WebGoat/attack");
}
}
}
return (screen);
}
/**
* This method sets the required expiration headers in the response for a
* given RunData object. This method attempts to set all relevant headers,
* both for HTTP 1.0 and HTTP 1.1.
*
* @param response The new cacheHeaders value
* @param expiry The new cacheHeaders value
*/
protected static void setCacheHeaders(HttpServletResponse response, int expiry) {
if (expiry == 0) {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", formatHttpDate(new Date()));
} else {
Date expiryDate = new Date(System.currentTimeMillis() + expiry);
response.setHeader("Expires", formatHttpDate(expiryDate));
}
}
/**
* Description of the Method
*
* @param request Description of the Parameter
* @param response Description of the Parameter
* @param context Description of the Parameter
* @return Description of the Return Value
* @throws java.io.IOException
*/
protected WebSession updateSession(HttpServletRequest request, HttpServletResponse response, ServletContext context)
throws IOException {
HttpSession hs;
// session should already be created by spring security
hs = request.getSession(false);
logger.debug("HH Entering Session_id: " + hs.getId());
// dumpSession( hs );
// Get our session object out of the HTTP session
WebSession session = null;
Object o = hs.getAttribute(WebSession.SESSION);
if ((o != null) && o instanceof WebSession) {
session = (WebSession) o;
hs.setAttribute(WebSession.COURSE, session.getCourse());
} else {
// Create new custom session and save it in the HTTP session
logger.warn("HH Creating new WebSession");
session = new WebSession(webgoatContext, context);
// Ensure splash screen shows on any restart
// rlawson - removed this since we show splash screen at login now
//hs.removeAttribute(WELCOMED);
hs.setAttribute(WebSession.SESSION, session);
// reset timeout
hs.setMaxInactiveInterval(sessionTimeoutSeconds);
}
session.update(request, response, this.getServletName());
// update last attack request info (cookies, parms)
// this is so the REST services can have access to them via the session
session.updateLastAttackRequestInfo(request);
// to authenticate
logger.debug("HH Leaving Session_id: " + hs.getId());
//dumpSession( hs );
return (session);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param screen
* @param response Description of the Parameter
* @exception IOException Description of the Exception
*/
protected void writeScreen(WebSession s, Screen screen, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (s == null) {
screen = new ErrorScreen(s, "Page to display was null");
}
// set the content-length of the response.
// Trying to avoid chunked-encoding. (Aspect required)
response.setContentLength(screen.getContentLength());
response.setHeader("Content-Length", screen.getContentLength() + "");
screen.output(out);
out.flush();
out.close();
}
}

View File

@ -1,185 +0,0 @@
package org.owasp.webgoat;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public class LessonSource extends HammerHead {
/**
*
*/
private static final long serialVersionUID = 2588430536196446145L;
/**
* Description of the Field
*/
public final static String START_SOURCE_SKIP = "START_OMIT_SOURCE";
public final static String END_SOURCE_SKIP = "END_OMIT_SOURCE";
/**
* Description of the Method
*
* @param request Description of the Parameter
* @param response Description of the Parameter
* @exception IOException Description of the Exception
* @exception ServletException Description of the Exception
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String source = null;
try {
// System.out.println( "Entering doPost: " );
// System.out.println( " - request " + request);
// System.out.println( " - principle: " + request.getUserPrincipal()
// );
// setCacheHeaders(response, 0);
WebSession session = (WebSession) request.getSession(true).getAttribute(WebSession.SESSION);
// FIXME: Too much in this call.
session.update(request, response, this.getServletName());
boolean showSolution = session.getParser().getBooleanParameter("solution", false);
boolean showSource = session.getParser().getBooleanParameter("source", false);
if (showSolution) {
// Get the Java solution of the lesson.
source = getSolution(session);
int scr = session.getCurrentScreen();
Course course = session.getCourse();
AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
lesson.getLessonTracker(session).setViewedSolution(true);
} else if (showSource) {
// Get the Java source of the lesson. FIXME: Not needed
source = getSource(session);
int scr = session.getCurrentScreen();
Course course = session.getCourse();
AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
lesson.getLessonTracker(session).setViewedSource(true);
}
} catch (Throwable t) {
t.printStackTrace();
log("ERROR: " + t);
} finally {
try {
this.writeSource(source, response);
} catch (Throwable thr) {
thr.printStackTrace();
log(request, "Could not write error screen: " + thr.getMessage());
}
// System.out.println( "Leaving doPost: " );
}
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected String getSource(WebSession s) {
String source = null;
int scr = s.getCurrentScreen();
Course course = s.getCourse();
if (s.isUser() || s.isChallenge()) {
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
if (lesson != null) {
source = lesson.getSource(s);
}
}
if (source == null) {
return "Source code is not available. Contact "
+ s.getWebgoatContext().getFeedbackAddressHTML();
}
return (source.replaceAll("(?s)" + START_SOURCE_SKIP + ".*" + END_SOURCE_SKIP,
"Code Section Deliberately Omitted"));
}
protected String getSolution(WebSession s) {
String source = null;
int scr = s.getCurrentScreen();
Course course = s.getCourse();
if (s.isUser() || s.isChallenge()) {
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
if (lesson != null) {
source = lesson.getSolution(s);
}
}
if (source == null) {
return "Solution is not available. Contact "
+ s.getWebgoatContext().getFeedbackAddressHTML();
}
return (source);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param response Description of the Parameter
* @exception IOException Description of the Exception
*/
protected void writeSource(String s, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (s == null) {
s = new String();
}
out.print(s);
out.close();
}
}

View File

@ -1,88 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.application;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Singleton which is created on context startup
*
* @author rlawson
*/
public class Application {
private static final Application INSTANCE = new Application();
private Application() {
}
public static final Application getInstance() {
return INSTANCE;
}
private String version = "SNAPSHOT";
private String build = "local";
private String name = "WebGoat";
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion(String version) {
if (StringUtils.isNotBlank(version)) {
this.version = version;
}
}
/**
* @return the build
*/
public String getBuild() {
return build;
}
/**
* @param build the build to set
*/
public void setBuild(String build) {
if (StringUtils.isNotBlank(build)) {
this.build = build;
}
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
if (StringUtils.isNotBlank(name)) {
this.name = name;
}
}
@Override
public String toString() {
return new ToStringBuilder(this).
append("name", name).
append("version", version).
append("build", build).
toString();
}
}

View File

@ -1,52 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.application;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
/**
* Web application lifecycle listener.
*
* @author rlawson
*/
public class WebGoatServletListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
context.log("WebGoat is starting");
setApplicationVariables(context);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
context.log("WebGoat is stopping");
}
private void setApplicationVariables(ServletContext context) {
Application app = Application.getInstance();
try {
InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(inputStream);
Attributes attr = manifest.getMainAttributes();
String name = attr.getValue("Specification-Title");
String version = attr.getValue("Specification-Version");
String build = attr.getValue("Implementation-Version");
app.setName(name);
app.setVersion(version);
app.setBuild(build);
} catch (IOException ioe) {
context.log("Error setting application variables", ioe);
}
}
}

View File

@ -1,49 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author rlawson
*/
@Controller
public class About {
final Logger logger = LoggerFactory.getLogger(About.class);
private static final String WELCOMED = "welcomed";
@RequestMapping(value = "about.mvc", method = RequestMethod.GET)
public ModelAndView welcome(HttpServletRequest request,
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
// set the welcome attribute
// this is so the attack servlet does not also
// send them to the welcome page
HttpSession session = request.getSession();
if (session.getAttribute(WELCOMED) == null) {
session.setAttribute(WELCOMED, "true");
}
//go ahead and send them to webgoat (skip the welcome page)
ModelAndView model = new ModelAndView();
//model.setViewName("welcome");
//model.setViewName("main_new");
model.setViewName("about");
return model;
}
}

View File

@ -1,39 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author rlawson
*/
@Controller
public class Login {
@RequestMapping(value = "login.mvc", method = RequestMethod.GET)
public ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
}

View File

@ -1,45 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author rlawson
*/
@Controller
public class Logout {
final Logger logger = LoggerFactory.getLogger(Logout.class);
@RequestMapping(value = "logout.mvc", method = RequestMethod.GET)
public ModelAndView logout(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
logger.info("Logging user out");
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("logout");
return model;
}
}

View File

@ -1,97 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.controller;
import java.util.Collection;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.owasp.webgoat.application.Application;
import org.owasp.webgoat.session.WebSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author rlawson
*/
@Controller
public class Start {
final Logger logger = LoggerFactory.getLogger(Start.class);
private static final String WELCOMED = "welcomed";
@Autowired
private ServletContext servletContext;
@RequestMapping(value = "start.mvc", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView start(HttpServletRequest request,
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
// make sure session is set up correctly
// if not redirect user to login
if (checkWebSession(request.getSession()) == false) {
model.setViewName("redirect:/login.mvc");
return model;
}
String role = getRole();
String user = request.getUserPrincipal().getName();
model.addObject("role", role);
model.addObject("user", user);
String contactEmail = servletContext.getInitParameter("email");
model.addObject("contactEmail", contactEmail);
String emailList = servletContext.getInitParameter("emaillist");
model.addObject("emailList", emailList);
Application app = Application.getInstance();
logger.info("Setting application properties: " + app);
model.addObject("version", app.getVersion());
model.addObject("build", app.getBuild());
// if everything ok then go to webgoat UI
model.setViewName("main_new");
return model;
}
private String getRole() {
Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
String role = "N/A";
for (GrantedAuthority authority : authorities) {
authority.getAuthority();
role = authority.getAuthority();
role = StringUtils.lowerCase(role);
role = StringUtils.remove(role, "role_");
break;
}
return role;
}
public boolean checkWebSession(HttpSession session) {
Object o = session.getAttribute(WebSession.SESSION);
if (o == null) {
logger.error("No valid WebSession object found, has session timed out? [" + session.getId() + "]");
return false;
}
if (!(o instanceof WebSession)) {
logger.error("Invalid WebSession object found, this is probably a bug! [" + o.getClass() + " | " + session.getId() + "]");
return false;
}
return true;
}
}

View File

@ -1,49 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author rlawson
*/
@Controller
public class Welcome {
final Logger logger = LoggerFactory.getLogger(Welcome.class);
private static final String WELCOMED = "welcomed";
@RequestMapping(value = "welcome.mvc", method = RequestMethod.GET)
public ModelAndView welcome(HttpServletRequest request,
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
// set the welcome attribute
// this is so the attack servlet does not also
// send them to the welcome page
HttpSession session = request.getSession();
if (session.getAttribute(WELCOMED) == null) {
session.setAttribute(WELCOMED, "true");
}
//go ahead and send them to webgoat (skip the welcome page)
ModelAndView model = new ModelAndView();
//model.setViewName("welcome");
//model.setViewName("main_new");
model.setViewName("forward:/attack?start=true");
return model;
}
}

View File

@ -1,835 +0,0 @@
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.Body;
import org.apache.ecs.html.Form;
import org.apache.ecs.html.Head;
import org.apache.ecs.html.Html;
import org.apache.ecs.html.IMG;
import org.apache.ecs.html.PRE;
import org.apache.ecs.html.Title;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
import org.owasp.webgoat.session.WebgoatProperties;
import org.owasp.webgoat.util.BeanProvider;
import org.owasp.webgoat.util.LabelManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* *************************************************************************************************
* <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.
* <p>
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public abstract class AbstractLesson extends Screen implements Comparable<Object> {
private static final Logger logger = LoggerFactory.getLogger(AbstractLesson.class);
/**
* Description of the Field
*/
public final static String ADMIN_ROLE = "admin";
public final static String CHALLENGE_ROLE = "challenge";
/**
* Description of the Field
*/
public final static String HACKED_ADMIN_ROLE = "hacked_admin";
/**
* Description of the Field
*/
public final static String USER_ROLE = "user";
private static int count = 1;
private Integer id = null;
final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next").setBorder(0).setHspace(0).setVspace(0);
final static IMG previousGrey = new IMG("images/left14.gif").setAlt("Previous").setBorder(0).setHspace(0)
.setVspace(0);
private Integer ranking;
private Category category;
private boolean hidden;
private String sourceFileName;
private Map<String, String> lessonPlanFileName = new HashMap<String, String>();
private String lessonSolutionFileName;
private WebgoatContext webgoatContext;
private LinkedList<String> availableLanguages = new LinkedList<String>();
private String defaultLanguage = "en";
private LabelManager labelManager = null;
/**
* Constructor for the Lesson object
*/
public AbstractLesson() {
id = new Integer(++count);
}
public String getName() {
String className = getClass().getName();
return className.substring(className.lastIndexOf('.') + 1);
}
public void setRanking(Integer ranking) {
this.ranking = ranking;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public void update(WebgoatProperties properties) {
String className = getClass().getName();
className = className.substring(className.lastIndexOf(".") + 1);
setRanking(new Integer(properties.getIntProperty("lesson." + className + ".ranking", getDefaultRanking()
.intValue())));
String categoryRankingKey = "category." + getDefaultCategory().getName() + ".ranking";
// System.out.println("Category ranking key: " + categoryRankingKey);
Category tempCategory = Category.getCategory(getDefaultCategory().getName());
tempCategory.setRanking(new Integer(properties.getIntProperty(categoryRankingKey, getDefaultCategory()
.getRanking().intValue())));
category = tempCategory;
setHidden(properties.getBooleanProperty("lesson." + className + ".hidden", getDefaultHidden()));
// System.out.println(className + " in " + tempCategory.getName() + "
// (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking:
// " + getRanking() + ", hidden:" + hidden +")");
}
public boolean isCompleted(WebSession s) {
return getLessonTracker(s, this).getCompleted();
}
/**
* Gets the credits attribute of the AbstractLesson object
*
* @return The credits value
* @deprecated - Credits have moved to the about page
*/
public abstract Element getCredits();
/**
* Description of the Method
*
* @param obj Description of the Parameter
* @return Description of the Return Value
*/
public int compareTo(Object obj) {
return this.getRanking().compareTo(((AbstractLesson) obj).getRanking());
}
/**
* Description of the Method
*
* @param obj Description of the Parameter
* @return Description of the Return Value
*/
public boolean equals(Object obj) {
return this.getScreenId() == ((AbstractLesson) obj).getScreenId();
}
/**
* Gets the category attribute of the Lesson object
*
* @return The category value
*/
public Category getCategory() {
return category;
}
protected abstract Integer getDefaultRanking();
protected abstract Category getDefaultCategory();
protected abstract boolean getDefaultHidden();
/**
* Gets the fileMethod attribute of the Lesson class
*
* @param reader Description of the Parameter
* @param methodName Description of the Parameter
* @param numbers Description of the Parameter
* @return The fileMethod value
*/
public static String getFileMethod(BufferedReader reader, String methodName, boolean numbers) {
int count = 0;
StringBuffer sb = new StringBuffer();
boolean echo = false;
boolean startCount = false;
int parenCount = 0;
try {
String line;
while ((line = reader.readLine()) != null) {
if ((line.indexOf(methodName) != -1)
&& ((line.indexOf("public") != -1) || (line.indexOf("protected") != -1) || (line
.indexOf("private") != -1))) {
echo = true;
startCount = true;
}
if (echo && startCount) {
if (numbers) {
sb.append(pad(++count) + " ");
}
sb.append(line + "\n");
}
if (echo && (line.indexOf("{") != -1)) {
parenCount++;
}
if (echo && (line.indexOf("}") != -1)) {
parenCount--;
if (parenCount == 0) {
startCount = false;
echo = false;
}
}
}
reader.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
return (sb.toString());
}
/**
* Reads text from a file into an ElementContainer. Each line in the file is
* represented in the ElementContainer by a StringElement. Each
* StringElement is appended with a new-line character.
*
* @param reader Description of the Parameter
* @param numbers Description of the Parameter
* @return Description of the Return Value
*/
public static String readFromFile(BufferedReader reader, boolean numbers) {
return (getFileText(reader, numbers));
}
/**
* Gets the fileText attribute of the Screen class
*
* @param reader Description of the Parameter
* @param numbers Description of the Parameter
* @return The fileText value
*/
public static String getFileText(BufferedReader reader, boolean numbers) {
int count = 0;
StringBuffer sb = new StringBuffer();
try {
String line;
while ((line = reader.readLine()) != null) {
if (numbers) {
sb.append(pad(++count) + " ");
}
sb.append(line + System.getProperty("line.separator"));
}
reader.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
return (sb.toString());
}
/**
* Will this screen be included in an enterprise edition.
*
* @return The ranking value
*/
public boolean isEnterprise() {
return false;
}
/**
* Gets the hintCount attribute of the Lesson object
*
* @param s The user's WebSession
* @return The hintCount value
*/
public int getHintCount(WebSession s) {
return getHints(s).size();
}
protected abstract List<String> getHints(WebSession s);
// @TODO we need to restrict access at the service layer
// rather than passing session object around
public List<String> getHintsPublic(WebSession s) {
List<String> hints = getHints(s);
return hints;
}
/**
* Fill in a minor hint that will help people who basically get it, but are
* stuck on somthing silly.
*
* @param s The users WebSession
* @return The hint1 value
*/
public String getHint(WebSession s, int hintNumber) {
return "Hint: " + getHints(s).get(hintNumber);
}
/**
* Gets the instructions attribute of the AbstractLesson object
*
* @return The instructions value
*/
public abstract String getInstructions(WebSession s);
/**
* Gets the lessonPlan attribute of the Lesson object
*
* @return The lessonPlan value
*/
protected String getLessonName() {
return this.getClass().getSimpleName();
}
/**
* Gets the title attribute of the HelloScreen object
*
* @return The title value
*/
public abstract String getTitle();
/**
* Gets the content of lessonPlanURL
*
* @param s The user's WebSession
* @return The HTML content of the current lesson plan
*/
public String getLessonPlan(WebSession s) {
StringBuffer src = new StringBuffer();
String lang = s.getCurrrentLanguage();
try {
// System.out.println("Loading lesson plan file: " +
// getLessonPlanFileName());
String filename = getLessonPlanFileName(lang);
if (filename == null) {
filename = getLessonPlanFileName(getDefaultLanguage());
}
src.append(readFromFile(new BufferedReader(new FileReader(filename)), false));
} catch (Exception e) {
// s.setMessage( "Could not find lesson plan for " +
// getLessonName());
src = new StringBuffer("Could not find lesson plan for: " + getLessonName() + " and language " + lang);
}
return src.toString();
}
/**
* Gets the ranking attribute of the Lesson object
*
* @return The ranking value
*/
public Integer getRanking() {
if (ranking != null) {
return ranking;
} else {
return getDefaultRanking();
}
}
/**
* Gets the hidden value of the Lesson Object
*
* @return The hidden value
*/
public boolean getHidden() {
return this.hidden;
}
/**
* Gets the role attribute of the AbstractLesson object
*
* @return The role value
*/
public String getRole() {
// 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.
return USER_ROLE;
}
/**
* Gets the uniqueID attribute of the AbstractLesson object
*
* @return The uniqueID value
*/
public int getScreenId() {
return id.intValue();
}
public String getHtml_DELETE_ME(WebSession s) {
String html = null;
// FIXME: This doesn't work for the labs since they do not implement
// createContent().
String rawHtml = createContent(s).toString();
// System.out.println("Getting raw html content: " +
// rawHtml.substring(0, Math.min(rawHtml.length(), 100)));
html = convertMetachars(AbstractLesson.readFromFile(new BufferedReader(new StringReader(rawHtml)), true));
// System.out.println("Getting encoded html content: " +
// html.substring(0, Math.min(html.length(), 100)));
return html;
}
public String getSource(WebSession s) {
String source = null;
String src = null;
try {
// System.out.println("Loading source file: " +
// getSourceFileName());
src = convertMetacharsJavaCode(readFromFile(new BufferedReader(new FileReader(getSourceFileName())), true));
// TODO: For styled line numbers and better memory efficiency,
// use a custom FilterReader
// that performs the convertMetacharsJavaCode() transform plus
// optionally adds a styled
// line number. Wouldn't color syntax be great too?
} catch (Exception e) {
s.setMessage("Could not find source file");
src = ("Could not find the source file or source file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ "?subject=Source " + getSourceFileName() + " not found. Lesson: "
+ s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext()
.getFeedbackAddress() + "</a>");
}
Html html = new Html();
Head head = new Head();
head.addElement(new Title(getSourceFileName()));
Body body = new Body();
body.addElement(new StringElement(src));
html.addElement(head);
html.addElement(body);
source = html.toString();
return source;
}
public String getRawSource(WebSession s) {
String src;
try {
logger.debug("Loading source file: " + getSourceFileName());
src = readFromFile(new BufferedReader(new FileReader(getSourceFileName())), false);
} catch (FileNotFoundException e) {
s.setMessage("Could not find source file");
src = ("Could not find the source file or source file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ "?subject=Source " + getSourceFileName() + " not found. Lesson: "
+ s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext()
.getFeedbackAddress() + "</a>");
}
return src;
}
public String getSolution(WebSession s) {
String src = null;
try {
// System.out.println("Solution: " + getLessonSolutionFileName());
src = readFromFile(new BufferedReader(new FileReader(getLessonSolutionFileName())), false);
} catch (Exception e) {
logger.error("Could not find solution for {}", getLessonSolutionFileName());
s.setMessage("Could not find the solution file");
src = ("Could not find the solution file or solution file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ "?subject=Solution " + getLessonSolutionFileName() + " not found. Lesson: "
+ s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext()
.getFeedbackAddress() + "</a>");
}
// Solutions are html files
return src;
}
/**
* <p>
* Returns the default "path" portion of a lesson's URL.</p>
* <p>
* <p>
* Legacy webgoat lesson links are of the form
* "attack?Screen=Xmenu=Ystage=Z". This method returns the path portion of
* the url, i.e., "attack" in the string above.</p>
* <p>
* <p>
* Newer, Spring-Controller-based classes will override this method to
* return "*.do"-styled paths.</p>
*/
protected String getPath() {
return "#attack";
}
/**
* Get the link that can be used to request this screen.
*
* @return
*/
public String getLink() {
StringBuffer link = new StringBuffer();
// mvc update:
link.append(getPath()).append("/");
link.append(getScreenId());
link.append("/");
link.append(getCategory().getRanking());
return link.toString();
}
/**
* Get the link to the jsp page used to render this screen.
*
* @return
*/
public String getPage(WebSession s) {
return null;
}
/**
* Get the link to the jsp template page used to render this screen.
*
* @return
*/
public String getTemplatePage(WebSession s) {
return null;
}
public abstract String getCurrentAction(WebSession s);
public abstract void setCurrentAction(WebSession s, String lessonScreen);
/**
* Override this method to implement accesss control in a lesson.
*
* @param s
* @param functionId
* @return
*/
public boolean isAuthorized(WebSession s, int employeeId, String functionId) {
return false;
}
/**
* Override this method to implement accesss control in a lesson.
*
* @param s
* @param functionId
* @return
*/
public boolean isAuthorized(WebSession s, String role, String functionId) {
logger.info("Checking if " + role + " authorized for: " + functionId);
boolean authorized = false;
try {
String query = "SELECT * FROM auth WHERE role = '" + role + "' and functionid = '" + functionId + "'";
try {
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
authorized = answer_results.first();
logger.info("authorized: " + authorized);
} catch (SQLException sqle) {
s.setMessage("Error authorizing");
logger.error("Error authorizing", sqle);
}
} catch (Exception e) {
s.setMessage("Error authorizing");
logger.error("Error authorizing", e);
}
return authorized;
}
public int getUserId(WebSession s) throws ParameterNotFoundException {
return -1;
}
public String getUserName(WebSession s) throws ParameterNotFoundException {
return null;
}
/**
* Description of the Method
*
* @param windowName Description of the Parameter
* @return Description of the Return Value
*/
public static String makeWindowScript(String windowName) {
// FIXME: make this string static
StringBuffer script = new StringBuffer();
script.append("<script language=\"JavaScript\">\n");
script.append(" <!--\n");
script.append(" function makeWindow(url) {\n");
script.append("\n");
script.append(" agent = navigator.userAgent;\n");
script.append("\n");
script.append(" params = \"\";\n");
script.append(" params += \"toolbar=0,\";\n");
script.append(" params += \"location=0,\";\n");
script.append(" params += \"directories=0,\";\n");
script.append(" params += \"status=0,\";\n");
script.append(" params += \"menubar=0,\";\n");
script.append(" params += \"scrollbars=1,\";\n");
script.append(" params += \"resizable=1,\";\n");
script.append(" params += \"width=500,\";\n");
script.append(" params += \"height=350\";\n");
script.append("\n");
script.append(" // close the window to vary the window size\n");
script.append(" if (typeof(win) == \"object\" && !win.closed){\n");
script.append(" win.close();\n");
script.append(" }\n");
script.append("\n");
script.append(" win = window.open(url, '" + windowName + "' , params);\n");
script.append("\n");
script.append(" // bring the window to the front\n");
script.append(" win.focus();\n");
script.append(" }\n");
script.append(" //-->\n");
script.append(" </script>\n");
return script.toString();
}
/**
* Simply reads a url into an Element for display. CAUTION: you might want
* to tinker with any non-https links (href)
*
* @param url Description of the Parameter
* @return Description of the Return Value
*/
public static Element readFromURL(String url) {
ElementContainer ec = new ElementContainer();
try {
URL u = new URL(url);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(huc.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
ec.addElement(new StringElement(line));
}
reader.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
return (ec);
}
/**
* Description of the Method
*
* @param reader Description of the Parameter
* @param numbers Description of the Parameter
* @param methodName Description of the Parameter
* @return Description of the Return Value
*/
public static Element readMethodFromFile(BufferedReader reader, String methodName, boolean numbers) {
PRE pre = new PRE().addElement(getFileMethod(reader, methodName, numbers));
return (pre);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
*/
public void handleRequest(WebSession s) {
// call createContent first so messages will go somewhere
Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
form.addElement(createContent(s));
setContent(form);
s.getRequest().getRequestURL();
}
public String getFormAction() {
return getLink();
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
public String toString() {
return getTitle();
}
public String getDefaultLanguage() {
return this.defaultLanguage;
}
public String getLessonPlanFileName(String lang) {
String ret = lessonPlanFileName.get(lang);
if (ret == null) {
ret = lessonPlanFileName.get(getDefaultLanguage());
}
return ret;
}
public void setLessonPlanFileName(String lang, String lessonPlanFileName) {
this.lessonPlanFileName.put(lang, lessonPlanFileName);
this.availableLanguages.add(lang);
}
public List<String> getAvailableLanguages() {
return this.availableLanguages;
}
public String getLessonSolutionFileName() {
return lessonSolutionFileName;
}
public void setLessonSolutionFileName(String lessonSolutionFileName) {
this.lessonSolutionFileName = lessonSolutionFileName;
}
public String getSourceFileName() {
return sourceFileName;
}
public void setSourceFileName(String sourceFileName) {
logger.debug("Setting source file of lesson " + this + " to: " + sourceFileName);
this.sourceFileName = sourceFileName;
}
public WebgoatContext getWebgoatContext() {
return webgoatContext;
}
public void setWebgoatContext(WebgoatContext webgoatContext) {
this.webgoatContext = webgoatContext;
}
protected LabelManager getLabelManager() {
if (labelManager == null) {
labelManager = BeanProvider.getBean("labelManager", LabelManager.class);
}
return labelManager;
}
/**
* A reference from an image, script and link tag must include the context path.
* <p>
* A reference in include directives are made from within the web application on the server.
* However, img tags (and the like) make references from the client browser.
* In such external references, the context path must be included.
*/
protected final String buildImagePath(WebSession w, String imgResourceName) {
return w.getRequest()
.getContextPath() + "/plugin_extracted/plugin/" + getLessonName() + "/images/" + imgResourceName;
}
protected final String buildJspPath(WebSession w, String jspResourceName, boolean includeContextPath) {
String path = includeContextPath ? w.getContext().getContextPath() : "";
return path + "/plugin_extracted/plugin/" + getLessonName() + "/jsp/" + jspResourceName;
}
protected final String buildJsPath(WebSession w, String jsResourceName) {
return w.getRequest()
.getContextPath() + "/plugin_extracted/plugin/" + getLessonName() + "/js/" + jsResourceName;
}
protected final File getLessonDirectory(WebSession w) {
return new File(w.getContext().getRealPath("/plugin_extracted/plugin/" + getLessonName() + "/"));
}
}

View File

@ -1,166 +0,0 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public class Category implements Comparable {
public final static Category INTRODUCTION = new Category("Introduction", new Integer(5));
public final static Category GENERAL = new Category("General", new Integer(100));
public final static Category ACCESS_CONTROL = new Category("Access Control Flaws", new Integer(200));
public final static Category AJAX_SECURITY = new Category("AJAX Security", new Integer(400));
public final static Category AUTHENTICATION = new Category("Authentication Flaws", new Integer(500));
public final static Category BUFFER_OVERFLOW = new Category("Buffer Overflows", new Integer(600));
public final static Category CODE_QUALITY = new Category("Code Quality", new Integer(700));
public final static Category CONCURRENCY = new Category("Concurrency", new Integer(800));
public final static Category XSS = new Category("Cross-Site Scripting (XSS)", new Integer(900));
public final static Category ERROR_HANDLING = new Category("Improper Error Handling", new Integer(1000));
public final static Category INJECTION = new Category("Injection Flaws", new Integer(1100));
public final static Category DOS = new Category("Denial of Service", new Integer(1200));
public final static Category INSECURE_COMMUNICATION = new Category("Insecure Communication", new Integer(1300));
public final static Category INSECURE_CONFIGURATION = new Category("Insecure Configuration", new Integer(1400));
public final static Category INSECURE_STORAGE = new Category("Insecure Storage", new Integer(1500));
public final static Category MALICIOUS_EXECUTION = new Category("Malicious Execution", new Integer(1600));
public final static Category PARAMETER_TAMPERING = new Category("Parameter Tampering", new Integer(1700));
public final static Category SESSION_MANAGEMENT = new Category("Session Management Flaws", new Integer(1800));
public final static Category WEB_SERVICES = new Category("Web Services", new Integer(1900));
public final static Category ADMIN_FUNCTIONS = new Category("Admin Functions", new Integer(2000));
public final static Category CHALLENGE = new Category("Challenge", new Integer(3000));
private static final List<Category> categories = new ArrayList<Category>();
private String category;
private Integer ranking;
static {
categories.add(INTRODUCTION);
categories.add(PARAMETER_TAMPERING);
categories.add(ACCESS_CONTROL);
categories.add(AUTHENTICATION);
categories.add(SESSION_MANAGEMENT);
categories.add(XSS);
categories.add(BUFFER_OVERFLOW);
categories.add(INJECTION);
categories.add(MALICIOUS_EXECUTION);
categories.add(ERROR_HANDLING);
categories.add(INSECURE_STORAGE);
categories.add(DOS);
categories.add(INSECURE_CONFIGURATION);
categories.add(WEB_SERVICES);
categories.add(AJAX_SECURITY);
categories.add(ADMIN_FUNCTIONS);
categories.add(GENERAL);
categories.add(CODE_QUALITY);
categories.add(CONCURRENCY);
categories.add(INSECURE_COMMUNICATION);
categories.add(CHALLENGE);
}
public static synchronized void addCategory(Category c) {
categories.add(c);
}
public static synchronized Category getCategory(String name) {
Iterator<Category> it = categories.iterator();
while (it.hasNext()) {
Category c = it.next();
if (c.getName().equals(name)) {
return c;
}
}
return null;
}
public Category(String category, Integer ranking) {
this.category = category;
this.ranking = ranking;
}
@Override
public int compareTo(Object obj) {
int value = 1;
if (obj instanceof Category) {
value = this.getRanking().compareTo(((Category) obj).getRanking());
}
return value;
}
public Integer getRanking() {
return ranking;
}
public Integer setRanking(Integer ranking) {
return this.ranking = ranking;
}
public String getName() {
return category;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Category) && getName().equals(((Category) obj).getName());
}
@Override
public String toString() {
return getName();
}
}

View File

@ -1,244 +0,0 @@
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.Center;
import org.apache.ecs.html.H3;
import org.apache.ecs.html.P;
import org.apache.ecs.html.PRE;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public abstract class LessonAdapter extends AbstractLesson {
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s) {
// Mark this lesson as completed.
makeSuccess(s);
ElementContainer ec = new ElementContainer();
ec.addElement(new Center().addElement(new H3().addElement(new StringElement(
"Detailed Lesson Creation Instructions."))));
ec.addElement(new P());
ec
.addElement(new StringElement(
"Lesson are simple to create and very little coding is required. &nbsp;&nbsp;"
+ "In fact, most lessons can be created by following the easy to use instructions in the "
+ "<A HREF=http://www.owasp.org/index.php/WebGoat_User_and_Install_Guide_Table_of_Contents>WebGoat User Guide.</A>&nbsp;&nbsp;"
+ "If you would prefer, send your lesson ideas to "
+ getWebgoatContext().getFeedbackAddressHTML()));
String fileName = s.getContext().getRealPath("WEB-INF/classes/New Lesson Instructions.txt");
if (fileName != null) {
try {
PRE pre = new PRE();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = in.readLine()) != null) {
pre.addElement(line + "\n");
}
ec.addElement(pre);
} catch (Exception e) {
e.printStackTrace();
}
}
return (ec);
}
/**
* Gets the category attribute of the LessonAdapter object. The default
* category is "General" Only override this method if you wish to create a
* new category or if you wish this lesson to reside within a category other
* the "General"
*
* @return The category value
*/
protected Category getDefaultCategory() {
return Category.GENERAL;
}
protected boolean getDefaultHidden() {
return false;
}
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() {
return DEFAULT_RANKING;
}
/**
* Gets the hintCount attribute of the LessonAdapter object
*
* @return The hintCount value
*/
public int getHintCount(WebSession s) {
return getHints(s).size();
}
/**
* Fill in a minor hint that will help people who basically get it, but are
* stuck on somthing silly. Hints will be returned to the user in the order
* they appear below. The user must click on the "next hint" button before
* the hint will be displayed.
*
* @return The hint1 value
*/
protected List<String> getHints(WebSession s) {
List<String> hints = new ArrayList<String>();
hints.add("There are no hints defined.");
return hints;
}
/**
* Gets the credits attribute of the AbstractLesson object
*
* @deprecated Credits are in the about page. This method s no
* longer called from WebGoat
* @return The credits value
*/
public Element getCredits() {
return new StringElement();
}
/**
* Gets the instructions attribute of the LessonAdapter object. Instructions
* will rendered as html and will appear below the control area and above
* the actual lesson area. Instructions should provide the user with the
* general setup and goal of the lesson.
*
* @return The instructions value
*/
public String getInstructions(WebSession s) {
StringBuffer buff = new StringBuffer();
String lang = s.getCurrrentLanguage();
try {
String fileName = getLessonPlanFileName(lang);
if (fileName != null) {
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
boolean startAppending = false;
while ((line = in.readLine()) != null) {
if (line.indexOf("<!-- Start Instructions -->") != -1) {
startAppending = true;
continue;
}
if (line.indexOf("<!-- Stop Instructions -->") != -1) {
startAppending = false;
continue;
}
if (startAppending) {
buff.append(line + "\n");
}
}
}
} catch (Exception e) {
}
return buff.toString();
}
/**
* Fill in a descriptive title for this lesson. The title of the lesson.
* This will appear above the control area at the top of the page. This
* field will be rendered as html.
*
* @return The title value
*/
public String getTitle() {
return "Untitled Lesson " + getScreenId();
}
public String getCurrentAction(WebSession s) {
return s.getLessonSession(this).getCurrentLessonScreen();
}
public void setCurrentAction(WebSession s, String lessonScreen) {
s.getLessonSession(this).setCurrentLessonScreen(lessonScreen);
}
public Object getSessionAttribute(WebSession s, String key) {
return s.getRequest().getSession().getAttribute(key);
}
public void setSessionAttribute(WebSession s, String key, Object value) {
s.getRequest().getSession().setAttribute(key, value);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeSuccess(WebSession s) {
getLessonTracker(s).setCompleted(true);
s.setMessage(getLabelManager().get("LessonCompleted"));
return (null);
}
/**
* Gets the credits attribute of the AbstractLesson object
*
* @return The credits value
*/
protected Element getCustomCredits(String text, Element e) {
Table t = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("RIGHT");
TR tr = new TR();
tr.addElement(new TD(text).setVAlign("MIDDLE").setAlign("RIGHT").setWidth("100%"));
tr.addElement(new TD(e).setVAlign("MIDDLE").setAlign("RIGHT"));
t.addElement(tr);
return t;
}
}

View File

@ -1,99 +0,0 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
import java.sql.SQLException;
import org.owasp.webgoat.session.CreateDB;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.LessonTracker;
import org.owasp.webgoat.session.RandomLessonTracker;
import org.owasp.webgoat.session.WebSession;
public abstract class RandomLessonAdapter extends LessonAdapter
{
public abstract String[] getStages();
public void setStage(WebSession s, String stage)
{
getLessonTracker(s).setStage(stage);
try
{
Connection connection = DatabaseUtilities.getConnection(s);
CreateDB db = new CreateDB();
db.makeDB(connection);
System.out.println("Successfully refreshed the database.");
} catch (SQLException sqle)
{
System.out.println("Error refreshing the database!");
sqle.printStackTrace();
}
}
public String getStage(WebSession s)
{
return getLessonTracker(s).getStage();
}
public void setStageComplete(WebSession s, String stage)
{
RandomLessonTracker lt = getLessonTracker(s);
lt.setStageComplete(stage, true);
if (lt.getCompleted())
{
s.setMessage("Congratulations, you have completed this lab");
}
else
{
s.setMessage("You have completed Stage " + (lt.getStageNumber(stage) + 1) + ": " + stage + ".");
if (!stage.equals(lt.getStage()))
s.setMessage(" Welcome to Stage " + (lt.getStageNumber(lt.getStage()) + 1) + ": " + lt.getStage());
}
try
{
Connection connection = DatabaseUtilities.getConnection(s);
CreateDB db = new CreateDB();
db.makeDB(connection);
System.out.println("Successfully refreshed the database.");
} catch (SQLException sqle)
{
System.out.println("Error refreshing the database!");
sqle.printStackTrace();
}
}
public boolean isStageComplete(WebSession s, String stage)
{
return getLessonTracker(s).hasCompleted(stage);
}
@Override
public RandomLessonTracker getLessonTracker(WebSession s)
{
return (RandomLessonTracker) super.getLessonTracker(s);
}
@Override
public RandomLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson)
{
return (RandomLessonTracker) super.getLessonTracker(s, lesson);
}
@Override
public RandomLessonTracker getLessonTracker(WebSession s, String userNameOverride)
{
return (RandomLessonTracker) super.getLessonTracker(s, userNameOverride);
}
@Override
public LessonTracker createLessonTracker()
{
return new RandomLessonTracker(getStages());
}
}

View File

@ -1,138 +0,0 @@
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
import org.owasp.webgoat.session.LessonTracker;
import org.owasp.webgoat.session.SequentialLessonTracker;
import org.owasp.webgoat.session.WebSession;
public abstract class SequentialLessonAdapter extends LessonAdapter
{
public void setStage(WebSession s, int stage)
{
// System.out.println("Changed to stage " + stage);
getLessonTracker(s).setStage(stage);
}
/*
* By default returns 1 stage. (non-Javadoc)
*/
public int getStageCount()
{
return 1;
}
public int getStage(WebSession s)
{
int stage = getLessonTracker(s).getStage();
// System.out.println("In stage " + stage);
return stage;
}
@Override
public SequentialLessonTracker getLessonTracker(WebSession s)
{
return (SequentialLessonTracker) super.getLessonTracker(s);
}
@Override
public SequentialLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson)
{
return (SequentialLessonTracker) super.getLessonTracker(s, lesson);
}
@Override
public SequentialLessonTracker getLessonTracker(WebSession s, String userNameOverride)
{
return (SequentialLessonTracker) super.getLessonTracker(s, userNameOverride);
}
@Override
public LessonTracker createLessonTracker()
{
return new SequentialLessonTracker();
}
protected Element createStagedContent(WebSession s)
{
try
{
int stage = getLessonTracker(s).getStage();
// int stage = Integer.parseInt(
// getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE,"1"));
switch (stage)
{
case 1:
return (doStage1(s));
case 2:
return (doStage2(s));
case 3:
return (doStage3(s));
case 4:
return (doStage4(s));
case 5:
return (doStage5(s));
case 6:
return (doStage6(s));
default:
throw new Exception("Invalid stage");
}
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
// System.out.println(e);
e.printStackTrace();
}
return (new StringElement(""));
}
protected Element doStage1(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
ec.addElement("Stage 1 Stub");
return ec;
}
protected Element doStage2(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
ec.addElement("Stage 2 Stub");
return ec;
}
protected Element doStage3(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
ec.addElement("Stage 3 Stub");
return ec;
}
protected Element doStage4(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
ec.addElement("Stage 4 Stub");
return ec;
}
protected Element doStage5(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
ec.addElement("Stage 5 Stub");
return ec;
}
protected Element doStage6(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
ec.addElement("Stage 6 Stub");
return ec;
}
}

View File

@ -1,145 +0,0 @@
package org.owasp.webgoat.lessons;
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.Center;
import org.apache.ecs.html.Form;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003
*/
public class WelcomeScreen extends Screen
{
/**
* Constructor for the WelcomeScreen object
*
* @param s
* Description of the Parameter
*/
public WelcomeScreen(WebSession s)
{
setup(s);
}
/**
* Constructor for the WelcomeScreen object
*/
public WelcomeScreen()
{
}
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);
}
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);
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
Element b = ECSFactory.makeButton("Start the Course!");
ec.addElement(new Center(b));
return (ec);
}
/**
* Gets the instructions attribute of the WelcomeScreen object
*
* @return The instructions value
*/
protected String getInstructions()
{
String instructions = "Enter your name and learn how HTTP really works!";
return (instructions);
}
/**
* Gets the title attribute of the WelcomeScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Welcome to the Penetration Testing Course");
}
/*
* (non-Javadoc)
* @see session.Screen#getRole()
*/
public String getRole()
{
return AbstractLesson.USER_ROLE;
}
}

View File

@ -1,104 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.WebSession;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003
*/
public abstract class AdminScreen extends Screen
{
/**
* Description of the Field
*/
protected String query = null;
/**
* Constructor for the AdminScreen object
*
* @param s
* Description of the Parameter
* @param q
* Description of the Parameter
*/
public AdminScreen(WebSession s, String q)
{
setQuery(q);
// setupAdmin(s); FIXME: what was this supposed to do?
}
/**
* Constructor for the AdminScreen object
*
* @param s
* Description of the Parameter
*/
public AdminScreen(WebSession s)
{
}
/**
* Constructor for the AdminScreen object
*/
public AdminScreen()
{
}
/**
* Gets the title attribute of the AdminScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Admin Information");
}
public String getRole()
{
return AbstractLesson.ADMIN_ROLE;
}
/**
* Sets the query attribute of the AdminScreen object
*
* @param q
* The new query value
*/
public void setQuery(String q)
{
query = q;
}
}

View File

@ -1,121 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003
*/
public class ProductsAdminScreen extends LessonAdapter
{
private final static String QUERY = "SELECT * FROM product_system_data";
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
try
{
Connection connection = DatabaseUtilities.getConnection(s);
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(QUERY);
if (results != null)
{
makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
}
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
/**
* Gets the category attribute of the ProductsAdminScreen object
*
* @return The category value
*/
protected Category getDefaultCategory()
{
return Category.ADMIN_FUNCTIONS;
}
/**
* Gets the role attribute of the ProductsAdminScreen object
*
* @return The role value
*/
public String getRole()
{
return HACKED_ADMIN_ROLE;
}
/**
* Gets the title attribute of the ProductsAdminScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Product Information");
}
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
}

View File

@ -1,157 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import java.sql.Connection;
import org.owasp.webgoat.lessons.*;
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.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003
*/
public class RefreshDBScreen extends LessonAdapter
{
private final static String REFRESH = "Refresh";
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
try
{
boolean refresh = s.getParser().getBooleanParameter(REFRESH, false);
if (refresh)
{
refreshDB(s);
ec.addElement(new StringElement("Successfully refreshed the database."));
}
else
{
Element label = new StringElement("Refresh the database? ");
A link1 = ECSFactory.makeLink("Yes", REFRESH, true);
A link2 = ECSFactory.makeLink("No", REFRESH, false);
TD td1 = new TD().addElement(label);
TD td2 = new TD().addElement(link1);
TD td3 = new TD().addElement(link2);
TR row = new TR().addElement(td1).addElement(td2).addElement(td3);
Table t = new Table().setCellSpacing(40).setWidth("50%");
if (s.isColor())
{
t.setBorder(1);
}
t.addElement(row);
ec.addElement(t);
}
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
/**
* Gets the category attribute of the RefreshDBScreen object
*
* @return The category value
*/
protected Category getDefaultCategory()
{
return Category.ADMIN_FUNCTIONS;
}
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the role attribute of the RefreshDBScreen object
*
* @return The role value
*/
public String getRole()
{
return ADMIN_ROLE;
}
/**
* Gets the title attribute of the RefreshDBScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Refresh Database");
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
*/
public void refreshDB(WebSession s)
{
try
{
Connection connection = DatabaseUtilities.getConnection(s);
CreateDB db = new CreateDB();
db.makeDB(connection);
System.out.println("Successfully refreshed the database.");
} catch (Exception e)
{
s.setMessage("Error refreshing database " + this.getClass().getName());
e.printStackTrace();
}
}
}

View File

@ -1,294 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import java.util.Iterator;
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.Center;
import org.apache.ecs.html.H2;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.LessonTracker;
import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public class ReportCardScreen extends LessonAdapter
{
/**
* Description of the Field
*/
protected final static String USERNAME = "Username";
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
String user = null;
try
{
if (s.getRequest().isUserInRole(WebSession.WEBGOAT_ADMIN))
{
user = s.getParser().getRawParameter(USERNAME);
}
else
{
user = s.getUserName();
}
} catch (Exception e)
{
}
if (user == null)
{
user = s.getUserName();
}
ec.addElement(makeFeedback(s));
ec.addElement(makeReportCard(s, user));
return ec;
}
private Element makeFeedback(WebSession s)
{
ElementContainer ec = new ElementContainer();
ec.addElement(new StringElement("Comments and suggestions are welcome. "
+ getWebgoatContext().getFeedbackAddressHTML() + "<br><br>"));
return ec;
}
/**
* Gets the category attribute of the UserAdminScreen object
*
* @return The category value
*/
protected Category getDefaultCategory()
{
return Category.ADMIN_FUNCTIONS;
}
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the role attribute of the UserAdminScreen object
*
* @return The role value
*/
public String getRole()
{
return USER_ROLE;
}
/**
* Gets the title attribute of the UserAdminScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Report Card");
}
/**
* Description of the Method
*
* @param screen
* Description of the Parameter
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
private TR makeLessonRow(WebSession s, String user, Screen screen)
{
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(s, user, screen);
TR tr = new TR();
if (lessonTracker.getCompleted())
{
tr.setBgColor(HtmlColor.LIGHTGREEN);
}
else if (lessonTracker.getNumVisits() == 0)
{
tr.setBgColor(HtmlColor.LIGHTBLUE);
}
else if (!lessonTracker.getCompleted() && lessonTracker.getNumVisits() > 10)
{
tr.setBgColor(HtmlColor.RED);
}
else
{
tr.setBgColor(HtmlColor.YELLOW);
}
tr.addElement(new TD().addElement(screen.getTitle()));
tr.addElement(new TD().setAlign("CENTER").addElement(lessonTracker.getCompleted() ? "Y" : "N"));
tr.addElement(new TD().setAlign("CENTER").addElement(Integer.toString(lessonTracker.getNumVisits())));
tr.addElement(new TD().setAlign("CENTER").addElement(Integer.toString(lessonTracker.getMaxHintLevel())));
return tr;
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeMessages(WebSession s)
{
ElementContainer ec = new ElementContainer();
return (ec);
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
public Element makeReportCard(WebSession s, String user)
{
ElementContainer ec = new ElementContainer();
ec.addElement(makeUser(s, user));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1);
if (s.isColor())
{
t.setBorder(1);
}
TR tr = new TR();
t.addElement(makeUserHeaderRow());
// These are all the user lesson
tr = new TR();
tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement("Normal user lessons"));
t.addElement(tr);
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.USER_ROLE).iterator(); lessonIter
.hasNext();)
{
Screen screen = (Screen) lessonIter.next();
t.addElement(makeLessonRow(s, user, screen));
}
// The user figured out there was a hackable admin acocunt
tr = new TR();
tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement("Hackable Admin Screens"));
t.addElement(tr);
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{
Screen screen = (Screen) lessonIter.next();
t.addElement(makeLessonRow(s, user, screen));
}
// The user figured out how to actually hack the admin acocunt
tr = new TR();
tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement("Actual Admin Screens"));
t.addElement(tr);
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{
Screen screen = (Screen) lessonIter.next();
t.addElement(makeLessonRow(s, user, screen));
}
ec.addElement(t);
return (ec);
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeUser(WebSession s, String user)
{
H2 h2 = new H2();
// FIXME: The session is the current session, not the session of the user we are reporting.
// String type = s.isAdmin() ? " [Administrative User]" : s.isHackedAdmin() ?
// " [Normal User - Hacked Admin Access]" : " [Normal User]";
String type = "";
h2.addElement(new StringElement("Results for: " + user + type));
return h2;
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
private TR makeUserHeaderRow()
{
TR tr = new TR();
tr.addElement(new TH("Lesson"));
tr.addElement(new TH("Complete"));
tr.addElement(new TH("Visits"));
tr.addElement(new TH("Hints"));
return tr;
}
}

View File

@ -1,314 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import java.util.Enumeration;
import java.util.Iterator;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.HtmlColor;
import org.apache.ecs.html.Center;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.P;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.LessonTracker;
import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce mayhew <a href="http://code.google.com">WebGoat</a>
* @created October 28, 2003
*/
public class SummaryReportCardScreen extends LessonAdapter
{
private int totalUsersNormalComplete = 0;
private int totalUsersAdminComplete = 0;
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
String selectedUser = null;
try
{
if (s.getRequest().isUserInRole(WebSession.WEBGOAT_ADMIN))
{
Enumeration e = s.getParser().getParameterNames();
while (e.hasMoreElements())
{
String key = (String) e.nextElement();
if (key.startsWith("View_"))
{
selectedUser = key.substring("View_".length());
ReportCardScreen reportCard = new ReportCardScreen();
return reportCard.makeReportCard(s, selectedUser);
}
if (key.startsWith("Delete_"))
{
selectedUser = key.substring("Delete_".length());
deleteUser(selectedUser);
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
ec.addElement(new Center().addElement(makeSummary(s)));
ec.addElement(new P());
Table t = new Table().setCellSpacing(0).setCellPadding(4).setBorder(1).setWidth("100%");
if (s.isColor())
{
t.setBorder(1);
}
t.addElement(makeUserSummaryHeader());
for (Iterator<String> userIter = UserTracker.instance().getAllUsers(WebSession.WEBGOAT_USER).iterator(); userIter
.hasNext();)
{
String user = userIter.next();
t.addElement(makeUserSummaryRow(s, user));
}
ec.addElement(new Center().addElement(t));
return ec;
}
protected Element makeSummary(WebSession s)
{
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("100%");
if (s.isColor())
{
t.setBorder(1);
}
TR tr = new TR();
// tr.addElement( new TH().addElement( "Summary").setColSpan(1));
// t.addElement( tr );
tr = new TR();
tr.addElement(new TD().setWidth("60%").addElement("Total number of users"));
tr.addElement(new TD().setAlign("LEFT").addElement(
Integer.toString(UserTracker.instance()
.getAllUsers(WebSession.WEBGOAT_USER).size())));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().setWidth("60%").addElement("Total number of users that completed all normal lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(Integer.toString(totalUsersNormalComplete)));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().setWidth("60%").addElement("Total number of users that completed all admin lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(Integer.toString(totalUsersAdminComplete)));
t.addElement(tr);
return t;
}
private void deleteUser(String user)
{
UserTracker.instance().deleteUser(user);
}
/**
* Gets the category attribute of the UserAdminScreen object
*
* @return The category value
*/
protected Category getDefaultCategory()
{
return Category.ADMIN_FUNCTIONS;
}
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the role attribute of the UserAdminScreen object
*
* @return The role value
*/
public String getRole()
{
return ADMIN_ROLE;
}
/**
* Gets the title attribute of the UserAdminScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Summary Report Card");
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeMessages(WebSession s)
{
ElementContainer ec = new ElementContainer();
return (ec);
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
protected Element makeUserSummaryHeader()
{
TR tr = new TR();
tr.addElement(new TH("User Name"));
tr.addElement(new TH("Normal Complete"));
tr.addElement(new TH("Admin Complete"));
tr.addElement(new TH("View"));
tr.addElement(new TH("Delete"));
return tr;
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeUserSummaryRow(WebSession s, String user)
{
TR tr = new TR();
tr.addElement(new TD().setAlign("LEFT").addElement(user));
int lessonCount = 0;
int passedCount = 0;
boolean normalComplete = false;
boolean adminComplete = false;
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.USER_ROLE).iterator(); lessonIter
.hasNext();)
{
lessonCount++;
Screen screen = (Screen) lessonIter.next();
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(s, user, screen);
if (lessonTracker.getCompleted())
{
passedCount++;
}
}
if (lessonCount == passedCount)
{
normalComplete = true;
totalUsersNormalComplete++;
}
String text = Integer.toString(passedCount) + " of " + Integer.toString(lessonCount);
tr.addElement(new TD().setAlign("CENTER").addElement(text));
lessonCount = 0;
passedCount = 0;
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{
lessonCount++;
Screen screen = (Screen) lessonIter.next();
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(s, user, screen);
if (lessonTracker.getCompleted())
{
passedCount++;
}
}
if (lessonCount == passedCount)
{
adminComplete = true;
totalUsersAdminComplete++;
}
text = Integer.toString(passedCount) + " of " + Integer.toString(lessonCount);
tr.addElement(new TD().setAlign("CENTER").addElement(text));
tr.addElement(new TD().setAlign("CENTER").addElement(new Input(Input.SUBMIT, "View_" + user, "View")));
tr.addElement(new TD().setAlign("CENTER").addElement(new Input(Input.SUBMIT, "Delete_" + user, "Delete")));
if (normalComplete && adminComplete)
{
tr.setBgColor(HtmlColor.GREEN);
}
else if (normalComplete)
{
tr.setBgColor(HtmlColor.LIGHTGREEN);
}
else
{
tr.setBgColor(HtmlColor.LIGHTBLUE);
}
return (tr);
}
public boolean isEnterprise()
{
return true;
}
}

View File

@ -1,121 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public class UserAdminScreen extends LessonAdapter
{
private final static String QUERY = "SELECT * FROM user_system_data";
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
try
{
Connection connection = DatabaseUtilities.getConnection(s);
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(QUERY);
if (results != null)
{
makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
}
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
/**
* Gets the category attribute of the UserAdminScreen object
*
* @return The category value
*/
protected Category getDefaultCategory()
{
return Category.ADMIN_FUNCTIONS;
}
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the role attribute of the UserAdminScreen object
*
* @return The role value
*/
public String getRole()
{
return HACKED_ADMIN_ROLE;
}
/**
* Gets the title attribute of the UserAdminScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("User Information");
}
}

View File

@ -1,162 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.owasp.webgoat.lessons.*;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.Input;
import 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003
*/
public class ViewDatabase extends LessonAdapter
{
private final static String SQL = "sql";
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
try
{
ec.addElement(new StringElement("Enter a SQL statement: "));
StringBuffer sqlStatement = new StringBuffer(s.getParser().getRawParameter(SQL, ""));
Input input = new Input(Input.TEXT, SQL, sqlStatement.toString());
ec.addElement(input);
Element b = ECSFactory.makeButton("Go!");
ec.addElement(b);
Connection connection = DatabaseUtilities.getConnection(s);
if (sqlStatement.length() > 0)
{
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(sqlStatement.toString());
if ((results != null) && (results.first() == true))
{
makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
}
}
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
/**
* Gets the category attribute of the DatabaseScreen object
*
* @return The category value
*/
protected Category getDefaultCategory()
{
return Category.ADMIN_FUNCTIONS;
}
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the hints attribute of the DatabaseScreen object
*
* @return The hints value
*/
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints.add("There are no hints defined");
return hints;
}
/**
* Gets the instructions attribute of the ViewDatabase object
*
* @return The instructions value
*/
public String getInstructions(WebSession s)
{
String instructions = "Please post a message to to the WebGoat forum. Your messages will be available for everyone to read.";
return (instructions);
}
/**
* Gets the role attribute of the ViewDatabase object
*
* @return The role value
*/
public String getRole()
{
return HACKED_ADMIN_ROLE;
}
/**
* Gets the title attribute of the DatabaseScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Adhoc Query");
}
}

View File

@ -1,89 +0,0 @@
package org.owasp.webgoat.lessons.admin;
import org.owasp.webgoat.lessons.WelcomeScreen;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.Center;
import org.apache.ecs.html.H1;
import org.owasp.webgoat.session.WebSession;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003
*/
public class WelcomeAdminScreen extends WelcomeScreen
{
/**
* Constructor for the WelcomeAdminScreen object
*
* @param s
* Description of the Parameter
*/
public WelcomeAdminScreen(WebSession s)
{
super(s);
}
/**
* Constructor for the WelcomeAdminScreen object
*/
public WelcomeAdminScreen()
{
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
ec.addElement(new Center(new H1("You are logged on as an administrator")));
ec.addElement(super.createContent(s));
return (ec);
}
/**
* Gets the title attribute of the WelcomeAdminScreen object
*
* @return The title value
*/
public String getTitle()
{
return ("Admin Welcome");
}
}

View File

@ -1,82 +0,0 @@
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.lessons.model;
/**
*
* @author rlawson
*/
public class Hint {
private String hint;
private String lesson;
private int number;
/**
* @return the hint
*/
public String getHint() {
return hint;
}
/**
* @param hint the hint to set
*/
public void setHint(String hint) {
this.hint = hint;
}
/**
* @return the lesson
*/
public String getLesson() {
return lesson;
}
/**
* @param lesson the lesson to set
*/
public void setLesson(String lesson) {
this.lesson = lesson;
}
/**
* @return the number
*/
public int getNumber() {
return number;
}
/**
* @param number the number to set
*/
public void setNumber(int number) {
this.number = number;
}
}

View File

@ -1,48 +0,0 @@
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.lessons.model;
/**
* Model component for the Http Basics lesson. Using a model
* for that simple lesson is architectural overkill. We do it anyway
* for illustrative purposes - to demonstrate the pattern that we will
* use for more complex lessons.
*
*/
public class HttpBasicsModel {
private String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}

View File

@ -1,160 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.lessons.model;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author rlawson
*/
public class LessonMenuItem {
private String name;
private LessonMenuItemType type;
private List<LessonMenuItem> children = new ArrayList<LessonMenuItem>();
private boolean complete;
private String link;
private boolean showSource = true;
private boolean showHints = true;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the children
*/
public List<LessonMenuItem> getChildren() {
return children;
}
/**
* @param children the children to set
*/
public void setChildren(List<LessonMenuItem> children) {
this.children = children;
}
/**
* @return the type
*/
public LessonMenuItemType getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(LessonMenuItemType type) {
this.type = type;
}
public void addChild(LessonMenuItem child) {
children.add(child);
}
@Override
public String toString() {
StringBuilder bldr = new StringBuilder();
bldr.append("Name: ").append(name).append(" | ");
bldr.append("Type: ").append(type).append(" | ");
return bldr.toString();
}
/**
* @return the complete
*/
public boolean isComplete() {
return complete;
}
/**
* @param complete the complete to set
*/
public void setComplete(boolean complete) {
this.complete = complete;
}
/**
* @return the link
*/
public String getLink() {
return link;
}
/**
* @param link the link to set
*/
public void setLink(String link) {
this.link = link;
}
/**
* @return the showSource
*/
public boolean isShowSource() {
return showSource;
}
/**
* @param showSource the showSource to set
*/
public void setShowSource(boolean showSource) {
this.showSource = showSource;
}
/**
* @return the showHints
*/
public boolean isShowHints() {
return showHints;
}
/**
* @param showHints the showHints to set
*/
public void setShowHints(boolean showHints) {
this.showHints = showHints;
}
}

View File

@ -1,39 +0,0 @@
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.lessons.model;
/**
*
* @author rlawson
*/
public enum LessonMenuItemType {
CATEGORY,
LESSON,
STAGE
}

View File

@ -1,66 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.lessons.model;
/**
*
* @author rlawson
*/
public class RequestParameter implements Comparable<RequestParameter> {
private final String name;
private final String value;
public RequestParameter(String name, String value) {
this.name = name;
this.value = value;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the values
*/
public String getValue() {
return value;
}
@Override
public int compareTo(RequestParameter o) {
return this.name.compareTo(o.getName());
}
}

View File

@ -1,31 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.lessons.model;
/**
*
* @author rlawson
*/
public class SourceListing {
private String source;
/**
* @return the source
*/
public String getSource() {
return source;
}
/**
* @param source the source to set
*/
public void setSource(String source) {
this.source = source;
}
}

View File

@ -1,26 +0,0 @@
package org.owasp.webgoat.plugins;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
public final class GlobalProperties {
private final Path pluginDirectory;
public GlobalProperties(Path pluginDirectory) {
this.pluginDirectory = Objects.requireNonNull(pluginDirectory, "pluginDirectory cannot be null");
}
public void loadProperties(Path globalPropertiesPath) {
try {
PluginFileUtils.createDirsIfNotExists(pluginDirectory);
List<Path> filesInDirectory = PluginFileUtils.getFilesInDirectory(globalPropertiesPath);
new Plugin(pluginDirectory).loadFiles(filesInDirectory, true);
} catch (IOException e) {
throw new IllegalStateException("Unable to load global properties, check your installation for the directory i18n: " + globalPropertiesPath.toString(), e);
}
}
}

View File

@ -1,256 +0,0 @@
package org.owasp.webgoat.plugins;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.WebgoatContext;
import org.owasp.webgoat.session.WebgoatProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* *************************************************************************************************
* <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.
* <p/>
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
public class LegacyLoader {
final Logger logger = LoggerFactory.getLogger(LegacyLoader.class);
private final List<String> files = new LinkedList<String>();
public LegacyLoader() {
}
/**
* Take an absolute file and return the filename.
* <p/>
* 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
* <p/>
* 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;
}
// skip over plugins and/or extracted plugins
if ( fileName.indexOf("lessons/plugin") >= 0 || fileName.indexOf("plugin_extracted") >= 0) {
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;
}
/**
* Load all of the filenames into a temporary cache
*
* @param context
* @param path
*/
public void loadFiles(ServletContext context, String path) {
logger.debug("Loading files into cache, path: " + path);
Set resourcePaths = context.getResourcePaths(path);
if (resourcePaths == null) {
logger.error("Unable to load file cache for courses, this is probably a bug or configuration issue");
return;
}
Iterator itr = resourcePaths.iterator();
while (itr.hasNext()) {
String file = (String) itr.next();
if (file.length() != 1 && file.endsWith("/")) {
loadFiles(context, file);
} else {
files.add(file);
}
}
}
/**
* Instantiate all the lesson objects into a cache
*
* @param path
* @param context
*/
public List<AbstractLesson> loadLessons(WebgoatContext webgoatContext, ServletContext context, String path, WebgoatProperties properties ) {
loadFiles(context, path);
List<AbstractLesson> lessons = new LinkedList<AbstractLesson>();
for (String file : files) {
String className = getClassFile(file, path);
if (className != null && !className.endsWith("_i") && className.startsWith("org.owasp.webgoat.lessons.admin")) {
try {
Class c = Class.forName(className);
Object o = c.newInstance();
if (o instanceof AbstractLesson) {
AbstractLesson lesson = (AbstractLesson) o;
lesson.setWebgoatContext(webgoatContext);
lesson.update(properties);
if (lesson.getHidden() == false) {
lessons.add(lesson);
}
}
} catch (Exception e) {
// Bruce says:
// I don't think we want to log the exception here. We could
// be potentially showing a lot of exceptions that don't matter.
// We would only care if the lesson extended AbstractLesson and we
// can't tell that because it threw the exception. Catch 22
// logger.error("Error in loadLessons: ", e);
}
}
}
loadResources(lessons);
return lessons;
}
private String getLanguageFromFileName(String first, String absoluteFile) {
int p1 = absoluteFile.indexOf("/", absoluteFile.indexOf(first) + 1);
int p2 = absoluteFile.indexOf("/", p1 + 1);
String langStr = absoluteFile.substring(p1 + 1, p2);
return langStr;
}
/**
* For each lesson, set the source file and lesson file
* @param lessons
*/
public void loadResources(List<AbstractLesson> lessons ) {
for (AbstractLesson lesson : lessons) {
logger.info("Loading resources for lesson -> " + lesson.getName());
String className = lesson.getClass().getName();
String classFile = getSourceFile(className);
logger.info("Lesson classname: " + className);
logger.info("Lesson java file: " + classFile);
for (String absoluteFile : files) {
String fileName = getFileName(absoluteFile);
//logger.debug("Course: looking at file: " + absoluteFile);
if (absoluteFile.endsWith(classFile)) {
logger.info("Set source file for " + classFile);
lesson.setSourceFileName(absoluteFile);
}
if (absoluteFile.startsWith("/lesson_plans") && absoluteFile.endsWith(".html")
&& className.endsWith(fileName)) {
logger.info("setting lesson plan file " + absoluteFile + " for lesson "
+ lesson.getClass().getName());
logger.info("fileName: " + fileName + " == className: " + className);
String language = getLanguageFromFileName("/lesson_plans", absoluteFile);
lesson.setLessonPlanFileName(language, absoluteFile);
}
if (absoluteFile.startsWith("/lesson_solutions") && absoluteFile.endsWith(".html")
&& className.endsWith(fileName)) {
logger.info("setting lesson solution file " + absoluteFile + " for lesson "
+ lesson.getClass().getName());
logger.info("fileName: " + fileName + " == className: " + className);
lesson.setLessonSolutionFileName(absoluteFile);
}
}
}
}
}

View File

@ -1,178 +0,0 @@
package org.owasp.webgoat.plugins;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.owasp.webgoat.classloader.PluginClassLoader;
import org.owasp.webgoat.lessons.AbstractLesson;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static org.owasp.webgoat.plugins.PluginFileUtils.fileEndsWith;
import static org.owasp.webgoat.plugins.PluginFileUtils.hasParentDirectoryWithName;
import static org.owasp.webgoat.plugins.PluginFileUtils.replaceInFiles;
public class Plugin {
private static final String NAME_LESSON_SOLUTION_DIRECTORY = "lessonSolutions";
private static final String NAME_LESSON_PLANS_DIRECTORY = "lessonPlans";
private static final String NAME_LESSON_I18N_DIRECTORY = "i18n";
private final Path pluginDirectory;
private Class<AbstractLesson> lesson;
private Map<String, File> solutionLanguageFiles = new HashMap<>();
private Map<String, File> lessonPlansLanguageFiles = new HashMap<>();
private List<File> pluginFiles = Lists.newArrayList();
private File lessonSourceFile;
public Plugin(Path pluginDirectory) {
Preconditions.checkNotNull(pluginDirectory, "plugin directory cannot be null");
Preconditions.checkArgument(Files.exists(pluginDirectory), "directory %s does not exists", pluginDirectory);
this.pluginDirectory = pluginDirectory;
}
public Plugin(Path pluginDirectory, List<String> classes) {
this(pluginDirectory);
findLesson(classes);
}
private void findLesson(List<String> classes) {
for (String clazzName : classes) {
findLesson(clazzName);
}
}
private void findLesson(String name) {
String realClassName = name.replaceFirst("/", "").replaceAll("/", ".").replaceAll(".class", "");
PluginClassLoader cl = (PluginClassLoader) Thread.currentThread().getContextClassLoader();
try {
Class clazz = cl.loadClass(realClassName, true);
if (AbstractLesson.class.isAssignableFrom(clazz)) {
this.lesson = clazz;
}
} catch (ClassNotFoundException ce) {
throw new PluginLoadingFailure("Class " + realClassName + " listed in jar but unable to load the class.", ce);
}
}
public void loadFiles(List<Path> files, boolean reload) {
for (Path file : files) {
if (fileEndsWith(file, ".html") && hasParentDirectoryWithName(file, NAME_LESSON_SOLUTION_DIRECTORY)) {
solutionLanguageFiles.put(file.getParent().getFileName().toString(), file.toFile());
}
if (fileEndsWith(file, ".html") && hasParentDirectoryWithName(file, NAME_LESSON_PLANS_DIRECTORY)) {
lessonPlansLanguageFiles.put(file.getParent().getFileName().toString(), file.toFile());
}
if (fileEndsWith(file, ".java")) {
lessonSourceFile = file.toFile();
}
if (fileEndsWith(file, ".properties") && hasParentDirectoryWithName(file, NAME_LESSON_I18N_DIRECTORY)) {
copyProperties(reload, file);
}
if (fileEndsWith(file, ".css", ".jsp", ".js")) {
pluginFiles.add(file.toFile());
}
}
}
private void copyProperties(boolean reload, Path file) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Files.copy(file, bos);
Path propertiesPath = createPropertiesDirectory();
ResourceBundleClassLoader.setPropertiesPath(propertiesPath);
PluginFileUtils.createDirsIfNotExists(file.getParent());
if (reload) {
Files.write(propertiesPath.resolve(file.getFileName()), bos.toByteArray(), CREATE, APPEND);
} else {
Files.write(propertiesPath.resolve(file.getFileName()), bos.toByteArray(), CREATE, TRUNCATE_EXISTING);
}
} catch (IOException io) {
throw new PluginLoadingFailure("Property file detected, but unable to copy the properties", io);
}
}
private Path createPropertiesDirectory() throws IOException {
if (Files.exists(pluginDirectory.resolve(NAME_LESSON_I18N_DIRECTORY))) {
return pluginDirectory.resolve(NAME_LESSON_I18N_DIRECTORY);
} else {
return Files.createDirectory(pluginDirectory.resolve(NAME_LESSON_I18N_DIRECTORY));
}
}
public void rewritePaths(Path pluginTarget) {
try {
replaceInFiles(this.lesson.getSimpleName() + "_files",
pluginTarget.getFileName().toString() + "/plugin/" + this.lesson
.getSimpleName() + "/lessonSolutions/en/" + this.lesson.getSimpleName() + "_files",
solutionLanguageFiles.values());
replaceInFiles(this.lesson.getSimpleName() + "_files",
pluginTarget.getFileName().toString() + "/plugin/" + this.lesson
.getSimpleName() + "/lessonPlans/en/" + this.lesson.getSimpleName() + "_files",
lessonPlansLanguageFiles.values());
String[] replacements = {"jsp", "js"};
for ( String replacement : replacements ) {
String s = String.format("plugin/%s/%s/", this.lesson.getSimpleName(), replacement);
String r = String.format("%s/plugin/%s/%s/", pluginTarget.getFileName().toString(),
this.lesson.getSimpleName(), replacement);
replaceInFiles(s,r, pluginFiles);
replaceInFiles(s,r, Arrays.asList(lessonSourceFile));
}
//CSS with url('/plugin/images') should not begin with / otherwise image cannot be found
String s = String.format("/plugin/%s/images/", this.lesson.getSimpleName());
String r = String.format("%s/plugin/%s/images/", pluginTarget.getFileName().toString(), this.lesson.getSimpleName());
replaceInFiles(s,r, pluginFiles);
replaceInFiles(s,r, Arrays.asList(lessonSourceFile));
} catch (IOException e) {
throw new PluginLoadingFailure("Unable to rewrite the paths in the solutions", e);
}
}
/**
* Lesson is optional, it is also possible that the supplied jar contains only helper classes.
*/
public Optional<AbstractLesson> getLesson() {
try {
if (lesson != null) {
return Optional.of(lesson.newInstance());
}
} catch (IllegalAccessException | InstantiationException e) {
throw new PluginLoadingFailure("Unable to instantiate the lesson " + lesson.getName(), e);
}
return Optional.absent();
}
public Optional<File> getLessonSolution(String language) {
return Optional.fromNullable(this.solutionLanguageFiles.get(language));
}
public Map<String, File> getLessonSolutions() {
return this.solutionLanguageFiles;
}
public Optional<File> getLessonSource() {
return Optional.fromNullable(lessonSourceFile);
}
public Map<String, File> getLessonPlans() {
return this.lessonPlansLanguageFiles;
}
}

View File

@ -1,29 +0,0 @@
package org.owasp.webgoat.plugins;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@WebListener
public class PluginBackgroundLoader implements ServletContextListener {
private ScheduledExecutorService scheduler;
@Override
public void contextInitialized(ServletContextEvent event) {
String pluginPath = event.getServletContext().getRealPath("plugin_lessons");
String targetPath = event.getServletContext().getRealPath("plugin_extracted");
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new PluginsLoader(Paths.get(pluginPath), Paths.get(targetPath)), 0, 5, TimeUnit.MINUTES);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}

View File

@ -1,69 +0,0 @@
package org.owasp.webgoat.plugins;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static java.lang.String.format;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static org.owasp.webgoat.plugins.PluginFileUtils.createDirsIfNotExists;
/**
* Extract the jar file and place them in the system temp directory in the folder webgoat and collect the files
* and classes.
*/
public class PluginExtractor {
private final Path pluginArchive;
private final List<String> classes = Lists.newArrayList();
private final List<Path> files = new ArrayList<>();
public PluginExtractor(Path pluginArchive) {
this.pluginArchive = pluginArchive;
}
public void extract(final Path target) {
try (FileSystem zip = createZipFileSystem()) {
final Path root = zip.getPath("/");
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toString().endsWith(".class")) {
classes.add(file.toString());
}
files.add(Files.copy(file, createDirsIfNotExists(Paths.get(target.toString(), file.toString())), REPLACE_EXISTING));
return FileVisitResult.CONTINUE;
}
});
} catch (Exception e) {
new PluginLoadingFailure(format("Unable to extract: %s", pluginArchive.getFileName()), e);
}
}
public List<String> getClasses() {
return this.classes;
}
public List<Path> getFiles() {
return this.files;
}
private FileSystem createZipFileSystem() throws Exception {
final URI uri = URI.create("jar:file:" + pluginArchive.toUri().getPath());
return FileSystems.newFileSystem(uri, new HashMap<String, Object>());
}
}

View File

@ -1,90 +0,0 @@
package org.owasp.webgoat.plugins;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class PluginFileUtils {
public static boolean fileEndsWith(Path p, String s) {
return p.getFileName().toString().endsWith(s);
}
public static boolean fileEndsWith(Path p, String... suffixes) {
for (String suffix : suffixes) {
if (fileEndsWith(p, suffix)) {
return true;
}
}
return false;
}
public static boolean hasParentDirectoryWithName(Path p, String s) {
if (p == null || p.getParent() == null || p.getParent().equals(p.getRoot())) {
return false;
}
if (p.getParent().getFileName().toString().equals(s)) {
return true;
}
return hasParentDirectoryWithName(p.getParent(), s);
}
public static Path createDirsIfNotExists(Path p) throws IOException {
if (Files.notExists(p)) {
Files.createDirectories(p);
}
return p;
}
public static List<Path> getFilesInDirectory(Path directory) throws IOException {
List<Path> files = new ArrayList<>();
DirectoryStream<Path> dirStream;
dirStream = Files.newDirectoryStream(directory);
for (Path entry : dirStream) {
files.add(entry);
}
dirStream.close();
return files;
}
public static void replaceInFiles(String replace, String with, Collection<File> files) throws IOException {
Preconditions.checkNotNull(replace);
Preconditions.checkNotNull(with);
Preconditions.checkNotNull(files);
for (File file : files) {
replaceInFile(replace, with, Paths.get(file.toURI()));
}
}
public static void replaceInFile(String replace, String with, Path file) throws IOException {
Preconditions.checkNotNull(replace);
Preconditions.checkNotNull(with);
Preconditions.checkNotNull(file);
byte[] fileAsBytes = Files.readAllBytes(file);
String fileAsString = new String(fileAsBytes);
fileAsString = fileAsString.replaceAll(replace, with);
Files.write(file, fileAsString.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
}
public static void writeFile(Path targetFile, byte[] bytes, OpenOption... options) throws IOException {
createDirsIfNotExists(targetFile.getParent());
if (!Files.exists(targetFile)) {
Files.createFile(targetFile);
}
Files.write(targetFile, bytes, options);
}
}

View File

@ -1,8 +0,0 @@
package org.owasp.webgoat.plugins;
public class PluginLoadingFailure extends RuntimeException {
public PluginLoadingFailure(String message, Exception e) {
super(message, e);
}
}

View File

@ -1,88 +0,0 @@
package org.owasp.webgoat.plugins;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.owasp.webgoat.classloader.PluginClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
public class PluginsLoader implements Runnable {
protected static final String WEBGOAT_PLUGIN_EXTENSION = "jar";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final Path pluginSource;
private Path pluginTarget;
public PluginsLoader(Path pluginSource, Path pluginTarget) {
Preconditions.checkNotNull(pluginSource, "plugin source cannot be null");
Preconditions.checkNotNull(pluginTarget, "plugin target cannot be null");
this.pluginSource = pluginSource;
this.pluginTarget = pluginTarget;
}
public List<Plugin> loadPlugins(final boolean reload) {
final PluginClassLoader cl = (PluginClassLoader)Thread.currentThread().getContextClassLoader();
List<Plugin> plugins = Lists.newArrayList();
try {
PluginFileUtils.createDirsIfNotExists(pluginTarget);
List<URL> jars = listJars();
cl.addURL(jars);
plugins = processPlugins(jars, reload);
} catch (IOException | URISyntaxException e) {
logger.error("Loading plugins failed", e);
}
return plugins;
}
private List<URL> listJars() throws IOException {
final List<URL> jars = Lists.newArrayList();
Files.walkFileTree(pluginSource, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (PluginFileUtils.fileEndsWith(file, WEBGOAT_PLUGIN_EXTENSION)) {
jars.add(file.toUri().toURL());
}
return FileVisitResult.CONTINUE;
}
});
return jars;
}
private List<Plugin> processPlugins(List<URL> jars, boolean reload) throws URISyntaxException, IOException {
final List<Plugin> plugins = Lists.newArrayList();
for (URL jar : jars) {
PluginExtractor extractor = new PluginExtractor(Paths.get(jar.toURI()));
extractor.extract(pluginTarget);
Plugin plugin = new Plugin(pluginTarget, extractor.getClasses());
if (plugin.getLesson().isPresent()) {
PluginFileUtils.createDirsIfNotExists(pluginTarget);
plugin.loadFiles(extractor.getFiles(), reload);
plugin.rewritePaths(pluginTarget);
plugins.add(plugin);
}
}
return plugins;
}
@Override
public void run() {
loadPlugins(true);
}
}

View File

@ -1,33 +0,0 @@
package org.owasp.webgoat.plugins;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class ResourceBundleClassLoader {
private final static ResourceBundleClassLoader classLoader = new ResourceBundleClassLoader();
private Path propertiesPath;
private ResourceBundleClassLoader() {
}
public static void setPropertiesPath(Path path) {
classLoader.propertiesPath = path;
}
public static ClassLoader createPropertyFilesClassLoader() {
final List<URL> urls = new ArrayList<>();
try {
urls.add(classLoader.propertiesPath.toUri().toURL());
} catch (IOException e) {
throw new PluginLoadingFailure("Unable to load the properties for the classloader", e);
}
return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
}
}

View File

@ -1,59 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.application.Application;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class ApplicationService extends BaseService {
/**
* Returns global application info
*
* @param session
* @return
*/
@RequestMapping(value = "/application.mvc", produces = "application/json")
public @ResponseBody
Application showApplication(HttpSession session) {
Application app = Application.getInstance();
return app;
}
}

View File

@ -1,88 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.session.WebSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author rlawson
*/
@RequestMapping("/service")
public abstract class BaseService {
private static final Logger logger = LoggerFactory.getLogger(BaseService.class);
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.I_AM_A_TEAPOT)
public @ResponseBody
ExceptionInfo handleException(HttpServletRequest request, Exception ex) {
String url = request.getRequestURL().toString();
logger.error("Exception handler for service caught exception when processing: " + url, ex);
ExceptionInfo response = new ExceptionInfo();
response.setUrl(url);
response.setMessage(getStringStackTrace(ex));
return response;
}
public WebSession getWebSession(HttpSession session) {
WebSession ws;
Object o = session.getAttribute(WebSession.SESSION);
if (o == null) {
throw new IllegalArgumentException("No valid WebSession object found, has session timed out? [" + session.getId() + "]");
}
if (!(o instanceof WebSession)) {
throw new IllegalArgumentException("Invalid WebSession object found, this is probably a bug! [" + o.getClass() + " | " + session.getId() + "]");
}
ws = (WebSession) o;
return ws;
}
public String getStringStackTrace(Throwable t){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
}

View File

@ -1,83 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.lessons.model.RequestParameter;
import org.owasp.webgoat.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author rlawson
*/
@Controller
public class CookieService extends BaseService {
/**
* Returns cookies for last attack
*
* @param session
* @return
*/
@RequestMapping(value = "/cookie.mvc", produces = "application/json")
public @ResponseBody
List<Cookie> showCookies(HttpSession session) {
WebSession ws = getWebSession(session);
List<Cookie> cookies = ws.getCookiesOnLastRequest();
return cookies;
}
/**
* Returns cookies and params for current lesson
*
* @param session
* @return
*/
@RequestMapping(value = "/cookies_widget.mvc", produces = "text/html")
public ModelAndView showCookiesAndParamsAsHtml(HttpSession session) {
ModelAndView model = new ModelAndView();
WebSession ws = getWebSession(session);
List<Cookie> cookies = ws.getCookiesOnLastRequest();
List<RequestParameter> listParms = ws.getParmsOnLastRequest();
Collections.sort(listParms);
model.addObject("wgcookies", cookies);
model.addObject("wgparams", listParms);
model.setViewName("widgets/cookies_and_params");
return model;
}
}

View File

@ -1,51 +0,0 @@
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class DummyService extends BaseService{
@RequestMapping(value = "/first.mvc", produces = "application/json")
public @ResponseBody
List<String> firstNames() {
List<String> test = new ArrayList<String>();
test.add("one");
test.add("two)");
return test;
}
}

View File

@ -1,54 +0,0 @@
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
/**
*
* @author rlawson
*/
public class ExceptionInfo {
private String url;
private String message;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -1,86 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.service;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.model.Hint;
import org.owasp.webgoat.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author rlawson
*/
@Controller
public class HintService extends BaseService {
/**
* Returns hints for current lesson
*
* @param session
* @return
*/
@RequestMapping(value = "/hint.mvc", produces = "application/json")
public @ResponseBody
List<Hint> showHint(HttpSession session) {
List<Hint> listHints = new ArrayList<Hint>();
WebSession ws = getWebSession(session);
AbstractLesson l = ws.getCurrentLesson();
if (l == null) {
return listHints;
}
List<String> hints;
hints = l.getHintsPublic(ws);
if (hints == null) {
return listHints;
}
int idx = 0;
for (String h : hints) {
Hint hint = new Hint();
hint.setHint(h);
hint.setLesson(l.getName());
hint.setNumber(idx);
listHints.add(hint);
idx++;
}
return listHints;
}
@RequestMapping(value = "/hint_widget.mvc", produces = "text/html")
public
ModelAndView showHintsAsHtml(HttpSession session) {
ModelAndView model = new ModelAndView();
List<Hint> listHints = new ArrayList<Hint>();
model.addObject("hints", listHints);
WebSession ws = getWebSession(session);
AbstractLesson l = ws.getCurrentLesson();
if (l == null) {
return model;
}
List<String> hints;
hints = l.getHintsPublic(ws);
if (hints == null) {
return model;
}
int idx = 0;
for (String h : hints) {
Hint hint = new Hint();
hint.setHint(h);
hint.setLesson(l.getName());
hint.setNumber(idx);
listHints.add(hint);
idx++;
}
model.setViewName("widgets/hints");
return model;
}
}

View File

@ -1,133 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at
* https://github.com/WebGoat/WebGoat, a repository for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.RandomLessonAdapter;
import org.owasp.webgoat.lessons.model.LessonMenuItem;
import org.owasp.webgoat.lessons.model.LessonMenuItemType;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class LessonMenuService extends BaseService {
private static final Logger logger = LoggerFactory.getLogger(LessonMenuService.class);
/**
* Returns the lesson menu which is used to build the left nav
*
* @param session
* @return
*/
@RequestMapping(value = "/lessonmenu.mvc", produces = "application/json")
public @ResponseBody
List<LessonMenuItem> showLeftNav(HttpSession session) {
List<LessonMenuItem> menu = new ArrayList<LessonMenuItem>();
WebSession ws = getWebSession(session);
// Get the categories, these are the main menu items
Course course = ws.getCourse();
List<Category> categories = course.getCategories();
for (Category category : categories) {
LessonMenuItem categoryItem = new LessonMenuItem();
categoryItem.setName(category.getName());
categoryItem.setType(LessonMenuItemType.CATEGORY);
// check for any lessons for this category
List<AbstractLesson> lessons = ws.getLessons(category);
String role = ws.getRole();
logger.info("Role: " + role);
for (AbstractLesson lesson : lessons) {
LessonMenuItem lessonItem = new LessonMenuItem();
lessonItem.setName(lesson.getTitle());
lessonItem.setLink(lesson.getLink());
lessonItem.setType(LessonMenuItemType.LESSON);
if (lesson.isCompleted(ws)) {
lessonItem.setComplete(true);
}
/* @TODO - do this in a more efficient way
if (lesson.isAuthorized(ws, role, WebSession.SHOWHINTS)) {
lessonItem.setShowHints(true);
}
if (lesson.isAuthorized(ws, role, WebSession.SHOWSOURCE)) {
lessonItem.setShowSource(true);
}
*/
// special handling for challenge role
if (Category.CHALLENGE.equals(lesson.getCategory())) {
lessonItem.setShowHints(lesson.isAuthorized(ws, AbstractLesson.CHALLENGE_ROLE, WebSession.SHOWHINTS));
lessonItem.setShowSource(lesson.isAuthorized(ws, AbstractLesson.CHALLENGE_ROLE, WebSession.SHOWHINTS));
}
categoryItem.addChild(lessonItem);
// Does the lesson have stages
if (lesson instanceof RandomLessonAdapter) {
RandomLessonAdapter rla = (RandomLessonAdapter) lesson;
String[] stages = rla.getStages();
if (stages != null) {
String lessonLink = lesson.getLink();
int stageIdx = 1;
for (String stage : stages) {
LessonMenuItem stageItem = new LessonMenuItem();
stageItem.setName("Stage " + stageIdx + ": " + stage);
// build the link for the stage
String stageLink = lessonLink + "&stage=" + stageIdx;
stageItem.setLink(stageLink);
stageItem.setType(LessonMenuItemType.STAGE);
if (rla.isStageComplete(ws, stage)) {
stageItem.setComplete(true);
}
lessonItem.addChild(stageItem);
stageIdx++;
}
}
}
}
menu.add(categoryItem);
}
return menu;
}
}

View File

@ -1,93 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import javax.servlet.http.HttpSession;
import static org.owasp.webgoat.LessonSource.END_SOURCE_SKIP;
import static org.owasp.webgoat.LessonSource.START_SOURCE_SKIP;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.model.SourceListing;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class LessonPlanService extends BaseService {
/**
* Returns source for current attack
*
* @param session
* @return
*/
@RequestMapping(value = "/lessonplan.mvc", produces = "application/html")
public @ResponseBody
String showPlan(HttpSession session) {
WebSession ws = getWebSession(session);
String plan = getPlan(ws);
return plan;
//SourceListing sl = new SourceListing();
//sl.setSource(source);
//return sl;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected String getPlan(WebSession s) {
String plan = null;
int scr = s.getCurrentScreen();
Course course = s.getCourse();
if (s.isUser() || s.isChallenge()) {
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
if (lesson != null) {
plan = lesson.getLessonPlan(s);
}
}
if (plan == null) {
plan = "Plan is not available for this lesson.";
}
return plan;
}
}

View File

@ -1,40 +0,0 @@
package org.owasp.webgoat.service;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class LessonTitleService extends BaseService {
/**
* Returns the title for the current attack
*
* @param session
* @return
*/
@RequestMapping(value = "/lessontitle.mvc", produces = "application/html")
public @ResponseBody
String showPlan(HttpSession session) {
WebSession ws = getWebSession(session);
return getLessonTitle(ws);
}
private String getLessonTitle(WebSession s) {
String title = "";
int scr = s.getCurrentScreen();
Course course = s.getCourse();
if (s.isUser() || s.isChallenge()) {
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
title = lesson != null ? lesson.getTitle() : "";
}
return title;
}
}

View File

@ -1,68 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.lessons.model.RequestParameter;
import org.owasp.webgoat.session.WebSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class ParameterService extends BaseService {
final Logger logger = LoggerFactory.getLogger(ParameterService.class);
/**
* Returns request parameters for last attack
*
* @param session
* @return
*/
@RequestMapping(value = "/parameter.mvc", produces = "application/json")
public @ResponseBody
List<RequestParameter> showParameters(HttpSession session) {
WebSession ws = getWebSession(session);
List<RequestParameter> listParms = ws.getParmsOnLastRequest();
Collections.sort(listParms);
return listParms;
}
}

View File

@ -1,59 +0,0 @@
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class RestartLessonService extends BaseService {
/**
* Returns current lesson
*
* @param session
* @return
*/
@RequestMapping(value = "/restartlesson.mvc", produces = "text/text")
public @ResponseBody
String restartLesson(HttpSession session) {
WebSession ws = getWebSession(session);
int currentScreen = ws.getCurrentScreen();
if(currentScreen > 0){
ws.restartLesson(currentScreen);
}
return ws.getCurrentLesson().getLink();
}
}

View File

@ -1,57 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.owasp.webgoat.service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class SessionService extends BaseService {
/**
* Returns hints for current lesson
*
* @param session
* @return
*/
@RequestMapping(value = "/session.mvc", produces = "application/json")
public @ResponseBody
String showSession(HttpServletRequest request, HttpSession session) {
StringBuilder sb = new StringBuilder();
sb.append("id").append(" = ").append(session.getId()).append("\n");
sb.append("created").append(" = ").append(new Date(session.getCreationTime())).append("\n");
sb.append("last access").append(" = ").append(new Date(session.getLastAccessedTime())).append("\n");
sb.append("timeout (secs)").append(" = ").append(session.getMaxInactiveInterval()).append("\n");
sb.append("session from cookie?").append(" = ").append(request.isRequestedSessionIdFromCookie()).append("\n");
sb.append("session from url?").append(" = ").append(request.isRequestedSessionIdFromURL()).append("\n");
sb.append("=====================================\n");
// get attributes
List<String> attributes = new ArrayList<String>();
Enumeration keys = session.getAttributeNames();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
attributes.add(name);
}
Collections.sort(attributes);
for (String attribute : attributes) {
String value = session.getAttribute(attribute) + "";
sb.append(attribute).append(" = ").append(value).append("\n");
}
return sb.toString();
}
}

View File

@ -1,82 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class SolutionService extends BaseService {
/**
* Returns solution for current attack
*
* @param session
* @return
*/
@RequestMapping(value = "/solution.mvc", produces = "text/html")
public @ResponseBody
String showSolution(HttpSession session) {
WebSession ws = getWebSession(session);
String source = getSolution(ws);
return source;
}
protected String getSolution(WebSession s) {
String source = null;
int scr = s.getCurrentScreen();
Course course = s.getCourse();
if (s.isUser() || s.isChallenge()) {
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
if (lesson != null) {
source = lesson.getSolution(s);
}
}
if (source == null) {
return "Solution is not available. Contact "
+ s.getWebgoatContext().getFeedbackAddressHTML();
}
return (source);
}
}

View File

@ -1,96 +0,0 @@
/**
* *************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository
* for free software projects.
*
* For details, please see http://webgoat.github.io
*/
package org.owasp.webgoat.service;
import javax.servlet.http.HttpSession;
import static org.owasp.webgoat.LessonSource.END_SOURCE_SKIP;
import static org.owasp.webgoat.LessonSource.START_SOURCE_SKIP;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author rlawson
*/
@Controller
public class SourceService extends BaseService {
/**
* Returns source for current attack
*
* @param session
* @return
*/
@RequestMapping(value = "/source.mvc", produces = "application/text")
public @ResponseBody
String showSource(HttpSession session) {
WebSession ws = getWebSession(session);
String source = getSource(ws);
if (source == null) {
source = "No source listing found";
}
return source;
//SourceListing sl = new SourceListing();
//sl.setSource(source);
//return sl;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
protected String getSource(WebSession s) {
String source = null;
int scr = s.getCurrentScreen();
Course course = s.getCourse();
if (s.isUser() || s.isChallenge()) {
AbstractLesson lesson = course.getLesson(s, scr, AbstractLesson.USER_ROLE);
if (lesson != null) {
source = lesson.getRawSource(s);
}
}
if (source == null) {
return "Source code is not available for this lesson.";
}
return (source.replaceAll("(?s)" + START_SOURCE_SKIP + ".*" + END_SOURCE_SKIP,
"Code Section Deliberately Omitted"));
}
}

View File

@ -1 +0,0 @@
package org.owasp.webgoat.servlets;

View File

@ -1,53 +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.
*
* For details, please see http://webgoat.github.io
*/
public class Authorization
{
Map<Integer, Integer> permissions = new Hashtable<Integer, Integer>();
public Authorization()
{
}
public void setPermission(int userId, int functionId)
{
permissions.put(new Integer(userId), new Integer(functionId));
}
public boolean isAllowed(int userId, int functionId)
{
return (permissions.get(new Integer(userId)) != null);
}
}

View File

@ -1,344 +0,0 @@
package org.owasp.webgoat.session;
import org.owasp.webgoat.HammerHead;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.plugins.GlobalProperties;
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.GlobalProperties;
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;
/**
* *************************************************************************************************
* <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.
* <p/>
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
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 final List<String> files = new LinkedList<String>();
private WebgoatContext webgoatContext;
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.
* <p/>
* 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
* <p/>
* 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;
}
/**
* 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;
}
/**
* Gets the firstLesson attribute of the Course object
*
* @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
* @param lessonId Description of the Parameter
* @param roles
* @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();
// System.out.println("getLesson() at role: " + lesson.getRole());
if (lesson.getScreenId() == lessonId && roles.contains(lesson.getRole())) {
return lesson;
}
}
return null;
}
public AbstractLesson getLesson(WebSession s, int lessonId, String role) {
List<String> roles = new ArrayList<String>();
roles.add(role);
return getLesson(s, lessonId, roles);
}
public List 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
* @param roles
* @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 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(WebSession s, Category category, List<String> roles) {
if (s.isHackedAdmin()) {
roles.add(AbstractLesson.HACKED_ADMIN_ROLE);
}
return getLessons(category, roles);
}
public AbstractLesson getLesson(int lessonId) {
for (AbstractLesson l : lessons) {
if (l.getScreenId() == lessonId) {
return l;
}
}
return null;
}
private 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;
}
new GlobalProperties(Paths.get(targetPath)).loadProperties(Paths.get(context.getRealPath("container//i18n")));
List<Plugin> plugins = new PluginsLoader(Paths.get(pluginPath), Paths.get(targetPath)).loadPlugins(true);
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());
}
} catch (Exception e) {
logger.error("Error in loadLessons: ", e);
}
}
}
/**
* Description of the Method
*
* @param webgoatContext
* @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));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,173 +0,0 @@
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;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/
public class DatabaseUtilities
{
private static Map<String, Connection> connections = new HashMap<String, Connection>();
private static Map<String, Boolean> dbBuilt = new HashMap<String, Boolean>();
public static Connection getConnection(WebSession s) throws SQLException
{
return getConnection(s.getUserName(), s.getWebgoatContext());
}
public static synchronized Connection getConnection(String user, WebgoatContext context) throws SQLException
{
Connection conn = connections.get(user);
if (conn != null && !conn.isClosed()) return conn;
conn = makeConnection(user, context);
connections.put(user, conn);
if (dbBuilt.get(user) == null)
{
new CreateDB().makeDB(conn);
dbBuilt.put(user, Boolean.TRUE);
}
return conn;
}
public static synchronized void returnConnection(String user)
{
try
{
Connection connection = connections.get(user);
if (connection == null || connection.isClosed()) return;
if (connection.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle")) connection.close();
} catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
private static Connection makeConnection(String user, WebgoatContext context) throws SQLException
{
try
{
Class.forName(context.getDatabaseDriver());
if (context.getDatabaseConnectionString().contains("hsqldb")) return getHsqldbConnection(user, context);
String userPrefix = context.getDatabaseUser();
String password = context.getDatabasePassword();
String url = context.getDatabaseConnectionString();
return DriverManager.getConnection(url, userPrefix + "_" + user, password);
} catch (ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
throw new SQLException("Couldn't load the database driver: " + cnfe.getLocalizedMessage());
}
}
private static Connection getHsqldbConnection(String user, WebgoatContext context) throws ClassNotFoundException,
SQLException
{
String url = context.getDatabaseConnectionString().replaceAll("\\$\\{USER\\}", user);
return DriverManager.getConnection(url, "sa", "");
}
/**
* Description of the Method
*
* @param results
* 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
*/
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,746 +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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams (jeff.williams@aspectsecurity.com)
* @created October 29, 2003
*/
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);
}
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
*/
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 name
* Description of the Parameter
* @param options
* Description of the Parameter
* @param list
* 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 name
* Description of the Parameter
* @param options
* 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 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,241 +0,0 @@
package org.owasp.webgoat.session;
import java.io.Serializable;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*/
public class Employee implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -1901957360367218399L;
public final static String EMPLOYEE_ROLE = "employee";
public final static String MANAGER_ROLE = "manager";
public final static String HR_ROLE = "hr";
private int id;
private String firstName;
private String lastName;
private String title;
private String ssn;
private String phone;
private String address1;
private String address2;
private int manager;
private String startDate;
private int salary;
private String ccn;
private int ccnLimit;
private String disciplinaryActionDate;
private String disciplinaryActionNotes;
private String personalDescription;
// FIXME: To be deleted
public Employee()
{
}
public Employee(int id, String firstName, String lastName, String ssn, String title, String phone, String address1,
String address2, int manager, String startDate, int salary, String ccn, int ccnLimit,
String disciplinaryActionDate, String disciplinaryActionNotes, String personalDescription)
{
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.ssn = ssn;
this.title = title;
this.phone = phone;
this.address1 = address1;
this.address2 = address2;
this.manager = manager;
this.startDate = startDate;
this.salary = salary;
this.ccn = ccn;
this.ccnLimit = ccnLimit;
this.disciplinaryActionDate = disciplinaryActionDate;
this.disciplinaryActionNotes = disciplinaryActionNotes;
this.personalDescription = personalDescription;
}
public String getAddress1()
{
return address1;
}
public void setAddress1(String address1)
{
this.address1 = address1;
}
public String getAddress2()
{
return address2;
}
public void setAddress2(String address2)
{
this.address2 = address2;
}
public String getCcn()
{
return ccn;
}
public void setCcn(String ccn)
{
this.ccn = ccn;
}
public int getCcnLimit()
{
return ccnLimit;
}
public void setCcnLimit(int ccnLimit)
{
this.ccnLimit = ccnLimit;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getPhoneNumber()
{
return phone;
}
public void setPhoneNumber(String phone)
{
this.phone = phone;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
public String getSsn()
{
return ssn;
}
public void setSsn(String ssn)
{
this.ssn = ssn;
}
public String getStartDate()
{
return startDate;
}
public void setStartDate(String startDate)
{
this.startDate = startDate;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getTitle()
{
return this.title;
}
public int getManager()
{
return this.manager;
}
public String getDisciplinaryActionDate()
{
return this.disciplinaryActionDate;
}
public String getDisciplinaryActionNotes()
{
return this.disciplinaryActionNotes;
}
public String getPersonalDescription()
{
return this.personalDescription;
}
}

View File

@ -1,82 +0,0 @@
package org.owasp.webgoat.session;
import java.io.Serializable;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*/
public class EmployeeStub implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -7109162877797765632L;
private int id;
private String firstName;
private String lastName;
private String role;
public EmployeeStub(int id, String firstName, String lastName)
{
this(id, firstName, lastName, Employee.EMPLOYEE_ROLE);
}
public EmployeeStub(int id, String firstName, String lastName, String role)
{
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.role = role;
}
public String getFirstName()
{
return firstName;
}
public int getId()
{
return id;
}
public String getLastName()
{
return lastName;
}
public String getRole()
{
return role;
}
}

View File

@ -1,264 +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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created November 4, 2003
*/
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);
}
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);
}
}
}
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);
}
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);
}
/**
* Description of the Method
*
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
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");
}
public String getRole()
{
return AbstractLesson.USER_ROLE;
}
}

View File

@ -1,63 +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.
*
* For details, please see http://webgoat.github.io
*
* 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>
* @created January 19, 2006
*/
public class LessonSession
{
private boolean isAuthenticated = false;
private String currentLessonScreen;
public void setAuthenticated(boolean isAuthenticated)
{
this.isAuthenticated = isAuthenticated;
}
public boolean isAuthenticated()
{
return this.isAuthenticated;
}
public void setCurrentLessonScreen(String currentLessonScreen)
{
this.currentLessonScreen = currentLessonScreen;
}
public String getCurrentLessonScreen()
{
return this.currentLessonScreen;
}
}

View File

@ -1,404 +0,0 @@
package org.owasp.webgoat.session;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 29, 2003
*/
public class LessonTracker
{
private boolean completed = false;
private int maxHintLevel = 0;
private int numVisits = 0;
private boolean viewedCookies = false;
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;
}
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
*/
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();
}
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 s
* Description of the Parameter
* @return Description of the Return Value
*/
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 viewedSource
* The new viewedSource value
*/
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
*/
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
*/
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();
}
/**
* @return Returns the lessonProperties.
*/
public Properties getLessonProperties()
{
return lessonProperties;
}
/**
* @param lessonProperties
* The lessonProperties to set.
*/
public void setLessonProperties(Properties lessonProperties)
{
this.lessonProperties = lessonProperties;
}
}

View File

@ -1,81 +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.
*
* For details, please see http://webgoat.github.io
*/
public class Parameter implements Comparable
{
String name;
String value;
public Parameter(String name, String value)
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
public String getValue()
{
return value;
}
// @Override
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
public int hashCode()
{
return toString().hashCode();
}
// @Override
public String toString()
{
return (name + "=" + value);
}
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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/
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,872 +0,0 @@
package org.owasp.webgoat.session;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.servlet.ServletRequest;
import org.owasp.webgoat.util.HtmlEncoder;
/**
* *************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect
* Security</a>
*/
public class ParameterParser {
private final static String ALLOWED_CHARACTERS = "_$()-?.@!,:;=//+"; // Don't
// allow
// #&
// specifically
private ServletRequest request;
/**
* Constructs a new ParameterParser to handle the parameters of the given
* request.
*
* @param request the servlet request
*/
public ParameterParser(ServletRequest request) {
this.request = request;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @return Description of the Return Value
*/
private String clean(String s) {
StringBuffer clean = new StringBuffer();
for (int loop = 0; loop < s.length(); loop++) {
char c = s.charAt(loop);
if (Character.isLetterOrDigit(c) || Character.isWhitespace(c) || (ALLOWED_CHARACTERS.indexOf(c) != -1)) {
clean.append(c);
} else {
clean.append('.');
}
}
return (clean.toString());
}
/**
* Gets the named parameter value as a boolean
*
* @param name the parameter name
* @return the parameter value as a boolean
* @exception ParameterNotFoundException if the parameter was not found
*/
public boolean getBooleanParameter(String name) throws ParameterNotFoundException {
return new Boolean(getStringParameter(name)).booleanValue();
}
/**
* Gets the named parameter value as a boolean, with a default. Returns the
* default value if the parameter is not found.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a boolean, or the default
*/
public boolean getBooleanParameter(String name, boolean def) {
try {
return getBooleanParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the booleanSubParameter attribute of the ParameterParser object
*
* @param first Description of the Parameter
* @param next Description of the Parameter
* @param def Description of the Parameter
* @return The booleanSubParameter value
*/
public boolean getBooleanSubParameter(String first, String next, boolean def) {
try {
return new Boolean(getSubParameter(first, next)).booleanValue();
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as a byte
*
* @param name the parameter name
* @return the parameter value as a byte
* @exception ParameterNotFoundException if the parameter was not found
* @exception NumberFormatException if the parameter value could not be
* converted to a byte
*/
public byte getByteParameter(String name) throws ParameterNotFoundException, NumberFormatException {
return Byte.parseByte(getStringParameter(name));
}
/**
* Gets the named parameter value as a byte, with a default. Returns the
* default value if the parameter is not found or cannot be converted to a
* byte.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a byte, or the default
*/
public byte getByteParameter(String name, byte def) {
try {
return getByteParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as a char
*
* @param name the parameter name
* @return the parameter value as a char
* @exception ParameterNotFoundException if the parameter was not found or
* was the empty string
*/
public char getCharParameter(String name) throws ParameterNotFoundException {
String param = getStringParameter(name);
if (param.length() == 0) {
throw new ParameterNotFoundException(name + " is empty string");
} else {
return (param.charAt(0));
}
}
/**
* Gets the named parameter value as a char, with a default. Returns the
* default value if the parameter is not found.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a char, or the default
*/
public char getCharParameter(String name, char def) {
try {
return getCharParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the classNameParameter attribute of the ParameterParser object
*
* @param name Description of the Parameter
* @return The classNameParameter value
*/
public String getClassNameParameter(String name) throws ParameterNotFoundException {
String p = getStringParameter(name);
StringTokenizer st = new StringTokenizer(p);
return (st.nextToken().trim());
}
// FIXME: check for [a-zA-Z].([a-zA-Z])*
/**
* Gets the classNameParameter attribute of the ParameterParser object
*
* @param name Description of the Parameter
* @param def Description of the Parameter
* @return The classNameParameter value
*/
public String getClassNameParameter(String name, String def) {
try {
return getClassNameParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as a double
*
* @param name the parameter name
* @return the parameter value as a double
* @exception ParameterNotFoundException if the parameter was not found
* @exception NumberFormatException if the parameter could not be converted
* to a double
*/
public double getDoubleParameter(String name) throws ParameterNotFoundException, NumberFormatException {
return new Double(getStringParameter(name)).doubleValue();
}
/**
* Gets the named parameter value as a double, with a default. Returns the
* default value if the parameter is not found.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a double, or the default
*/
public double getDoubleParameter(String name, double def) {
try {
return getDoubleParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as a float
*
* @param name the parameter name
* @return the parameter value as a float
* @exception ParameterNotFoundException if the parameter was not found
* @exception NumberFormatException if the parameter could not be converted
* to a float
*/
public float getFloatParameter(String name) throws ParameterNotFoundException, NumberFormatException {
return new Float(getStringParameter(name)).floatValue();
}
/**
* Gets the named parameter value as a float, with a default. Returns the
* default value if the parameter is not found.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a float, or the default
*/
public float getFloatParameter(String name, float def) {
try {
return getFloatParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as an IP String, with a default. Returns
* the default value if the parameter is not found or is the empty string.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a String, or the default
*/
public String getIPParameter(String name, String def) {
try {
return getIPParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as an IP String
*
* @param name the parameter name
* @return the parameter value as a valid IP String or an Empty string if
* invalid
* @exception ParameterNotFoundException if the parameter was not found or
* was the empty string
*/
public String getIPParameter(String name) throws ParameterNotFoundException {
boolean valid = true;
String[] values = request.getParameterValues(name);
String value;
if (values == null) {
throw new ParameterNotFoundException(name + " not found");
} else if (values[0].length() == 0) {
throw new ParameterNotFoundException(name + " was empty");
} else {
// trim illegal characters
value = clean(values[0].trim());
if (value.indexOf("&") > 0) {
// truncate additional parameters that follow &
value = value.substring(0, value.indexOf("&"));
}
// validate the IP ex: 124.143.12.254
int startIndex = 0;
int endIndex = 0;
int octetCount = 0;
int octetValue;
String octet;
// if no .'s then it's not an IP
if (value.indexOf(".") >= 0) {
while ((valid == true) && (octetCount < 4)) {
endIndex = value.indexOf(".", startIndex);
if (endIndex == -1) {
endIndex = value.length();
}
octet = value.substring(startIndex, endIndex);
startIndex = endIndex + 1;
try {
octetValue = Integer.parseInt(octet);
if ((octetValue <= 0) || (octetValue >= 256)) {
valid = false;
}
} catch (Exception e) {
valid = false;
}
octetCount++;
}
} else {
// Not a valid IP
valid = false;
}
// Check for any extra garbage. If the last octet was a large value
// it would be trapped by the above range check.
if (value.length() != endIndex) {
valid = false;
}
return valid ? value : null;
}
}
/**
* Gets the named parameter value as a int
*
* @param name the parameter name
* @return the parameter value as a int
* @exception ParameterNotFoundException if the parameter was not found
* @exception NumberFormatException if the parameter could not be converted
* to a int
*/
public int getIntParameter(String name) throws ParameterNotFoundException, NumberFormatException {
return Integer.parseInt(getStringParameter(name));
}
/**
* Gets the named parameter value as a int, with a default. Returns the
* default value if the parameter is not found.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a int, or the default
*/
public int getIntParameter(String name, int def) {
try {
return getIntParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as a long
*
* @param name the parameter name
* @return the parameter value as a long
* @exception ParameterNotFoundException if the parameter was not found
* @exception NumberFormatException if the parameter could not be converted
* to a long
*/
public long getLongParameter(String name) throws ParameterNotFoundException, NumberFormatException {
return Long.parseLong(getStringParameter(name));
}
/**
* Gets the named parameter value as a long, with a default. Returns the
* default value if the parameter is not found.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a long, or the default
*/
public long getLongParameter(String name, long def) {
try {
return getLongParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Determines which of the required parameters were missing from the
* request. Returns null if all the parameters are present.
*
* @param requestuired Description of the Parameter
* @return an array of missing parameters, or null if none are missing
*/
public String[] getMissingParameters(String[] requestuired) {
Vector<String> missing = new Vector<String>();
for (int i = 0; i < requestuired.length; i++) {
String val = getStringParameter(requestuired[i], null);
if (val == null) {
missing.addElement(requestuired[i]);
}
}
if (missing.size() == 0) {
return null;
} else {
String[] ret = new String[missing.size()];
missing.copyInto(ret);
return ret;
}
}
/**
* Gets the parameterNames attribute of the ParameterParser object
*
* @return The parameterNames value
*/
public Enumeration getParameterNames() {
if (request == null) {
return (null);
}
return request.getParameterNames();
}
/**
* Gets the parameterValues attribute of the ParameterParser object
*
* @param name Description of the Parameter
* @return The parameterValues value
*/
public String[] getParameterValues(String name) {
if (request == null) {
return (null);
}
return request.getParameterValues(name);
}
/**
* Gets the rawParameter attribute of the ParameterParser object
*
* @param name Description of the Parameter
* @param def Description of the Parameter
* @return The rawParameter value
*/
public String getRawParameter(String name, String def) {
try {
return getRawParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the rawParameter attribute of the ParameterParser object
*
* @param name Description of the Parameter
* @return The rawParameter value
* @exception ParameterNotFoundException Description of the Exception
*/
public String getRawParameter(String name) throws ParameterNotFoundException {
String[] values = request.getParameterValues(name);
if (values == null) {
throw new ParameterNotFoundException(name + " not found");
} else if (values[0].length() == 0) {
throw new ParameterNotFoundException(name + " was empty");
}
return (values[0]);
}
/**
* Gets the named parameter value as a short
*
* @param name the parameter name
* @return the parameter value as a short
* @exception ParameterNotFoundException if the parameter was not found
* @exception NumberFormatException if the parameter could not be converted
* to a short
*/
public short getShortParameter(String name) throws ParameterNotFoundException, NumberFormatException {
return Short.parseShort(getStringParameter(name));
}
/**
* Gets the named parameter value as a short, with a default. Returns the
* default value if the parameter is not found.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a short, or the default
*/
public short getShortParameter(String name, short def) {
try {
return getShortParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the named parameter value as a String
*
* @param name the parameter name
* @return the parameter value as a String
* @exception ParameterNotFoundException if the parameter was not found or
* was the empty string
*/
public String getStringParameter(String name) throws ParameterNotFoundException {
String[] values = request.getParameterValues(name);
String value;
if (values == null) {
throw new ParameterNotFoundException(name + " not found");
} else if (values[0].length() == 0) {
throw new ParameterNotFoundException(name + " was empty");
} else {
// trim illegal characters
value = clean(values[0].trim());
if (value.indexOf("&") > 0) {
// truncate additional parameters that follow &
value = value.substring(0, value.indexOf("&"));
}
return value;
}
}
/**
* Gets the named parameter value as a String, with a default. Returns the
* default value if the parameter is not found or is the empty string.
*
* @param name the parameter name
* @param def the default parameter value
* @return the parameter value as a String, or the default
*/
public String getStringParameter(String name, String def) {
try {
return getStringParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the subParameter attribute of the ParameterParser object
*
* @param first Description of the Parameter
* @param next Description of the Parameter
* @param def Description of the Parameter
* @return The subParameter value
*/
public String getSubParameter(String first, String next, String def) {
try {
return getSubParameter(first, next);
} catch (Exception e) {
return def;
}
}
/**
* Gets the parameter named 'next' following the parameter 'first'. Presumes
* the structure: first=firstvalue&next=nextValue
*
* @param first Description of the Parameter
* @param next Description of the Parameter
* @return The subParameter value
* @exception ParameterNotFoundException Description of the Exception
*/
public String getSubParameter(String first, String next) throws ParameterNotFoundException {
String[] values = request.getParameterValues(first);
String value;
if (values == null) {
throw new ParameterNotFoundException(first + " not found");
} else if (values[0].length() == 0) {
throw new ParameterNotFoundException(first + " was empty");
} else {
value = clean(values[0].trim());
int idx = value.indexOf("&") + 1;
// index of first char of first sub-param name
if (idx == 0) {
throw new ParameterNotFoundException("No subparameter key");
}
value = value.substring(idx);
// System.out.println("= = = = = =Parameter parser looking for " +
// next + " in " + value );
int nextValueIndex = value.indexOf(next + "=");
// System.out.println("= = = = = =Parameter parser nextValueIndex =
// " + nextValueIndex );
if (nextValueIndex < 0) {
throw new ParameterNotFoundException("No subparameter value");
}
nextValueIndex += (next.length() + 1);
if (nextValueIndex >= 0) {
value = value.substring(nextValueIndex);
} else {
throw new ParameterNotFoundException(next + " not found");
}
}
if (value.indexOf("&") > 0) {
// truncate additional parameters that follow &
value = value.substring(0, value.indexOf("&"));
}
// System.out.println("=-=-=-=-=ParameterParser returning value " +
// value );
return value;
}
/**
* Gets the wordParameter attribute of the ParameterParser object
*
* @param name Description of the Parameter
* @return The wordParameter value
*/
public String getWordParameter(String name) throws ParameterNotFoundException {
String p = getStringParameter(name);
StringTokenizer st = new StringTokenizer(p);
return (st.nextToken().trim());
}
// FIXME: check for [a-zA-Z]
/**
* Gets the wordParameter attribute of the ParameterParser object
*
* @param name Description of the Parameter
* @param def Description of the Parameter
* @return The wordParameter value
*/
public String getWordParameter(String name, String def) {
try {
return getWordParameter(name);
} catch (Exception e) {
return def;
}
}
/**
* Gets the specified parameter from the request and validates it against
* the provided regular expression. If the regular expression check fails,
* the default value is returned instead.
*
* @param name The name of the parameter to retrieve from the request.
* @param def The default value of the parameter.
* @param regexpattern The precompiled regular expression to be used to
* validate the parameter.
* @return The validated parameter value, or the default value if validation
* failed.
*/
private String getRegexParameter(String name, String def, Pattern regexpattern) throws ValidationException {
try {
return getRegexParameter(name, regexpattern);
} catch (Exception e) {
// System.out.println("Exception occured in defined pattern match");
// e.printStackTrace();
return def;
}
}
/**
* Gets the specified parameter from the request and validates it against
* the provided regular expression. If the regular expression check fails,
* the default value is returned instead.
*
* @param name The name of the parameter to retrieve from the request.
* @param def The default value of the parameter.
* @param regexpattern The precompiled regular expression to be used to
* validate the parameter.
* @return The validated parameter value, or the default value if validation
* failed.
*/
private String getRegexParameter(String name, Pattern regexpattern) throws ParameterNotFoundException,
ValidationException {
String param = getStringParameter(name);
if (regexpattern.matcher(param).matches()) {
return param;
} else {
// System.out.println(param + " didn't match defined pattern.");
throw new ValidationException(name + " contained an invalid value");
}
}
public String getStrictAlphaParameter(String name, int maxLength) throws ParameterNotFoundException,
ValidationException {
String alphaRegEx = "^[a-zA-Z\\s]{0," + maxLength + "}$";
Pattern alphaPattern = Pattern.compile(alphaRegEx);
return getRegexParameter(name, alphaPattern);
}
public String getStrictNumericParameter(String name, int maxLength) throws ParameterNotFoundException,
ValidationException {
String numericRegEx = "^\\d{0," + maxLength + "}$";
Pattern numericPattern = Pattern.compile(numericRegEx);
return getRegexParameter(name, numericPattern);
}
private static final String SSNREGEX = "^\\d{3}-\\d{2}-\\d{4}$";
private static final Pattern Ssnpattern = Pattern.compile(SSNREGEX);
public String getSsnParameter(String name) throws ParameterNotFoundException, ValidationException {
return getRegexParameter(name, Ssnpattern);
}
// Validates format for major brands of credit card.
// private static final String CCNREGEX =
// "^(?:(?<Visa>4\\d{3})|(?<Mastercard>5[1-5]\\d{2})|(?<Discover>6011)|(?<DinersClub>(?:3[68]\\d{2})|(?:30[0-5]\\d))|(?<AmericanExpress>3[47]\\d{2}))([
//-]?)(?(DinersClub)(?:\\d{6}\\1\\d{4})|(?(AmericanExpress)(?:\\d{6}\\1\\d{5})|(?:\\d{4}\\1\\d{4
// }\\1\\d{4})))$";
private static final String CCNREGEX = "^\\d{16}$";
private static final Pattern Ccnpattern = Pattern.compile(CCNREGEX);
public String getCcnParameter(String name) throws ParameterNotFoundException, ValidationException {
return getRegexParameter(name, Ccnpattern);
}
private static final String ZIPREGEX = "^\\d{5}(-\\d{4})?$";
private static final Pattern Zippattern = Pattern.compile(ZIPREGEX);
public String getZipParameter(String name) throws ParameterNotFoundException, ValidationException {
return getZipParameter(name, null);
}
public String getZipParameter(String name, String def) throws ValidationException {
return getRegexParameter(name, def, Zippattern);
}
private static final String PHONEREGEX = "^\\(?[\\d]{3}\\)?[\\s-]?[\\d]{3}[\\s-]?[\\d]{4}$";
// Or this more forgiving pattern:
// private static final String PHONEREGEX = "^([\\-()+ 0-9x])+$";
private static final Pattern phonepattern = Pattern.compile(PHONEREGEX);
public String getPhoneParameter(String name) throws ParameterNotFoundException, ValidationException {
return getPhoneParameter(name, null);
}
public String getPhoneParameter(String name, String def) throws ValidationException {
return getRegexParameter(name, def, phonepattern);
}
private static final String EMAILREGEX = "^[\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}$";
private static final Pattern emailpattern = Pattern.compile(EMAILREGEX);
public String getEMailParameter(String name) throws ParameterNotFoundException, ValidationException {
return getEMailParameter(name, null);
}
public String getEMailParameter(String name, String def) throws ValidationException {
return getRegexParameter(name, def, emailpattern);
}
private static final String DATEREGEX = "([\\/ .,:0-9a-zA-Z])+$";
private static final Pattern datepattern = Pattern.compile(DATEREGEX);
public String getDateParameter(String name) throws ParameterNotFoundException, ValidationException {
return getDateParameter(name, null);
}
public String getDateParameter(String name, String def) throws ValidationException {
return getRegexParameter(name, def, datepattern);
}
private static final String URLREGEX = "^(((https?)://)([-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$";
private static final Pattern URLpattern = Pattern.compile(URLREGEX);
public String getURLParameter(String name) throws ParameterNotFoundException, ValidationException {
return getURLParameter(name, null);
}
public String getURLParameter(String name, String def) throws ValidationException {
return getRegexParameter(name, def, URLpattern);
}
protected static String htmlEncode(String s) {
return HtmlEncoder.encode(s);
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public String toString() {
StringBuffer s = new StringBuffer("[");
Enumeration e = getParameterNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
s.append(key + "=" + getParameterValues(key)[0]);
// FIXME: Other values?
if (e.hasMoreElements()) {
s.append(",");
}
}
s.append("]");
return (s.toString());
}
/**
* Description of the Method
*
* @param request Description of the Parameter
*/
public void update(ServletRequest request) {
this.request = request;
}
}

View File

@ -1,117 +0,0 @@
package org.owasp.webgoat.session;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class RandomLessonTracker extends LessonTracker
{
private String[] stages;
private String stage;
private Map<String, Boolean> completed = new HashMap<String, Boolean>();
public RandomLessonTracker(String[] stages)
{
if (stages == null) stages = new String[0];
this.stages = stages;
}
public void setStage(String stage)
{
this.stage = stage;
}
public String getStage()
{
if (this.stage == null && stages.length > 0) return stages[0];
return this.stage;
}
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]);
}
public int getStageNumber(String stage)
{
for (int i = 0; i < stages.length; i++)
if (stages[i].equals(stage)) return i;
return -1;
}
public boolean hasCompleted(String stage)
{
Boolean complete = completed.get(stage);
return complete == null ? false : complete.booleanValue();
}
@Override
public boolean getCompleted()
{
for (int i = 0; i < stages.length; i++)
if (!hasCompleted(stages[i])) return false;
return true;
}
@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]);
}
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"));
}
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);
}
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,13 +0,0 @@
package org.owasp.webgoat.session;
public class Role {
private String rolename;
public Role(String rolename) {
this.rolename = rolename;
}
public String getRolename() {
return this.rolename;
}
}

View File

@ -1,277 +0,0 @@
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;
/**
* *************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect
* Security</a>
* @created October 28, 2003
*/
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.
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
*
* @param userName Description of the Parameter
* @return The lessonTracker value
*/
public LessonTracker getLessonTracker(WebSession s) {
UserTracker userTracker = UserTracker.instance();
return userTracker.getLessonTracker(s, this);
}
public LessonTracker getLessonTracker(WebSession s, String userNameOverride) {
UserTracker userTracker = UserTracker.instance();
return userTracker.getLessonTracker(s, userNameOverride, this);
}
public LessonTracker getLessonTracker(WebSession s, AbstractLesson lesson) {
UserTracker userTracker = UserTracker.instance();
return userTracker.getLessonTracker(s, lesson);
}
/**
* Fill in a descriptive title for this lesson
*
* @return The title value
*/
public abstract String getTitle();
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);
}
public String getSponsor() {
return "Aspect Security";
}
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.
*
*/
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
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,38 +0,0 @@
package org.owasp.webgoat.session;
import java.util.Properties;
public class SequentialLessonTracker extends LessonTracker
{
private int currentStage = 1;
public int getStage()
{
return currentStage;
}
public void setStage(int stage)
{
currentStage = stage;
}
protected void setProperties(Properties props, Screen screen)
{
super.setProperties(props, screen);
currentStage = Integer.parseInt(props.getProperty(screen.getTitle() + ".currentStage"));
}
public void store(WebSession s, Screen screen, String user)
{
lessonProperties.setProperty(screen.getTitle() + ".currentStage", Integer.toString(currentStage));
super.store(s, screen, user);
}
public String toString()
{
return super.toString() + " - currentStage:....... " + currentStage + "\n";
}
}

View File

@ -1,39 +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.
*
* For details, please see http://webgoat.github.io
*/
public class UnauthenticatedException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 97865025446819061L;
}

View File

@ -1,39 +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.
*
* For details, please see http://webgoat.github.io
*/
public class UnauthorizedException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 5245519486798464814L;
}

View File

@ -1,26 +0,0 @@
package org.owasp.webgoat.session;
import java.util.ArrayList;
import java.util.Iterator;
public class User {
private String username;
private ArrayList<Role> roles;
public User(String username) {
this.username = username;
this.roles = new ArrayList<Role>();
}
public String getUsername() {
return username;
}
public Iterator<Role> getRoles() {
return roles.iterator();
}
public void addRole(String rolename) {
roles.add(new Role(rolename));
}
}

View File

@ -1,214 +0,0 @@
package org.owasp.webgoat.session;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.File;
class UserDatabase {
private Connection userDB;
private final String USER_DB_URI = "jdbc:h2:" + System.getProperty("user.dir") + File.separator + "UserDatabase";
private final String CREATE_USERS_TABLE = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTO_INCREMENT, username VARCHAR(255) NOT NULL UNIQUE);";
private final String CREATE_ROLES_TABLE = "CREATE TABLE IF NOT EXISTS roles (id INTEGER PRIMARY KEY AUTO_INCREMENT, rolename VARCHAR(255) NOT NULL UNIQUE);";
private final String CREATE_USER_ROLES_TABLE = "CREATE TABLE IF NOT EXISTS user_roles (id INTEGER PRIMARY KEY AUTO_INCREMENT, user_id INTEGER NOT NULL, role_id INTEGER NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (role_id) REFERENCES roles(id));";
private final String ADD_DEFAULT_USERS = "INSERT INTO users (username) VALUES ('webgoat'),('basic'),('guest');";
private final String ADD_DEFAULT_ROLES = "INSERT INTO roles (rolename) VALUES ('webgoat_basic'),('webgoat_admin'),('webgoat_user');";
private final String ADD_ROLE_TO_USER = "INSERT INTO user_roles (user_id, role_id) SELECT users.id, roles.id FROM users, roles WHERE users.username = ? AND roles.rolename = ?;";
private final String QUERY_ALL_USERS = "SELECT username FROM users;";
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 = ?;";
public UserDatabase() {
createDefaultTables();
if (getTableCount("users") <= 0) {
createDefaultUsers();
}
if (getTableCount("roles") <= 0) {
createDefaultRoles();
}
if (getTableCount("user_roles") <= 0) {
addDefaultRolesToDefaultUsers();
}
}
public boolean open() {
try {
if (userDB == null || userDB.isClosed()) {
Class.forName("org.h2.Driver");
userDB = DriverManager.getConnection(USER_DB_URI, "webgoat_admin", "");
}
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean close() {
try {
if (userDB != null && !userDB.isClosed())
userDB.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public int getTableCount(String tableName) {
int count = 0;
try {
open();
Statement statement = userDB.createStatement();
ResultSet countResult = statement.executeQuery(QUERY_TABLE_COUNT.replace("table", tableName));
if (countResult.next()) {
count = countResult.getInt("count");
}
countResult.close();
statement.close();
close();
} catch (SQLException e) {
e.printStackTrace();
count = -1;
}
return count;
}
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();
}
public boolean addRoleToUser(String username, String rolename) {
try {
open();
PreparedStatement statement = userDB.prepareStatement(ADD_ROLE_TO_USER);
statement.setString(1, username);
statement.setString(2, rolename);
statement.execute();
statement.close();
close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean removeUser(User user) {
return removeUser(user.getUsername());
}
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.
*/
private boolean createDefaultTables() {
try {
open();
Statement statement = userDB.createStatement();
statement.execute(CREATE_USERS_TABLE);
statement.execute(CREATE_ROLES_TABLE);
statement.execute(CREATE_USER_ROLES_TABLE);
statement.close();
close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
private boolean createDefaultUsers() {
try {
open();
Statement statement = userDB.createStatement();
statement.execute(ADD_DEFAULT_USERS);
statement.close();
close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
private boolean createDefaultRoles() {
try {
open();
Statement statement = userDB.createStatement();
statement.execute(ADD_DEFAULT_ROLES);
statement.close();
close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
private void addDefaultRolesToDefaultUsers() {
addRoleToUser("webgoat", "webgoat_admin");
addRoleToUser("basic", "webgoat_user");
addRoleToUser("basic", "webgoat_basic");
addRoleToUser("guest", "webgoat_user");
}
}

View File

@ -1,269 +0,0 @@
package org.owasp.webgoat.session;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
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.
*
* For details, please see http://webgoat.github.io
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 29, 2003
*/
public class UserTracker
{
private static UserTracker instance;
// FIXME: persist this somehow!
private static HashMap<String, HashMap<String, LessonTracker>> storage = new HashMap<String, HashMap<String, LessonTracker>>();
private static UserDatabase usersDB = new UserDatabase();
/**
* Constructor for the UserTracker object
*/
private UserTracker()
{
}
/**
* Gets the completed attribute of the UserTracker object
*
* @param userName
* Description of the Parameter
* @return The completed value
*/
public int getCompleted(String userName)
{
HashMap usermap = getUserMap(userName);
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();
}
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;
}
}
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
* @param userName
* Description of the Parameter
* @return The lessonTracker value
*/
public LessonTracker getLessonTracker(WebSession s, Screen screen)
{
return getLessonTracker(s, s.getUserName(), screen);
}
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
* @param userName
* Description of the Parameter
* @return The status value
*/
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 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);
}
}

View File

@ -1,48 +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.
*
* For details, please see http://webgoat.github.io
*/
public class ValidationException extends Exception
{
/**
*
*/
private static final long serialVersionUID = -8358754606830400708L;
public ValidationException()
{
super();
}
public ValidationException(String message)
{
super(message);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,218 +0,0 @@
package org.owasp.webgoat.session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServlet;
public class WebgoatContext {
final Logger logger = LoggerFactory.getLogger(WebgoatContext.class);
public final static String DATABASE_CONNECTION_STRING = "DatabaseConnectionString";
public final static String DATABASE_DRIVER = "DatabaseDriver";
public final static String DATABASE_USER = "DatabaseUser";
public final static String DATABASE_PASSWORD = "DatabasePassword";
public final static String ENTERPRISE = "Enterprise";
public final static String CODING_EXERCISES = "CodingExercises";
public final static String SHOWCOOKIES = "ShowCookies";
public final static String SHOWPARAMS = "ShowParams";
public final static String SHOWREQUEST = "ShowRequest";
public final static String SHOWSOURCE = "ShowSource";
public final static String SHOWSOLUTION = "ShowSolution";
public final static String SHOWHINTS = "ShowHints";
public final static String DEFUSEOSCOMMANDS = "DefuseOSCommands";
public final static String FEEDBACK_ADDRESS_HTML = "FeedbackAddressHTML";
public final static String FEEDBACK_ADDRESS = "email";
public final static String DEBUG = "debug";
public final static String DEFAULTLANGUAGE = "DefaultLanguage";
private String databaseConnectionString;
private String realConnectionString = null;
private String databaseDriver;
private String databaseUser;
private String databasePassword;
private boolean showCookies = false;
private boolean showParams = false;
private boolean showRequest = false;
private boolean showSource = false;
private boolean showSolution = false;
private boolean defuseOSCommands = false;
private boolean enterprise = false;
private boolean codingExercises = false;
private String feedbackAddress = "webgoat@owasp.org";
private String feedbackAddressHTML = "<A HREF=mailto:webgoat@owasp.org>webgoat@owasp.org</A>";
private boolean isDebug = false;
private String servletName;
private HttpServlet servlet;
private String defaultLanguage;
private java.nio.file.Path pluginDirectory;
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));
defuseOSCommands = "true".equals(getParameter(servlet, DEFUSEOSCOMMANDS));
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
*
* @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;
}
/**
* Gets the databaseDriver attribute of the WebSession object
*
* @return The databaseDriver value
*/
public String getDatabaseDriver() {
return (databaseDriver);
}
/**
* Gets the databaseUser attribute of the WebSession object
*
* @return The databaseUser value
*/
public String getDatabaseUser() {
return (databaseUser);
}
/**
* Gets the databasePassword attribute of the WebSession object
*
* @return The databasePassword value
*/
public String getDatabasePassword() {
return (databasePassword);
}
public boolean isDefuseOSCommands() {
return defuseOSCommands;
}
public boolean isEnterprise() {
return enterprise;
}
public boolean isCodingExercises() {
return codingExercises;
}
public String getFeedbackAddress() {
return feedbackAddress;
}
public String getFeedbackAddressHTML() {
return feedbackAddressHTML;
}
public boolean isDebug() {
return isDebug;
}
public String getServletName() {
return servletName;
}
public boolean isShowCookies() {
return showCookies;
}
public boolean isShowParams() {
return showParams;
}
public boolean isShowRequest() {
return showRequest;
}
public boolean isShowSource() {
return showSource;
}
public boolean isShowSolution() {
return showSolution;
}
public String getDefaultLanguage() {
return defaultLanguage;
}
}

View File

@ -1,119 +0,0 @@
package org.owasp.webgoat.session;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.owasp.webgoat.HammerHead;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* *************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*/
public class WebgoatProperties extends Properties {
/**
*
*/
private static final long serialVersionUID = 4351681705558227918L;
final Logger logger = LoggerFactory.getLogger(WebgoatProperties.class);
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);
}
public int getIntProperty(String key, int defaultValue) {
int value = defaultValue;
String s = getProperty(key);
if (s != null) {
value = Integer.parseInt(s);
}
return value;
}
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;
}
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"));
}
}

View File

@ -1,63 +0,0 @@
package org.owasp.webgoat.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*/
@Component
public class BeanProvider implements ApplicationContextAware
{
private static ApplicationContext ctx;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
ctx = applicationContext;
}
/**
* Get access to managed beans from id.
*
* @param beanName
* the id of the searched bean
* @param beanClass
* the type of tye searched bean
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(final String beanName, final Class<T> beanClass)
{
return (T) ctx.getBean(beanName);
}
}

View File

@ -1,527 +0,0 @@
package org.owasp.webgoat.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.BitSet;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003
*/
public class Exec
{
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @param input
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execInput(String command, String input)
{
return (execOptions(command, input, 0, 0, false));
}
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execLazy(String command)
{
return (execOptions(command, "", 0, 0, true));
}
/*
* Execute an OS command and capture the output in an ExecResults. All exceptions are caught and
* stored in the ExecResults. @param String command is the OS command to execute @param String
* input is piped into the OS command @param int successCode is the expected return code if the
* command completes successfully @param int timeout is the number of milliseconds to wait
* before interrupting the command @param boolean quit tells the method to exit when there is no
* more output waiting
*/
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @param input
* Description of the Parameter
* @param successCode
* Description of the Parameter
* @param timeout
* Description of the Parameter
* @param lazy
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execOptions(String[] command, String input, int successCode, int timeout, boolean lazy)
{
Process child = null;
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream();
ExecResults results = new ExecResults(Arrays.asList(command).toString(), input, successCode, timeout);
BitSet interrupted = new BitSet(1);
boolean lazyQuit = false;
ThreadWatcher watcher;
try
{
// start the command
child = Runtime.getRuntime().exec(command);
// get the streams in and out of the command
InputStream processIn = child.getInputStream();
InputStream processError = child.getErrorStream();
OutputStream processOut = child.getOutputStream();
// start the clock running
if (timeout > 0)
{
watcher = new ThreadWatcher(child, interrupted, timeout);
new Thread(watcher).start();
}
// Write to the child process' input stream
if ((input != null) && !input.equals(""))
{
try
{
processOut.write(input.getBytes());
processOut.flush();
processOut.close();
} catch (IOException e1)
{
results.setThrowable(e1);
}
}
// Read from the child process' output stream
// The process may get killed by the watcher at any time
int c = 0;
try
{
while (true)
{
if (interrupted.get(0) || lazyQuit)
{
break;
}
// interrupted
c = processIn.read();
if (c == -1)
{
break;
}
// end of stream
output.write(c);
if (lazy && (processIn.available() < 1))
{
lazyQuit = true;
}
// if lazy and nothing then quit (after at least one read)
}
processIn.close();
} catch (IOException e2)
{
results.setThrowable(e2);
} finally
{
if (interrupted.get(0))
{
results.setInterrupted();
}
results.setOutput(output.toString());
}
// Read from the child process' error stream
// The process may get killed by the watcher at any time
try
{
while (true)
{
if (interrupted.get(0) || lazyQuit)
{
break;
}
// interrupted
c = processError.read();
if (c == -1)
{
break;
}
// end of stream
output.write(c);
if (lazy && (processError.available() < 1))
{
lazyQuit = true;
}
// if lazy and nothing then quit (after at least one read)
}
processError.close();
} catch (IOException e3)
{
results.setThrowable(e3);
} finally
{
if (interrupted.get(0))
{
results.setInterrupted();
}
results.setErrors(errors.toString());
}
// wait for the return value of the child process.
if (!interrupted.get(0) && !lazyQuit)
{
int returnCode = child.waitFor();
results.setReturnCode(returnCode);
if (returnCode != successCode)
{
results.setError(ExecResults.BADRETURNCODE);
}
}
} catch (InterruptedException i)
{
results.setInterrupted();
} catch (Throwable t)
{
results.setThrowable(t);
} finally
{
if (child != null)
{
child.destroy();
}
}
return (results);
}
/*
* Execute an OS command and capture the output in an ExecResults. All exceptions are caught and
* stored in the ExecResults. @param String command is the OS command to execute @param String
* input is piped into the OS command @param int successCode is the expected return code if the
* command completes successfully @param int timeout is the number of milliseconds to wait
* before interrupting the command @param boolean quit tells the method to exit when there is no
* more output waiting
*/
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @param input
* Description of the Parameter
* @param successCode
* Description of the Parameter
* @param timeout
* Description of the Parameter
* @param lazy
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execOptions(String command, String input, int successCode, int timeout, boolean lazy)
{
Process child = null;
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream();
ExecResults results = new ExecResults(command, input, successCode, timeout);
BitSet interrupted = new BitSet(1);
boolean lazyQuit = false;
ThreadWatcher watcher;
try
{
// start the command
child = Runtime.getRuntime().exec(command);
// get the streams in and out of the command
InputStream processIn = child.getInputStream();
InputStream processError = child.getErrorStream();
OutputStream processOut = child.getOutputStream();
// start the clock running
if (timeout > 0)
{
watcher = new ThreadWatcher(child, interrupted, timeout);
new Thread(watcher).start();
}
// Write to the child process' input stream
if ((input != null) && !input.equals(""))
{
try
{
processOut.write(input.getBytes());
processOut.flush();
processOut.close();
} catch (IOException e1)
{
results.setThrowable(e1);
}
}
// Read from the child process' output stream
// The process may get killed by the watcher at any time
int c = 0;
try
{
while (true)
{
if (interrupted.get(0) || lazyQuit)
{
break;
}
// interrupted
c = processIn.read();
if (c == -1)
{
break;
}
// end of stream
output.write(c);
if (lazy && (processIn.available() < 1))
{
lazyQuit = true;
}
// if lazy and nothing then quit (after at least one read)
}
processIn.close();
} catch (IOException e2)
{
results.setThrowable(e2);
} finally
{
if (interrupted.get(0))
{
results.setInterrupted();
}
results.setOutput(output.toString());
}
// Read from the child process' error stream
// The process may get killed by the watcher at any time
try
{
while (true)
{
if (interrupted.get(0) || lazyQuit)
{
break;
}
// interrupted
c = processError.read();
if (c == -1)
{
break;
}
// end of stream
output.write(c);
if (lazy && (processError.available() < 1))
{
lazyQuit = true;
}
// if lazy and nothing then quit (after at least one read)
}
processError.close();
} catch (IOException e3)
{
results.setThrowable(e3);
} finally
{
if (interrupted.get(0))
{
results.setInterrupted();
}
results.setErrors(errors.toString());
}
// wait for the return value of the child process.
if (!interrupted.get(0) && !lazyQuit)
{
int returnCode = child.waitFor();
results.setReturnCode(returnCode);
if (returnCode != successCode)
{
results.setError(ExecResults.BADRETURNCODE);
}
}
} catch (InterruptedException i)
{
results.setInterrupted();
} catch (Throwable t)
{
results.setThrowable(t);
} finally
{
if (child != null)
{
child.destroy();
}
}
return (results);
}
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execSimple(String[] command)
{
return (execOptions(command, "", 0, 0, false));
}
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execSimple(String command)
{
return (execOptions(command, "", 0, 0, false));
}
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @param args
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execSimple(String command, String args)
{
return (execOptions(command, args, 0, 0, false));
}
/**
* Description of the Method
*
* @param command
* Description of the Parameter
* @param timeout
* Description of the Parameter
* @return Description of the Return Value
*/
public static ExecResults execTimeout(String command, int timeout)
{
return (execOptions(command, "", 0, timeout, false));
}
/**
* The main program for the Exec class
*
* @param args
* The command line arguments
*/
public static void main(String[] args)
{
ExecResults results;
String sep = System.getProperty("line.separator");
System.out.println("-------------------------------------------" + sep + "TEST 1: execSimple");
results = Exec.execSimple("c:/swarm-2.1.1/bin/whoami.exe");
System.out.println(results);
System.out.println("-------------------------------------------" + sep + "TEST 2: execSimple (with search)");
results = Exec.execSimple("netstat -r");
System.out.println(results);
if (results.outputContains("localhost:1031"))
{
System.out.println("ERROR: listening on 1031");
}
System.out.println("-------------------------------------------" + sep + "TEST 3: execInput");
results = Exec.execInput("find \"cde\"", "abcdefg1\nhijklmnop\nqrstuv\nabcdefg2");
System.out.println(results);
System.out.println("-------------------------------------------" + sep + "TEST 4:execTimeout");
results = Exec.execTimeout("ping -t 127.0.0.1", 5 * 1000);
System.out.println(results);
System.out.println("-------------------------------------------" + sep + "TEST 5:execLazy");
results = Exec.execLazy("ping -t 127.0.0.1");
System.out.println(results);
System.out.println("-------------------------------------------" + sep
+ "TEST 6:ExecTimeout process never outputs");
results = Exec.execTimeout("c:/swarm-2.1.1/bin/sleep.exe 20", 5 * 1000);
System.out.println(results);
System.out.println("-------------------------------------------" + sep
+ "TEST 7:ExecTimeout process waits for input");
results = Exec.execTimeout("c:/swarm-2.1.1/bin/cat", 5 * 1000);
System.out.println(results);
}
}

View File

@ -1,353 +0,0 @@
package org.owasp.webgoat.util;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/
public class ExecResults
{
/**
* Description of the Field
*/
public final static int BADRETURNCODE = 2;
/**
* Description of the Field
*/
public final static int THROWABLE = 1;
private String myCommand;
private boolean myError = false;
private int myErrorType = 0;
private String myErrors = null;
private String myInput;
private boolean myInterrupted = false;
private String myOutput = null;
private int myReturnCode = 0;
private int mySuccessCode;
private Throwable myThrowable = null;
private int myTimeout;
/**
* Constructor for the ExecResults object
*
* @param command
* Description of the Parameter
* @param input
* Description of the Parameter
* @param successCode
* Description of the Parameter
* @param timeout
* Description of the Parameter
*/
public ExecResults(String command, String input, int successCode, int timeout)
{
myCommand = command.trim();
myInput = input.trim();
mySuccessCode = successCode;
myTimeout = timeout;
}
/**
* Description of the Method
*
* @param haystack
* Description of the Parameter
* @param needle
* Description of the Parameter
* @param fromIndex
* Description of the Parameter
* @return Description of the Return Value
*/
private boolean contains(String haystack, String needle, int fromIndex)
{
return (haystack.trim().toLowerCase().indexOf(needle.trim().toLowerCase(), fromIndex) != -1);
}
/**
* Description of the Method
*
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public boolean errorsContains(String value)
{
return (errorsContains(value, 0));
}
/**
* Description of the Method
*
* @param value
* Description of the Parameter
* @param fromIndex
* Description of the Parameter
* @return Description of the Return Value
*/
public boolean errorsContains(String value, int fromIndex)
{
return (contains(myErrors, value, fromIndex));
}
/**
* Gets the error attribute of the ExecResults object
*
* @return The error value
*/
public boolean getError()
{
return (myError);
}
/**
* Gets the errorMessage attribute of the ExecResults object
*
* @return The errorMessage value
*/
public String getErrorMessage()
{
switch (getErrorType())
{
case THROWABLE:
return ("Exception: " + myThrowable.getMessage());
case BADRETURNCODE:
return ("Bad return code (expected " + mySuccessCode + ")");
default:
return ("Unknown error");
}
}
/**
* Gets the errorType attribute of the ExecResults object
*
* @return The errorType value
*/
public int getErrorType()
{
return (myErrorType);
}
/**
* Gets the errors attribute of the ExecResults object
*
* @return The errors value
*/
public String getErrors()
{
return (myErrors);
}
/**
* Gets the interrupted attribute of the ExecResults object
*
* @return The interrupted value
*/
public boolean getInterrupted()
{
return (myInterrupted);
}
/**
* Gets the output attribute of the ExecResults object
*
* @return The output value
*/
public String getOutput()
{
return (myOutput);
}
/**
* Gets the returnCode attribute of the ExecResults object
*
* @return The returnCode value
*/
public int getReturnCode()
{
return (myReturnCode);
}
/**
* Gets the throwable attribute of the ExecResults object
*
* @return The throwable value
*/
public Throwable getThrowable()
{
return (myThrowable);
}
/**
* Description of the Method
*
* @param value
* Description of the Parameter
* @return Description of the Return Value
*/
public boolean outputContains(String value)
{
return (outputContains(value, 0));
}
/**
* Description of the Method
*
* @param value
* Description of the Parameter
* @param fromIndex
* Description of the Parameter
* @return Description of the Return Value
*/
public boolean outputContains(String value, int fromIndex)
{
return (contains(myOutput, value, fromIndex));
}
/**
* Sets the error attribute of the ExecResults object
*
* @param value
* The new error value
*/
public void setError(int value)
{
myError = true;
myErrorType = value;
}
/**
* Sets the errors attribute of the ExecResults object
*
* @param errors
* The new errors value
*/
public void setErrors(String errors)
{
myErrors = errors.trim();
}
/**
* Sets the interrupted attribute of the ExecResults object
*/
public void setInterrupted()
{
myInterrupted = true;
}
/**
* Sets the output attribute of the ExecResults object
*
* @param value
* The new output value
*/
public void setOutput(String value)
{
myOutput = value.trim();
}
/**
* Sets the returnCode attribute of the ExecResults object
*
* @param value
* The new returnCode value
*/
public void setReturnCode(int value)
{
myReturnCode = value;
}
/**
* Sets the throwable attribute of the ExecResults object
*
* @param value
* The new throwable value
*/
public void setThrowable(Throwable value)
{
setError(THROWABLE);
myThrowable = value;
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public String toString()
{
String sep = System.getProperty("line.separator");
StringBuffer value = new StringBuffer();
value.append("ExecResults for \'" + myCommand + "\'" + sep);
if ((myInput != null) && !myInput.equals(""))
{
value.append(sep + "Input..." + sep + myInput + sep);
}
if ((myOutput != null) && !myOutput.equals(""))
{
value.append(sep + "Output..." + sep + myOutput + sep);
}
if ((myErrors != null) && !myErrors.equals(""))
{
value.append(sep + "Errors..." + sep + myErrors + sep);
}
value.append(sep);
if (myInterrupted)
{
value.append("Command timed out after " + (myTimeout / 1000) + " seconds " + sep);
}
value.append("Returncode: " + myReturnCode + sep);
if (myError)
{
value.append(getErrorMessage() + sep);
}
return (value.toString());
}
}

View File

@ -1,59 +0,0 @@
package org.owasp.webgoat.util;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/
public class ExecutionException extends Exception
{
/**
*
*/
private static final long serialVersionUID = 7282947463831152092L;
/**
* Constructor for the ExecutionException object
*/
public ExecutionException()
{
super();
}
/**
* Constructor for the ExecutionException object
*
* @param msg
* Description of the Parameter
*/
public ExecutionException(String msg)
{
super(msg);
}
}

View File

@ -1,225 +0,0 @@
package org.owasp.webgoat.util;
import java.util.HashMap;
import java.util.Map;
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* For details, please see http://webgoat.github.io
*/
public class HtmlEncoder
{
static Map<String, Integer> e2i = new HashMap<String, Integer>();
static Map<Integer, String> i2e = new HashMap<Integer, String>();
// html entity list
private static Object[][] entities = { { "quot", new Integer(34) }, // " - double-quote
{ "amp", new Integer(38) }, // & - ampersand
{ "lt", new Integer(60) }, // < - less-than
{ "gt", new Integer(62) }, // > - greater-than
{ "nbsp", new Integer(160) }, // non-breaking space
{ "copy", new Integer(169) }, // <20> - copyright
{ "reg", new Integer(174) }, // <20> - registered trademark
{ "Agrave", new Integer(192) }, // <20> - uppercase A, grave accent
{ "Aacute", new Integer(193) }, // <20> - uppercase A, acute accent
{ "Acirc", new Integer(194) }, // <20> - uppercase A, circumflex accent
{ "Atilde", new Integer(195) }, // <20> - uppercase A, tilde
{ "Auml", new Integer(196) }, // <20> - uppercase A, umlaut
{ "Aring", new Integer(197) }, // <20> - uppercase A, ring
{ "AElig", new Integer(198) }, // <20> - uppercase AE
{ "Ccedil", new Integer(199) }, // <20> - uppercase C, cedilla
{ "Egrave", new Integer(200) }, // <20> - uppercase E, grave accent
{ "Eacute", new Integer(201) }, // <20> - uppercase E, acute accent
{ "Ecirc", new Integer(202) }, // <20> - uppercase E, circumflex accent
{ "Euml", new Integer(203) }, // <20> - uppercase E, umlaut
{ "Igrave", new Integer(204) }, // <20> - uppercase I, grave accent
{ "Iacute", new Integer(205) }, // <20> - uppercase I, acute accent
{ "Icirc", new Integer(206) }, // <20> - uppercase I, circumflex accent
{ "Iuml", new Integer(207) }, // <20> - uppercase I, umlaut
{ "ETH", new Integer(208) }, // <20> - uppercase Eth, Icelandic
{ "Ntilde", new Integer(209) }, // <20> - uppercase N, tilde
{ "Ograve", new Integer(210) }, // <20> - uppercase O, grave accent
{ "Oacute", new Integer(211) }, // <20> - uppercase O, acute accent
{ "Ocirc", new Integer(212) }, // <20> - uppercase O, circumflex accent
{ "Otilde", new Integer(213) }, // <20> - uppercase O, tilde
{ "Ouml", new Integer(214) }, // <20> - uppercase O, umlaut
{ "Oslash", new Integer(216) }, // <20> - uppercase O, slash
{ "Ugrave", new Integer(217) }, // <20> - uppercase U, grave accent
{ "Uacute", new Integer(218) }, // <20> - uppercase U, acute accent
{ "Ucirc", new Integer(219) }, // <20> - uppercase U, circumflex accent
{ "Uuml", new Integer(220) }, // <20> - uppercase U, umlaut
{ "Yacute", new Integer(221) }, // <20> - uppercase Y, acute accent
{ "THORN", new Integer(222) }, // <20> - uppercase THORN, Icelandic
{ "szlig", new Integer(223) }, // <20> - lowercase sharps, German
{ "agrave", new Integer(224) }, // <20> - lowercase a, grave accent
{ "aacute", new Integer(225) }, // <20> - lowercase a, acute accent
{ "acirc", new Integer(226) }, // <20> - lowercase a, circumflex accent
{ "atilde", new Integer(227) }, // <20> - lowercase a, tilde
{ "auml", new Integer(228) }, // <20> - lowercase a, umlaut
{ "aring", new Integer(229) }, // <20> - lowercase a, ring
{ "aelig", new Integer(230) }, // <20> - lowercase ae
{ "ccedil", new Integer(231) }, // <20> - lowercase c, cedilla
{ "egrave", new Integer(232) }, // <20> - lowercase e, grave accent
{ "eacute", new Integer(233) }, // <20> - lowercase e, acute accent
{ "ecirc", new Integer(234) }, // <20> - lowercase e, circumflex accent
{ "euml", new Integer(235) }, // <20> - lowercase e, umlaut
{ "igrave", new Integer(236) }, // <20> - lowercase i, grave accent
{ "iacute", new Integer(237) }, // <20> - lowercase i, acute accent
{ "icirc", new Integer(238) }, // <20> - lowercase i, circumflex accent
{ "iuml", new Integer(239) }, // <20> - lowercase i, umlaut
{ "igrave", new Integer(236) }, // <20> - lowercase i, grave accent
{ "iacute", new Integer(237) }, // <20> - lowercase i, acute accent
{ "icirc", new Integer(238) }, // <20> - lowercase i, circumflex accent
{ "iuml", new Integer(239) }, // <20> - lowercase i, umlaut
{ "eth", new Integer(240) }, // <20> - lowercase eth, Icelandic
{ "ntilde", new Integer(241) }, // <20> - lowercase n, tilde
{ "ograve", new Integer(242) }, // <20> - lowercase o, grave accent
{ "oacute", new Integer(243) }, // <20> - lowercase o, acute accent
{ "ocirc", new Integer(244) }, // <20> - lowercase o, circumflex accent
{ "otilde", new Integer(245) }, // <20> - lowercase o, tilde
{ "ouml", new Integer(246) }, // <20> - lowercase o, umlaut
{ "oslash", new Integer(248) }, // <20> - lowercase o, slash
{ "ugrave", new Integer(249) }, // <20> - lowercase u, grave accent
{ "uacute", new Integer(250) }, // <20> - lowercase u, acute accent
{ "ucirc", new Integer(251) }, // <20> - lowercase u, circumflex accent
{ "uuml", new Integer(252) }, // <20> - lowercase u, umlaut
{ "yacute", new Integer(253) }, // <20> - lowercase y, acute accent
{ "thorn", new Integer(254) }, // <20> - lowercase thorn, Icelandic
{ "yuml", new Integer(255) }, // <20> - lowercase y, umlaut
{ "euro", new Integer(8364) },// Euro symbol
};
public HtmlEncoder()
{
for (int i = 0; i < entities.length; i++)
e2i.put((String) entities[i][0], (Integer) entities[i][1]);
for (int i = 0; i < entities.length; i++)
i2e.put((Integer) entities[i][1], (String) entities[i][0]);
}
/**
* Turns funky characters into HTML entity equivalents
* <p>
*
* e.g. <tt>"bread" & "butter"</tt> => <tt>&amp;quot;bread&amp;quot; &amp;amp;
* &amp;quot;butter&amp;quot;</tt> . Update: supports nearly all HTML entities, including funky
* accents. See the source code for more detail. Adapted from
* http://www.purpletech.com/code/src/com/purpletech/util/Utils.java.
*
* @param s1
* Description of the Parameter
* @return Description of the Return Value
*/
public static String encode(String s1)
{
StringBuffer buf = new StringBuffer();
int i;
for (i = 0; i < s1.length(); ++i)
{
char ch = s1.charAt(i);
String entity = i2e.get(new Integer((int) ch));
if (entity == null)
{
if (((int) ch) > 128)
{
buf.append("&#" + ((int) ch) + ";");
}
else
{
buf.append(ch);
}
}
else
{
buf.append("&" + entity + ";");
}
}
return buf.toString();
}
/**
* Given a string containing entity escapes, returns a string containing the actual Unicode
* characters corresponding to the escapes. Adapted from
* http://www.purpletech.com/code/src/com/purpletech/util/Utils.java.
*
* @param s1
* Description of the Parameter
* @return Description of the Return Value
*/
public static String decode(String s1)
{
StringBuffer buf = new StringBuffer();
int i;
for (i = 0; i < s1.length(); ++i)
{
char ch = s1.charAt(i);
if (ch == '&')
{
int semi = s1.indexOf(';', i + 1);
if (semi == -1)
{
buf.append(ch);
continue;
}
String entity = s1.substring(i + 1, semi);
Integer iso;
if (entity.charAt(0) == '#')
{
iso = new Integer(entity.substring(1));
}
else
{
iso = e2i.get(entity);
}
if (iso == null)
{
buf.append("&" + entity + ";");
}
else
{
buf.append((char) (iso.intValue()));
}
i = semi;
}
else
{
buf.append(ch);
}
}
return buf.toString();
}
}

View File

@ -1,143 +0,0 @@
/**
*
*/
package org.owasp.webgoat.util;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.net.Socket;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author sherif koussa - Macadamian Technologies
*
*/
public class Interceptor implements Filter
{
private static final String OSG_SERVER_NAME = "OSGServerName";
private static final String OSG_SERVER_PORT = "OSGServerPort";
/*
* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy()
{
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
Socket osgSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String osgServerName = req.getSession().getServletContext().getInitParameter(OSG_SERVER_NAME);
String osgServerPort = req.getSession().getServletContext().getInitParameter(OSG_SERVER_PORT);
try
{
// If these parameters are not defined then no communication will happen with OSG
if (osgServerName != null && osgServerName.length() != 0 && osgServerPort != null
&& osgServerPort.length() != 0)
{
osgSocket = new Socket(osgServerName, Integer.parseInt(osgServerPort));
if (osgSocket != null)
{
out = new PrintWriter(osgSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(osgSocket.getInputStream()));
// String message =
// "HTTPRECEIVEHTTPREQUEST,-,DataValidation_SqlInjection_Basic.aspx";
// out.println(message);
// System.out.println(in.readLine());
}
}
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
if (osgSocket != null)
{
osgSocket.close();
}
}
String url = req.getRequestURL().toString();
RequestDispatcher disp = req.getRequestDispatcher(url.substring(url.lastIndexOf(req.getContextPath() + "/")
+ req.getContextPath().length()));
disp.forward(request, response);
}
/*
* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig arg0) throws ServletException
{
// TODO Auto-generated method stub
}
}

View File

@ -1,41 +0,0 @@
package org.owasp.webgoat.util;
import java.util.Locale;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*/
public interface LabelManager
{
public void setLocale(Locale locale);
public String get(String labelKey);
}

View File

@ -1,61 +0,0 @@
package org.owasp.webgoat.util;
import java.util.Locale;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*/
@Component("labelManager")
@Scope(value="session", proxyMode=ScopedProxyMode.INTERFACES)
public class LabelManagerImpl implements LabelManager
{
@Resource
private LabelProvider labelProvider;
/** Locale mapped with current session. */
private Locale locale = new Locale(LabelProvider.DEFAULT_LANGUAGE);
public void setLocale(Locale locale)
{
if (locale != null)
{
this.locale = locale;
}
}
public String get(String labelKey)
{
return labelProvider.get(locale, labelKey);
}
}

View File

@ -1,70 +0,0 @@
package org.owasp.webgoat.util;
import org.owasp.webgoat.plugins.ResourceBundleClassLoader;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*/
@Component
public class LabelProvider
{
public final static String DEFAULT_LANGUAGE = Locale.ENGLISH.getLanguage();
private final HashMap<Locale, ResourceBundle> labels = new HashMap<Locale, ResourceBundle>();
private final WebGoatResourceBundleController localeController = new WebGoatResourceBundleController();
public String get(Locale locale, String strName)
{
if (!labels.containsKey(locale))
{
ClassLoader classLoader = ResourceBundleClassLoader.createPropertyFilesClassLoader();
ResourceBundle resBundle = ResourceBundle.getBundle("WebGoatLabels", locale, classLoader, localeController);
labels.put(locale, resBundle);
}
return labels.get(locale).getString(strName);
}
private class WebGoatResourceBundleController extends ResourceBundle.Control
{
private final Locale fallbackLocale = new Locale(DEFAULT_LANGUAGE);
@Override
public Locale getFallbackLocale(String baseName, Locale locale)
{
if (!fallbackLocale.equals(locale)) { return fallbackLocale; }
return Locale.ROOT;
}
}
}

View File

@ -1,103 +0,0 @@
package org.owasp.webgoat.util;
import java.util.BitSet;
/***************************************************************************************************
*
*
* 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.
*
* For details, please see http://webgoat.github.io
*
* @author jwilliams@aspectsecurity.com
* @created November 6, 2002
*/
public class ThreadWatcher implements Runnable
{
// time to live in milliseconds
private BitSet myInterrupted;
private Process myProcess;
private int myTimeout;
/**
* Constructor for the ThreadWatcher object
*
* @param p
* Description of the Parameter
* @param interrupted
* Description of the Parameter
* @param timeout
* Description of the Parameter
*/
public ThreadWatcher(Process p, BitSet interrupted, int timeout)
{
myProcess = p;
// thread used by whoever constructed this watcher
myTimeout = timeout;
myInterrupted = interrupted;
}
/*
* Interrupt the thread by marking the interrupted bit and killing the process
*/
/**
* Description of the Method
*/
public void interrupt()
{
myInterrupted.set(0);
// set interrupted bit (bit 0 of the bitset) to 1
myProcess.destroy();
/*
* try { myProcess.getInputStream().close(); } catch( IOException e1 ) { / do nothing --
* input streams are probably already closed } try { myProcess.getErrorStream().close(); }
* catch( IOException e2 ) { / do nothing -- input streams are probably already closed }
* myThread.interrupt();
*/
}
/**
* Main processing method for the ThreadWatcher object
*/
public void run()
{
try
{
Thread.sleep(myTimeout);
} catch (InterruptedException e)
{
// do nothing -- if watcher is interrupted, so is thread
}
interrupt();
}
}

View File

@ -1,66 +0,0 @@
package org.owasp.webgoat.util;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;
import org.owasp.webgoat.session.WebgoatContext;
@Deprecated
public class WebGoatI18N
{
private static HashMap<Locale, ResourceBundle> labels = new HashMap<Locale, ResourceBundle>();
private static Locale currentLocale;
private static WebGoatResourceBundleController localeController;
public WebGoatI18N(WebgoatContext context)
{
currentLocale = new Locale(context.getDefaultLanguage());
localeController = new WebGoatResourceBundleController(currentLocale);
}
@Deprecated
public static void loadLanguage(String language)
{
// Do nothing
}
public static void setCurrentLocale(Locale locale)
{
if (!currentLocale.equals(locale))
{
if (!labels.containsKey(locale))
{
ResourceBundle resBundle = ResourceBundle.getBundle("WebGoatLabels", locale, localeController);
labels.put(locale, resBundle);
}
WebGoatI18N.currentLocale = locale;
}
}
public static String get(String strName)
{
return labels.get(WebGoatI18N.currentLocale).getString(strName);
}
private static class WebGoatResourceBundleController extends ResourceBundle.Control
{
private Locale fallbackLocale;
public WebGoatResourceBundleController(Locale l)
{
fallbackLocale = l;
}
@Override
public Locale getFallbackLocale(String baseName, Locale locale)
{
if(! fallbackLocale.equals(locale)) {
return fallbackLocale;
}
return Locale.ROOT;
}
}
}