Added some files required to build OWASP release.

Modified License text and format to reflect GPL license.
Reformatted most of the code.

git-svn-id: http://webgoat.googlecode.com/svn/trunk@60 4033779f-a91e-0410-96ef-6bf7bf53c507
This commit is contained in:
mayhew64 2007-01-16 14:56:40 +00:00
parent 036964495b
commit fd9b60f98e
110 changed files with 23099 additions and 17996 deletions

View File

@ -0,0 +1,20 @@
Installing WebGoat WAR file into a Standard Tomcat Installation
===============================================================
To do this, you'll need to configure server.xml and tomcat-users.xml a bit. Basically, you'll want to change the port number in server.xml to 80 (or just stick with 8080). WebGoat also has some specific users and roles that it uses which are defined in tomcat-users.xml.
- Add the following users to tomcat-users.xml in tomcat/conf directory
<user username="webgoat" password="webgoat" roles="webgoat_admin"/>
<user username="basic" password="basic" roles="webgoat_user,webgoat_basic"/>
<user username="guest" password="guest" roles="webgoat_user"/>
<user username="admin" password="admin" roles="admin,manager"/>
This is explained in the readme.txt file in the root directory.
If you do not rename the war file to WebGoat.war you will need to
browse to:
http://localhost/WebGoat-VERSION_NUM/attack
Let us know if you are still having problems at the WebGoat mailing list: http://lists.sourceforge.net/lists/listinfo/owasp-webgoat.

View File

@ -139,12 +139,6 @@
--> -->
<target name="dist_CBT" depends="clean, compile"
description="Create CBT binary distribution">
<CopyWebCBTToBuild/>
<WarBuild/>
</target>
<target name="ZipProject" <target name="ZipProject"
description="Create a zip archive of all Eclipse project files from C:\WebGoatClassCD"> description="Create a zip archive of all Eclipse project files from C:\WebGoatClassCD">
@ -273,7 +267,7 @@
<zip destfile="${dist.home}/${ant.project.name}.zip"> <zip destfile="${dist.home}/${ant.project.name}.zip">
<zipfileset dir="." prefix="${install.home}" <zipfileset dir="." prefix="${install.home}"
includes="eclipse/, java/, project/, tomcat/, webscarab/, InfoZip/, eclipse.bat, webgoat.bat, webscarab.bat" includes="eclipse/, java/, project/, tomcat/, webscarab/, InfoZip/, eclipse.bat, webgoat.bat, webscarab.bat"
excludes="project/.*, project/.settings/**, project/dist/**, project/bin/**, project/build/**, project/web_CBT/**"/> excludes="project/.*, project/.settings/**, project/dist/**, project/bin/**, project/build/**"/>
<zipfileset src="project-student.zip" prefix="${install.home}"/> <zipfileset src="project-student.zip" prefix="${install.home}"/>
</zip> </zip>
<copy todir="${dist.home}"> <copy todir="${dist.home}">

View File

@ -25,17 +25,43 @@ import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker; import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class HammerHead extends HttpServlet public class HammerHead extends HttpServlet
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
@ -50,8 +76,8 @@ public class HammerHead extends HttpServlet
* Set the session timeout to be 2 days * Set the session timeout to be 2 days
*/ */
private final static int sessionTimeoutSeconds = 60 * 60 * 24 * 2; private final static int sessionTimeoutSeconds = 60 * 60 * 24 * 2;
//private final static int sessionTimeoutSeconds = 1;
// private final static int sessionTimeoutSeconds = 1;
/** /**
* Properties file path * Properties file path
@ -59,16 +85,20 @@ public class HammerHead extends HttpServlet
public static String propertiesPath = null; public static String propertiesPath = null;
/** /**
* Description of the Method * Description of the Method
* *
* @param request Description of the Parameter * @param request
* @param response Description of the Parameter * Description of the Parameter
* @exception IOException Description of the Exception * @param response
* @exception ServletException Description of the Exception * 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 public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{ {
doPost(request, response); doPost(request, response);
} }
@ -77,12 +107,17 @@ public class HammerHead extends HttpServlet
/** /**
* Description of the Method * Description of the Method
* *
* @param request Description of the Parameter * @param request
* @param response Description of the Parameter * Description of the Parameter
* @exception IOException Description of the Exception * @param response
* @exception ServletException Description of the Exception * 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 public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{ {
Screen screen = null; Screen screen = null;
@ -90,31 +125,42 @@ public class HammerHead extends HttpServlet
{ {
// System.out.println( "HH Entering doPost: " ); // System.out.println( "HH Entering doPost: " );
// System.out.println( " - HH request " + request); // System.out.println( " - HH request " + request);
//System.out.println( " - HH principle: " + request.getUserPrincipal() ); // System.out.println( " - HH principle: " +
// request.getUserPrincipal() );
// setCacheHeaders(response, 0); // setCacheHeaders(response, 0);
ServletContext context = getServletContext(); ServletContext context = getServletContext();
// FIXME: If a response is written by updateSession(), do not call makeScreen() and writeScreen() // FIXME: If a response is written by updateSession(), do not
// call makeScreen() and writeScreen()
mySession = updateSession(request, response, context); mySession = updateSession(request, response, context);
if (response.isCommitted()) if (response.isCommitted())
return; return;
// Note: For the lesson to track the status, we need to update the lesson tracker object // Note: For the lesson to track the status, we need to update
// from the screen.createContent() method. The create content is the only point // the lesson tracker object
// where the lesson "knows" what has happened. To track it at a latter point would // 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. // require the lesson to have memory.
screen = makeScreen( mySession ); // This calls the lesson's handleRequest() screen = makeScreen(mySession); // This calls the lesson's
// handleRequest()
if (response.isCommitted()) if (response.isCommitted())
return; return;
// if the screen parameter exists, the screen was visited via the menu categories, // if the screen parameter exists, the screen was visited via
// we won't count these as visits. The user may be able to manipulate the counts // the menu categories,
// by specifying the screen parameter using a proxy. Good for them! // we won't count these as visits. The user may be able to
String fromMenus = mySession.getParser().getRawParameter( WebSession.SCREEN, null ); // manipulate the counts
// by specifying the screen parameter using a proxy. Good for
// them!
String fromMenus = mySession.getParser().getRawParameter(
WebSession.SCREEN, null);
if (fromMenus == null) if (fromMenus == null)
{ {
// if the show source parameter exists, don't add the visit // if the show source parameter exists, don't add the visit
fromMenus = mySession.getParser().getRawParameter( WebSession.SHOW, null ); fromMenus = mySession.getParser().getRawParameter(
WebSession.SHOW, null);
if (fromMenus == null) if (fromMenus == null)
{ {
screen.getLessonTracker(mySession).incrementNumVisits(); screen.getLessonTracker(mySession).incrementNumVisits();
@ -124,7 +170,8 @@ public class HammerHead extends HttpServlet
// log the access to this screen for this user // log the access to this screen for this user
UserTracker userTracker = UserTracker.instance(); UserTracker userTracker = UserTracker.instance();
userTracker.update(mySession, screen); userTracker.update(mySession, screen);
log( request, screen.getClass().getName() + " | " + mySession.getParser().toString() ); log(request, screen.getClass().getName() + " | "
+ mySession.getParser().toString());
// Redirect the request to our View servlet // Redirect the request to our View servlet
String userAgent = request.getHeader("user-agent"); String userAgent = request.getHeader("user-agent");
@ -137,7 +184,8 @@ public class HammerHead extends HttpServlet
request.getSession().setAttribute("websession", mySession); request.getSession().setAttribute("websession", mySession);
request.getSession().setAttribute("course", mySession.getCourse()); request.getSession().setAttribute("course", mySession.getCourse());
request.getRequestDispatcher(getViewPage(mySession)).forward(request, response); request.getRequestDispatcher(getViewPage(mySession)).forward(
request, response);
} }
catch (Throwable t) catch (Throwable t)
{ {
@ -154,12 +202,14 @@ public class HammerHead extends HttpServlet
catch (Throwable thr) catch (Throwable thr)
{ {
thr.printStackTrace(); thr.printStackTrace();
log( request, "Could not write error screen: " + thr.getMessage() ); log(request, "Could not write error screen: "
+ thr.getMessage());
} }
// System.out.println( "HH Leaving doPost: " ); // System.out.println( "HH Leaving doPost: " );
} }
} }
private String getViewPage(WebSession webSession) private String getViewPage(WebSession webSession)
{ {
String page; String page;
@ -177,10 +227,12 @@ public class HammerHead extends HttpServlet
return page; return page;
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param session Description of the Parameter * @param session
* Description of the Parameter
*/ */
private void dumpSession(HttpSession session) private void dumpSession(HttpSession session)
{ {
@ -199,7 +251,8 @@ public class HammerHead extends HttpServlet
/** /**
* Description of the Method * Description of the Method
* *
* @param date Description of the Parameter * @param date
* Description of the Parameter
* @return RFC 1123 http date format * @return RFC 1123 http date format
*/ */
protected static String formatHttpDate(Date date) protected static String formatHttpDate(Date date)
@ -221,6 +274,7 @@ public class HammerHead extends HttpServlet
return "WebGoat is sponsored by Aspect Security."; return "WebGoat is sponsored by Aspect Security.";
} }
/** /**
* Return properties path * Return properties path
* *
@ -228,26 +282,32 @@ public class HammerHead extends HttpServlet
*/ */
public void init() throws ServletException public void init() throws ServletException
{ {
httpDateFormat = new SimpleDateFormat( "EEE, dd MMM yyyyy HH:mm:ss z", Locale.US ); httpDateFormat = new SimpleDateFormat("EEE, dd MMM yyyyy HH:mm:ss z",
Locale.US);
httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
propertiesPath = getServletContext().getRealPath( propertiesPath = getServletContext().getRealPath(
"." + System.getProperty("file.separator")+ "WEB-INF" + "/webgoat.properties"); "." + System.getProperty("file.separator") + "WEB-INF"
+ "/webgoat.properties");
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param request Description of the Parameter * @param request
* @param message Description of the Parameter * Description of the Parameter
* @param message
* Description of the Parameter
*/ */
public void log(HttpServletRequest request, String message) public void log(HttpServletRequest request, String message)
{ {
String output = new Date() + " | " + request.getRemoteHost() + ":" + request.getRemoteAddr() + " | " + message; String output = new Date() + " | " + request.getRemoteHost() + ":"
+ request.getRemoteAddr() + " | " + message;
log(output); log(output);
System.out.println(output); System.out.println(output);
} }
public List getCategories() public List getCategories()
{ {
Course course = mySession.getCourse(); Course course = mySession.getCourse();
@ -257,22 +317,19 @@ public class HammerHead extends HttpServlet
return course.getCategories(); return course.getCategories();
} }
/* /*
public List getLessons(Category category, String role) * public List getLessons(Category category, String role) { Course
{ * course = mySession.getCourse(); // May need to clone the List before
Course course = mySession.getCourse(); * returning it. //return new ArrayList(course.getLessons(category,
* role)); return course.getLessons(category, role); }
// 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 * Description of the Method
* *
* @param s Description of the Parameter * @param s
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Screen makeScreen(WebSession s) protected Screen makeScreen(WebSession s)
@ -289,20 +346,26 @@ public class HammerHead extends HttpServlet
} }
else else
{ {
AbstractLesson lesson = course.getLesson( s, scr, AbstractLesson.USER_ROLE ); AbstractLesson lesson = course.getLesson(s, scr,
AbstractLesson.USER_ROLE);
if (lesson == null && s.isHackedAdmin()) if (lesson == null && s.isHackedAdmin())
{ {
// If admin was hacked, let the user see some of the admin screens // If admin was hacked, let the user see some of the
lesson = course.getLesson( s, scr, AbstractLesson.HACKED_ADMIN_ROLE ); // admin screens
lesson = course.getLesson(s, scr,
AbstractLesson.HACKED_ADMIN_ROLE);
} }
if (lesson != null) if (lesson != null)
{ {
screen = lesson; screen = lesson;
// We need to do some bookkeeping for the hackable admin interface. // We need to do some bookkeeping for the hackable admin
// This is the only place we can tell if the user successfully hacked the hackable // interface.
// admin and has actually accessed an admin screen. You need BOTH pieces of information // 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. // in order to satisfy the remote admin lesson.
s.setHasHackableAdmin(screen.getRole()); s.setHasHackableAdmin(screen.getRole());
@ -312,7 +375,8 @@ public class HammerHead extends HttpServlet
} }
else else
{ {
screen = new ErrorScreen( s, "Invalid screen requested. Try: http://localhost/WebGoat/attack" ); screen = new ErrorScreen(s,
"Invalid screen requested. Try: http://localhost/WebGoat/attack");
} }
} }
} }
@ -326,10 +390,12 @@ public class HammerHead extends HttpServlet
{ {
// Admin can see all roles. // Admin can see all roles.
// FIXME: should be able to pass a list of roles. // FIXME: should be able to pass a list of roles.
AbstractLesson lesson = course.getLesson( s, scr, AbstractLesson.ADMIN_ROLE ); AbstractLesson lesson = course.getLesson(s, scr,
AbstractLesson.ADMIN_ROLE);
if (lesson == null) if (lesson == null)
{ {
lesson = course.getLesson( s, scr, AbstractLesson.HACKED_ADMIN_ROLE ); lesson = course.getLesson(s, scr,
AbstractLesson.HACKED_ADMIN_ROLE);
} }
if (lesson == null) if (lesson == null)
{ {
@ -340,9 +406,12 @@ public class HammerHead extends HttpServlet
{ {
screen = lesson; screen = lesson;
// We need to do some bookkeeping for the hackable admin interface. // We need to do some bookkeeping for the hackable admin
// This is the only place we can tell if the user successfully hacked the hackable // interface.
// admin and has actually accessed an admin screen. You need BOTH pieces of information // 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. // in order to satisfy the remote admin lesson.
s.setHasHackableAdmin(screen.getRole()); s.setHasHackableAdmin(screen.getRole());
@ -352,7 +421,9 @@ public class HammerHead extends HttpServlet
} }
else else
{ {
screen = new ErrorScreen( s, "Invalid screen requested. Try Setting Admin to false or Try: http://localhost/WebGoat/attack" ); screen = new ErrorScreen(
s,
"Invalid screen requested. Try Setting Admin to false or Try: http://localhost/WebGoat/attack");
} }
} }
} }
@ -362,13 +433,17 @@ public class HammerHead extends HttpServlet
/** /**
* This method sets the required expiration headers in the response for a given RunData object. * This method sets the required expiration headers in the response for
* This method attempts to set all relevant headers, both for HTTP 1.0 and HTTP 1.1. * 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 response
* @param expiry The new cacheHeaders value * The new cacheHeaders value
* @param expiry
* The new cacheHeaders value
*/ */
protected static void setCacheHeaders( HttpServletResponse response, int expiry ) protected static void setCacheHeaders(HttpServletResponse response,
int expiry)
{ {
if (expiry == 0) if (expiry == 0)
{ {
@ -387,12 +462,16 @@ public class HammerHead extends HttpServlet
/** /**
* Description of the Method * Description of the Method
* *
* @param request Description of the Parameter * @param request
* @param response Description of the Parameter * Description of the Parameter
* @param context Description of the Parameter * @param response
* Description of the Parameter
* @param context
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected WebSession updateSession( HttpServletRequest request, HttpServletResponse response, ServletContext context ) protected WebSession updateSession(HttpServletRequest request,
HttpServletResponse response, ServletContext context)
throws IOException throws IOException
{ {
HttpSession hs; HttpSession hs;
@ -431,11 +510,15 @@ public class HammerHead extends HttpServlet
/** /**
* Description of the Method * Description of the Method
* *
* @param s Description of the Parameter * @param s
* @param response Description of the Parameter * Description of the Parameter
* @exception IOException Description of the Exception * @param response
* Description of the Parameter
* @exception IOException
* Description of the Exception
*/ */
protected void writeScreen( Screen s, HttpServletResponse response ) throws IOException protected void writeScreen(Screen s, HttpServletResponse response)
throws IOException
{ {
response.setContentType("text/html"); response.setContentType("text/html");
@ -455,4 +538,3 @@ public class HammerHead extends HttpServlet
out.close(); out.close();
} }
} }

View File

@ -13,11 +13,34 @@ import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Course; import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -28,11 +51,11 @@ public class LessonSource extends HammerHead
/** /**
* Description of the Field * Description of the Field
*/ */
//protected WebSession tempSession;
public final static String START_SOURCE_SKIP = "START_OMIT_SOURCE"; 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";
/** /**
* Description of the Method * Description of the Method
* *
@ -41,7 +64,8 @@ public class LessonSource extends HammerHead
* @exception IOException Description of the Exception * @exception IOException Description of the Exception
* @exception ServletException Description of the Exception * @exception ServletException Description of the Exception
*/ */
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{ {
String source = null; String source = null;
@ -51,7 +75,8 @@ public class LessonSource extends HammerHead
//System.out.println( " - request " + request); //System.out.println( " - request " + request);
//System.out.println( " - principle: " + request.getUserPrincipal() ); //System.out.println( " - principle: " + request.getUserPrincipal() );
//setCacheHeaders(response, 0); //setCacheHeaders(response, 0);
WebSession session = (WebSession) request.getSession( true ).getAttribute( WebSession.SESSION ); WebSession session = (WebSession) request.getSession(true)
.getAttribute(WebSession.SESSION);
session.update(request, response, this.getServletName()); // FIXME: Too much in this call. session.update(request, response, this.getServletName()); // FIXME: Too much in this call.
// Get the Java source of the lesson. FIXME: Not needed // Get the Java source of the lesson. FIXME: Not needed
@ -59,7 +84,8 @@ public class LessonSource extends HammerHead
int scr = session.getCurrentScreen(); int scr = session.getCurrentScreen();
Course course = session.getCourse(); Course course = session.getCourse();
AbstractLesson lesson = course.getLesson( session, scr, AbstractLesson.USER_ROLE ); AbstractLesson lesson = course.getLesson(session, scr,
AbstractLesson.USER_ROLE);
lesson.getLessonTracker(session).setViewedSource(true); lesson.getLessonTracker(session).setViewedSource(true);
} }
catch (Throwable t) catch (Throwable t)
@ -76,7 +102,8 @@ public class LessonSource extends HammerHead
catch (Throwable thr) catch (Throwable thr)
{ {
thr.printStackTrace(); thr.printStackTrace();
log( request, "Could not write error screen: " + thr.getMessage() ); log(request, "Could not write error screen: "
+ thr.getMessage());
} }
//System.out.println( "Leaving doPost: " ); //System.out.println( "Leaving doPost: " );
@ -84,7 +111,8 @@ public class LessonSource extends HammerHead
} }
protected WebSession updateSession_DELETEME( HttpServletRequest request, HttpServletResponse response, ServletContext context ) protected WebSession updateSession_DELETEME(HttpServletRequest request,
HttpServletResponse response, ServletContext context)
{ {
HttpSession hs; HttpSession hs;
hs = request.getSession(true); hs = request.getSession(true);
@ -130,7 +158,8 @@ public class LessonSource extends HammerHead
if (s.isUser() || s.isChallenge()) if (s.isUser() || s.isChallenge())
{ {
AbstractLesson lesson = course.getLesson( s, scr, AbstractLesson.USER_ROLE ); AbstractLesson lesson = course.getLesson(s, scr,
AbstractLesson.USER_ROLE);
if (lesson != null) if (lesson != null)
{ {
@ -141,11 +170,11 @@ public class LessonSource extends HammerHead
{ {
return "Source code is not available. Contact webgoat@aspectsecurity.com"; return "Source code is not available. Contact webgoat@aspectsecurity.com";
} }
return ( source.replaceAll("(?s)" + START_SOURCE_SKIP + ".*" + END_SOURCE_SKIP, "Code Section Deliberately Omitted") ); return (source.replaceAll("(?s)" + START_SOURCE_SKIP + ".*"
+ END_SOURCE_SKIP, "Code Section Deliberately Omitted"));
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -153,7 +182,8 @@ public class LessonSource extends HammerHead
* @param response Description of the Parameter * @param response Description of the Parameter
* @exception IOException Description of the Exception * @exception IOException Description of the Exception
*/ */
protected void writeSource( String s, HttpServletResponse response ) throws IOException protected void writeSource(String s, HttpServletResponse response)
throws IOException
{ {
response.setContentType("text/html"); response.setContentType("text/html");
@ -168,4 +198,3 @@ public class LessonSource extends HammerHead
out.close(); out.close();
} }
} }

View File

@ -38,83 +38,124 @@ import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatProperties; import org.owasp.webgoat.session.WebgoatProperties;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is *
* published by OWASP under the GPL. You should read and accept the LICENSE before you use, modify * This file is part of WebGoat, an Open Web Application Security Project
* and/or redistribute this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public abstract class AbstractLesson extends Screen implements Comparable public abstract class AbstractLesson extends Screen implements Comparable
{ {
/**
* Description of the Field
*/
public final static Category A1 = new Category( "Unvalidated Parameters", new Integer( 110 ) );
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A10 = new Category( "Insecure Configuration Management", new Integer( 1010 ) ); public final static Category A1 = new Category("Unvalidated Parameters",
new Integer(110));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A2 = new Category( "Broken Access Control", new Integer( 210 ) ); public final static Category A10 = new Category(
"Insecure Configuration Management", new Integer(1010));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A3 = new Category( "Broken Authentication and Session Management", new Integer( 310 ) ); public final static Category A2 = new Category("Broken Access Control",
new Integer(210));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A4 = new Category( "Cross-Site Scripting (XSS)", new Integer( 410 ) ); public final static Category A3 = new Category(
"Broken Authentication and Session Management", new Integer(310));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A5 = new Category( "Buffer Overflows", new Integer( 510 ) ); public final static Category A4 = new Category(
"Cross-Site Scripting (XSS)", new Integer(410));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A6 = new Category( "Injection Flaws", new Integer( 610 ) ); public final static Category A5 = new Category("Buffer Overflows",
new Integer(510));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A7 = new Category( "Improper Error Handling", new Integer( 710 ) ); public final static Category A6 = new Category("Injection Flaws",
new Integer(610));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A8 = new Category( "Insecure Storage", new Integer( 810 ) ); public final static Category A7 = new Category("Improper Error Handling",
new Integer(710));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category A9 = new Category( "Denial of Service", new Integer( 910 ) ); public final static Category A8 = new Category("Insecure Storage",
new Integer(810));
/** /**
* Description of the Field * Description of the Field
*/ */
public final static Category WEB_SERVICES = new Category( "Web Services", new Integer( 1110 ) ); public final static Category A9 = new Category("Denial of Service",
new Integer(910));
public final static Category AJAX_SECURITY = new Category( "AJAX Security", new Integer( 1150 ) ); /**
* Description of the Field
*/
public final static Category WEB_SERVICES = new Category("Web Services",
new Integer(1110));
public final static Category NEW_LESSON = new Category ( "New Lessons" , new Integer ( 1210 ) ); public final static Category AJAX_SECURITY = new Category("AJAX Security",
new Integer(1150));
public final static Category ADMIN_FUNCTIONS = new Category( "Admin Functions", new Integer( 10 ) ); public final static Category NEW_LESSON = new Category("New Lessons",
new Integer(1210));
public final static Category GENERAL = new Category( "General", new Integer( 50 ) ); public final static Category ADMIN_FUNCTIONS = new Category(
"Admin Functions", new Integer(10));
public final static Category CODE_QUALITY = new Category( "Code Quality", new Integer( 70 ) ); public final static Category GENERAL = new Category("General", new Integer(
50));
public final static Category CHALLENGE = new Category( "Challenge", new Integer( 2000 ) ); public final static Category CODE_QUALITY = new Category("Code Quality",
new Integer(70));
public final static Category CHALLENGE = new Category("Challenge",
new Integer(2000));
/** /**
* Description of the Field * Description of the Field
@ -137,18 +178,22 @@ public abstract class AbstractLesson extends Screen implements Comparable
private Integer id = null; private Integer id = null;
final static IMG nextGrey = new IMG( "images/right16.gif" ).setAlt( "Next" ).setBorder( 0 ).setHspace( 0 ) final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next")
.setVspace( 0 ); .setBorder(0).setHspace(0).setVspace(0);
final static IMG previousGrey = new IMG( "images/left14.gif" ).setAlt( "Previous" ).setBorder( 0 ).setHspace( 0 ) final static IMG previousGrey = new IMG("images/left14.gif").setAlt(
.setVspace( 0 ); "Previous").setBorder(0).setHspace(0).setVspace(0);
private static Vector<Category> categories = new Vector<Category>(); private static Vector<Category> categories = new Vector<Category>();
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;
static static
@ -172,6 +217,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
categories.add(CHALLENGE); categories.add(CHALLENGE);
} }
/** /**
* Constructor for the Lesson object * Constructor for the Lesson object
*/ */
@ -180,22 +226,26 @@ public abstract class AbstractLesson extends Screen implements Comparable
id = new Integer(++count); id = new Integer(++count);
} }
public String getName() public String getName()
{ {
String className = getClass().getName(); String className = getClass().getName();
return className.substring(className.lastIndexOf('.') + 1); return className.substring(className.lastIndexOf('.') + 1);
} }
public void setRanking(Integer ranking) public void setRanking(Integer ranking)
{ {
this.ranking = ranking; this.ranking = ranking;
} }
public void setHidden(boolean hidden) public void setHidden(boolean hidden)
{ {
this.hidden = hidden; this.hidden = hidden;
} }
public static Category getCategory(String myCategoryName) public static Category getCategory(String myCategoryName)
{ {
Category myCategory = null; Category myCategory = null;
@ -215,18 +265,27 @@ public abstract class AbstractLesson extends Screen implements Comparable
return myCategory; return myCategory;
} }
public void update(WebgoatProperties properties) public void update(WebgoatProperties properties)
{ {
String className = getClass().getName(); String className = getClass().getName();
className = className.substring(className.lastIndexOf(".") + 1); className = className.substring(className.lastIndexOf(".") + 1);
setRanking(new Integer(properties.getIntProperty("lesson." + className + ".ranking", getDefaultRanking().intValue()))); setRanking(new Integer(properties.getIntProperty("lesson." + className
String categoryRankingKey = "category." + getDefaultCategory().getName() + ".ranking"; + ".ranking", getDefaultRanking().intValue())));
String categoryRankingKey = "category."
+ getDefaultCategory().getName() + ".ranking";
// System.out.println("Category ranking key: " + categoryRankingKey); // System.out.println("Category ranking key: " + categoryRankingKey);
Category tempCategory = AbstractLesson.getCategory(getDefaultCategory().getName()); Category tempCategory = AbstractLesson.getCategory(getDefaultCategory()
tempCategory.setRanking(new Integer(properties.getIntProperty(categoryRankingKey, getDefaultCategory().getRanking().intValue()))); .getName());
tempCategory.setRanking(new Integer(properties.getIntProperty(
categoryRankingKey, getDefaultCategory().getRanking()
.intValue())));
category = tempCategory; category = tempCategory;
setHidden(properties.getBooleanProperty("lesson." + className + ".hidden", getDefaultHidden())); setHidden(properties.getBooleanProperty("lesson." + className
//System.out.println(className + " in " + tempCategory.getName() + " (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking: " + getRanking() + ", hidden:" + hidden +")"); + ".hidden", getDefaultHidden()));
// System.out.println(className + " in " + tempCategory.getName() + "
// (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking:
// " + getRanking() + ", hidden:" + hidden +")");
} }
@ -235,6 +294,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return getLessonTracker(s, this).getCompleted(); return getLessonTracker(s, this).getCompleted();
} }
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
* *
@ -242,10 +302,12 @@ public abstract class AbstractLesson extends Screen implements Comparable
*/ */
public abstract Element getCredits(); public abstract Element getCredits();
/** /**
* Description of the Method * Description of the Method
* *
* @param obj Description of the Parameter * @param obj
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public int compareTo(Object obj) public int compareTo(Object obj)
@ -253,10 +315,12 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.getRanking().compareTo(((AbstractLesson) obj).getRanking()); return this.getRanking().compareTo(((AbstractLesson) obj).getRanking());
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param obj Description of the Parameter * @param obj
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public boolean equals(Object obj) public boolean equals(Object obj)
@ -264,6 +328,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.getScreenId() == ((AbstractLesson) obj).getScreenId(); return this.getScreenId() == ((AbstractLesson) obj).getScreenId();
} }
/** /**
* Gets the category attribute of the Lesson object * Gets the category attribute of the Lesson object
* *
@ -274,10 +339,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
return category; return category;
} }
protected abstract Integer getDefaultRanking(); protected abstract Integer getDefaultRanking();
protected abstract Category getDefaultCategory(); protected abstract Category getDefaultCategory();
protected abstract boolean getDefaultHidden(); protected abstract boolean getDefaultHidden();
@ -297,12 +365,16 @@ public abstract class AbstractLesson extends Screen implements Comparable
/** /**
* Gets the fileMethod attribute of the Lesson class * Gets the fileMethod attribute of the Lesson class
* *
* @param reader Description of the Parameter * @param reader
* @param methodName Description of the Parameter * Description of the Parameter
* @param numbers Description of the Parameter * @param methodName
* Description of the Parameter
* @param numbers
* Description of the Parameter
* @return The fileMethod value * @return The fileMethod value
*/ */
public static String getFileMethod( BufferedReader reader, String methodName, boolean numbers ) public static String getFileMethod(BufferedReader reader,
String methodName, boolean numbers)
{ {
int count = 0; int count = 0;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
@ -317,7 +389,8 @@ public abstract class AbstractLesson extends Screen implements Comparable
while ((line = reader.readLine()) != null) while ((line = reader.readLine()) != null)
{ {
if ((line.indexOf(methodName) != -1) if ((line.indexOf(methodName) != -1)
&& ( ( line.indexOf( "public" ) != -1 ) || ( line.indexOf( "protected" ) != -1 ) || ( line && ((line.indexOf("public") != -1)
|| (line.indexOf("protected") != -1) || (line
.indexOf("private") != -1))) .indexOf("private") != -1)))
{ {
echo = true; echo = true;
@ -362,13 +435,16 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (sb.toString()); return (sb.toString());
} }
/** /**
* Reads text from a file into an ElementContainer. Each line in the file is represented in the * Reads text from a file into an ElementContainer. Each line in the
* ElementContainer by a StringElement. Each StringElement is appended with a new-line * file is represented in the ElementContainer by a StringElement. Each
* character. * StringElement is appended with a new-line character.
* *
* @param reader Description of the Parameter * @param reader
* @param numbers Description of the Parameter * Description of the Parameter
* @param numbers
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static String readFromFile(BufferedReader reader, boolean numbers) public static String readFromFile(BufferedReader reader, boolean numbers)
@ -380,8 +456,10 @@ public abstract class AbstractLesson extends Screen implements Comparable
/** /**
* Gets the fileText attribute of the Screen class * Gets the fileText attribute of the Screen class
* *
* @param reader Description of the Parameter * @param reader
* @param numbers Description of the Parameter * Description of the Parameter
* @param numbers
* Description of the Parameter
* @return The fileText value * @return The fileText value
*/ */
public static String getFileText(BufferedReader reader, boolean numbers) public static String getFileText(BufferedReader reader, boolean numbers)
@ -413,6 +491,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (sb.toString()); return (sb.toString());
} }
/** /**
* Will this screen be included in an enterprise edition. * Will this screen be included in an enterprise edition.
* *
@ -423,6 +502,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return false; return false;
} }
/** /**
* Gets the hintCount attribute of the Lesson object * Gets the hintCount attribute of the Lesson object
* *
@ -433,11 +513,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
return getHints().size(); return getHints().size();
} }
protected abstract List getHints(); protected abstract List getHints();
/** /**
* Fill in a minor hint that will help people who basically get it, but are stuck on somthing * Fill in a minor hint that will help people who basically get it, but
* silly. * are stuck on somthing silly.
* *
* @return The hint1 value * @return The hint1 value
*/ */
@ -446,6 +528,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (String) getHints().get(hintNumber); return (String) getHints().get(hintNumber);
} }
/** /**
* Gets the instructions attribute of the AbstractLesson object * Gets the instructions attribute of the AbstractLesson object
* *
@ -453,6 +536,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
*/ */
public abstract String getInstructions(WebSession s); public abstract String getInstructions(WebSession s);
/** /**
* Gets the lessonPlan attribute of the Lesson object * Gets the lessonPlan attribute of the Lesson object
* *
@ -464,6 +548,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.getClass().getName().substring(index + "lessons.".length()); return this.getClass().getName().substring(index + "lessons.".length());
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -474,7 +559,9 @@ public abstract class AbstractLesson extends Screen implements Comparable
/** /**
* Gets the content of lessonPlanURL * Gets the content of lessonPlanURL
* @param s TODO *
* @param s
* TODO
* *
* @return The HTML content of the current lesson plan * @return The HTML content of the current lesson plan
*/ */
@ -484,19 +571,23 @@ public abstract class AbstractLesson extends Screen implements Comparable
try try
{ {
//System.out.println("Loading lesson plan file: " + getLessonPlanFileName()); // System.out.println("Loading lesson plan file: " +
src = readFromFile( new BufferedReader( new FileReader( s.getWebResource(getLessonPlanFileName()) ) ), false ); // getLessonPlanFileName());
src = readFromFile(new BufferedReader(new FileReader(s
.getWebResource(getLessonPlanFileName()))), false);
} }
catch (Exception e) catch (Exception e)
{ {
//s.setMessage( "Could not find lesson plan for " + getLessonName()); // s.setMessage( "Could not find lesson plan for " +
// getLessonName());
src = ("Could not find lesson plan for: " + getLessonName()); src = ("Could not find lesson plan for: " + getLessonName());
} }
return src; return src;
} }
/** /**
* Gets the ranking attribute of the Lesson object * Gets the ranking attribute of the Lesson object
* *
@ -514,6 +605,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
} }
} }
/** /**
* Gets the hidden value of the Lesson Object * Gets the hidden value of the Lesson Object
* *
@ -524,6 +616,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.hidden; return this.hidden;
} }
/** /**
* Gets the role attribute of the AbstractLesson object * Gets the role attribute of the AbstractLesson object
* *
@ -531,16 +624,19 @@ public abstract class AbstractLesson extends Screen implements Comparable
*/ */
public String getRole() public String getRole()
{ {
// FIXME: Each lesson should have a role assigned to it. Each user/student // 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 // should also have a role(s) assigned. The user would only be allowed
// to see lessons that correspond to their role. Eventually these roles // 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 // 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 // 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 // see the admin screens, once they figure out how to turn the admin
// switch on. // switch on.
return USER_ROLE; return USER_ROLE;
} }
/** /**
* Gets the uniqueID attribute of the AbstractLesson object * Gets the uniqueID attribute of the AbstractLesson object
* *
@ -551,19 +647,25 @@ public abstract class AbstractLesson extends Screen implements Comparable
return id.intValue(); return id.intValue();
} }
public String getHtml(WebSession s) public String getHtml(WebSession s)
{ {
String html = null; String html = null;
// FIXME: This doesn't work for the labs since they do not implement createContent(). // FIXME: This doesn't work for the labs since they do not implement
// createContent().
String rawHtml = createContent(s).toString(); String rawHtml = createContent(s).toString();
//System.out.println("Getting raw html content: " + rawHtml.substring(0, Math.min(rawHtml.length(), 100))); // System.out.println("Getting raw html content: " +
html = convertMetachars(AbstractLesson.readFromFile( new BufferedReader( new StringReader( rawHtml ) ), true ) ); // rawHtml.substring(0, Math.min(rawHtml.length(), 100)));
//System.out.println("Getting encoded html content: " + html.substring(0, Math.min(html.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; return html;
} }
public String getSource(WebSession s) public String getSource(WebSession s)
{ {
String source = null; String source = null;
@ -571,11 +673,16 @@ public abstract class AbstractLesson extends Screen implements Comparable
try try
{ {
//System.out.println("Loading source file: " + getSourceFileName()); // System.out.println("Loading source file: " +
src = convertMetacharsJavaCode( readFromFile( new BufferedReader( new FileReader( s.getWebResource(getSourceFileName()) ) ), true ) ); // 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 // TODO: For styled line numbers and better memory efficiency,
// that performs the convertMetacharsJavaCode() transform plus optionally adds a styled // use a custom FilterReader
// that performs the convertMetacharsJavaCode() transform plus
// optionally adds a styled
// line number. Wouldn't color syntax be great too? // line number. Wouldn't color syntax be great too?
} }
catch (IOException e) catch (IOException e)
@ -588,8 +695,11 @@ public abstract class AbstractLesson extends Screen implements Comparable
Head head = new Head(); Head head = new Head();
head.addElement(new Title(getSourceFileName())); head.addElement(new Title(getSourceFileName()));
head.addElement( new StringElement( "<meta name=\"Author\" content=\"Jeff Williams\">" ) ); head.addElement(new StringElement(
head.addElement( new StringElement( "<link rev=\"made\" href=\"mailto:jeff.williams@aspectsecurity.com\">" ) ); "<meta name=\"Author\" content=\"Jeff Williams\">"));
head
.addElement(new StringElement(
"<link rev=\"made\" href=\"mailto:jeff.williams@aspectsecurity.com\">"));
Body body = new Body(); Body body = new Body();
body.addElement(new StringElement(src)); body.addElement(new StringElement(src));
@ -602,6 +712,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return source; return source;
} }
/** /**
* Get the link that can be used to request this screen. * Get the link that can be used to request this screen.
* *
@ -619,6 +730,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return link.toString(); return link.toString();
} }
/** /**
* Get the link to the jsp page used to render this screen. * Get the link to the jsp page used to render this screen.
* *
@ -629,6 +741,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return null; return null;
} }
/** /**
* Get the link to the jsp template page used to render this screen. * Get the link to the jsp template page used to render this screen.
* *
@ -639,16 +752,20 @@ public abstract class AbstractLesson extends Screen implements Comparable
return null; return null;
} }
public abstract String getCurrentAction(WebSession s); public abstract String getCurrentAction(WebSession s);
public abstract void setCurrentAction(WebSession s, String lessonScreen); public abstract void setCurrentAction(WebSession s, String lessonScreen);
public void setStage(WebSession s, int stage) public void setStage(WebSession s, int stage)
{ {
// System.out.println("Changed to stage " + stage); // System.out.println("Changed to stage " + stage);
getLessonTracker(s).setStage(stage); getLessonTracker(s).setStage(stage);
} }
public int getStage(WebSession s) public int getStage(WebSession s)
{ {
int stage = getLessonTracker(s).getStage(); int stage = getLessonTracker(s).getStage();
@ -657,6 +774,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return stage; return stage;
} }
/** /**
* Override this method to implement accesss control in a lesson. * Override this method to implement accesss control in a lesson.
* *
@ -669,6 +787,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return false; return false;
} }
/** /**
* Override this method to implement accesss control in a lesson. * Override this method to implement accesss control in a lesson.
* *
@ -681,10 +800,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
boolean authorized = false; boolean authorized = false;
try try
{ {
String query = "SELECT * FROM auth WHERE role = '" + role + "' and functionid = '" + functionId + "'"; String query = "SELECT * FROM auth WHERE role = '" + role
+ "' and functionid = '" + functionId + "'";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
authorized = answer_results.first(); authorized = answer_results.first();
} }
@ -702,20 +824,24 @@ public abstract class AbstractLesson extends Screen implements Comparable
return authorized; return authorized;
} }
public int getUserId(WebSession s) throws ParameterNotFoundException public int getUserId(WebSession s) throws ParameterNotFoundException
{ {
return -1; return -1;
} }
public String getUserName(WebSession s) throws ParameterNotFoundException public String getUserName(WebSession s) throws ParameterNotFoundException
{ {
return null; return null;
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s Description of the Parameter * @param s
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected TD makeParamDump_DELETEME(WebSession s) protected TD makeParamDump_DELETEME(WebSession s)
@ -762,6 +888,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (new TD().setVAlign("TOP").addElement(ec)); return (new TD().setVAlign("TOP").addElement(ec));
} }
// this doesn't work -- I think it's because getting parameters // this doesn't work -- I think it's because getting parameters
// also causes the servlet container to read the request // also causes the servlet container to read the request
// but I'm not sure. // but I'm not sure.
@ -769,7 +896,8 @@ public abstract class AbstractLesson extends Screen implements Comparable
/** /**
* Description of the Method * Description of the Method
* *
* @param s Description of the Parameter * @param s
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeRequestDump_DELETEME(WebSession s) protected Element makeRequestDump_DELETEME(WebSession s)
@ -778,7 +906,8 @@ public abstract class AbstractLesson extends Screen implements Comparable
try try
{ {
el = new StringElement( readFromFile( s.getRequest().getReader(), false ) ); el = new StringElement(readFromFile(s.getRequest().getReader(),
false));
} }
catch (Exception e) catch (Exception e)
{ {
@ -796,15 +925,18 @@ public abstract class AbstractLesson extends Screen implements Comparable
t.setBorder(1); t.setBorder(1);
} }
t.addElement( new TR().addElement( new TD().setVAlign( "TOP" ).addElement( ec ) ) ); t.addElement(new TR().addElement(new TD().setVAlign("TOP").addElement(
ec)));
return (t); return (t);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s Description of the Parameter * @param s
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeSourceDump_DELETEME(WebSession s) protected Element makeSourceDump_DELETEME(WebSession s)
@ -818,19 +950,19 @@ public abstract class AbstractLesson extends Screen implements Comparable
Table t = new Table().setWidth(Screen.MAIN_SIZE); Table t = new Table().setWidth(Screen.MAIN_SIZE);
/* /*
if ( s.isColor() ) * if ( s.isColor() ) { t.setBorder( 1 ); t.setBgColor( HtmlColor.CORAL ); }
{
t.setBorder( 1 );
t.setBgColor( HtmlColor.CORAL );
}
*/ */
t.addElement(new TR().addElement(new TD().addElement(new HR()))); t.addElement(new TR().addElement(new TD().addElement(new HR())));
try try
{ {
t.addElement( new TR().addElement( new TD().addElement( convertMetachars( readFromFile( new BufferedReader( t
new FileReader( filename ) ), true ) ) ) ) ); .addElement(new TR()
.addElement(new TD()
.addElement(convertMetachars(readFromFile(
new BufferedReader(new FileReader(
filename)), true)))));
} }
catch (IOException e) catch (IOException e)
{ {
@ -841,10 +973,12 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (t); return (t);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param windowName Description of the Parameter * @param windowName
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static String makeWindowScript(String windowName) public static String makeWindowScript(String windowName)
@ -869,11 +1003,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
script.append(" params += \"height=350\";\n"); script.append(" params += \"height=350\";\n");
script.append("\n"); script.append("\n");
script.append(" // close the window to vary the window size\n"); script.append(" // close the window to vary the window size\n");
script.append( " if (typeof(win) == \"object\" && !win.closed){\n" ); script
.append(" if (typeof(win) == \"object\" && !win.closed){\n");
script.append(" win.close();\n"); script.append(" win.close();\n");
script.append(" }\n"); script.append(" }\n");
script.append("\n"); script.append("\n");
script.append( " win = window.open(url, '" + windowName + "' , params);\n" ); script.append(" win = window.open(url, '" + windowName
+ "' , params);\n");
script.append("\n"); script.append("\n");
script.append(" // bring the window to the front\n"); script.append(" // bring the window to the front\n");
script.append(" win.focus();\n"); script.append(" win.focus();\n");
@ -884,11 +1020,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
return script.toString(); return script.toString();
} }
/** /**
* Simply reads a url into an Element for display. CAUTION: you might want to tinker with any * Simply reads a url into an Element for display. CAUTION: you might
* non-https links (href) * want to tinker with any non-https links (href)
* *
* @param url Description of the Parameter * @param url
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Element readFromURL(String url) public static Element readFromURL(String url)
@ -899,7 +1037,8 @@ public abstract class AbstractLesson extends Screen implements Comparable
{ {
URL u = new URL(url); URL u = new URL(url);
HttpURLConnection huc = (HttpURLConnection) u.openConnection(); HttpURLConnection huc = (HttpURLConnection) u.openConnection();
BufferedReader reader = new BufferedReader( new InputStreamReader( huc.getInputStream() ) ); BufferedReader reader = new BufferedReader(new InputStreamReader(
huc.getInputStream()));
String line; String line;
while ((line = reader.readLine()) != null) while ((line = reader.readLine()) != null)
@ -918,84 +1057,87 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (ec); return (ec);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param reader Description of the Parameter * @param reader
* @param numbers Description of the Parameter * Description of the Parameter
* @param methodName Description of the Parameter * @param numbers
* Description of the Parameter
* @param methodName
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Element readMethodFromFile( BufferedReader reader, String methodName, boolean numbers ) public static Element readMethodFromFile(BufferedReader reader,
String methodName, boolean numbers)
{ {
PRE pre = new PRE().addElement( getFileMethod( reader, methodName, numbers ) ); PRE pre = new PRE().addElement(getFileMethod(reader, methodName,
numbers));
return (pre); return (pre);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s Description of the Parameter * @param s
* Description of the Parameter
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
// call createContent first so messages will go somewhere // call createContent first so messages will go somewhere
Form form = new Form( getFormAction(), Form.POST ).setName( "form" ).setEncType( "" ); Form form = new Form(getFormAction(), Form.POST).setName("form")
.setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
protected String getFormAction() protected String getFormAction()
{ {
return "attack" + "?menu=" + getCategory().getRanking(); return "attack" + "?menu=" + getCategory().getRanking();
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s Description of the Parameter * @param s
* Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
/* /*
public String makeSourceHTML( WebSession s ) * public String makeSourceHTML( WebSession s ) {
{ *
* String className = this.getClass().getName(); String lessonName =
String className = this.getClass().getName(); * className.substring( className.indexOf( '.' ) + 1 ); String filename =
String lessonName = className.substring( className.indexOf( '.' ) + 1 ); * s.getSourceFile( lessonName );
String filename = s.getSourceFile( lessonName ); *
* String src = null;
String src = null; *
* try { src = convertMetacharsJavaCode( readFromFile( new
try * BufferedReader( new FileReader( filename ) ), true ) );
{ * } catch ( IOException e ) { s.setMessage( "Could not find source
src = convertMetacharsJavaCode( readFromFile( new BufferedReader( new FileReader( filename ) ), true ) ); * file" ); src = ( "Could not find source file" ); }
*
} * Html html = new Html();
catch ( IOException e ) *
{ * Head head = new Head(); head.addElement( new Title( lessonName +
s.setMessage( "Could not find source file" ); * ".java" ) ); head.addElement( new StringElement( "<meta
src = ( "Could not find source file" ); * name=\"Author\" content=\"Jeff Williams\">" ) ); head.addElement( new
} * StringElement( "<link rev=\"made\"
* href=\"mailto:jeff.williams@aspectsecurity.com\">" ) );
Html html = new Html(); *
* Body body = new Body(); body.addElement( new StringElement( src ) );
Head head = new Head(); *
head.addElement( new Title( lessonName + ".java" ) ); * html.addElement( head ); html.addElement( body );
head.addElement( new StringElement( "<meta name=\"Author\" content=\"Jeff Williams\">" ) ); *
head.addElement( new StringElement( "<link rev=\"made\" href=\"mailto:jeff.williams@aspectsecurity.com\">" ) ); * return html.toString(); }
Body body = new Body();
body.addElement( new StringElement( src ) );
html.addElement( head );
html.addElement( body );
return html.toString();
}
*/ */
public String toString() public String toString()
@ -1024,7 +1166,8 @@ public abstract class AbstractLesson extends Screen implements Comparable
public void setSourceFileName(String sourceFileName) public void setSourceFileName(String sourceFileName)
{ {
//System.out.println("Setting source file of lesson " + this + " to: " + sourceFileName); // System.out.println("Setting source file of lesson " + this + " to: "
// + sourceFileName);
this.sourceFileName = sourceFileName; this.sourceFileName = sourceFileName;
} }
} }

View File

@ -9,12 +9,34 @@ import org.apache.ecs.html.P;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
@ -24,9 +46,16 @@ public class AccessControlMatrix extends LessonAdapter
{ {
private final static String RESOURCE = "Resource"; private final static String RESOURCE = "Resource";
private final static String USER = "User"; private final static String USER = "User";
private final static String[] resources = {"Public Share", "Time Card Entry", "Performance Review", "Time Card Approval", "Site Manager", "Account Manager"};
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[] roles = { "Public", "User", "Manager",
"Admin" };
private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" }; private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" };
@ -43,7 +72,8 @@ public class AccessControlMatrix extends LessonAdapter
try try
{ {
String user = s.getParser().getRawParameter(USER, users[0]); String user = s.getParser().getRawParameter(USER, users[0]);
String resource = s.getParser().getRawParameter( RESOURCE, resources[0] ); String resource = s.getParser().getRawParameter(RESOURCE,
resources[0]);
String credentials = getRoles(user).toString(); String credentials = getRoles(user).toString();
ec.addElement(new P().addElement("Change user:")); ec.addElement(new P().addElement("Change user:"));
ec.addElement(ECSFactory.makePulldown(USER, users, user, 1)); ec.addElement(ECSFactory.makePulldown(USER, users, user, 1));
@ -54,22 +84,27 @@ public class AccessControlMatrix extends LessonAdapter
// ec.addElement( new P().addElement( "Choose a resource:" ) ); // ec.addElement( new P().addElement( "Choose a resource:" ) );
// ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) ); // ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) );
ec.addElement(new P().addElement("Select resource: ")); ec.addElement(new P().addElement("Select resource: "));
ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) ); ec.addElement(ECSFactory.makePulldown(RESOURCE, resources,
resource, 1));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(ECSFactory.makeButton("Check Access")); ec.addElement(ECSFactory.makeButton("Check Access"));
if (isAllowed(user, resource)) if (isAllowed(user, resource))
{ {
if ( !getRoles( user ).contains( "Admin") && resource.equals("Account Manager")) if (!getRoles(user).contains("Admin")
&& resource.equals("Account Manager"))
{ {
makeSuccess(s); makeSuccess(s);
} }
s.setMessage( "User " + user + " " + credentials + " was allowed to access resource " + resource ); s.setMessage("User " + user + " " + credentials
+ " was allowed to access resource " + resource);
} }
else else
{ {
s.setMessage( "User " + user + " " + credentials + " did not have privilege to access resource " + resource ); s.setMessage("User " + user + " " + credentials
+ " did not have privilege to access resource "
+ resource);
} }
} }
catch (Exception e) catch (Exception e)
@ -82,7 +117,6 @@ public class AccessControlMatrix extends LessonAdapter
} }
/** /**
* Gets the category attribute of the RoleBasedAccessControl object * Gets the category attribute of the RoleBasedAccessControl object
* *
@ -95,7 +129,6 @@ public class AccessControlMatrix extends LessonAdapter
} }
/** /**
* Gets the hints attribute of the RoleBasedAccessControl object * Gets the hints attribute of the RoleBasedAccessControl object
* *
@ -104,19 +137,23 @@ public class AccessControlMatrix extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "Many sites attempt to restrict access to resources by role." ); hints
hints.add( "Developers frequently make mistakes implementing this scheme." ); .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."); hints.add("Attempt combinations of users, roles, and resources.");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the resources attribute of the RoleBasedAccessControl object * Gets the resources attribute of the RoleBasedAccessControl object
* *
@ -155,7 +192,6 @@ public class AccessControlMatrix extends LessonAdapter
} }
/** /**
* Gets the role attribute of the RoleBasedAccessControl object * Gets the role attribute of the RoleBasedAccessControl object
* *
@ -201,11 +237,11 @@ public class AccessControlMatrix extends LessonAdapter
return ("Using an Access Control Matrix"); return ("Using an Access Control Matrix");
} }
// private final static ArrayList userList = new ArrayList(Arrays.asList(users)); // private final static ArrayList userList = new ArrayList(Arrays.asList(users));
// private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources)); // private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources));
// private final static ArrayList roleList = new ArrayList(Arrays.asList(roles)); // 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 * Please do not ever implement an access control scheme this way! But it's not the worst I've
* seen. * seen.
@ -222,5 +258,3 @@ public class AccessControlMatrix extends LessonAdapter
return (resources.contains(resource)); return (resources.contains(resource));
} }
} }

View File

@ -22,22 +22,59 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
public class BackDoors extends LessonAdapter { /*******************************************************************************
*
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class BackDoors extends LessonAdapter
{
private static Connection connection = null; private static Connection connection = null;
private final static Integer DEFAULT_RANKING = new Integer(80); private final static Integer DEFAULT_RANKING = new Integer(80);
private final static String USERNAME = "username"; private final static String USERNAME = "username";
private final static String SELECT_ST = "select userid, password, ssn, salary from employee where userid="; private final static String SELECT_ST = "select userid, password, ssn, salary from employee where userid=";
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return concept1(s); return concept1(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return concept2(s); return concept2(s);
@ -58,19 +95,23 @@ public class BackDoors extends LessonAdapter {
userInput = SELECT_ST + userInput; userInput = SELECT_ST + userInput;
String[] arrSQL = userInput.split(";"); String[] arrSQL = userInput.split(";");
Connection conn = getConnection(s); Connection conn = getConnection(s);
Statement statement = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
if (arrSQL.length == 2) if (arrSQL.length == 2)
{ {
statement.executeUpdate(arrSQL[1]); statement.executeUpdate(arrSQL[1]);
getLessonTracker(s).setStage(2); 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]); ResultSet rs = statement.executeQuery(arrSQL[0]);
if (rs.next()) if (rs.next())
{ {
Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 1 ); Table t = new Table(0).setCellSpacing(0).setCellPadding(0)
.setBorder(1);
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD("User ID")); tr.addElement(new TD("User ID"));
tr.addElement(new TD("Password")); tr.addElement(new TD("Password"));
@ -94,6 +135,7 @@ public class BackDoors extends LessonAdapter {
return ec; return ec;
} }
protected Element concept2(WebSession s) throws Exception protected Element concept2(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -116,6 +158,7 @@ public class BackDoors extends LessonAdapter {
return ec; return ec;
} }
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
@ -125,25 +168,40 @@ public class BackDoors extends LessonAdapter {
switch (getStage(s)) switch (getStage(s))
{ {
case 1: case 1:
instructions = "Stage " + getStage(s) + ": Use String SQL Injection to execute more than one SQL Statement. "; instructions = "Stage "
instructions = instructions + " The first stage of this lesson is to teach you how to use a vulnerable field to create two SQL "; + getStage(s)
instructions = instructions + " statements. The first is the system's while the second is totally yours."; + ": Use String SQL Injection to execute more than one SQL Statement. ";
instructions = instructions + " Your account ID is 101. This page allows you to see your password, ssn and salary."; instructions = instructions
instructions = instructions + " Try to inject another update to update salary to something higher"; + " The first stage of this lesson is to teach you how to use a vulnerable field to create two SQL ";
instructions = instructions
+ " 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";
break; break;
case 2: case 2:
instructions = "Stage " + getStage(s) + ": Use String SQL Injection to inject a backdoor. " ; instructions = "Stage "
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." ; + getStage(s)
instructions = instructions + " Now try to use the same technique to inject a trigger that would act as " ; + ": Use String SQL Injection to inject a backdoor. ";
instructions = instructions + " SQL backdoor, the syntax of a trigger is: <br>"; instructions = instructions
instructions = instructions + " CREATE TRIGGER myBackDoor BEFORE INSERT ON employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com'WHERE userid = NEW.userid<br>"; + " 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 + " Note that nothing will actually be executed because the current underlying DB doesn't support triggers."; instructions = instructions
+ " Now try to use the same technique to inject a trigger that would act as ";
instructions = instructions
+ " SQL backdoor, the syntax of a trigger is: <br>";
instructions = instructions
+ " CREATE TRIGGER myBackDoor BEFORE INSERT ON employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com'WHERE userid = NEW.userid<br>";
instructions = instructions
+ " Note that nothing will actually be executed because the current underlying DB doesn't support triggers.";
break; break;
} }
} }
return instructions; return instructions;
} }
protected Element makeUsername(WebSession s) protected Element makeUsername(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -169,7 +227,8 @@ public class BackDoors extends LessonAdapter {
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
String formattedInput = "<span class='myClass'>" + userInput + "</span>"; String formattedInput = "<span class='myClass'>" + userInput
+ "</span>";
ec.addElement(new Div(SELECT_ST + formattedInput)); ec.addElement(new Div(SELECT_ST + formattedInput));
Input b = new Input(); Input b = new Input();
@ -183,6 +242,7 @@ public class BackDoors extends LessonAdapter {
return ec; return ec;
} }
public static synchronized Connection getConnection(WebSession s) public static synchronized Connection getConnection(WebSession s)
throws SQLException, ClassNotFoundException throws SQLException, ClassNotFoundException
{ {
@ -194,29 +254,38 @@ public class BackDoors extends LessonAdapter {
return connection; return connection;
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }
protected List getHints() {
protected List getHints()
{
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Your user id is 101. Use it to see your information"); 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("A semi-colon usually ends a SQL statement and starts a new one.");
hints.add("Try this 101; update employee set salary=100000"); hints.add("Try this 101; update employee set salary=100000");
hints.add( "For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON customers FOR EACH ROW BEGIN UPDATE customers SET email='john@hackme.com'WHERE userid = NEW.userid"); hints
.add("For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON customers FOR EACH ROW BEGIN UPDATE customers SET email='john@hackme.com'WHERE userid = NEW.userid");
return hints; return hints;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.A6; return AbstractLesson.A6;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return ("How to Use Database Backdoors "); return ("How to Use Database Backdoors ");

View File

@ -15,11 +15,34 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -28,15 +51,24 @@ public class BasicAuthentication extends LessonAdapter
{ {
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 * Description of the Method
* *
@ -48,6 +80,7 @@ public class BasicAuthentication extends LessonAdapter
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -56,33 +89,42 @@ public class BasicAuthentication extends LessonAdapter
String headerValue = null; String headerValue = null;
try try
{ {
headerName = new String( s.getParser().getStringParameter( HEADER_NAME, EMPTY_STRING ) ); headerName = new String(s.getParser().getStringParameter(
headerValue = new String( s.getParser().getStringParameter( HEADER_VALUE, EMPTY_STRING ) ); HEADER_NAME, EMPTY_STRING));
headerValue = new String(s.getParser().getStringParameter(
HEADER_VALUE, EMPTY_STRING));
//<START_OMIT_SOURCE> //<START_OMIT_SOURCE>
// FIXME: This won;t work for CBT, we need to use the UserTracker // FIXME: This won;t work for CBT, we need to use the UserTracker
//Authorization: Basic Z3Vlc3Q6Z3Vlc3Q= //Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
if ( headerName.equals(AUTHORIZATION) && if (headerName.equals(AUTHORIZATION)
( headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) && (headerValue.equals("guest:guest") || headerValue
.equals("webgoat:webgoat")))
{ {
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
return doStage2(s); return doStage2(s);
} }
else else
{ {
if ( headerName.length() > 0 && !headerName.equals(AUTHORIZATION)) if (headerName.length() > 0
&& !headerName.equals(AUTHORIZATION))
{ {
s.setMessage("Basic Authentication header name is incorrect."); s
.setMessage("Basic Authentication header name is incorrect.");
} }
if( headerValue.length() > 0 && !(headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) if (headerValue.length() > 0
&& !(headerValue.equals("guest:guest") || headerValue
.equals("webgoat:webgoat")))
{ {
s.setMessage("Basic Authentication header value is incorrect."); s
.setMessage("Basic Authentication header value is incorrect.");
} }
} }
//<END_OMIT_SOURCE> //<END_OMIT_SOURCE>
Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 ); Table t = new Table(0).setCellSpacing(0).setCellPadding(0)
.setBorder(0);
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
@ -90,11 +132,17 @@ public class BasicAuthentication extends LessonAdapter
TR row1 = new TR(); TR row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
row1.addElement( new TD( new StringElement( "What is the name of the authentication header: " ) ) ); row1.addElement(new TD(new StringElement(
row2.addElement( new TD( new StringElement( "What is the decoded value of the authentication header: " ) ) ); "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() ))); row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME,
row2.addElement( new TD( new Input( Input.TEXT, HEADER_VALUE, headerValue.toString() ))); headerName.toString())));
row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE,
headerValue.toString())));
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
@ -105,7 +153,6 @@ public class BasicAuthentication extends LessonAdapter
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
ec.addElement(b); ec.addElement(b);
} }
catch (Exception e) catch (Exception e)
{ {
@ -113,10 +160,10 @@ public class BasicAuthentication extends LessonAdapter
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -125,19 +172,24 @@ public class BasicAuthentication extends LessonAdapter
{ {
if (s.getRequest().isUserInRole(WEBGOAT_BASIC)) if (s.getRequest().isUserInRole(WEBGOAT_BASIC))
{ {
String originalUser = getLessonTracker(s).getLessonProperties().getProperty(ORIGINAL_USER,EMPTY_STRING); String originalUser = getLessonTracker(s).getLessonProperties()
.getProperty(ORIGINAL_USER, EMPTY_STRING);
getLessonTracker(s, originalUser).setCompleted(true); getLessonTracker(s, originalUser).setCompleted(true);
getLessonTracker(s, originalUser).setStage(1); getLessonTracker(s, originalUser).setStage(1);
getLessonTracker(s, originalUser).store(s, this); getLessonTracker(s, originalUser).store(s, this);
makeSuccess(s); makeSuccess(s);
s.setMessage("Close your browser and login as " + originalUser + " to get your green stars back."); s.setMessage("Close your browser and login as " + originalUser
+ " to get your green stars back.");
return ec; return ec;
} }
else else
{ {
// If we are still in the ORIGINAL_USER role see if the Basic Auth header has been manipulated // 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 originalAuth = getLessonTracker(s).getLessonProperties()
String originalSessionId = getLessonTracker(s).getLessonProperties().getProperty(JSESSIONID,s.getCookie(JSESSIONID)); .getProperty(ORIGINAL_AUTH, EMPTY_STRING);
String originalSessionId = getLessonTracker(s)
.getLessonProperties().getProperty(JSESSIONID,
s.getCookie(JSESSIONID));
// store the original user info in the BASIC properties files // store the original user info in the BASIC properties files
if (originalSessionId.equals(s.getCookie(JSESSIONID))) if (originalSessionId.equals(s.getCookie(JSESSIONID)))
@ -145,33 +197,45 @@ public class BasicAuthentication extends LessonAdapter
// Store the original user name in the "basic" user properties file. We need to use // 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. // the original user to access the correct properties file to update status.
// store the initial auth header // store the initial auth header
getLessonTracker(s).getLessonProperties().setProperty(JSESSIONID, originalSessionId); getLessonTracker(s).getLessonProperties().setProperty(
getLessonTracker(s).getLessonProperties().setProperty(ORIGINAL_AUTH, s.getHeader(AUTHORIZATION) ); JSESSIONID, originalSessionId);
getLessonTracker(s, BASIC).getLessonProperties().setProperty(ORIGINAL_USER, s.getUserName() ); 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).setStage(2);
getLessonTracker(s, BASIC).store(s, this, BASIC); getLessonTracker(s, BASIC).store(s, this, BASIC);
} }
s.setMessage("Congratulations, you have figured out the mechanics of basic authentication." ); s
s.setMessage("&nbsp;&nbsp;- Now you must try to make WebGoat reauthenticate you as: "); .setMessage("Congratulations, you have figured out the mechanics of basic authentication.");
s
.setMessage("&nbsp;&nbsp;- Now you must try to make WebGoat reauthenticate you as: ");
s.setMessage("&nbsp;&nbsp;&nbsp;&nbsp;- username: basic"); s.setMessage("&nbsp;&nbsp;&nbsp;&nbsp;- username: basic");
s.setMessage("&nbsp;&nbsp;&nbsp;&nbsp;- password: basic"); s.setMessage("&nbsp;&nbsp;&nbsp;&nbsp;- password: basic");
// If the auth header is different but still the original user - tell the user // 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 // that the original cookie was posted bak and basic auth uses the cookie before the
// authorization token // authorization token
if ( !originalAuth.equals("") && !originalAuth.equals( s.getHeader(AUTHORIZATION) )) if (!originalAuth.equals("")
&& !originalAuth.equals(s.getHeader(AUTHORIZATION)))
{ {
ec.addElement("You're almost there! You've modified the " + AUTHORIZATION + " header but you are " + ec
"still logged in as " + s.getUserName() + ". Look at the request after you typed in the 'basic' " + .addElement("You're almost there! You've modified the "
"user credentials and submitted the request. Remember the order of events that occur during Basic Authentication."); + 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))) 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. " + ec
"When you figure out how to force the server to perform an authentication request, you have to authenticate as:<br><br>" + .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. "
"&nbsp;&nbsp;&nbsp;&nbsp;user name: basic<br> " + + "When you figure out how to force the server to perform an authentication request, you have to authenticate as:<br><br>"
"&nbsp;&nbsp;&nbsp;&nbsp;password: basic<br>"); + "&nbsp;&nbsp;&nbsp;&nbsp;user name: basic<br> "
+ "&nbsp;&nbsp;&nbsp;&nbsp;password: basic<br>");
} }
else else
{ {
@ -187,7 +251,6 @@ public class BasicAuthentication extends LessonAdapter
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
@ -217,33 +280,41 @@ public class BasicAuthentication extends LessonAdapter
// switch ( stage ) // switch ( stage )
// { // {
// case 1: // case 1:
hints.add( "Basic authentication uses a cookie to pass the credentials. " + hints
"Use a proxy to intercept the request. Look at the cookies."); .add("Basic authentication uses a cookie to pass the credentials. "
hints.add( "Basic authentication uses Base64 encoding to 'scramble' the " + + "Use a proxy to intercept the request. Look at the cookies.");
"user's login credentials."); hints
hints.add( "Basic authentication uses 'Authorization' as the cookie name to " + .add("Basic authentication uses Base64 encoding to 'scramble' the "
"store the user's credentials."); + "user's login credentials.");
hints.add( "Use WebScarab -> Tools -> Transcoder to Base64 decode the " + hints
"the value in the Authorization cookie."); .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; // break;
// case 2: // case 2:
hints.add( "Basic authentication uses a cookie to pass the credentials. " + hints
"Use a proxy to intercept the request. Look at the cookies."); .add("Basic authentication uses a cookie to pass the credentials. "
hints.add( "Before the WebServer requests credentials from the client, the current " + + "Use a proxy to intercept the request. Look at the cookies.");
"session is checked for validitity."); hints
hints.add( "If the session is invalid the webserver will use the basic authentication credentials"); .add("Before the WebServer requests credentials from the client, the current "
hints.add( "If the session is invalid and the basic authentication credentials are invalid, " + + "session is checked for validitity.");
"new credentials will be requested from the client."); hints
hints.add( "Intercept the request and corrupt the JSESSIONID and the Authorization header."); .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; // break;
// } // }
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
@ -260,4 +331,3 @@ public class BasicAuthentication extends LessonAdapter
return ("Basic Authentication"); return ("Basic Authentication");
} }
} }

View File

@ -16,20 +16,45 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2005 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Chuck Willis <a href="http://www.securityfoundry.com">Chuck's web site</a> (this lesson is heavily based on Jeff Williams' SQL Injection lesson * @author Chuck Willis <a href="http://www.securityfoundry.com">Chuck's web site</a> (this lesson is heavily based on Jeff Williams' SQL Injection lesson
* @created January 14, 2005 * @created January 14, 2005
*/ */
public class BlindSqlInjection extends LessonAdapter 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;
private static Connection connection = null; private static Connection connection = null;
@ -52,44 +77,66 @@ public class BlindSqlInjection extends LessonAdapter
ec.addElement(new P().addElement("Enter your Account Number: ")); ec.addElement(new P().addElement("Enter your Account Number: "));
String accountNumber = s.getParser().getRawParameter( ACCT_NUM, "101" ); String accountNumber = s.getParser().getRawParameter(ACCT_NUM,
Input input = new Input( Input.TEXT, ACCT_NUM, accountNumber.toString() ); "101");
Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber
.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton("Go!"); Element b = ECSFactory.makeButton("Go!");
ec.addElement(b); ec.addElement(b);
String query = "SELECT * FROM user_data WHERE userid = " + accountNumber ; String query = "SELECT * FROM user_data WHERE userid = "
+ accountNumber;
String answer_query; String answer_query;
if(runningOnWindows()) { if (runningOnWindows())
answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " + TARGET_ACCT_NUM; {
} else { answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = "
answer_query = "SELECT first_name FROM user_data WHERE userid = " + TARGET_ACCT_NUM; + TARGET_ACCT_NUM;
}
else
{
answer_query = "SELECT first_name FROM user_data WHERE userid = "
+ TARGET_ACCT_NUM;
} }
try try
{ {
Statement answer_statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = connection.createStatement(
ResultSet answer_results = answer_statement.executeQuery( answer_query ); ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement
.executeQuery(answer_query);
answer_results.first(); answer_results.first();
if( accountNumber.toString().equals(answer_results.getString(1))) { if (accountNumber.toString()
.equals(answer_results.getString(1)))
{
makeSuccess(s); makeSuccess(s);
} else { }
else
{
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ec.addElement( new P().addElement("Account number is valid")); ec.addElement(new P()
} else { .addElement("Account number is valid"));
ec.addElement( new P().addElement("Invalid account number")); }
else
{
ec.addElement(new P()
.addElement("Invalid account number"));
} }
} }
} }
catch (SQLException sqle) catch (SQLException sqle)
{ {
ec.addElement( new P().addElement("An error occurred, please try again.")); ec.addElement(new P()
.addElement("An error occurred, please try again."));
} }
} }
catch (Exception e) catch (Exception e)
@ -102,7 +149,6 @@ public class BlindSqlInjection extends LessonAdapter
} }
/** /**
* Gets the category attribute of the SqlInjection object * Gets the category attribute of the SqlInjection object
* *
@ -121,9 +167,11 @@ public class BlindSqlInjection extends LessonAdapter
*/ */
public Element getCredits() public Element getCredits()
{ {
return new StringElement("By Chuck Willis (edited 14 Dec 05 - Hints need to updated for non-Windows systems)"); return new StringElement(
"By Chuck Willis (edited 14 Dec 05 - Hints need to updated for non-Windows systems)");
} }
/** /**
* *
* Determines the OS that WebGoat is running on. Needed because different DB backends * Determines the OS that WebGoat is running on. Needed because different DB backends
@ -131,7 +179,8 @@ public class BlindSqlInjection extends LessonAdapter
* *
* @return true if running on Windows, false otherwise * @return true if running on Windows, false otherwise
*/ */
private boolean runningOnWindows() { private boolean runningOnWindows()
{
String os = System.getProperty("os.name", "Windows"); String os = System.getProperty("os.name", "Windows");
if (os.toLowerCase().indexOf("window") != -1) if (os.toLowerCase().indexOf("window") != -1)
{ {
@ -152,54 +201,84 @@ public class BlindSqlInjection extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
if (runningOnWindows()) { 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 " + hints
"select the first character of the target element and do a start narrowing " + .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
"down the character using > and <" + + "Create a SQL statement that you can use as a true/false test and then "
"<br><br>The backend database is Microsoft Access. Keep that in mind if you research SQL functions " + + "select the first character of the target element and do a start narrowing "
"on the Internet since different databases use some different functions and syntax."); + "down the character using > and <"
hints.add( "This is the code for the query being built and issued by WebGoat:<br><br> " + + "<br><br>The backend database is Microsoft Access. Keep that in mind if you research SQL functions "
"\"SELECT * FROM user_data WHERE userid = \" + accountNumber " ); + "on the Internet since different databases use some different functions and syntax.");
hints.add( "The application is taking your input and inserting it at the end of a pre-formed SQL command. "+ hints
"You will need to make use of the following SQL functions: " + .add("This is the code for the query being built and issued by WebGoat:<br><br> "
"<br><br>SELECT - query for your target data and get a string "+ + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
"<br><br>mid(string, start, length) - returns a " hints
+ "substring of string starting at the start character and going for length characters "+ .add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
"<br><br>asc(string) will return the ascii value of the first character in string " + + "You will need to make use of the following SQL functions: "
"<br><br>&gt and &lt - once you have a character's value, compare it to a choosen one"); + "<br><br>SELECT - query for your target data and get a string "
hints.add( "Example: is the first character of the first_name of userid " + TARGET_ACCT_NUM + " less than 'M' (ascii 77)? " + + "<br><br>mid(string, start, length) - returns a "
"<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM + ") , 1 , 1) ) < 77 ); " + + "substring of string starting at the start character and going for length characters "
"<br><br>If you get back that account number is valid, then yes. If get back that the number is" + + "<br><br>asc(string) will return the ascii value of the first character in string "
"invalid then answer is no."); + "<br><br>&gt and &lt - once you have a character's value, compare it to a choosen one");
hints.add( "Another example: is the second character of the first_name of userid " + TARGET_ACCT_NUM + " greater than 'm' (ascii 109)? " + hints
"<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM + ") , 2 , 1) ) > 109 ); " + .add("Example: is the first character of the first_name of userid "
"<br><br>If you get back that account number is valid, then yes. If get back that the number is " + + TARGET_ACCT_NUM
"invalid then answer is no."); + " less than 'M' (ascii 77)? "
} else { + "<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " + + TARGET_ACCT_NUM
"Create a SQL statement that you can use as a true/false test and then " + + ") , 1 , 1) ) < 77 ); "
"select the first character of the target element and do a start narrowing " + + "<br><br>If you get back that account number is valid, then yes. If get back that the number is"
"down the character using > and <" ); + "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)? "
+ "<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
+ TARGET_ACCT_NUM
+ ") , 2 , 1) ) > 109 ); "
+ "<br><br>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 : <a href=\"http://www.instantdb.com/doc/syntax.html\" target=\"_blank\">http://www.instantdb.com/doc/syntax.html</a>"); hints
hints.add( "This is the code for the query being built and issued by WebGoat:<br><br> " + .add("The database backend is InstantDB. Here is a reference guide : <a href=\"http://www.instantdb.com/doc/syntax.html\" target=\"_blank\">http://www.instantdb.com/doc/syntax.html</a>");
"\"SELECT * FROM user_data WHERE userid = \" + accountNumber " ); hints
hints.add( "THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND. <br><br>The application is taking your input and inserting it at the end of a pre-formed SQL command. "+ .add("This is the code for the query being built and issued by WebGoat:<br><br> "
"You will need to make use of the following SQL functions: " + + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
"<br><br>SELECT - query for your target data and get a string "+ hints
"<br><br>mid(string, start, length) - returns a " .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND. <br><br>The application is taking your input and inserting it at the end of a pre-formed SQL command. "
+ "substring of string starting at the start character and going for length characters "+ + "You will need to make use of the following SQL functions: "
"<br><br>asc(string) will return the ascii value of the first character in string " + + "<br><br>SELECT - query for your target data and get a string "
"<br><br>&gt and &lt - once you have a character's value, compare it to a choosen one"); + "<br><br>mid(string, start, length) - returns a "
hints.add( "THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND. <br><br>Example: is the first character of the first_name of userid " + TARGET_ACCT_NUM + " less than 'M' (ascii 77)? " + + "substring of string starting at the start character and going for length characters "
"<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM + ") , 1 , 1) ) < 77 ); " + + "<br><br>asc(string) will return the ascii value of the first character in string "
"<br><br>If you get back that account number is valid, then yes. If get back that the number is" + + "<br><br>&gt and &lt - once you have a character's value, compare it to a choosen one");
"invalid then answer is no."); hints
hints.add( "THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND. <br><br> example: is the second character of the first_name of userid " + TARGET_ACCT_NUM + " greater than 'm' (ascii 109)? " + .add("THIS HINT IS FOR THE MS ACCESS DB. IT NEEDS TO BE ALTERED FOR THE INSTANTDB BACKEND. <br><br>Example: is the first character of the first_name of userid "
"<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM + ") , 2 , 1) ) > 109 ); " + + TARGET_ACCT_NUM
"<br><br>If you get back that account number is valid, then yes. If get back that the number is " + + " less than 'M' (ascii 77)? "
"invalid then answer is no."); + "<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
+ TARGET_ACCT_NUM
+ ") , 1 , 1) ) < 77 ); "
+ "<br><br>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. <br><br> example: is the second character of the first_name of userid "
+ TARGET_ACCT_NUM
+ " greater than 'm' (ascii 109)? "
+ "<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
+ TARGET_ACCT_NUM
+ ") , 2 , 1) ) > 109 ); "
+ "<br><br>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; return hints;
} }
@ -212,20 +291,20 @@ public class BlindSqlInjection extends LessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The form below allows a user to enter an account number and determine if "+ 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. "+ + "it is valid or not. Use this form to develop a true / false test check other entries in the database. "
"<br><br>Reference Ascii Values: 'A' = 65 'Z' = 90 'a' = 97 'z' = 122 " + + "<br><br>Reference Ascii Values: 'A' = 65 'Z' = 90 'a' = 97 'z' = 122 "
"<br><br>The goal is to find the value of "+ + "<br><br>The goal is to find the value of "
"the first_name in table user_data for userid " + TARGET_ACCT_NUM + ". Put that name in the form to pass the lesson."; + "the first_name in table user_data for userid "
+ TARGET_ACCT_NUM
+ ". Put that name in the form to pass the lesson.";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(70); private final static Integer DEFAULT_RANKING = new Integer(70);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
@ -266,5 +345,3 @@ public class BlindSqlInjection extends LessonAdapter
} }
} }
} }

View File

@ -8,11 +8,34 @@ import org.apache.ecs.StringElement;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -59,15 +82,15 @@ public class BufferOverflow extends LessonAdapter
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(15); private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -78,9 +101,10 @@ public class BufferOverflow extends LessonAdapter
return ("Buffer Overflow"); return ("Buffer Overflow");
} }
public Element getCredits() public Element getCredits()
{ {
return new StringElement("This screen created by: Your name could go here"); return new StringElement(
"This screen created by: Your name could go here");
} }
} }

View File

@ -24,7 +24,35 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class CSRF extends LessonAdapter { public class CSRF extends LessonAdapter {
private final static String MESSAGE = "message"; private final static String MESSAGE = "message";

View File

@ -1,10 +1,33 @@
package org.owasp.webgoat.lessons; package org.owasp.webgoat.lessons;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -13,14 +36,17 @@ public class Category implements Comparable
{ {
private String category; private String category;
private Integer ranking; private Integer ranking;
public Category(String category, Integer ranking) public Category(String category, Integer ranking)
{ {
this.category = category; this.category = category;
this.ranking = ranking; this.ranking = ranking;
} }
public int compareTo(Object obj) public int compareTo(Object obj)
{ {
int value = 1; int value = 1;
@ -33,26 +59,31 @@ public class Category implements Comparable
return value; return value;
} }
public Integer getRanking() public Integer getRanking()
{ {
return ranking; return ranking;
} }
public Integer setRanking(Integer ranking) public Integer setRanking(Integer ranking)
{ {
return this.ranking = ranking; return this.ranking = ranking;
} }
public String getName() public String getName()
{ {
return category; return category;
} }
public boolean equals(Object obj) public boolean equals(Object obj)
{ {
return getName().equals(((Category) obj).getName()); return getName().equals(((Category) obj).getName());
} }
public String toString() public String toString()
{ {
return getName(); return getName();

View File

@ -37,17 +37,41 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.Exec; import org.owasp.webgoat.util.Exec;
import org.owasp.webgoat.util.ExecResults; import org.owasp.webgoat.util.ExecResults;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class Challenge2Screen extends LessonAdapter public class Challenge2Screen extends LessonAdapter
{ {
private static final String USER_COOKIE = "user"; private static final String USER_COOKIE = "user";
private static final String JSP = ".jsp"; private static final String JSP = ".jsp";
@ -92,8 +116,11 @@ public class Challenge2Screen extends LessonAdapter
* Description of the Field * Description of the Field
*/ */
protected final static String USERNAME = "Username"; protected final static String USERNAME = "Username";
private static Connection connection = null; private static Connection connection = null;
private String pass = "goodbye"; private String pass = "goodbye";
private String user = "youaretheweakestlink"; private String user = "youaretheweakestlink";
@ -108,6 +135,7 @@ public class Challenge2Screen extends LessonAdapter
return super.createStagedContent(s); return super.createStagedContent(s);
} }
/** /**
* Determine the username and password * Determine the username and password
* *
@ -165,7 +193,8 @@ public class Challenge2Screen extends LessonAdapter
s.getResponse().addCookie(newCookie); s.getResponse().addCookie(newCookie);
ElementContainer ec = new ElementContainer(); 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"); s.setMessage("Welcome to stage 3 -- deface the site");
setStage(s, 3); setStage(s, 3);
@ -179,10 +208,12 @@ public class Challenge2Screen extends LessonAdapter
connection = DatabaseUtilities.makeConnection(s); connection = DatabaseUtilities.makeConnection(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 // pull the USER_COOKIE from the cookies
String user = getCookie(s); String user = getCookie(s);
String query = "SELECT * FROM user_data WHERE last_name = '" + user +"'"; String query = "SELECT * FROM user_data WHERE last_name = '" + user
+ "'";
Vector<String> v = new Vector<String>(); Vector<String> v = new Vector<String>();
try try
{ {
@ -197,8 +228,10 @@ public class Challenge2Screen extends LessonAdapter
if (v.size() > 2) if (v.size() > 2)
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
ec.addElement(ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(3)")); resultsMetaData));
ec.addElement(ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE
+ "(3)"));
} }
else else
{ {
@ -206,12 +239,14 @@ public class Challenge2Screen extends LessonAdapter
ec.addElement(buildCart(s)); ec.addElement(buildCart(s));
//Table t = ECSFactory.makeTable( s.isColor(), HtmlColor.ALICEBLUE ); //Table t = ECSFactory.makeTable( s.isColor(), HtmlColor.ALICEBLUE );
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 2 ).setBorder( 0 ).setWidth( "90%" ).setAlign( Table t = new Table().setCellSpacing(0).setCellPadding(2)
"center" ); .setBorder(0).setWidth("90%").setAlign("center");
ec.addElement(new BR()); ec.addElement(new BR());
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TD().addElement( "Please select credit card for this purchase: " ) ); tr
.addElement(new TD()
.addElement("Please select credit card for this purchase: "));
Element p = ECSFactory.makePulldown(CREDIT, v); Element p = ECSFactory.makePulldown(CREDIT, v);
tr.addElement(new TD().addElement(p).setAlign("right")); tr.addElement(new TD().addElement(p).setAlign("right"));
t.addElement(tr); t.addElement(tr);
@ -232,12 +267,11 @@ public class Challenge2Screen extends LessonAdapter
s.setMessage("An error occurred in the woods"); s.setMessage("An error occurred in the woods");
} }
return (ec); return (ec);
//<END_OMIT_SOURCE> //<END_OMIT_SOURCE>
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -253,7 +287,8 @@ public class Challenge2Screen extends LessonAdapter
//<START_OMIT_SOURCE> //<START_OMIT_SOURCE>
ElementContainer ec = new ElementContainer(); 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); setStage(s, 4);
// Reset the defaced webpage so the lesson can start over // Reset the defaced webpage so the lesson can start over
@ -267,13 +302,15 @@ public class Challenge2Screen extends LessonAdapter
{ {
ec.addElement(new HR()); ec.addElement(new HR());
s.setMessage("CONGRATULATIONS - You have defaced the site!"); 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()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); 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); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(showDefaceAttempt(s))); tr.addElement(new TD().addElement(showDefaceAttempt(s)));
@ -289,7 +326,8 @@ public class Challenge2Screen extends LessonAdapter
ec.addElement(new H1("Current Network Status:")); ec.addElement(new H1("Current Network Status:"));
ec.addElement(netstatResults); 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()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
@ -297,19 +335,24 @@ public class Challenge2Screen extends LessonAdapter
String[] list = { "TCP", "TCPv6", "IP", "IPv6", "UDP", "UDPv6" }; String[] list = { "TCP", "TCPv6", "IP", "IPv6", "UDP", "UDPv6" };
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TD().addElement( ECSFactory.makeButton( "View Network" ))); tr.addElement(new TD().addElement(ECSFactory
tr.addElement( new TD().setWidth("35%").addElement( ECSFactory.makePulldown( PROTOCOL, list, "", 5 ))); .makeButton("View Network")));
tr.addElement(new TD().setWidth("35%").addElement(
ECSFactory.makePulldown(PROTOCOL, list, "", 5)));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); 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()); 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()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
@ -331,10 +374,14 @@ public class Challenge2Screen extends LessonAdapter
try try
{ {
// get current text and compare to the new text // get current text and compare to the new text
String origpath = s.getContext(). getRealPath( WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP ); String origpath = s.getContext().getRealPath(
String masterFilePath = s.getContext().getRealPath( WEBGOAT_CHALLENGE_JSP ); WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String defacedText = getFileText( new BufferedReader( new FileReader( origpath ) ), false ); String masterFilePath = s.getContext().getRealPath(
String origText = getFileText( new BufferedReader( new FileReader( masterFilePath ) ), false ); 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)); defaced = (!origText.equals(defacedText));
} }
@ -346,14 +393,18 @@ public class Challenge2Screen extends LessonAdapter
//<END_OMIT_SOURCE> //<END_OMIT_SOURCE>
} }
private Element showDefaceAttempt(WebSession s) throws Exception private Element showDefaceAttempt(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
// get current text and compare to the new text // get current text and compare to the new text
String origpath = s.getContext(). getRealPath( WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP ); String origpath = s.getContext().getRealPath(
String defaced = getFileText( new BufferedReader( new FileReader( origpath ) ), false ); WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String origText = getFileText( new BufferedReader( new FileReader( s.getContext(). getRealPath( WEBGOAT_CHALLENGE_JSP ))), false); String defaced = getFileText(new BufferedReader(
new FileReader(origpath)), false);
String origText = getFileText(new BufferedReader(new FileReader(s
.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP))), false);
// show webgoat.jsp text // show webgoat.jsp text
ec.addElement(new H1().addElement("Original Website Text")); ec.addElement(new H1().addElement("Original Website Text"));
@ -367,19 +418,21 @@ public class Challenge2Screen extends LessonAdapter
} }
private void resetWebPage(WebSession s) private void resetWebPage(WebSession s)
{ {
try try
{ {
// get current text and compare to the new text // get current text and compare to the new text
String defacedpath = s.getContext(). getRealPath( WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP ); String defacedpath = s.getContext().getRealPath(
String masterFilePath = s.getContext().getRealPath( WEBGOAT_CHALLENGE_JSP ); WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String masterFilePath = s.getContext().getRealPath(
WEBGOAT_CHALLENGE_JSP);
// replace the defaced text with the original // replace the defaced text with the original
File usersFile = new File(defacedpath); File usersFile = new File(defacedpath);
FileWriter fw = new FileWriter(usersFile); FileWriter fw = new FileWriter(usersFile);
fw.write( getFileText( new BufferedReader( new FileReader( masterFilePath ) ), false ) ); fw.write(getFileText(new BufferedReader(new FileReader(
masterFilePath)), false));
fw.close(); fw.close();
// System.out.println("webgoat_guest replaced: " + getFileText( new BufferedReader( new FileReader( defacedpath ) ), false ) ); // System.out.println("webgoat_guest replaced: " + getFileText( new BufferedReader( new FileReader( defacedpath ) ), false ) );
} }
@ -389,11 +442,13 @@ public class Challenge2Screen extends LessonAdapter
} }
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return CHALLENGE; return CHALLENGE;
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -407,7 +462,9 @@ public class Challenge2Screen extends LessonAdapter
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Thanks for coming!")); ec.addElement(new H1().addElement("Thanks for coming!"));
ec.addElement(new BR()); 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); return (ec);
} }
@ -452,10 +509,12 @@ public class Challenge2Screen extends LessonAdapter
//<START_OMIT_SOURCE> //<START_OMIT_SOURCE>
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "You need to gain access to the Java source code for this lesson." ); hints
.add("You need to gain access to the Java source code for this lesson.");
hints.add("Seriously, no more hints -- it's a CHALLENGE!"); hints.add("Seriously, no more hints -- it's a CHALLENGE!");
hints.add("Come on -- give it a rest!"); hints.add("Come on -- give it a rest!");
if (getStage(s) != 1); if (getStage(s) != 1)
;
{ {
hints.add("Persistance is always rewarded"); hints.add("Persistance is always rewarded");
} }
@ -465,12 +524,14 @@ public class Challenge2Screen extends LessonAdapter
//<END_OMIT_SOURCE> //<END_OMIT_SOURCE>
} }
protected Element makeLogin(WebSession s) protected Element makeLogin(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Sign In ")); 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()) if (s.isColor())
{ {
@ -478,7 +539,10 @@ public class Challenge2Screen extends LessonAdapter
} }
TR tr = new TR(); 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.") 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")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
@ -509,6 +573,7 @@ public class Challenge2Screen extends LessonAdapter
return (ec); return (ec);
} }
/** /**
* Gets the instructions attribute of the ChallengeScreen object * Gets the instructions attribute of the ChallengeScreen object
* *
@ -516,16 +581,15 @@ public class Challenge2Screen extends LessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "Your mission is to break the authentication scheme, " + String instructions = "Your mission is to break the authentication scheme, "
"steal all the credit cards from the database, and then deface the website. " + + "steal all the credit cards from the database, and then deface the website. "
"You will have to use many of the techniques you have learned in the other lessons. " + + "You will have to use many of the techniques you have learned in the other lessons. "
"The main webpage for this site is 'webgoat_challenge_&lt;username&gt;.jsp'"; + "The main webpage for this site is 'webgoat_challenge_&lt;username&gt;.jsp'";
return (instructions); return (instructions);
} }
/** /**
* Gets the ranking attribute of the ChallengeScreen object * Gets the ranking attribute of the ChallengeScreen object
* *
@ -560,7 +624,8 @@ public class Challenge2Screen extends LessonAdapter
ElementContainer ec = new ElementContainer(); 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())
{ {
@ -611,7 +676,8 @@ public class Challenge2Screen extends LessonAdapter
// command injection, we will wrap the screen at 4 columns // command injection, we will wrap the screen at 4 columns
int columnCount = 4; int columnCount = 4;
tr = new TR(); tr = new TR();
StringTokenizer tokens = new StringTokenizer( lines.nextToken(), "\t "); StringTokenizer tokens = new StringTokenizer(lines.nextToken(),
"\t ");
while (tokens.hasMoreTokens() && columnCount-- > 0) while (tokens.hasMoreTokens() && columnCount-- > 0)
{ {
tr.addElement(new TD().addElement(tokens.nextToken())); tr.addElement(new TD().addElement(tokens.nextToken()));
@ -664,13 +730,16 @@ public class Challenge2Screen extends LessonAdapter
} }
} }
protected Element buildCart(WebSession s) protected Element buildCart(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement( new Center().addElement( new H1().addElement( "Shopping Cart " ))); ec.addElement(new Center().addElement(new H1()
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 2 ).setBorder( 1 ).setWidth("90%").setAlign("center"); .addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1)
.setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
@ -678,7 +747,8 @@ public class Challenge2Screen extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now")
.setWidth("80%"));
tr.addElement(new TH().addElement("Price:").setWidth("10%")); tr.addElement(new TH().addElement("Price:").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity:").setWidth("3%")); tr.addElement(new TH().addElement("Quantity:").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%")); tr.addElement(new TH().addElement("Total").setWidth("7%"));
@ -693,7 +763,8 @@ public class Challenge2Screen extends LessonAdapter
ec.addElement(t); 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()) if (s.isColor())
{ {
@ -702,7 +773,8 @@ public class Challenge2Screen extends LessonAdapter
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "The total charged to your credit card:" ) ); tr.addElement(new TD()
.addElement("The total charged to your credit card:"));
tr.addElement(new TD().addElement("59.99")); tr.addElement(new TD().addElement("59.99"));
t.addElement(tr); t.addElement(tr);
@ -711,11 +783,13 @@ public class Challenge2Screen extends LessonAdapter
return (ec); return (ec);
} }
public boolean canHaveClues() public boolean canHaveClues()
{ {
return false; return false;
} }
/** /**
* Gets the cookie attribute of the CookieScreen object * Gets the cookie attribute of the CookieScreen object
* *
@ -738,4 +812,3 @@ public class Challenge2Screen extends LessonAdapter
} }
} }

View File

@ -18,18 +18,43 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.Exec; import org.owasp.webgoat.util.Exec;
import org.owasp.webgoat.util.ExecResults; import org.owasp.webgoat.util.ExecResults;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class CommandInjection extends LessonAdapter 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");
@ -45,9 +70,11 @@ public class CommandInjection extends LessonAdapter
boolean illegalCommand = s.isDefuseOSCommands(); boolean illegalCommand = s.isDefuseOSCommands();
try try
{ {
String helpFile = s.getParser().getRawParameter( HELP_FILE, "BasicAuthentication.help" ); String helpFile = s.getParser().getRawParameter(HELP_FILE,
"BasicAuthentication.help");
String safeDirName; String safeDirName;
if ( s.isDefuseOSCommands() && ( helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1) ) if (s.isDefuseOSCommands()
&& (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1))
{ {
int index = helpFile.indexOf('&'); int index = helpFile.indexOf('&');
if (index == -1) if (index == -1)
@ -56,45 +83,63 @@ public class CommandInjection extends LessonAdapter
} }
index = index + 1; index = index + 1;
int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote
System.out.println("Command = [" + helpFile.substring(index, helpFileLen).trim().toLowerCase() + "]"); System.out.println("Command = ["
if (( osName.indexOf( "Windows" ) != -1 && + helpFile.substring(index, helpFileLen).trim()
( helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a") || .toLowerCase() + "]");
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir") || if ((osName.indexOf("Windows") != -1 && (helpFile.substring(
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls") || index, helpFileLen).trim().toLowerCase().equals(
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig") || "netstat -a")
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig") )) || || helpFile.substring(index, helpFileLen).trim()
(helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a #") || .toLowerCase().equals("dir")
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir #") || || helpFile.substring(index, helpFileLen).trim()
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls #") || .toLowerCase().equals("ls")
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls -l #") || || helpFile.substring(index, helpFileLen).trim()
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig #") || .toLowerCase().equals("ifconfig") || helpFile
helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig #") )) .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; illegalCommand = false;
} }
else else
{ {
s.setMessage("It appears that you are on the right track. " + s
"Commands that may compromise the operating system have been disabled. " + .setMessage("It appears that you are on the right track. "
"The following commands are allowed: netstat -a, dir, ls, ifconfig, and ipconfig"); + "Commands that may compromise the operating system have been disabled. "
+ "The following commands are allowed: netstat -a, dir, ls, ifconfig, and ipconfig");
} }
} }
if ( s.isDefuseOSCommands() && helpFile.indexOf('&') == -1 && helpFile.indexOf(';') == -1 ) if (s.isDefuseOSCommands() && helpFile.indexOf('&') == -1
&& helpFile.indexOf(';') == -1)
{ {
if (helpFile.length() > 0) if (helpFile.length() > 0)
{ {
if (upDirCount(helpFile) <= 3) if (upDirCount(helpFile) <= 3)
{ {
// FIXME: This value isn't used. What is the goal here? // FIXME: This value isn't used. What is the goal here?
safeDirName = s.getContext().getRealPath("/") + helpFile; safeDirName = s.getContext().getRealPath("/")
+ helpFile;
illegalCommand = false; illegalCommand = false;
} }
else else
{ {
s.setMessage("It appears that you are on the right track. " + s
"Commands that may compromise the operating system have been disabled. " + .setMessage("It appears that you are on the right track. "
"This lesson is a command injection lesson, not access control."); + "Commands that may compromise the operating system have been disabled. "
+ "This lesson is a command injection lesson, not access control.");
} }
} }
else else
@ -105,11 +150,14 @@ public class CommandInjection extends LessonAdapter
} }
File safeDir = new File(s.getContext().getRealPath("/lesson_plans")); File safeDir = new File(s.getContext().getRealPath("/lesson_plans"));
ec.addElement( new StringElement( "You are currently viewing: <b>" ec
+ ( helpFile.toString().length() == 0 ? "&lt;select file from list below&gt;" : helpFile.toString() ) .addElement(new StringElement(
+ "</b>") ); "You are currently viewing: <b>"
+ (helpFile.toString().length() == 0 ? "&lt;select file from list below&gt;"
: helpFile.toString()) + "</b>"));
if ( !illegalCommand ) { if (!illegalCommand)
{
String results; String results;
String fileData = null; String fileData = null;
helpFile = helpFile.replaceAll("\\.help", "\\.html"); helpFile = helpFile.replaceAll("\\.help", "\\.html");
@ -117,20 +165,30 @@ public class CommandInjection extends LessonAdapter
if (osName.indexOf("Windows") != -1) if (osName.indexOf("Windows") != -1)
{ {
// Add quotes around the filename to avoid having special characters in DOS filenames // Add quotes around the filename to avoid having special characters in DOS filenames
results = exec( s, "cmd.exe /c dir /b \"" + safeDir.getPath() + "\""); results = exec(s, "cmd.exe /c dir /b \""
fileData = exec(s, "cmd.exe /c type \"" + new File(safeDir, helpFile).getPath() + "\""); + safeDir.getPath() + "\"");
fileData = exec(s, "cmd.exe /c type \""
+ new File(safeDir, helpFile).getPath() + "\"");
} }
else else
{ {
String[] cmd1 = {"/bin/sh", "-c", "ls \"" + safeDir.getPath() + "\""}; String[] cmd1 = { "/bin/sh", "-c",
"ls \"" + safeDir.getPath() + "\"" };
results = exec(s, cmd1); results = exec(s, cmd1);
String[] cmd2 = {"/bin/sh", "-c", "cat \"" + new File(safeDir, helpFile).getPath() + "\""}; String[] cmd2 = {
"/bin/sh",
"-c",
"cat \"" + new File(safeDir, helpFile).getPath()
+ "\"" };
fileData = exec(s, cmd2); fileData = exec(s, cmd2);
} }
ec.addElement( new P().addElement( "Select the lesson plan to view: " ) ); ec.addElement(new P()
ec.addElement( ECSFactory.makePulldown( HELP_FILE, parseResults( results.replaceAll("(?s)\\.html", "\\.help") )) ); .addElement("Select the lesson plan to view: "));
ec.addElement(ECSFactory.makePulldown(HELP_FILE,
parseResults(results.replaceAll("(?s)\\.html",
"\\.help"))));
//ec.addElement( results ); //ec.addElement( results );
Element b = ECSFactory.makeButton("View"); Element b = ECSFactory.makeButton("View");
ec.addElement(b); ec.addElement(b);
@ -138,10 +196,11 @@ public class CommandInjection extends LessonAdapter
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement( new StringElement( fileData.replaceAll(System.getProperty("line.separator"),"<br>") ec.addElement(new StringElement(fileData.replaceAll(
.replaceAll("(?s)<!DOCTYPE.*/head>","") System.getProperty("line.separator"), "<br>")
.replaceAll("<br><br>","<br>") .replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll(
.replaceAll("<br>\\s<br>","<br>"))); "<br><br>", "<br>").replaceAll("<br>\\s<br>",
"<br>")));
} }
} }
@ -154,9 +213,11 @@ public class CommandInjection extends LessonAdapter
return (ec); return (ec);
} }
private String parseResults(String results) private String parseResults(String results)
{ {
return results.replaceAll("(?s).*Output...\\s","").replaceAll("(?s)Returncode.*",""); return results.replaceAll("(?s).*Output...\\s", "").replaceAll(
"(?s)Returncode.*", "");
} }
@ -176,6 +237,7 @@ public class CommandInjection extends LessonAdapter
return count; return count;
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -187,7 +249,8 @@ public class CommandInjection extends LessonAdapter
{ {
System.out.println("Executing OS command: " + command); System.out.println("Executing OS command: " + command);
ExecResults er = Exec.execSimple(command); ExecResults er = Exec.execSimple(command);
if (( command.indexOf("&" ) != -1 || command.indexOf(";") != -1 ) && !er.getError() ) if ((command.indexOf("&") != -1 || command.indexOf(";") != -1)
&& !er.getError())
{ {
makeSuccess(s); makeSuccess(s);
} }
@ -226,9 +289,11 @@ public class CommandInjection extends LessonAdapter
*/ */
private Element exec(WebSession s, String command, String args) private Element exec(WebSession s, String command, String args)
{ {
System.out.println("Executing OS command: '" + command + "' with args: '" + args + "'"); System.out.println("Executing OS command: '" + command
+ "' with args: '" + args + "'");
ExecResults er = Exec.execSimple(command, args); ExecResults er = Exec.execSimple(command, args);
if (( args.indexOf("&" ) != -1 || args.indexOf(";") != -1 ) && !er.getError() ) if ((args.indexOf("&") != -1 || args.indexOf(";") != -1)
&& !er.getError())
{ {
makeSuccess(s); makeSuccess(s);
} }
@ -257,10 +322,14 @@ public class CommandInjection extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "The application is using a system command to return the contents of a file." ); hints
hints.add( "The ampersand(&) separates commands in the Windows 2000 command shell. In Unix the separator is typically a semi-colon(;)" ); .add("The application is using a system command to return the contents of a file.");
hints.add( "Use a proxy to insert & netstat -a on Windows or ;netstat -a on Unix." ); hints
hints.add( "Note that the server may enclose the submitted file name within quotes" ); .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 hints; return hints;
} }
@ -273,21 +342,21 @@ public class CommandInjection extends LessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "Choose the lesson plan you would like to view. " + String instructions = "Choose the lesson plan you would like to view. "
"Try to inject a command to the operating system."; + "Try to inject a command to the operating system.";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(40); private final static Integer DEFAULT_RANKING = new Integer(40);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
@ -298,4 +367,3 @@ public class CommandInjection extends LessonAdapter
return "How to Perform Command Injection"; return "How to Perform Command Injection";
} }
} }

View File

@ -25,51 +25,107 @@ import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /**
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web /*******************************************************************************
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute *
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
*/ */
public class CrossSiteScripting extends LessonAdapter public class CrossSiteScripting extends LessonAdapter
{ {
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 String LESSON_NAME = "CrossSiteScripting"; private final static String LESSON_NAME = "CrossSiteScripting";
private final static String JSP_PATH = "/lessons/" + LESSON_NAME + "/"; private final static String JSP_PATH = "/lessons/" + LESSON_NAME + "/";
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
@ -78,6 +134,7 @@ public class CrossSiteScripting extends LessonAdapter
private Map lessonFunctions = new Hashtable(); private Map lessonFunctions = new Hashtable();
public static synchronized Connection getConnection(WebSession s) public static synchronized Connection getConnection(WebSession s)
throws SQLException, ClassNotFoundException throws SQLException, ClassNotFoundException
{ {
@ -89,6 +146,7 @@ public class CrossSiteScripting extends LessonAdapter
return connection; return connection;
} }
public CrossSiteScripting() public CrossSiteScripting()
{ {
String myClassName = parseClassName(this.getClass().getName()); String myClassName = parseClassName(this.getClass().getName());
@ -99,13 +157,19 @@ public class CrossSiteScripting extends LessonAdapter
registerAction(new EditProfile(this, myClassName, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, myClassName, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, myClassName, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); registerAction(new Login(this, myClassName, LOGIN_ACTION,
registerAction(new Logout(this, myClassName, LOGOUT_ACTION, getAction(LOGIN_ACTION))); getAction(LISTSTAFF_ACTION)));
registerAction(new FindProfile(this, myClassName, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new Logout(this, myClassName, LOGOUT_ACTION,
registerAction(new UpdateProfile(this, myClassName, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); getAction(LOGIN_ACTION)));
registerAction(new DeleteProfile(this, myClassName, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); registerAction(new FindProfile(this, myClassName, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, myClassName,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, myClassName,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
protected static String parseClassName(String fqcn) protected static String parseClassName(String fqcn)
{ {
String className = fqcn; String className = fqcn;
@ -117,11 +181,13 @@ public class CrossSiteScripting extends LessonAdapter
return className; return className;
} }
protected void registerAction(LessonAction action) protected void registerAction(LessonAction action)
{ {
lessonFunctions.put(action.getActionName(), action); lessonFunctions.put(action.getActionName(), action);
} }
/** /**
* Gets the category attribute of the CrossSiteScripting object * Gets the category attribute of the CrossSiteScripting object
* *
@ -144,24 +210,34 @@ public class CrossSiteScripting extends LessonAdapter
// Stage 1 // Stage 1
hints.add("You can put HTML tags in form input fields."); 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
hints.add( "Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in message fields." ); .add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
hints.add( "Enter this: &lt;script&gtalert(\"document.cookie\");&lt;/script&gt; in message fields." ); hints
.add("Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in message fields.");
hints
.add("Enter this: &lt;script&gtalert(\"document.cookie\");&lt;/script&gt; in message fields.");
// Stage 2 // Stage 2
hints.add( "Many scripts rely on the use of special characters such as: &lt;" ); hints
hints.add( "Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering)." ); .add("Many scripts rely on the use of special characters such as: &lt;");
hints.add( "The java.util.regex package is useful for filtering string values." ); 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 // Stage 3
hints.add( "Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags." ); hints
hints.add( "An HTML entity encoder is provided in the ParameterParser class." ); .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 // Stage 4
hints.add( "Examine content served in response to form submissions looking for data taken from the form." ); hints
.add("Examine content served in response to form submissions looking for data taken from the form.");
// Stage 5 // Stage 5
hints.add( "Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");" ); hints
.add("Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");");
return hints; return hints;
} }
@ -181,33 +257,45 @@ public class CrossSiteScripting extends LessonAdapter
switch (getStage(s)) switch (getStage(s))
{ {
case 1: case 1:
instructions = "Stage " + getStage(s) + ": Execute a Stored Cross Site Scripting (XSS) attack.<br>" + instructions = "Stage "
"For this exercise, your mission is to cause the application to serve a script of your making " + + getStage(s)
" to some other user."; + ": Execute a Stored Cross Site Scripting (XSS) attack.<br>"
+ "For this exercise, your mission is to cause the application to serve a script of your making "
+ " to some other user.";
break; break;
case 2: case 2:
instructions = "Stage " + getStage(s) + ": Block Stored XSS using Input Validation.<br>" + instructions = "Stage "
"You will modify the application to perform input validation on the vulnerable input field " + + getStage(s)
"you just exploited."; + ": Block Stored XSS using Input Validation.<br>"
+ "You will modify the application to perform input validation on the vulnerable input field "
+ "you just exploited.";
break; break;
case 3: case 3:
instructions = "Stage " + getStage(s) + ": Execute a previously Stored Cross Site Scripting (XSS) attack.<br>" + instructions = "Stage "
"The application is still vulnerable to scripts in the database. Trigger a pre-stored " + + getStage(s)
"script by logging in as employee 'David' and viewing Bruce's profile."; + ": Execute a previously Stored Cross Site Scripting (XSS) attack.<br>"
+ "The application is still vulnerable to scripts in the database. Trigger a pre-stored "
+ "script by logging in as employee 'David' and viewing Bruce's profile.";
break; break;
case 4: case 4:
instructions = "Stage " + getStage(s) + ": Block Stored XSS using Output Encoding.<br>" + instructions = "Stage "
"Encode data served from the database to the client so that any scripts are rendered harmless."; + getStage(s)
+ ": Block Stored XSS using Output Encoding.<br>"
+ "Encode data served from the database to the client so that any scripts are rendered harmless.";
break; break;
case 5: case 5:
instructions = "Stage " + getStage(s) + ": Execute a Reflected XSS attack.<br>" + instructions = "Stage "
"Your goal here is to craft a link containing a script which the application will " + + getStage(s)
"serve right back to any client that activates the link."; + ": Execute a Reflected XSS attack.<br>"
+ "Your goal here is to craft a link containing a script which the application will "
+ "serve right back to any client that activates the link.";
break; break;
case 6: case 6:
instructions = "Stage " + getStage(s) + ": Block Reflected XSS using Input Validation.<br>" + instructions = "Stage "
"Use the input validation techniques learned ealier in this lesson to close the vulnerability " + + getStage(s)
"you just exploited."; + ": Block Reflected XSS using Input Validation.<br>"
+ "Use the input validation techniques learned ealier in this lesson to close the vulnerability "
+ "you just exploited.";
break; break;
default: default:
// Illegal stage value // Illegal stage value
@ -225,6 +313,7 @@ public class CrossSiteScripting extends LessonAdapter
return (LessonAction) lessonFunctions.get(actionName); return (LessonAction) lessonFunctions.get(actionName);
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if (s.getLessonSession(this) == null) if (s.getLessonSession(this) == null)
@ -249,7 +338,8 @@ public class CrossSiteScripting extends LessonAdapter
if (action != null) if (action != null)
{ {
if (!action.requiresAuthentication() || action.isAuthenticated(s)) if (!action.requiresAuthentication()
|| action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
//setCurrentAction(s, action.getNextPage(s)); //setCurrentAction(s, action.getNextPage(s));
@ -297,30 +387,38 @@ public class CrossSiteScripting extends LessonAdapter
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
public boolean isAuthorized(WebSession s, int userId, String functionId) public boolean isAuthorized(WebSession s, int userId, String functionId)
{ {
//System.out.println("Checking authorization from " + getCurrentAction(s)); //System.out.println("Checking authorization from " + getCurrentAction(s));
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.isAuthorized(s, userId, functionId); return action.isAuthorized(s, userId, functionId);
} }
public int getUserId(WebSession s) throws ParameterNotFoundException public int getUserId(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.getUserId(s); return action.getUserId(s);
} }
public String getUserName(WebSession s) throws ParameterNotFoundException public String getUserName(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.getUserName(s); return action.getUserName(s);
} }
public String getTemplatePage(WebSession s) public String getTemplatePage(WebSession s)
{ {
return JSP_PATH + LESSON_NAME + ".jsp"; return JSP_PATH + LESSON_NAME + ".jsp";
} }
public String getPage(WebSession s) public String getPage(WebSession s)
{ {
String page = JSP_PATH + getCurrentAction(s) + ".jsp"; String page = JSP_PATH + getCurrentAction(s) + ".jsp";
@ -329,11 +427,13 @@ public class CrossSiteScripting extends LessonAdapter
return page; return page;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CrossSiteScripting object * Gets the title attribute of the CrossSiteScripting object
* *
@ -344,6 +444,7 @@ public class CrossSiteScripting extends LessonAdapter
return "LAB: Cross Site Scripting (XSS)"; return "LAB: Cross Site Scripting (XSS)";
} }
public String getSourceFileName() public String getSourceFileName()
{ {
// FIXME: Need to generalize findSourceResource() and use it on the currently active // FIXME: Need to generalize findSourceResource() and use it on the currently active

View File

@ -12,37 +12,73 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class EditProfile extends DefaultLessonAction
{ {
public EditProfile(AbstractLesson lesson, String lessonName, String actionName)
public EditProfile(AbstractLesson lesson, String lessonName,
String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getUserId(s); int userId = getUserId(s);
int employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(
CrossSiteScripting.EMPLOYEE_ID);
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return CrossSiteScripting.EDITPROFILE_ACTION; return CrossSiteScripting.EDITPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId)
throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, int userId,
int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
@ -53,28 +89,29 @@ public class EditProfile extends DefaultLessonAction
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); .getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +
@ -98,8 +135,8 @@ public class EditProfile extends DefaultLessonAction
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) public Employee getEmployeeProfile_BACKUP(WebSession s, int userId,
throws UnauthorizedException int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
@ -110,28 +147,29 @@ public class EditProfile extends DefaultLessonAction
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); .getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +

View File

@ -18,34 +18,71 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class FindProfile extends DefaultLessonAction public class FindProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public FindProfile(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public FindProfile(AbstractLesson lesson, String lessonName,
String actionName, LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.USER_ID);
String searchName = null; String searchName = null;
try try
{ {
searchName = getRequestParameter(s, CrossSiteScripting.SEARCHNAME); searchName = getRequestParameter(s,
CrossSiteScripting.SEARCHNAME);
Employee employee = null; Employee employee = null;
employee = findEmployeeProfile(s, userId, searchName); employee = findEmployeeProfile(s, userId, searchName);
if (employee == null) if (employee == null)
{ {
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY, setSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY,
"Employee " + searchName + " not found."); "Employee " + searchName + " not found.");
} }
} }
@ -53,7 +90,8 @@ public class FindProfile extends DefaultLessonAction
{ {
if (getStage(s) == 6) if (getStage(s) == 6)
{ {
s.setMessage("Congratulations. You have successfully completed this lesson"); s
.setMessage("Congratulations. You have successfully completed this lesson");
getLesson().getLessonTracker(s).setCompleted(true); getLesson().getLessonTracker(s).setCompleted(true);
} }
throw e; throw e;
@ -61,7 +99,9 @@ public class FindProfile extends DefaultLessonAction
if (getStage(s) == 5) if (getStage(s) == 5)
{ {
if (searchName.indexOf("<script>") > -1 && searchName.indexOf("alert") > -1 && searchName.indexOf("</script>") > -1) if (searchName.indexOf("<script>") > -1
&& searchName.indexOf("alert") > -1
&& searchName.indexOf("</script>") > -1)
{ {
s.setMessage("Welcome to stage 6 - more input validation"); s.setMessage("Welcome to stage 6 - more input validation");
setStage(s, 6); setStage(s, 6);
@ -91,6 +131,7 @@ public class FindProfile extends DefaultLessonAction
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String page = CrossSiteScripting.SEARCHSTAFF_ACTION; String page = CrossSiteScripting.SEARCHSTAFF_ACTION;
@ -101,18 +142,21 @@ public class FindProfile extends DefaultLessonAction
return page; return page;
} }
protected String getRequestParameter(WebSession s, String name) protected String getRequestParameter(WebSession s, String name)
throws ParameterNotFoundException, ValidationException throws ParameterNotFoundException, ValidationException
{ {
return s.getParser().getRawParameter(name); return s.getParser().getRawParameter(name);
} }
protected String getRequestParameter_BACKUP(WebSession s, String name) protected String getRequestParameter_BACKUP(WebSession s, String name)
throws ParameterNotFoundException, ValidationException throws ParameterNotFoundException, ValidationException
{ {
return s.getParser().getRawParameter(name); return s.getParser().getRawParameter(name);
} }
public Employee findEmployeeProfile(WebSession s, int userId, String pattern) public Employee findEmployeeProfile(WebSession s, int userId, String pattern)
throws UnauthorizedException throws UnauthorizedException
{ {
@ -125,8 +169,10 @@ public class FindProfile extends DefaultLessonAction
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); .getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
answer_statement.setString(1, "%" + pattern + "%"); answer_statement.setString(1, "%" + pattern + "%");
answer_statement.setString(2, "%" + pattern + "%"); answer_statement.setString(2, "%" + pattern + "%");
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
@ -136,21 +182,19 @@ public class FindProfile extends DefaultLessonAction
{ {
int id = answer_results.getInt("userid"); int id = answer_results.getInt("userid");
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(id, answer_results
id, .getString("first_name"), answer_results
answer_results.getString("first_name"), .getString("last_name"), answer_results
answer_results.getString("last_name"), .getString("ssn"), answer_results
answer_results.getString("ssn"), .getString("title"), answer_results
answer_results.getString("title"), .getString("phone"), answer_results
answer_results.getString("phone"), .getString("address1"), answer_results
answer_results.getString("address1"), .getString("address2"), answer_results
answer_results.getString("address2"), .getInt("manager"), answer_results
answer_results.getInt("manager"), .getString("start_date"), answer_results
answer_results.getString("start_date"), .getInt("salary"), answer_results.getString("ccn"),
answer_results.getInt("salary"), answer_results.getInt("ccn_limit"), answer_results
answer_results.getString("ccn"), .getString("disciplined_date"),
answer_results.getInt("ccn_limit"),
answer_results.getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
@ -158,7 +202,9 @@ public class FindProfile extends DefaultLessonAction
profile.getFirstName() + " " + profile.getLastName() + profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")"); " (" + profile.getId() + ")");
*/ */
setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer.toString(id)); setRequestAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ID, Integer
.toString(id));
} }
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -176,22 +222,25 @@ public class FindProfile extends DefaultLessonAction
return profile; return profile;
} }
private boolean foundEmployee(WebSession s) private boolean foundEmployee(WebSession s)
{ {
boolean found = false; boolean found = false;
try try
{ {
getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); getIntRequestAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ID);
found = true; found = true;
} }
catch (ParameterNotFoundException e) catch (ParameterNotFoundException e)
{ {}
}
return found; return found;
} }
protected String validate(final String parameter, final Pattern pattern) throws ValidationException
protected String validate(final String parameter, final Pattern pattern)
throws ValidationException
{ {
Matcher matcher = pattern.matcher(parameter); Matcher matcher = pattern.matcher(parameter);
if (!matcher.matches()) if (!matcher.matches())
@ -203,7 +252,8 @@ public class FindProfile extends DefaultLessonAction
protected static Map patterns = new HashMap(); protected static Map patterns = new HashMap();
static static
{ {
patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}")); patterns.put(CrossSiteScripting.SEARCHNAME, Pattern
.compile("[a-zA-Z ]{0,20}"));
} }
} }

View File

@ -19,24 +19,60 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class UpdateProfile extends DefaultLessonAction public class UpdateProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public UpdateProfile(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public UpdateProfile(AbstractLesson lesson, String lessonName,
String actionName, LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.USER_ID);
int subjectId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID, 0); int subjectId = s.getParser().getIntParameter(
CrossSiteScripting.EMPLOYEE_ID, 0);
Employee employee = null; Employee employee = null;
try try
@ -47,7 +83,8 @@ public class UpdateProfile extends DefaultLessonAction
{ {
if (getStage(s) == 2) if (getStage(s) == 2)
{ {
s.setMessage( "Welcome to stage 3 - demonstrate Stored XSS again" ); s
.setMessage("Welcome to stage 3 - demonstrate Stored XSS again");
setStage(s, 3); setStage(s, 3);
} }
throw e; throw e;
@ -56,12 +93,13 @@ public class UpdateProfile extends DefaultLessonAction
if (subjectId > 0) if (subjectId > 0)
{ {
this.changeEmployeeProfile(s, userId, subjectId, employee); this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer.toString(subjectId)); setRequestAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ID, Integer
.toString(subjectId));
} }
else else
this.createEmployeeProfile(s, userId, employee); this.createEmployeeProfile(s, userId, employee);
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
@ -81,6 +119,7 @@ public class UpdateProfile extends DefaultLessonAction
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
protected Employee parseEmployeeProfile(int subjectId, WebSession s) protected Employee parseEmployeeProfile(int subjectId, WebSession s)
throws ParameterNotFoundException, ValidationException throws ParameterNotFoundException, ValidationException
{ {
@ -96,17 +135,23 @@ public class UpdateProfile extends DefaultLessonAction
String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); int manager = Integer.parseInt(request
.getParameter(CrossSiteScripting.MANAGER));
String startDate = request.getParameter(CrossSiteScripting.START_DATE); String startDate = request.getParameter(CrossSiteScripting.START_DATE);
int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); int salary = Integer.parseInt(request
.getParameter(CrossSiteScripting.SALARY));
String ccn = request.getParameter(CrossSiteScripting.CCN); String ccn = request.getParameter(CrossSiteScripting.CCN);
int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); int ccnLimit = Integer.parseInt(request
String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); .getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); String disciplinaryActionDate = request
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); .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, Employee employee = new Employee(subjectId, firstName, lastName, ssn,
address1, address2, manager, startDate, salary, title, phone, address1, address2, manager, startDate, salary,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
@ -129,17 +174,23 @@ public class UpdateProfile extends DefaultLessonAction
String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); int manager = Integer.parseInt(request
.getParameter(CrossSiteScripting.MANAGER));
String startDate = request.getParameter(CrossSiteScripting.START_DATE); String startDate = request.getParameter(CrossSiteScripting.START_DATE);
int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); int salary = Integer.parseInt(request
.getParameter(CrossSiteScripting.SALARY));
String ccn = request.getParameter(CrossSiteScripting.CCN); String ccn = request.getParameter(CrossSiteScripting.CCN);
int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); int ccnLimit = Integer.parseInt(request
String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); .getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); String disciplinaryActionDate = request
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); .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, Employee employee = new Employee(subjectId, firstName, lastName, ssn,
address1, address2, manager, startDate, salary, title, phone, address1, address2, manager, startDate, salary,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
@ -147,8 +198,9 @@ public class UpdateProfile extends DefaultLessonAction
} }
protected Employee doParseEmployeeProfile(int subjectId, ParameterParser parser) protected Employee doParseEmployeeProfile(int subjectId,
throws ParameterNotFoundException, ValidationException ParameterParser parser) throws ParameterNotFoundException,
ValidationException
{ {
// Fix this method using the org.owasp.webgoat.session.ParameterParser class // Fix this method using the org.owasp.webgoat.session.ParameterParser class
return null; return null;
@ -160,72 +212,39 @@ public class UpdateProfile extends DefaultLessonAction
return CrossSiteScripting.VIEWPROFILE_ACTION; return CrossSiteScripting.VIEWPROFILE_ACTION;
} }
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException public void changeEmployeeProfile(WebSession s, int userId, int subjectId,
Employee employee) throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = '" + employee.getFirstName() + String query = "UPDATE employee SET first_name = '"
"', last_name = '" + employee.getLastName() + + employee.getFirstName() + "', last_name = '"
"', ssn = '" + employee.getSsn() + + employee.getLastName() + "', ssn = '" + employee.getSsn()
"', title = '" + employee.getTitle() + + "', title = '" + employee.getTitle() + "', phone = '"
"', phone = '" + employee.getPhoneNumber() + + employee.getPhoneNumber() + "', address1 = '"
"', address1 = '" + employee.getAddress1() + + employee.getAddress1() + "', address2 = '"
"', address2 = '" + employee.getAddress2() + + employee.getAddress2() + "', manager = "
"', manager = " + employee.getManager() + + employee.getManager()
", start_date = '" + employee.getStartDate() + + ", start_date = '"
"', ccn = '" + employee.getCcn() + + employee.getStartDate()
"', ccn_limit = " + employee.getCcnLimit() + + "', ccn = '"
+ employee.getCcn()
+ "', ccn_limit = "
+ employee.getCcnLimit()
+
// "', disciplined_date = '" + employee.getDisciplinaryActionDate() + // "', disciplined_date = '" + employee.getDisciplinaryActionDate() +
// "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() + // "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() +
", personal_description = '" + employee.getPersonalDescription() + ", personal_description = '"
"' WHERE userid = " + subjectId; + employee.getPersonalDescription() + "' WHERE userid = "
+ subjectId;
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
answer_statement.executeUpdate( query ); .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
} ResultSet.CONCUR_READ_ONLY);
catch ( SQLException sqle )
{
s.setMessage( "Error updating employee profile" );
sqle.printStackTrace();
}
}
catch ( Exception e )
{
s.setMessage( "Error updating employee profile" );
e.printStackTrace();
}
}
public void doChangeEmployeeProfile_BACKUP(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 = '" + employee.getFirstName() +
"', last_name = '" + employee.getLastName() +
"', ssn = '" + employee.getSsn() +
"', title = '" + employee.getTitle() +
"', phone = '" + employee.getPhoneNumber() +
"', address1 = '" + employee.getAddress1() +
"', address2 = '" + employee.getAddress2() +
"', manager = " + employee.getManager() +
", start_date = '" + employee.getStartDate() +
"', ccn = '" + employee.getCcn() +
"', ccn_limit = " + employee.getCcnLimit() +
// "', disciplined_date = '" + employee.getDisciplinaryActionDate() +
// "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() +
", personal_description = '" + employee.getPersonalDescription() +
"' WHERE userid = " + subjectId;
//System.out.println("Query: " + query);
try
{
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
answer_statement.executeUpdate(query); answer_statement.executeUpdate(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -243,36 +262,81 @@ public class UpdateProfile extends DefaultLessonAction
} }
public void createEmployeeProfile(WebSession s, int userId, Employee employee) public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId,
throws UnauthorizedException int subjectId, Employee employee) throws UnauthorizedException
{
try
{
// Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = '"
+ employee.getFirstName() + "', last_name = '"
+ employee.getLastName() + "', ssn = '" + employee.getSsn()
+ "', title = '" + employee.getTitle() + "', phone = '"
+ employee.getPhoneNumber() + "', address1 = '"
+ employee.getAddress1() + "', address2 = '"
+ employee.getAddress2() + "', manager = "
+ employee.getManager()
+ ", start_date = '"
+ employee.getStartDate()
+ "', ccn = '"
+ employee.getCcn()
+ "', ccn_limit = "
+ employee.getCcnLimit()
+
// "', disciplined_date = '" + employee.getDisciplinaryActionDate() +
// "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() +
", personal_description = '"
+ employee.getPersonalDescription() + "' WHERE userid = "
+ subjectId;
//System.out.println("Query: " + query);
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
answer_statement.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(WebSession s, int userId,
Employee employee) throws UnauthorizedException
{ {
try try
{ {
// FIXME: Cannot choose the id because we cannot guarantee uniqueness // FIXME: Cannot choose the id because we cannot guarantee uniqueness
String query = "INSERT INTO employee VALUES ( max(userid)+1, '" String query = "INSERT INTO employee VALUES ( max(userid)+1, '"
+ employee.getFirstName() + "','" + employee.getFirstName() + "','" + employee.getLastName()
+ employee.getLastName() + "','" + "','" + employee.getSsn() + "','"
+ employee.getSsn() + "','"
+ employee.getFirstName().toLowerCase() + "','" + employee.getFirstName().toLowerCase() + "','"
+ employee.getTitle() + "','" + employee.getTitle() + "','" + employee.getPhoneNumber()
+ employee.getPhoneNumber() + "','" + "','" + employee.getAddress1() + "','"
+ employee.getAddress1() + "','" + employee.getAddress2() + "'," + employee.getManager()
+ employee.getAddress2() + "'," + ",'" + employee.getStartDate() + "',"
+ employee.getManager() + ",'" + employee.getSalary() + ",'" + employee.getCcn() + "',"
+ employee.getStartDate() + "',"
+ employee.getSalary() + ",'"
+ employee.getCcn() + "',"
+ employee.getCcnLimit() + ",'" + employee.getCcnLimit() + ",'"
+ employee.getDisciplinaryActionDate() + "','" + employee.getDisciplinaryActionDate() + "','"
+ employee.getDisciplinaryActionNotes() + "','" + employee.getDisciplinaryActionNotes() + "','"
+ employee.getPersonalDescription() + employee.getPersonalDescription() + "')";
+ "')";
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement statement = WebSession.getConnection(s).createStatement(); Statement statement = WebSession.getConnection(s)
.createStatement();
statement.executeUpdate(query); statement.executeUpdate(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -288,36 +352,33 @@ public class UpdateProfile extends DefaultLessonAction
} }
} }
public void createEmployeeProfile_BACKUP(WebSession s, int userId, Employee employee)
throws UnauthorizedException public void createEmployeeProfile_BACKUP(WebSession s, int userId,
Employee employee) throws UnauthorizedException
{ {
try try
{ {
// FIXME: Cannot choose the id because we cannot guarantee uniqueness // FIXME: Cannot choose the id because we cannot guarantee uniqueness
String query = "INSERT INTO employee VALUES ( max(userid)+1, '" String query = "INSERT INTO employee VALUES ( max(userid)+1, '"
+ employee.getFirstName() + "','" + employee.getFirstName() + "','" + employee.getLastName()
+ employee.getLastName() + "','" + "','" + employee.getSsn() + "','"
+ employee.getSsn() + "','"
+ employee.getFirstName().toLowerCase() + "','" + employee.getFirstName().toLowerCase() + "','"
+ employee.getTitle() + "','" + employee.getTitle() + "','" + employee.getPhoneNumber()
+ employee.getPhoneNumber() + "','" + "','" + employee.getAddress1() + "','"
+ employee.getAddress1() + "','" + employee.getAddress2() + "'," + employee.getManager()
+ employee.getAddress2() + "'," + ",'" + employee.getStartDate() + "',"
+ employee.getManager() + ",'" + employee.getSalary() + ",'" + employee.getCcn() + "',"
+ employee.getStartDate() + "',"
+ employee.getSalary() + ",'"
+ employee.getCcn() + "',"
+ employee.getCcnLimit() + ",'" + employee.getCcnLimit() + ",'"
+ employee.getDisciplinaryActionDate() + "','" + employee.getDisciplinaryActionDate() + "','"
+ employee.getDisciplinaryActionNotes() + "','" + employee.getDisciplinaryActionNotes() + "','"
+ employee.getPersonalDescription() + employee.getPersonalDescription() + "')";
+ "')";
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement statement = WebSession.getConnection(s).createStatement(); Statement statement = WebSession.getConnection(s)
.createStatement();
statement.executeUpdate(query); statement.executeUpdate(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -334,7 +395,6 @@ public class UpdateProfile extends DefaultLessonAction
} }
/** /**
* Validates that the given parameter value matches the given regular expression pattern. * Validates that the given parameter value matches the given regular expression pattern.
* *
@ -343,7 +403,8 @@ public class UpdateProfile extends DefaultLessonAction
* @return * @return
* @throws ValidationException * @throws ValidationException
*/ */
protected String validate(final String parameter, final Pattern pattern) throws ValidationException protected String validate(final String parameter, final Pattern pattern)
throws ValidationException
{ {
Matcher matcher = pattern.matcher(parameter); Matcher matcher = pattern.matcher(parameter);
if (!matcher.matches()) if (!matcher.matches())

View File

@ -13,35 +13,72 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class ViewProfile extends DefaultLessonAction
{ {
public ViewProfile(AbstractLesson lesson, String lessonName, String actionName)
public ViewProfile(AbstractLesson lesson, String lessonName,
String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, 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()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.USER_ID);
int employeeId = -1; int employeeId = -1;
try try
{ {
// User selected employee // User selected employee
employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); employeeId = s.getParser().getIntParameter(
CrossSiteScripting.EMPLOYEE_ID);
} }
catch (ParameterNotFoundException e) catch (ParameterNotFoundException e)
{ {
// May be an internally selected employee // May be an internally selected employee
employeeId = getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); employeeId = getIntRequestAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ID);
} }
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
updateLessonStatus(s, employee); updateLessonStatus(s, employee);
} }
@ -49,43 +86,47 @@ public class ViewProfile extends DefaultLessonAction
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return CrossSiteScripting.VIEWPROFILE_ACTION; return CrossSiteScripting.VIEWPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, int userId,
int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +
@ -108,8 +149,9 @@ public class ViewProfile extends DefaultLessonAction
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId)
throws UnauthorizedException 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 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 // Query the database for the profile data of the given employee if "owned" by the given user
@ -119,30 +161,32 @@ public class ViewProfile extends DefaultLessonAction
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +
@ -166,31 +210,37 @@ public class ViewProfile extends DefaultLessonAction
} }
private void updateLessonStatus(WebSession s, Employee employee) private void updateLessonStatus(WebSession s, Employee employee)
{ {
switch (getStage(s)) switch (getStage(s))
{ {
case 1: case 1:
String address1 = employee.getAddress1().toLowerCase(); String address1 = employee.getAddress1().toLowerCase();
if (address1.indexOf("<script>") > -1 && address1.indexOf("alert") > -1 && address1.indexOf("</script>") > -1) if (address1.indexOf("<script>") > -1
&& address1.indexOf("alert") > -1
&& address1.indexOf("</script>") > -1)
{ {
s.setMessage( "Welcome to stage 2 - implement input validation" ); s
.setMessage("Welcome to stage 2 - implement input validation");
setStage(s, 2); setStage(s, 2);
} }
break; break;
case 3: case 3:
String address2 = employee.getAddress1().toLowerCase(); String address2 = employee.getAddress1().toLowerCase();
if (address2.indexOf("<script>") > -1 && address2.indexOf("alert") > -1 && address2.indexOf("</script>") > -1) if (address2.indexOf("<script>") > -1
&& address2.indexOf("alert") > -1
&& address2.indexOf("</script>") > -1)
{ {
s.setMessage( "Welcome to stage 4 - implement output encoding" ); s
.setMessage("Welcome to stage 4 - implement output encoding");
setStage(s, 4); setStage(s, 4);
} }
break; break;
case 4: case 4:
if (employee.getAddress1().toLowerCase().indexOf("&lt;") > -1) if (employee.getAddress1().toLowerCase().indexOf("&lt;") > -1)
{ {
s.setMessage( "Welcome to stage 5 - demonstrate reflected XSS" ); s
.setMessage("Welcome to stage 5 - demonstrate reflected XSS");
setStage(s, 5); setStage(s, 5);
} }
break; break;
@ -199,5 +249,4 @@ public class ViewProfile extends DefaultLessonAction
} }
} }
} }

View File

@ -15,12 +15,49 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
public class DOMInjection extends LessonAdapter { /*******************************************************************************
*
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Sherif Koussa <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @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";
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
String key = "K1JFWP8BSO8HI52LNPQS8F5L01N"; String key = "K1JFWP8BSO8HI52LNPQS8F5L01N";
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -29,11 +66,13 @@ public class DOMInjection extends LessonAdapter {
{ {
String userKey = s.getParser().getRawParameter(KEY, ""); String userKey = s.getParser().getRawParameter(KEY, "");
String fromAJAX = s.getParser().getRawParameter("from", ""); String fromAJAX = s.getParser().getRawParameter("from", "");
if (fromAJAX.equalsIgnoreCase("ajax") && userKey.length()!= 0 && userKey.equals(key)) if (fromAJAX.equalsIgnoreCase("ajax") && userKey.length() != 0
&& userKey.equals(key))
{ {
s.getResponse().setContentType("text/html"); s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse()
.getOutputStream());
out.print("document.forms[0].SUBMIT.disabled = false;"); out.print("document.forms[0].SUBMIT.disabled = false;");
out.flush(); out.flush();
out.close(); out.close();
@ -51,35 +90,36 @@ public class DOMInjection extends LessonAdapter {
} }
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep + String script = "<script>" + lineSep + "function validate() {"
"function validate() {" + lineSep + + lineSep + "var keyField = document.getElementById('key');"
"var keyField = document.getElementById('key');" + lineSep + + lineSep + "var url = '/WebGoat/attack?Screen="
"var url = '/WebGoat/attack?Screen=" + String.valueOf(getScreenId()) + + String.valueOf(getScreenId()) + "&menu="
"&menu=" + getDefaultCategory().getRanking().toString() + + getDefaultCategory().getRanking().toString()
"&from=ajax&key=' + encodeURIComponent(keyField.value);" + lineSep + + "&from=ajax&key=' + encodeURIComponent(keyField.value);"
"if (typeof XMLHttpRequest != 'undefined') {" + lineSep + + lineSep + "if (typeof XMLHttpRequest != 'undefined') {"
"req = new XMLHttpRequest();" + lineSep + + lineSep + "req = new XMLHttpRequest();" + lineSep
"} else if (window.ActiveXObject) {" + lineSep + + "} else if (window.ActiveXObject) {" + lineSep
"req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep + + "req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep
" }" + lineSep + + " }" + lineSep + " req.open('GET', url, true);" + lineSep
" req.open('GET', url, true);" + lineSep + + " req.onreadystatechange = callback;" + lineSep
" req.onreadystatechange = callback;" + lineSep + + " req.send(null);" + lineSep + "}" + lineSep
" req.send(null);" + lineSep + + "function callback() {" + lineSep
"}" + lineSep + + " if (req.readyState == 4) { " + lineSep
"function callback() {" + lineSep + + " if (req.status == 200) { " + lineSep
" if (req.readyState == 4) { " + lineSep + + " var message = req.responseText;" + lineSep
" if (req.status == 200) { " + lineSep + + " eval(message);" + lineSep + " }}}" + lineSep
" var message = req.responseText;" + lineSep + + "</script>" + lineSep;
" eval(message);" + lineSep +
" }}}" + lineSep +
"</script>" + lineSep;
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
ec.addElement( new BR().addElement (new H1().addElement( "Welcome to WebGoat Registration Page:"))); ec.addElement(new BR().addElement(new H1()
ec.addElement( new BR().addElement ("Please enter the license key that was emailed to you to start using the application.")); .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());
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("70%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
.setWidth("70%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD(new StringElement("License Key: "))); tr.addElement(new TD(new StringElement("License Key: ")));
@ -106,34 +146,45 @@ public class DOMInjection extends LessonAdapter {
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
return ec; return ec;
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return AJAX_SECURITY; return AJAX_SECURITY;
} }
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected List getHints() {
protected List getHints()
{
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("This page is using XMLHTTP to comunicate with the server."); 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
hints.add( "Intercept the reply and replace the body withx document.forms[0].SUBMIT.disabled = false;" ); .add("Try to find a way to inject the DOM to enable the Activate button.");
hints
.add("Intercept the reply and replace the body withx document.forms[0].SUBMIT.disabled = false;");
return hints; return hints;
} }
public String getTitle() {
public String getTitle()
{
return "DOM Injection"; return "DOM Injection";
} }

View File

@ -23,22 +23,46 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class DOS_Login extends LessonAdapter public class DOS_Login extends LessonAdapter
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String PASSWORD = "Password"; protected final static String PASSWORD = "Password";
/** /**
* Description of the Field * Description of the Field
*/ */
@ -67,62 +91,78 @@ public class DOS_Login extends LessonAdapter
// don;t allow user name from other lessons. it would be too simple. // don;t allow user name from other lessons. it would be too simple.
if (username.equals("jeff") || username.equals("dave")) if (username.equals("jeff") || username.equals("dave"))
{ {
ec.addElement( new H2( "Login Failed: 'jeff' and 'dave' are not valid for this lesson" )); ec
.addElement(new H2(
"Login Failed: 'jeff' and 'dave' are not valid for this lesson"));
return (ec.addElement(makeLogin(s))); return (ec.addElement(makeLogin(s)));
} }
// Check if the login is valid // Check if the login is valid
if (connection == null) if (connection == null)
{ {
connection = DatabaseUtilities.makeConnection(s); connection = DatabaseUtilities.makeConnection(s);
} }
String query = "SELECT * FROM user_system_data WHERE user_name = '" + username + "' and password = '" + password + "'" ; String query = "SELECT * FROM user_system_data WHERE user_name = '"
+ username + "' and password = '" + password + "'";
ec.addElement(new StringElement(query)); ec.addElement(new StringElement(query));
try try
{ {
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
if (results.getRow() >= 1) if (results.getRow() >= 1)
{ {
// Make sure this isn't data from an sql injected query. // Make sure this isn't data from an sql injected query.
if ( results.getString(2).equals( username ) && results.getString(3).equals( password ) ) if (results.getString(2).equals(username)
&& results.getString(3).equals(password))
{ {
String insertData1 = "INSERT INTO user_login VALUES ( '" + username + "', '" + s.getUserName() + "' )"; String insertData1 = "INSERT INTO user_login VALUES ( '"
+ username
+ "', '"
+ s.getUserName()
+ "' )";
statement.executeUpdate(insertData1); statement.executeUpdate(insertData1);
} }
// check the total count of logins // check the total count of logins
query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'" ; query = "SELECT * FROM user_login WHERE webgoat_user = '"
+ s.getUserName() + "'";
results = statement.executeQuery(query); results = statement.executeQuery(query);
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
if (results.getRow() >= 3) if (results.getRow() >= 3)
{ {
makeSuccess(s); makeSuccess(s);
String deleteData1 = "DELETE from user_login WHERE webgoat_user = '" + s.getUserName() + "'" ; String deleteData1 = "DELETE from user_login WHERE webgoat_user = '"
+ s.getUserName() + "'";
statement.executeUpdate(deleteData1); statement.executeUpdate(deleteData1);
return (new H1("Congratulations! Lesson Completed")); return (new H1("Congratulations! Lesson Completed"));
} }
ec.addElement( new H2( "Login Succeeded: Total login count: " + results.getRow() )); ec.addElement(new H2(
"Login Succeeded: Total login count: "
+ results.getRow()));
} }
} }
else else
{ {
ec.addElement(new H2("Login Failed")); ec.addElement(new H2("Login Failed"));
// check the total count of logins // check the total count of logins
query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'" ; query = "SELECT * FROM user_login WHERE webgoat_user = '"
+ s.getUserName() + "'";
results = statement.executeQuery(query); results = statement.executeQuery(query);
results.last(); results.last();
ec.addElement( new H2( "Successfull login count: " + results.getRow() )); ec.addElement(new H2("Successfull login count: "
+ results.getRow()));
} }
} }
@ -141,7 +181,6 @@ public class DOS_Login extends LessonAdapter
} }
/** /**
* Gets the category attribute of the WeakAuthenticationCookie object * Gets the category attribute of the WeakAuthenticationCookie object
* *
@ -153,7 +192,6 @@ public class DOS_Login extends LessonAdapter
} }
/** /**
* Gets the hints attribute of the CookieScreen object * Gets the hints attribute of the CookieScreen object
* *
@ -163,18 +201,22 @@ public class DOS_Login extends LessonAdapter
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Use a SQL Injection to obtain the user names. "); 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
hints.add( "Try &quot;dont_care' or '1' = '1&quot; in the password field"); .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 &quot;dont_care' or '1' = '1&quot; in the password field");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(90); private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CookieScreen object * Gets the title attribute of the CookieScreen object
* *
@ -223,6 +265,4 @@ public class DOS_Login extends LessonAdapter
return (ec); return (ec);
} }
} }

View File

@ -11,7 +11,35 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public abstract class DefaultLessonAction implements LessonAction public abstract class DefaultLessonAction implements LessonAction
{ {
// FIXME: We could parse this class name to get defaults for these fields. // FIXME: We could parse this class name to get defaults for these fields.

View File

@ -33,11 +33,34 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003

View File

@ -6,17 +6,41 @@ import java.util.List;
import org.apache.ecs.Element; import org.apache.ecs.Element;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class FailOpenAuthentication extends WeakAuthenticationCookie public class FailOpenAuthentication extends WeakAuthenticationCookie
{ {
/** /**
* Description of the Method * Description of the Method
* *
@ -56,12 +80,14 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
catch (Exception e) catch (Exception e)
{ {
// The parameter was omitted. set fail open status complete // The parameter was omitted. set fail open status complete
if ( username.length() > 0 && e.getMessage().indexOf( "not found") != -1 ) if (username.length() > 0
&& e.getMessage().indexOf("not found") != -1)
{ {
if ((username != null) && (username.length() > 0)) if ((username != null) && (username.length() > 0))
{ {
makeSuccess(s); makeSuccess(s);
return ( makeUser( s, username, "Fail Open Error Handling" ) ); return (makeUser(s, username,
"Fail Open Error Handling"));
} }
} }
} }
@ -84,7 +110,8 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
// otherwise authentication is good, show the content // otherwise authentication is good, show the content
if ((username != null) && (username.length() > 0)) if ((username != null) && (username.length() > 0))
{ {
return ( makeUser( s, username, "Parameters. You did not exploit the fail open." ) ); return (makeUser(s, username,
"Parameters. You did not exploit the fail open."));
} }
} }
catch (Exception e) catch (Exception e)
@ -116,8 +143,10 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("You can force errors during the authentication process."); hints.add("You can force errors during the authentication process.");
hints.add( "You can change length, existance, or values of authentication parameters." ); hints
hints.add( "Try removing a parameter ENTIRELY with <A href=\"http://www.owasp.org/development/webscarab\">WebScarab</A>." ); .add("You can change length, existance, or values of authentication parameters.");
hints
.add("Try removing a parameter ENTIRELY with <A href=\"http://www.owasp.org/development/webscarab\">WebScarab</A>.");
return hints; return hints;
} }
@ -130,20 +159,20 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
return "Due to an error handling problem in the authentication mechanism, it is possible to authenticate " + 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 " + + "as the 'webgoat' user without entering a password. Try to login as the webgoat user without "
"specifying a password."; + "specifying a password.";
} }
private final static Integer DEFAULT_RANKING = new Integer(20); private final static Integer DEFAULT_RANKING = new Integer(20);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AuthenticateScreen object * Gets the title attribute of the AuthenticateScreen object
* *
@ -154,4 +183,3 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
return ("How to Bypass a Fail Open Authentication Scheme"); return ("How to Bypass a Fail Open Authentication Scheme");
} }
} }

View File

@ -6,30 +6,52 @@ import java.util.List;
import org.apache.ecs.Element; import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement; import org.apache.ecs.StringElement;
import org.apache.ecs.html.B;
import org.apache.ecs.html.BR; import org.apache.ecs.html.BR;
import org.apache.ecs.html.H1; import org.apache.ecs.html.H1;
import org.apache.ecs.html.Input; import org.apache.ecs.html.Input;
import org.apache.ecs.html.TD; import org.apache.ecs.html.TD;
import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR; import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute
* this software.
* *
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* @author Sherif Koussa <a href="http://www.macadamian.com">Macadamian Technologies.</a> * @author Sherif Koussa <a href="http://www.macadamian.com">Macadamian Technologies.</a>
* @created November 02, 2006 * @created November 02, 2006
*/ */
public class ForcedBrowsing extends LessonAdapter public class ForcedBrowsing extends LessonAdapter
{ {
private final static String SUCCEEDED = "succeeded"; private final static String SUCCEEDED = "succeeded";
/** /**
* Description of the Method * Description of the Method
* *
@ -39,15 +61,19 @@ public class ForcedBrowsing extends LessonAdapter
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); 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")) if (success.length() != 0 && success.equals("yes"))
{ {
ec.addElement( new BR().addElement (new H1().addElement( "Welcome to WebGoat Configuration Page"))); ec.addElement(new BR().addElement(new H1()
.addElement("Welcome to WebGoat Configuration Page")));
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0)
.setBorder(0).setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TD( new StringElement( "Set Admin Privileges for: " ) )); tr.addElement(new TD(
new StringElement("Set Admin Privileges for: ")));
Input input1 = new Input(Input.TEXT, "", ""); Input input1 = new Input(Input.TEXT, "", "");
tr.addElement(new TD(input1)); tr.addElement(new TD(input1));
@ -68,7 +94,8 @@ public class ForcedBrowsing extends LessonAdapter
} }
else else
{ {
ec.addElement( "Can you try to force browse to the config page which " ec
.addElement("Can you try to force browse to the config page which "
+ "should only be accessed by maintenance personnel."); + "should only be accessed by maintenance personnel.");
} }
return ec; return ec;
@ -97,18 +124,21 @@ public class ForcedBrowsing extends LessonAdapter
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Try to guess the URL for the config page"); hints.add("Try to guess the URL for the config page");
hints.add("The config page is guessable and hackable"); hints.add("The config page is guessable and hackable");
hints.add( "Play with the URL and try to guess what the can you replace 'attack' with." ); hints
.add("Play with the URL and try to guess what the can you replace 'attack' with.");
hints.add("Try to navigate to http://localhost/WebGoat/config"); hints.add("Try to navigate to http://localhost/WebGoat/config");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(15); private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -119,8 +149,9 @@ public class ForcedBrowsing extends LessonAdapter
return ("Forced Browsing"); return ("Forced Browsing");
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }
} }

View File

@ -20,26 +20,59 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Eric Sheridan <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Eric Sheridan <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created December 18, 2005 * @created December 18, 2005
*/ */
public class ForgotPassword extends LessonAdapter public class ForgotPassword extends LessonAdapter
{ {
final static IMG ASPECT_LOGO = new IMG( "images/logos/aspect.jpg" ).setAlt( "Aspect Security" ).setBorder( 0 ).setHspace( 0 ).setVspace( 0 );
final static IMG ASPECT_LOGO = 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<String, String> USERS = new HashMap<String, String>(); private final static HashMap<String, String> USERS = new HashMap<String, String>();
private final static HashMap<String, String> COLORS = new HashMap<String, String>(); private final static HashMap<String, String> COLORS = new HashMap<String, String>();
private void populateTables() private void populateTables()
{ {
USERS.put("admin", "2275$starBo0rn3"); USERS.put("admin", "2275$starBo0rn3");
@ -55,12 +88,15 @@ public class ForgotPassword extends LessonAdapter
COLORS.put("webgoat", "red"); COLORS.put("webgoat", "red");
} }
protected Element doStage1(WebSession s) protected Element doStage1(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement( new BR().addElement( new H1().addElement( "Webgoat Password Recovery " ))); ec.addElement(new BR().addElement(new H1()
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 2 ).setBorder( 0 ).setWidth("90%").setAlign("center"); .addElement("Webgoat Password Recovery ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
.setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
@ -68,7 +104,10 @@ public class ForgotPassword extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Please input your username. See the OWASP admin if you do not have an account.") tr
.addElement(new TH()
.addElement(
"Please input your username. See the OWASP admin if you do not have an account.")
.setColSpan(2).setAlign("left")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
@ -95,13 +134,13 @@ public class ForgotPassword extends LessonAdapter
} }
protected Element doStage2(WebSession s) protected Element doStage2(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Webgoat Password Recovery ")); ec.addElement(new H1().addElement("Webgoat Password Recovery "));
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())
{ {
@ -109,8 +148,9 @@ public class ForgotPassword extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Secret Question: What is your favorite color?") tr.addElement(new TH().addElement(
.setColSpan(2).setAlign("left")); "Secret Question: What is your favorite color?").setColSpan(2)
.setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
@ -135,12 +175,14 @@ public class ForgotPassword extends LessonAdapter
return (ec); return (ec);
} }
protected Element doStage3(WebSession s) protected Element doStage3(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Webgoat Password Recovery ")); ec.addElement(new H1().addElement("Webgoat Password Recovery "));
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())
{ {
@ -148,24 +190,32 @@ public class ForgotPassword extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("For security reasons, please change your password immediately.") tr
.addElement(new TH()
.addElement(
"For security reasons, please change your password immediately.")
.setColSpan(2).setAlign("left")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new 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); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( new StringElement("Username: " + USERNAME_RESPONSE))); tr.addElement(new TD().addElement(new StringElement("Username: "
+ USERNAME_RESPONSE)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement( new StringElement("Color: " + COLOR_RESPONSE))); tr.addElement(new TD().addElement(new StringElement("Color: "
+ COLOR_RESPONSE)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement( new StringElement("Password: " + USERS.get(USERNAME_RESPONSE).toString()))); tr.addElement(new TD().addElement(new StringElement("Password: "
+ USERS.get(USERNAME_RESPONSE).toString())));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
@ -174,13 +224,16 @@ public class ForgotPassword extends LessonAdapter
{ {
makeSuccess(s); makeSuccess(s);
} }
else if(!USERNAME_RESPONSE.equals("webgoat") && USERS.containsKey(USERNAME_RESPONSE)) 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; return ec;
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -200,7 +253,6 @@ public class ForgotPassword extends LessonAdapter
else else
STAGE = 1; STAGE = 1;
if (USERS.size() == 0) if (USERS.size() == 0)
{ {
populateTables(); populateTables();
@ -218,7 +270,8 @@ public class ForgotPassword extends LessonAdapter
} }
else else
{ {
s.setMessage("Incorrect response for " + USERNAME_RESPONSE + ". Please try again!"); s.setMessage("Incorrect response for " + USERNAME_RESPONSE
+ ". Please try again!");
ec.addElement(doStage2(s)); ec.addElement(doStage2(s));
} }
} }
@ -269,24 +322,25 @@ public class ForgotPassword extends LessonAdapter
public List getHints() public List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "There is no lock out policy in place, brute force your way!" ); hints
hints.add( "Try using usernames you might encounter throughout WebGoat." ); .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("There are only so many possible colors, can you guess one?");
hints.add("The administrative account is \"admin\""); hints.add("The administrative account is \"admin\"");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(15); private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -303,4 +357,3 @@ public class ForgotPassword extends LessonAdapter
return super.getCustomCredits("The Intern", ASPECT_LOGO); return super.getCustomCredits("The Intern", ASPECT_LOGO);
} }
} }

View File

@ -18,28 +18,54 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class HiddenFieldTampering extends LessonAdapter public class HiddenFieldTampering extends LessonAdapter
{ {
private final static String PRICE = "Price"; private final static String PRICE = "Price";
private final static String PRICE_TV = "2999.99"; private final static String PRICE_TV = "2999.99";
private final static String PRICE_TV_HACKED = "9.99"; private final static String PRICE_TV_HACKED = "9.99";
/** /**
* Constructor for the HiddenFieldScreen object * Constructor for the HiddenFieldScreen object
*/ */
public HiddenFieldTampering() { } public HiddenFieldTampering()
{}
/** /**
* Description of the Method * Description of the Method
@ -59,9 +85,11 @@ public class HiddenFieldTampering extends LessonAdapter
if (price.equals(PRICE_TV)) if (price.equals(PRICE_TV))
{ {
ec.addElement( new Center().addElement( new H1().addElement( "Shopping Cart " ))); ec.addElement(new Center().addElement(new H1()
.addElement("Shopping Cart ")));
ec.addElement(new BR()); ec.addElement(new BR());
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())
{ {
@ -69,22 +97,26 @@ public class HiddenFieldTampering extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); tr.addElement(new TH().addElement(
"Shopping Cart Items -- To Buy Now").setWidth("80%"));
tr.addElement(new TH().addElement("Price:").setWidth("10%")); tr.addElement(new TH().addElement("Price:").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity:").setWidth("3%")); tr.addElement(new TH().addElement("Quantity:").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%")); tr.addElement(new TH().addElement("Total").setWidth("7%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement("56 inch HDTV (model KTV-551)")); tr.addElement(new TD()
.addElement("56 inch HDTV (model KTV-551)"));
tr.addElement(new TD().addElement(PRICE_TV).setAlign("right")); tr.addElement(new TD().addElement(PRICE_TV).setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY", 1 )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY", 1)).setAlign("right"));
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); 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()) if (s.isColor())
{ {
@ -93,10 +125,13 @@ public class HiddenFieldTampering extends LessonAdapter
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "The total charged to your credit card:" ) ); tr.addElement(new TD()
.addElement("The total charged to your credit card:"));
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
tr.addElement( new TD().addElement( ECSFactory.makeButton( "Update Cart" ))); tr.addElement(new TD().addElement(ECSFactory
tr.addElement( new TD().addElement( ECSFactory.makeButton( "Purchase" ))); .makeButton("Update Cart")));
tr.addElement(new TD().addElement(ECSFactory
.makeButton("Purchase")));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
@ -116,7 +151,9 @@ public class HiddenFieldTampering extends LessonAdapter
ec.addElement(new P().addElement("Your total price is:")); ec.addElement(new P().addElement("Your total price is:"));
ec.addElement(new B("$" + total)); ec.addElement(new B("$" + total));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement( new P().addElement( "This amount will be charged to your credit card immediately." ) ); ec
.addElement(new P()
.addElement("This amount will be charged to your credit card immediately."));
} }
} }
catch (Exception e) catch (Exception e)
@ -148,10 +185,13 @@ public class HiddenFieldTampering extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "This application is using hidden fields to transmit price information to the server." ); hints
hints.add( "Use a program to intercept and change the value in the hidden field." ); .add("This application is using hidden fields to transmit price information to the server.");
hints.add( "Use <A href=\"http://www.owasp.org/development/webscarab\">WebScarab</A> to change the price of the TV from " + hints
PRICE_TV + " to " + PRICE_TV_HACKED + "." ); .add("Use a program to intercept and change the value in the hidden field.");
hints
.add("Use <A href=\"http://www.owasp.org/development/webscarab\">WebScarab</A> to change the price of the TV from "
+ PRICE_TV + " to " + PRICE_TV_HACKED + ".");
return hints; return hints;
} }
@ -169,16 +209,15 @@ public class HiddenFieldTampering extends LessonAdapter
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(50); private final static Integer DEFAULT_RANKING = new Integer(50);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HiddenFieldScreen object * Gets the title attribute of the HiddenFieldScreen object
* *
@ -189,4 +228,3 @@ public class HiddenFieldTampering extends LessonAdapter
return ("How to Exploit Hidden Fields"); return ("How to Exploit Hidden Fields");
} }
} }

View File

@ -19,25 +19,52 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class HtmlClues extends LessonAdapter public class HtmlClues extends LessonAdapter
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String PASSWORD = "Password"; protected final static String PASSWORD = "Password";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String USERNAME = "Username"; protected final static String USERNAME = "Username";
/** /**
* Description of the Method * Description of the Method
* *
@ -102,11 +129,13 @@ public class HtmlClues extends LessonAdapter
* @return Description of the Return Value * @return Description of the Return Value
* @exception Exception Description of the Exception * @exception Exception Description of the Exception
*/ */
protected Element makeUser( WebSession s, String user, String method ) throws Exception protected Element makeUser(WebSession s, String user, String method)
throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement("Welcome, " + user)); ec.addElement(new P().addElement("Welcome, " + user));
ec.addElement( new P().addElement( "You have been authenticated with " + method ) ); ec.addElement(new P().addElement("You have been authenticated with "
+ method));
return (ec); return (ec);
} }
@ -117,7 +146,8 @@ public class HtmlClues extends LessonAdapter
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Sign In ")); 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()) if (s.isColor())
{ {
@ -125,7 +155,10 @@ public class HtmlClues extends LessonAdapter
} }
TR tr = new TR(); 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.") 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")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
@ -156,6 +189,7 @@ public class HtmlClues extends LessonAdapter
return (ec); return (ec);
} }
/** /**
* Gets the hints attribute of the CluesScreen object * Gets the hints attribute of the CluesScreen object
* *
@ -164,9 +198,11 @@ public class HtmlClues extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "You can view the HTML source by selecting 'view source' in the browser menu." ); 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("There are lots of clues in the HTML");
hints.add( "Search for the word HIDDEN, look at URLs, look for comments." ); hints
.add("Search for the word HIDDEN, look at URLs, look for comments.");
return hints; return hints;
} }
@ -184,16 +220,15 @@ public class HtmlClues extends LessonAdapter
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(30); private final static Integer DEFAULT_RANKING = new Integer(30);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the category attribute of the FailOpenAuthentication object * Gets the category attribute of the FailOpenAuthentication object
* *
@ -204,6 +239,7 @@ public class HtmlClues extends LessonAdapter
return AbstractLesson.CODE_QUALITY; return AbstractLesson.CODE_QUALITY;
} }
/** /**
* Gets the title attribute of the CluesScreen object * Gets the title attribute of the CluesScreen object
* *
@ -214,4 +250,3 @@ public class HtmlClues extends LessonAdapter
return ("How to Discover Clues in the HTML"); return ("How to Discover Clues in the HTML");
} }
} }

View File

@ -9,17 +9,41 @@ import org.apache.ecs.StringElement;
import org.apache.ecs.html.Input; import org.apache.ecs.html.Input;
import org.owasp.webgoat.session.*; import org.owasp.webgoat.session.*;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class HttpBasics extends LessonAdapter public class HttpBasics extends LessonAdapter
{ {
private final static String PERSON = "person"; private final static String PERSON = "person";
@ -38,7 +62,8 @@ public class HttpBasics extends LessonAdapter
{ {
ec.addElement(new StringElement("Enter your name: ")); ec.addElement(new StringElement("Enter your name: "));
person = new StringBuffer( s.getParser().getStringParameter( PERSON, "" ) ); person = new StringBuffer(s.getParser().getStringParameter(PERSON,
""));
person.reverse(); person.reverse();
Input input = new Input(Input.TEXT, PERSON, person.toString()); Input input = new Input(Input.TEXT, PERSON, person.toString());
@ -53,7 +78,8 @@ public class HttpBasics extends LessonAdapter
e.printStackTrace(); e.printStackTrace();
} }
if ( !person.toString().equals( "" ) && getLessonTracker( s ).getNumVisits() > 3 ) if (!person.toString().equals("")
&& getLessonTracker(s).getNumVisits() > 3)
{ {
makeSuccess(s); makeSuccess(s);
} }
@ -61,6 +87,7 @@ public class HttpBasics extends LessonAdapter
return (ec); return (ec);
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
@ -76,7 +103,6 @@ public class HttpBasics extends LessonAdapter
return hints; return hints;
} }
/** /**
* Gets the ranking attribute of the HelloScreen object * Gets the ranking attribute of the HelloScreen object
* *
@ -84,11 +110,13 @@ public class HttpBasics extends LessonAdapter
*/ */
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.GENERAL; return AbstractLesson.GENERAL;
@ -105,4 +133,3 @@ public class HttpBasics extends LessonAdapter
return ("Http Basics"); return ("Http Basics");
} }
} }

View File

@ -18,7 +18,35 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import sun.misc.BASE64Encoder; 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/
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class HttpOnly extends LessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(125); private final static Integer DEFAULT_RANKING = new Integer(125);

View File

@ -1,4 +1,5 @@
package org.owasp.webgoat.lessons; package org.owasp.webgoat.lessons;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.text.DateFormat; import java.text.DateFormat;
@ -12,23 +13,49 @@ import org.apache.ecs.html.*;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the *
* custody of the Open Web Application Security Project *
* (http://www.owasp.org) This software package is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you * utility. For details, please see http://www.owasp.org/
* use, modify and/or redistribute this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author sherif@macadamian.com * @author sherif@macadamian.com
* @created September 30, 2006 * @created September 30, 2006
*/ */
public class HttpSplitting extends LessonAdapter { public class HttpSplitting extends LessonAdapter
{
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";
/** /**
* Description of the Method * Description of the Method
* *
@ -37,16 +64,17 @@ public class HttpSplitting extends LessonAdapter {
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
//Setting a special action to be able to submit to redirect.jsp //Setting a special action to be able to submit to redirect.jsp
Form form = new Form( "/WebGoat/lessons/General/redirect.jsp?" + Form form = new Form("/WebGoat/lessons/General/redirect.jsp?"
"Screen=" + String.valueOf(getScreenId()) + + "Screen=" + String.valueOf(getScreenId()) + "&menu="
"&menu=" + getDefaultCategory().getRanking().toString() + getDefaultCategory().getRanking().toString(), Form.POST)
, Form.POST ).setName( "form" ).setEncType( "" ); .setName("form").setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
protected Element doHTTPSplitting(WebSession s) protected Element doHTTPSplitting(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -55,21 +83,24 @@ public class HttpSplitting extends LessonAdapter {
try try
{ {
ec.addElement(createAttackEnvironment(s)); ec.addElement(createAttackEnvironment(s));
lang = URLDecoder.decode(s.getParser().getRawParameter( LANGUAGE, "" ), "UTF-8") ; lang = URLDecoder.decode(s.getParser()
.getRawParameter(LANGUAGE, ""), "UTF-8");
//Check if we are coming from the redirect page //Check if we are coming from the redirect page
String fromRedirect = s.getParser().getStringParameter ( "fromRedirect" , ""); String fromRedirect = s.getParser().getStringParameter(
"fromRedirect", "");
if (lang.length() != 0 && fromRedirect.length() != 0) if (lang.length() != 0 && fromRedirect.length() != 0)
{ {
//Split by the line separator line.separator is platform independant //Split by the line separator line.separator is platform independant
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String[] arrTokens = lang.toString().toUpperCase().split(lineSep); String[] arrTokens = lang.toString().toUpperCase().split(
lineSep);
//Check if the user ended the first request and wrote the second malacious reply //Check if the user ended the first request and wrote the second malacious reply
if (Arrays.binarySearch(arrTokens, "CONTENT-LENGTH: 0") >= 0 && if (Arrays.binarySearch(arrTokens, "CONTENT-LENGTH: 0") >= 0
Arrays.binarySearch(arrTokens, "HTTP/1.1 200 OK") >= 0 ) && Arrays.binarySearch(arrTokens, "HTTP/1.1 200 OK") >= 0)
{ {
HttpServletResponse res = s.getResponse(); HttpServletResponse res = s.getResponse();
res.setContentType("text/html"); res.setContentType("text/html");
@ -85,9 +116,12 @@ public class HttpSplitting extends LessonAdapter {
StringBuffer msg = new StringBuffer(); StringBuffer msg = new StringBuffer();
msg.append("Good Job! "); msg.append("Good Job! ");
msg.append("This lesson has detected your successfull attack, "); msg
msg.append("time to elevate your attack to a higher level. "); .append("This lesson has detected your successfull attack, ");
msg.append("Try again and add Last-Modified header, intercept"); 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."); msg.append("the reply and replace it with a 304 reply.");
s.setMessage(msg.toString()); s.setMessage(msg.toString());
@ -102,21 +136,26 @@ public class HttpSplitting extends LessonAdapter {
} }
return (ec); return (ec);
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return doHTTPSplitting(s); return doHTTPSplitting(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return doCachePoisining(s); return doCachePoisining(s);
} }
protected Element createAttackEnvironment(WebSession s) throws Exception protected Element createAttackEnvironment(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -132,7 +171,8 @@ public class HttpSplitting extends LessonAdapter {
} }
ec.addElement(new StringElement("Search by country : ")); ec.addElement(new StringElement("Search by country : "));
lang = URLDecoder.decode(s.getParser().getRawParameter( LANGUAGE, "" ), "UTF-8") ; lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""),
"UTF-8");
//add the search by field //add the search by field
Input input = new Input(Input.TEXT, LANGUAGE, lang.toString()); Input input = new Input(Input.TEXT, LANGUAGE, lang.toString());
@ -145,35 +185,43 @@ public class HttpSplitting extends LessonAdapter {
return ec; return ec;
} }
protected Element doCachePoisining(WebSession s) throws Exception protected Element doCachePoisining(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
s.setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison" + s
" the victim's cache. Type 'restart' in the input field if you wish to " + .setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison"
" to return to the HTTP Splitting lesson.<br><br>"); + " the victim's cache. Type 'restart' in the input field if you wish to "
if ( s.getParser().getRawParameter( LANGUAGE, "YOUR_NAME" ).equals("restart")) + " to return to the HTTP Splitting lesson.<br><br>");
if (s.getParser().getRawParameter(LANGUAGE, "YOUR_NAME").equals(
"restart"))
{ {
getLessonTracker(s).getLessonProperties().setProperty(STAGE,"1"); getLessonTracker(s).getLessonProperties().setProperty(STAGE,
"1");
return (doHTTPSplitting(s)); return (doHTTPSplitting(s));
} }
ec.addElement(createAttackEnvironment(s)); ec.addElement(createAttackEnvironment(s));
String lang = URLDecoder.decode(s.getParser().getRawParameter( LANGUAGE, "" ), "UTF-8") ; String lang = URLDecoder.decode(s.getParser().getRawParameter(
String fromRedirect = s.getParser().getStringParameter ( REDIRECT , ""); LANGUAGE, ""), "UTF-8");
String fromRedirect = s.getParser()
.getStringParameter(REDIRECT, "");
if (lang.length() != 0 && fromRedirect.length() != 0) if (lang.length() != 0 && fromRedirect.length() != 0)
{ {
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String dateStr = lang.substring(lang.indexOf("Last-Modified:") + "Last-Modified:".length(), String dateStr = lang.substring(lang.indexOf("Last-Modified:")
lang.indexOf(lineSep, lang.indexOf("Last-Modified:") )); + "Last-Modified:".length(), lang.indexOf(lineSep, lang
.indexOf("Last-Modified:")));
if (dateStr.length() != 0) if (dateStr.length() != 0)
{ {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); DateFormat sdf = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
if (sdf.parse(dateStr.trim()).after(cal.getTime())) if (sdf.parse(dateStr.trim()).after(cal.getTime()))
{ {
@ -189,35 +237,45 @@ public class HttpSplitting extends LessonAdapter {
return ec; return ec;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.GENERAL; return AbstractLesson.GENERAL;
} }
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Enter a language for the system to search by."); 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("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("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("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&lt;html&gt;Insert undesireable content here&lt;/html&gt;" ); hints
hints.add( "Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date." ); .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&lt;html&gt;Insert undesireable content here&lt;/html&gt;");
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&lt;html&gt;Insert undesireable content here&lt;/html&gt;" ); hints
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"); .add("Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date.");
hints.add( "Try to intercept the reply and add HTTP/1.1 304 Not Modified0d%0aDate:%20Mon,%2027%20Oct%202030%2014:50:18%20GMT"); 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&lt;html&gt;Insert undesireable content here&lt;/html&gt;");
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; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(20); private final static Integer DEFAULT_RANKING = new Integer(20);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -228,7 +286,9 @@ public class HttpSplitting extends LessonAdapter {
return ("HTTP Splitting"); return ("HTTP Splitting");
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }

View File

@ -17,41 +17,73 @@ import java.io.PrintWriter;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
public class JSONInjection extends LessonAdapter { /*******************************************************************************
*
private final static Integer DEFAULT_RANKING = new Integer(30); *
private final static String TRAVEL_FROM = "travelFrom"; * This file is part of WebGoat, an Open Web Application Security Project
private final static String TRAVEL_TO = "travelTo"; * utility. For details, please see http://www.owasp.org/
*
/** * Copyright (c) 2002 - 2007 Bruce Mayhew
* Copyright (c) 2002 Free Software Foundation developed under the *
* custody of the Open Web Application Security Project * This program is free software; you can redistribute it and/or modify it under
* (http://www.owasp.org) This software package is published by OWASP * the terms of the GNU General Public License as published by the Free Software
* under the GPL. You should read and accept the LICENSE before you * Foundation; either version 2 of the License, or (at your option) any later
* use, modify and/or redistribute this software. * version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author sherif@macadamian.com * @author sherif@macadamian.com
* @created December 25, 2006 * @created December 25, 2006
*/ */
public void handleRequest(WebSession s) { public class JSONInjection extends LessonAdapter
{
private final static Integer DEFAULT_RANKING = new Integer(30);
private final static String TRAVEL_FROM = "travelFrom";
private final static String TRAVEL_TO = "travelTo";
public void handleRequest(WebSession s)
{
try try
{ {
if (s.getParser().getRawParameter("from", "").equals("ajax")) if (s.getParser().getRawParameter("from", "").equals("ajax"))
{ {
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String jsonStr = "{" + lineSep + String jsonStr = "{"
"\"From\": \"Boston\"," + lineSep + + lineSep
"\"To\": \"Seattle\", " + lineSep + + "\"From\": \"Boston\","
"\"flights\": [" + lineSep + + lineSep
"{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"600$\"}," + lineSep + + "\"To\": \"Seattle\", "
"{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"300$\"} " + lineSep + + lineSep
"]" + 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().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse()
.getOutputStream());
out.print(jsonStr); out.print(jsonStr);
out.flush(); out.flush();
out.close(); out.close();
@ -63,7 +95,8 @@ public class JSONInjection extends LessonAdapter {
ex.printStackTrace(); ex.printStackTrace();
} }
Form form = new Form( getFormAction(), Form.POST ).setName( "form" ).setEncType( "" ); Form form = new Form(getFormAction(), Form.POST).setName("form")
.setEncType("");
form.setOnSubmit("check();"); form.setOnSubmit("check();");
form.addElement(createContent(s)); form.addElement(createContent(s));
@ -72,6 +105,7 @@ public class JSONInjection extends LessonAdapter {
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -82,56 +116,106 @@ public class JSONInjection extends LessonAdapter {
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep + String script = "<script>"
"function getFlights() {" + lineSep + + lineSep
"var fromField = document.getElementById('" + TRAVEL_FROM + "');" + lineSep + + "function getFlights() {"
"if (fromField.value.length < 3 ) { return; }" + lineSep + + lineSep
"var toField = document.getElementById('" + TRAVEL_TO + "');" + lineSep + + "var fromField = document.getElementById('"
"if (toField.value.length < 3 ) { return; }" + lineSep + + TRAVEL_FROM
"var url = '/WebGoat/attack?Screen=" + String.valueOf(getScreenId()) + + "');"
"&menu=" + getDefaultCategory().getRanking().toString() + + lineSep
"&from=ajax&" + TRAVEL_FROM + "=' + encodeURIComponent(fromField.value) +" + + "if (fromField.value.length < 3 ) { return; }"
"'&" + TRAVEL_TO + "=' + encodeURIComponent(toField.value);" + lineSep + + lineSep
"if (typeof XMLHttpRequest != 'undefined') {" + lineSep + + "var toField = document.getElementById('"
"req = new XMLHttpRequest();" + lineSep + + TRAVEL_TO
"} else if (window.ActiveXObject) {" + lineSep + + "');"
"req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep + + lineSep
" }" + lineSep + + "if (toField.value.length < 3 ) { return; }"
" req.open('GET', url, true);" + lineSep + + lineSep
" req.onreadystatechange = callback;" + lineSep + + "var url = '/WebGoat/attack?Screen="
" req.send(null);" + lineSep + + String.valueOf(getScreenId())
"}" + lineSep + + "&menu="
"function callback() {" + lineSep + + getDefaultCategory().getRanking().toString()
" if (req.readyState == 4) { " + lineSep + + "&from=ajax&"
" if (req.status == 200) { " + lineSep + + TRAVEL_FROM
" var card = eval('(' + req.responseText + ')');" + lineSep + + "=' + encodeURIComponent(fromField.value) +"
" var flightsDiv = document.getElementById('flightsDiv');" + lineSep + + "'&"
" flightsDiv.innerHTML = '';" + lineSep + + TRAVEL_TO
" var strHTML='';"+ lineSep + + "=' + encodeURIComponent(toField.value);"
" strHTML = '<tr><td>&nbsp;</td><td>No of Stops</td>';" + lineSep + + lineSep
" strHTML = strHTML + '<td>Stops</td><td>Prices</td></tr>';" + lineSep + + "if (typeof XMLHttpRequest != 'undefined') {"
" for(var i=0; i<card.flights.length; i++){" + lineSep + + lineSep
" var node = card.flights[i];" + lineSep + + "req = new XMLHttpRequest();"
" strHTML = strHTML + '<tr><td><input name=\"radio' + i +'\" type=\"radio\"></td><td>';" + lineSep + + lineSep
" strHTML = strHTML + card.flights[i].stops + '</td><td>';" + lineSep + + "} else if (window.ActiveXObject) {"
" strHTML = strHTML + card.flights[i].transit + '</td><td>';" + lineSep + + lineSep
" strHTML = strHTML + '<div name=\"priceID'+i+'\" id=\"priceID'+i+'\">' + card.flights[i].price + '</div></td></tr>';" + lineSep + + "req = new ActiveXObject('Microsoft.XMLHTTP');"
" }" + lineSep + + lineSep
" strHTML = '<table border=\"1\">' + strHTML + '</table>';" + lineSep + + " }"
" flightsDiv.innerHTML = strHTML;"+ lineSep + + lineSep
" }}}" + lineSep + + " req.open('GET', url, true);"
+ lineSep
+ " req.onreadystatechange = callback;"
+ lineSep
+ " req.send(null);"
+ lineSep
+ "}"
+ lineSep
+ "function callback() {"
+ lineSep
+ " if (req.readyState == 4) { "
+ lineSep
+ " if (req.status == 200) { "
+ lineSep
+ " var card = eval('(' + req.responseText + ')');"
+ lineSep
+ " var flightsDiv = document.getElementById('flightsDiv');"
+ lineSep
+ " flightsDiv.innerHTML = '';"
+ lineSep
+ " var strHTML='';"
+ lineSep
+ " strHTML = '<tr><td>&nbsp;</td><td>No of Stops</td>';"
+ lineSep
+ " strHTML = strHTML + '<td>Stops</td><td>Prices</td></tr>';"
+ lineSep
+ " for(var i=0; i<card.flights.length; i++){"
+ lineSep
+ " var node = card.flights[i];"
+ lineSep
+ " strHTML = strHTML + '<tr><td><input name=\"radio' + i +'\" type=\"radio\"></td><td>';"
+ lineSep
+ " strHTML = strHTML + card.flights[i].stops + '</td><td>';"
+ lineSep
+ " strHTML = strHTML + card.flights[i].transit + '</td><td>';"
+ lineSep
+ " strHTML = strHTML + '<div name=\"priceID'+i+'\" id=\"priceID'+i+'\">' + card.flights[i].price + '</div></td></tr>';"
+ lineSep
+ " }"
+ lineSep
+ " strHTML = '<table border=\"1\">' + strHTML + '</table>';"
+ lineSep
+ " flightsDiv.innerHTML = strHTML;"
+ lineSep
+ " }}}"
+ lineSep
+
"function check(){" + lineSep + "function check(){"
" if ( document.getElementById('radio0').checked )" + lineSep + + lineSep
" { document.getElementById('price2Submit').value = document.getElementById('priceID0').innerText; }" + lineSep + + " if ( document.getElementById('radio0').checked )"
" else if ( document.getElementById('radio1').checked )" + lineSep + + lineSep
" { document.getElementById('price2Submit').value = document.getElementById('priceID1').innerText; }" + lineSep + + " { document.getElementById('price2Submit').value = document.getElementById('priceID0').innerText; }"
" else " + lineSep + + lineSep
" { alert('Please choose one flight'); }" + lineSep + + " else if ( document.getElementById('radio1').checked )"
"}" + lineSep + + lineSep
"</script>" + lineSep; + " { document.getElementById('price2Submit').value = document.getElementById('priceID1').innerText; }"
+ lineSep + " else " + lineSep
+ " { alert('Please choose one flight'); }" + lineSep + "}"
+ lineSep + "</script>" + lineSep;
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
.setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
@ -179,17 +263,23 @@ public class JSONInjection extends LessonAdapter {
} }
else else
{ {
s.setMessage("You are close, try to set the price for the non-stop flight to be less than 600$"); s
.setMessage("You are close, try to set the price for the non-stop flight to be less than 600$");
} }
} }
return ec; return ec;
} }
public Element getCredits() {
return new StringElement("Created by Sherif Koussa");
}
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.AJAX_SECURITY; return AbstractLesson.AJAX_SECURITY;
} }
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
@ -201,11 +291,13 @@ public class JSONInjection extends LessonAdapter {
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -216,8 +308,4 @@ public class JSONInjection extends LessonAdapter {
return ("JSON Injection"); return ("JSON Injection");
} }
public Element getCredits() {
return new StringElement("Created by Sherif Koussa");
}
} }

View File

@ -14,12 +14,34 @@ import org.apache.ecs.html.TextArea;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
@ -45,7 +67,6 @@ public class JavaScriptValidation extends LessonAdapter
// you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one for JavaScript // 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 regex1 = "^[a-z]{3}$";// any three lowercase letters
String regex2 = "^[0-9]{3}$";// any three digits String regex2 = "^[0-9]{3}$";// any three digits
String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation
@ -61,36 +82,68 @@ public class JavaScriptValidation extends LessonAdapter
Pattern pattern6 = Pattern.compile(regex6); Pattern pattern6 = Pattern.compile(regex6);
Pattern pattern7 = Pattern.compile(regex7); Pattern pattern7 = Pattern.compile(regex7);
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<SCRIPT>" + lineSep + String script = "<SCRIPT>"
"regex1=/" + regex1 + "/;" + lineSep + + lineSep
"regex2=/" + regex2 + "/;" + lineSep + + "regex1=/"
"regex3=/" + regex3 + "/;" + lineSep + + regex1
"regex4=/" + regex4 + "/;" + lineSep + + "/;"
"regex5=/" + regex5 + "/;" + lineSep + + lineSep
"regex6=/" + regex6 + "/;" + lineSep + + "regex2=/"
"regex7=/" + regex7 + "/;" + lineSep + + regex2
"function validate() { " + lineSep + + "/;"
"msg='JavaScript found form errors'; err=0; " + lineSep + + lineSep
"if (!regex1.test(document.form.field1.value)) {err+=1; msg+='\\n bad field1';}" + lineSep + + "regex3=/"
"if (!regex2.test(document.form.field2.value)) {err+=1; msg+='\\n bad field2';}" + lineSep + + regex3
"if (!regex3.test(document.form.field3.value)) {err+=1; msg+='\\n bad field3';}" + lineSep + + "/;"
"if (!regex4.test(document.form.field4.value)) {err+=1; msg+='\\n bad field4';}" + lineSep + + lineSep
"if (!regex5.test(document.form.field5.value)) {err+=1; msg+='\\n bad field5';}" + lineSep + + "regex4=/"
"if (!regex6.test(document.form.field6.value)) {err+=1; msg+='\\n bad field6';}" + lineSep + + regex4
"if (!regex7.test(document.form.field7.value)) {err+=1; msg+='\\n bad field7';}" + lineSep + + "/;"
"if ( err > 0 ) alert(msg);" + lineSep + + lineSep
"else document.form.submit();" + lineSep + + "regex5=/"
"} " + lineSep + + regex5
"</SCRIPT>" + lineSep; + "/;"
+ lineSep
+ "regex6=/"
+ regex6
+ "/;"
+ lineSep
+ "regex7=/"
+ regex7
+ "/;"
+ lineSep
+ "function validate() { "
+ lineSep
+ "msg='JavaScript found form errors'; err=0; "
+ lineSep
+ "if (!regex1.test(document.form.field1.value)) {err+=1; msg+='\\n bad field1';}"
+ lineSep
+ "if (!regex2.test(document.form.field2.value)) {err+=1; msg+='\\n bad field2';}"
+ lineSep
+ "if (!regex3.test(document.form.field3.value)) {err+=1; msg+='\\n bad field3';}"
+ lineSep
+ "if (!regex4.test(document.form.field4.value)) {err+=1; msg+='\\n bad field4';}"
+ lineSep
+ "if (!regex5.test(document.form.field5.value)) {err+=1; msg+='\\n bad field5';}"
+ lineSep
+ "if (!regex6.test(document.form.field6.value)) {err+=1; msg+='\\n bad field6';}"
+ lineSep
+ "if (!regex7.test(document.form.field7.value)) {err+=1; msg+='\\n bad field7';}"
+ lineSep + "if ( err > 0 ) alert(msg);" + lineSep
+ "else document.form.submit();" + lineSep + "} " + lineSep
+ "</SCRIPT>" + lineSep;
try try
{ {
String param1 = s.getParser().getRawParameter("field1", "abc"); String param1 = s.getParser().getRawParameter("field1", "abc");
String param2 = s.getParser().getRawParameter("field2", "123"); String param2 = s.getParser().getRawParameter("field2", "123");
String param3 = s.getParser().getRawParameter( "field3", "abc 123 ABC" ); String param3 = s.getParser().getRawParameter("field3",
"abc 123 ABC");
String param4 = s.getParser().getRawParameter("field4", "seven"); String param4 = s.getParser().getRawParameter("field4", "seven");
String param5 = s.getParser().getRawParameter("field5", "90210"); String param5 = s.getParser().getRawParameter("field5", "90210");
String param6 = s.getParser().getRawParameter( "field6", "90210-1111" ); String param6 = s.getParser().getRawParameter("field6",
String param7 = s.getParser().getRawParameter( "field7", "301-604-4882" ); "90210-1111");
String param7 = s.getParser().getRawParameter("field7",
"301-604-4882");
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
TextArea input1 = new TextArea("field1", 1, 25).addElement(param1); TextArea input1 = new TextArea("field1", 1, 25).addElement(param1);
TextArea input2 = new TextArea("field2", 1, 25).addElement(param2); TextArea input2 = new TextArea("field2", 1, 25).addElement(param2);
@ -104,25 +157,36 @@ public class JavaScriptValidation extends LessonAdapter
b.setType(Input.BUTTON); b.setType(Input.BUTTON);
b.setValue("Submit"); b.setValue("Submit");
b.addAttribute("onclick", "validate();"); b.addAttribute("onclick", "validate();");
ec.addElement( new Div().addElement( new StringElement( "Field1: exactly three lowercase characters (" + regex1 + ")" ) ) ); ec.addElement(new Div().addElement(new StringElement(
"Field1: exactly three lowercase characters (" + regex1
+ ")")));
ec.addElement(new Div().addElement(input1)); ec.addElement(new Div().addElement(input1));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement( new Div().addElement( new StringElement( "Field2: exactly three digits (" + regex2 + ")" ) ) ); ec.addElement(new Div().addElement(new StringElement(
"Field2: exactly three digits (" + regex2 + ")")));
ec.addElement(new Div().addElement(input2)); ec.addElement(new Div().addElement(input2));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement( new Div().addElement( new StringElement( "Field3: letters, numbers, and space only (" + regex3 + ")" ) ) ); ec.addElement(new Div()
.addElement(new StringElement(
"Field3: letters, numbers, and space only ("
+ regex3 + ")")));
ec.addElement(new Div().addElement(input3)); ec.addElement(new Div().addElement(input3));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement( new Div().addElement( new StringElement( "Field4: enumeration of numbers (" + regex4 + ")" ) ) ); ec.addElement(new Div().addElement(new StringElement(
"Field4: enumeration of numbers (" + regex4 + ")")));
ec.addElement(new Div().addElement(input4)); ec.addElement(new Div().addElement(input4));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement( new Div().addElement( new StringElement( "Field5: simple zip code (" + regex5 + ")" ) ) ); ec.addElement(new Div().addElement(new StringElement(
"Field5: simple zip code (" + regex5 + ")")));
ec.addElement(new Div().addElement(input5)); ec.addElement(new Div().addElement(input5));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement( new Div().addElement( new StringElement( "Field6: zip with optional dash four (" + regex6 + ")" ) ) ); ec.addElement(new Div().addElement(new StringElement(
"Field6: zip with optional dash four (" + regex6 + ")")));
ec.addElement(new Div().addElement(input6)); ec.addElement(new Div().addElement(input6));
ec.addElement(new P()); 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(new StringElement(
"Field7: US phone number with or without dashes (" + regex7
+ ")")));
ec.addElement(new Div().addElement(input7)); ec.addElement(new Div().addElement(input7));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(b); ec.addElement(b);
@ -195,6 +259,7 @@ public class JavaScriptValidation extends LessonAdapter
return (ec); return (ec);
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
@ -206,7 +271,6 @@ public class JavaScriptValidation extends LessonAdapter
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
@ -217,14 +281,15 @@ public class JavaScriptValidation extends LessonAdapter
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("The validation is happening in your browser."); hints.add("The validation is happening in your browser.");
hints.add( "Try modifying the values with a proxy after they leave your browser" ); hints
hints.add( "Another way is to delete the JavaScript before you view the page." ); .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.");
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the WeakAccessControl object * Gets the instructions attribute of the WeakAccessControl object
* *
@ -232,24 +297,22 @@ public class JavaScriptValidation extends LessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "This website performs both client and server side validation. " + 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 " + + "For this exercise, your job is to break the client side validation and send the "
" website input that it wasn't expecting." + + " website input that it wasn't expecting."
"<b> You must break all 7 validators at the same time. </b>"; + "<b> You must break all 7 validators at the same time. </b>";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
@ -260,5 +323,3 @@ public class JavaScriptValidation extends LessonAdapter
return ("How to Bypass Client Side JavaScript Validation"); return ("How to Bypass Client Side JavaScript Validation");
} }
} }

View File

@ -18,18 +18,45 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public abstract class LessonAdapter extends AbstractLesson public abstract class LessonAdapter extends AbstractLesson
{ {
final static IMG WEBGOAT_LOGO = new IMG( "images/logos/WebGoat.jpg" ).setAlt( "WebGoat Logo" ).setBorder( 0 ).setHspace( 0 ).setVspace( 0 );
final static IMG WEBGOAT_LOGO = new IMG("images/logos/WebGoat.jpg").setAlt(
"WebGoat Logo").setBorder(0).setHspace(0).setVspace(0);
/** /**
* Description of the Method * Description of the Method
* *
@ -43,14 +70,21 @@ public abstract class LessonAdapter extends AbstractLesson
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement( new Center().addElement( new H3().addElement( new StringElement( "This lesson needs a creator." ) ) ) ); ec
.addElement(new Center().addElement(new H3()
.addElement(new StringElement(
"This lesson needs a creator."))));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement( new StringElement( "Lesson are simple to create and very little coding is required. &nbsp;&nbsp;" + ec
"In fact, most lessons can be created by following the easy to use instructions in the " + .addElement(new StringElement(
"<A HREF=http://prdownloads.sourceforge.net/owasp/WebGoatVersion2UserGuide.pdf?download>WebGoat User Guide.</A>&nbsp;&nbsp;" + "Lesson are simple to create and very little coding is required. &nbsp;&nbsp;"
"If you would prefer, send your lesson ideas to " + s.getFeedbackAddress() ) ); + "In fact, most lessons can be created by following the easy to use instructions in the "
+ "<A HREF=http://prdownloads.sourceforge.net/owasp/WebGoatVersion2UserGuide.pdf?download>WebGoat User Guide.</A>&nbsp;&nbsp;"
+ "If you would prefer, send your lesson ideas to "
+ s.getFeedbackAddress()));
String fileName = s.getContext().getRealPath( "doc/New Lesson Instructions.txt"); String fileName = s.getContext().getRealPath(
"doc/New Lesson Instructions.txt");
if (fileName != null) if (fileName != null)
{ {
try try
@ -64,7 +98,8 @@ public abstract class LessonAdapter extends AbstractLesson
} }
ec.addElement(pre); ec.addElement(pre);
} }
catch ( Exception e ){} catch (Exception e)
{}
} }
return (ec); return (ec);
} }
@ -153,6 +188,7 @@ public abstract class LessonAdapter extends AbstractLesson
return ec; return ec;
} }
/** /**
* Gets the category attribute of the LessonAdapter object. The default category is "General" Only * 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 * override this method if you wish to create a new category or if you wish this lesson to reside
@ -165,6 +201,7 @@ public abstract class LessonAdapter extends AbstractLesson
return GENERAL; return GENERAL;
} }
protected boolean getDefaultHidden() protected boolean getDefaultHidden()
{ {
return false; return false;
@ -172,11 +209,13 @@ public abstract class LessonAdapter extends AbstractLesson
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the hintCount attribute of the LessonAdapter object * Gets the hintCount attribute of the LessonAdapter object
* *
@ -203,11 +242,13 @@ public abstract class LessonAdapter extends AbstractLesson
return hints; return hints;
} }
public String getHint(int hintNumber) public String getHint(int hintNumber)
{ {
return (String) getHints().get(hintNumber); return (String) getHints().get(hintNumber);
} }
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
* *
@ -225,6 +266,7 @@ public abstract class LessonAdapter extends AbstractLesson
} }
} }
/** /**
* Gets the instructions attribute of the LessonAdapter object. Instructions will rendered as html * 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 * and will appear below the control area and above the actual lesson area. Instructions should
@ -262,7 +304,8 @@ public abstract class LessonAdapter extends AbstractLesson
} }
} }
} }
catch ( Exception e ){} catch (Exception e)
{}
return buff.toString(); return buff.toString();
@ -280,24 +323,31 @@ public abstract class LessonAdapter extends AbstractLesson
return "Untitled Lesson " + getScreenId(); return "Untitled Lesson " + getScreenId();
} }
public String getCurrentAction(WebSession s) public String getCurrentAction(WebSession s)
{ {
return s.getLessonSession(this).getCurrentLessonScreen(); return s.getLessonSession(this).getCurrentLessonScreen();
} }
public void setCurrentAction(WebSession s, String lessonScreen) public void setCurrentAction(WebSession s, String lessonScreen)
{ {
s.getLessonSession(this).setCurrentLessonScreen(lessonScreen); s.getLessonSession(this).setCurrentLessonScreen(lessonScreen);
} }
public Object getSessionAttribute(WebSession s, String key) {
public Object getSessionAttribute(WebSession s, String key)
{
return s.getRequest().getSession().getAttribute(key); return s.getRequest().getSession().getAttribute(key);
} }
public void setSessionAttribute(WebSession s, String key, Object value) {
public void setSessionAttribute(WebSession s, String key, Object value)
{
s.getRequest().getSession().setAttribute(key, value); s.getRequest().getSession().setAttribute(key, value);
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -308,7 +358,8 @@ public abstract class LessonAdapter extends AbstractLesson
{ {
getLessonTracker(s).setCompleted(true); getLessonTracker(s).setCompleted(true);
s.setMessage("Congratulations. You have successfully completed this lesson."); s
.setMessage("Congratulations. You have successfully completed this lesson.");
return (null); return (null);
} }
@ -321,13 +372,14 @@ public abstract class LessonAdapter extends AbstractLesson
*/ */
protected Element getCustomCredits(String text, IMG logo) protected Element getCustomCredits(String text, IMG logo)
{ {
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 ).setWidth("90%").setAlign("RIGHT"); Table t = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
.setWidth("90%").setAlign("RIGHT");
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TD(text).setVAlign("MIDDLE").setAlign("RIGHT").setWidth("100%")); tr.addElement(new TD(text).setVAlign("MIDDLE").setAlign("RIGHT")
.setWidth("100%"));
tr.addElement(new TD(logo).setVAlign("MIDDLE").setAlign("RIGHT")); tr.addElement(new TD(logo).setVAlign("MIDDLE").setAlign("RIGHT"));
t.addElement(tr); t.addElement(tr);
return t; return t;
} }
} }

View File

@ -17,28 +17,57 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Sherif Koussa <a href="http://www.macadamian.com">Macadamian Technologies</a> * @author Sherif Koussa <a href="http://www.macadamian.com">Macadamian Technologies</a>
* @created October 28, 2006 * @created October 28, 2006
*/ */
public class LogSpoofing extends LessonAdapter { 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";
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
ElementContainer ec = null; ElementContainer ec = null;
String inputUsername = null; String inputUsername = null;
try{ try
{
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 row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
TR row3 = new TR(); TR row3 = new TR();
@ -62,7 +91,8 @@ public class LogSpoofing extends LessonAdapter {
ec = new ElementContainer(); ec = new ElementContainer();
ec.addElement(t); ec.addElement(t);
inputUsername = new String( s.getParser().getRawParameter( USERNAME, "" ) ); inputUsername = new String(s.getParser().getRawParameter(USERNAME,
""));
if (inputUsername.length() != 0) if (inputUsername.length() != 0)
{ {
inputUsername = URLDecoder.decode(inputUsername, "UTF-8"); inputUsername = URLDecoder.decode(inputUsername, "UTF-8");
@ -70,17 +100,21 @@ public class LogSpoofing extends LessonAdapter {
ec.addElement(new PRE(" ")); ec.addElement(new PRE(" "));
Table t2 = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 ); Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0)
.setBorder(0);
TR row4 = new TR(); TR row4 = new TR();
row4.addElement( new TD(new PRE ("Login failed for username: " + inputUsername ))).setBgColor( HtmlColor.GRAY); row4.addElement(
new TD(new PRE("Login failed for username: "
+ inputUsername))).setBgColor(HtmlColor.GRAY);
t2.addElement(row4); t2.addElement(row4);
ec.addElement(t2); ec.addElement(t2);
if (inputUsername.length() != 0
if ( inputUsername.length() != 0 && && inputUsername.toUpperCase().indexOf(
inputUsername.toUpperCase().indexOf( System.getProperty("line.separator") + "LOGIN SUCCEEDED FOR USERNAME:") >= 0) System.getProperty("line.separator")
+ "LOGIN SUCCEEDED FOR USERNAME:") >= 0)
{ {
makeSuccess(s); makeSuccess(s);
} }
@ -95,32 +129,43 @@ public class LogSpoofing extends LessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(72); private final static Integer DEFAULT_RANKING = new Integer(72);
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
@Override @Override
protected List getHints() { protected List getHints()
{
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Try to fool the humane eye by using new lines."); 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("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");
hints.add( "Try: Smith%0d%0aLogin Succeeded for username: admin&lt;script&gt;alert(document.cookie)&lt;/script&gt;" ); hints
.add("Try: Smith%0d%0aLogin Succeeded for username: admin&lt;script&gt;alert(document.cookie)&lt;/script&gt;");
return hints; return hints;
} }
@Override @Override
public String getTitle() { public String getTitle()
{
return "How to Perform Log Spoofing"; return "How to Perform Log Spoofing";
} }
@Override @Override
protected Category getDefaultCategory() { protected Category getDefaultCategory()
{
return AbstractLesson.A6; return AbstractLesson.A6;
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }
} }

View File

@ -5,17 +5,41 @@ import org.apache.ecs.StringElement;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Sherif Koussa <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Sherif Koussa <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class NewLesson extends LessonAdapter public class NewLesson extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
@ -28,6 +52,8 @@ public class NewLesson extends LessonAdapter
makeSuccess(s); makeSuccess(s);
return (new StringElement("Welcome to the WebGoat hall of fame !!")); return (new StringElement("Welcome to the WebGoat hall of fame !!"));
} }
/** /**
* Gets the category attribute of the NEW_LESSON object * Gets the category attribute of the NEW_LESSON object
* *
@ -40,11 +66,13 @@ public class NewLesson extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
@ -55,8 +83,9 @@ public class NewLesson extends LessonAdapter
return ("How to add a new WebGoat lesson"); return ("How to add a new WebGoat lesson");
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }
} }

View File

@ -18,17 +18,41 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class PathBasedAccessControl extends LessonAdapter public class PathBasedAccessControl extends LessonAdapter
{ {
private final static String FILE = "File"; private final static String FILE = "File";
@ -47,7 +71,8 @@ public class PathBasedAccessControl extends LessonAdapter
String dir = s.getContext().getRealPath("/lesson_plans"); String dir = s.getContext().getRealPath("/lesson_plans");
File d = new File(dir); File d = new File(dir);
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()) if (s.isColor())
{ {
@ -55,20 +80,24 @@ public class PathBasedAccessControl extends LessonAdapter
} }
String[] list = d.list(); String[] list = d.list();
String listing = " <p><B>Current Directory is:</B> " + Encoding.urlDecode( dir ) + "<br><br> Choose the file to view:</p>"; String listing = " <p><B>Current Directory is:</B> "
+ Encoding.urlDecode(dir)
+ "<br><br> Choose the file to view:</p>";
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().setColSpan(2).addElement( new StringElement(listing) )); tr.addElement(new TD().setColSpan(2).addElement(
new StringElement(listing)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().setWidth("35%").addElement( ECSFactory.makePulldown( FILE, list, "", 15 ))); tr.addElement(new TD().setWidth("35%").addElement(
tr.addElement( new TD().addElement( ECSFactory.makeButton( "View File" ))); ECSFactory.makePulldown(FILE, list, "", 15)));
tr.addElement(new TD().addElement(ECSFactory
.makeButton("View File")));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
// FIXME: would be cool to allow encodings here -- hex, percent, url, etc... // FIXME: would be cool to allow encodings here -- hex, percent, url, etc...
String file = s.getParser().getRawParameter(FILE, ""); String file = s.getParser().getRawParameter(FILE, "");
@ -81,16 +110,18 @@ public class PathBasedAccessControl extends LessonAdapter
if (upDirCount(file) == 3 && !file.endsWith("LICENSE")) if (upDirCount(file) == 3 && !file.endsWith("LICENSE"))
{ {
s.setMessage("Access denied"); s.setMessage("Access denied");
s.setMessage( "It appears that you are on the right track. " + s
"Commands that may compromise the operating system have been disabled. " + .setMessage("It appears that you are on the right track. "
"You are only allowed to see one file in this directory. ");; + "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("Access denied");
s.setMessage( "It appears that you are on the right track. " + s
"Commands that may compromise the operating system have been disabled. " + .setMessage("It appears that you are on the right track. "
"You are only allowed to see files in the webgoat directory. "); + "Commands that may compromise the operating system have been disabled. "
+ "You are only allowed to see files in the webgoat directory. ");
} }
else else
{ {
@ -122,18 +153,23 @@ public class PathBasedAccessControl extends LessonAdapter
if (upDirCount(file) >= 1) if (upDirCount(file) >= 1)
{ {
s.setMessage("Congratulations! Access to file allowed"); s.setMessage("Congratulations! Access to file allowed");
s.setMessage( " ==> " + Encoding.urlDecode( f.getCanonicalPath() )); s.setMessage(" ==> "
+ Encoding.urlDecode(f.getCanonicalPath()));
makeSuccess(s); makeSuccess(s);
} }
else else
{ {
s.setMessage( "File is already in allowed directory - try again!" ); s
s.setMessage( " ==> " + Encoding.urlDecode( f.getCanonicalPath() )); .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() ) + "\" denied" ); s.setMessage("Access to file/directory \""
+ Encoding.urlDecode(f.getCanonicalPath())
+ "\" denied");
} }
else else
{ {
@ -153,22 +189,24 @@ public class PathBasedAccessControl extends LessonAdapter
{ {
throw new Exception("File is too large"); throw new Exception("File is too large");
} }
String fileData= getFileText( new BufferedReader( new FileReader( f ) ), false ); String fileData = getFileText(new BufferedReader(
new FileReader(f)), false);
if (fileData.indexOf(0x00) != -1) if (fileData.indexOf(0x00) != -1)
{ {
throw new Exception("File is binary"); throw new Exception("File is binary");
} }
ec.addElement( new StringElement( fileData.replaceAll(System.getProperty("line.separator"),"<br>") ec.addElement(new StringElement(fileData.replaceAll(
System.getProperty("line.separator"), "<br>")
.replaceAll("(?s)<!DOCTYPE.*/head>", "") .replaceAll("(?s)<!DOCTYPE.*/head>", "")
.replaceAll("<br><br>","<br>") .replaceAll("<br><br>", "<br>").replaceAll(
.replaceAll("<br>\\s<br>","<br>") "<br>\\s<br>", "<br>").replaceAll("<\\?",
.replaceAll("<\\?", "&lt;") "&lt;").replaceAll("<(r|u|t)", "&lt;$1")));
.replaceAll("<(r|u|t)", "&lt;$1")));
} }
catch (Exception e) catch (Exception e)
{ {
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement("The following error occurred while accessing the file: <"); ec
.addElement("The following error occurred while accessing the file: <");
ec.addElement(e.getMessage()); ec.addElement(e.getMessage());
} }
} }
@ -182,6 +220,7 @@ public class PathBasedAccessControl extends LessonAdapter
return (ec); return (ec);
} }
private int upDirCount(String fileName) private int upDirCount(String fileName)
{ {
int count = 0; int count = 0;
@ -194,6 +233,7 @@ public class PathBasedAccessControl extends LessonAdapter
return count; return count;
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
@ -213,8 +253,10 @@ public class PathBasedAccessControl extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "Most operating systems allow special characters in the path." ); hints
hints.add( "Use a file explorer to find the tomcat\\webapps\\WebGoat\\lesson_plans directory" ); .add("Most operating systems allow special characters in the path.");
hints
.add("Use a file explorer to find the tomcat\\webapps\\WebGoat\\lesson_plans directory");
hints.add("Try .. in the path"); hints.add("Try .. in the path");
hints.add("Try ..\\..\\..\\LICENSE"); hints.add("Try ..\\..\\..\\LICENSE");
@ -229,20 +271,20 @@ public class PathBasedAccessControl extends LessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The '" + s.getUserName() + "' user has access to all the files in the " + String instructions = "The '"
"lesson_plans directory. Try to break the access control mechanism and access a " + + s.getUserName()
"resource that is not in the listed directory. After selecting a file to view, WebGoat " + + "' user has access to all the files in the "
"will report if access to the file was granted. An interesting file to try and obtain might " + + "lesson_plans directory. Try to break the access control mechanism and access a "
"be a file like tomcat/conf/tomcat-users.xml"; + "resource that is not in the listed directory. After selecting a file to view, WebGoat "
+ "will report if access to the file was granted. An interesting file to try and obtain might "
+ "be a file like tomcat/conf/tomcat-users.xml";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
@ -259,4 +301,3 @@ public class PathBasedAccessControl extends LessonAdapter
return ("How to Bypass a Path Based Access Control Scheme"); return ("How to Bypass a Path Based Access Control Scheme");
} }
} }

View File

@ -19,13 +19,34 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
*
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web * This file is part of WebGoat, an Open Web Application Security Project
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * utility. For details, please see http://www.owasp.org/
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute *
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -51,7 +72,8 @@ public class ReflectedXSS extends LessonAdapter
try try
{ {
String param1 = s.getParser().getRawParameter("field1", "111"); String param1 = s.getParser().getRawParameter("field1", "111");
String param2 = HtmlEncoder.encode( s.getParser().getRawParameter( "field2", "4128 3214 0002 1999" ) ); String param2 = HtmlEncoder.encode(s.getParser().getRawParameter(
"field2", "4128 3214 0002 1999"));
float quantity = 1.0f; float quantity = 1.0f;
float total = 0.0f; float total = 0.0f;
float runningTotal = 0.0f; float runningTotal = 0.0f;
@ -64,14 +86,19 @@ public class ReflectedXSS extends LessonAdapter
makeSuccess(s); makeSuccess(s);
} }
s.setMessage( "Whoops! You entered " + param1 + " instead of your three digit code. Please try again." ); s
.setMessage("Whoops! You entered "
+ param1
+ " instead of your three digit code. Please try again.");
} }
// FIXME: encode output of field2, then s.setMessage( field2 ); // FIXME: encode output of field2, then s.setMessage( field2 );
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement( new Center().addElement( new H1().addElement( "Shopping Cart " ))); ec.addElement(new Center().addElement(new H1()
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 2 ).setBorder( 1 ).setWidth("90%").setAlign("center"); .addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
@ -79,44 +106,64 @@ public class ReflectedXSS extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); tr.addElement(new TH().addElement(
"Shopping Cart Items -- To Buy Now").setWidth("80%"));
tr.addElement(new TH().addElement("Price:").setWidth("10%")); tr.addElement(new TH().addElement("Price:").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity:").setWidth("3%")); tr.addElement(new TH().addElement("Quantity:").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%")); tr.addElement(new TH().addElement("Total").setWidth("7%"));
t.addElement(tr); t.addElement(tr);
tr = new 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("69.99").setAlign("right")); tr.addElement(new TD().addElement("69.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY1", s.getParser()
.getStringParameter("QTY1", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY1", 1.0f); quantity = s.getParser().getFloatParameter("QTY1", 1.0f);
total = quantity * 69.99f; total = quantity * 69.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement("Dynex - Traditional Notebook Case")); tr.addElement(new TD()
.addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement("27.99").setAlign("right")); tr.addElement(new TD().addElement("27.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY2", s.getParser()
.getStringParameter("QTY2", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY2", 1.0f); quantity = s.getParser().getFloatParameter("QTY2", 1.0f);
total = quantity * 27.99f; total = quantity * 27.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new 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("1599.99").setAlign("right")); tr.addElement(new TD().addElement("1599.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY3", s.getParser()
.getStringParameter("QTY3", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY3", 1.0f); quantity = s.getParser().getFloatParameter("QTY3", 1.0f);
total = quantity * 1599.99f; total = quantity * 1599.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new 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("299.99").setAlign("right")); tr.addElement(new TD().addElement("299.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY4", s.getParser()
.getStringParameter("QTY4", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY4", 1.0f); quantity = s.getParser().getFloatParameter("QTY4", 1.0f);
total = quantity * 299.99f; total = quantity * 299.99f;
runningTotal += total; runningTotal += total;
@ -125,7 +172,8 @@ public class ReflectedXSS extends LessonAdapter
ec.addElement(t); 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()) if (s.isColor())
{ {
@ -135,25 +183,33 @@ public class ReflectedXSS extends LessonAdapter
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "The total charged to your credit card:" ) ); tr.addElement(new TD()
.addElement("The total charged to your credit card:"));
tr.addElement(new TD().addElement("$" + runningTotal)); tr.addElement(new TD().addElement("$" + runningTotal));
tr.addElement( new TD().addElement( ECSFactory.makeButton( "Update Cart" ))); tr.addElement(new TD().addElement(ECSFactory
.makeButton("Update Cart")));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "Enter your credit card number:" ) ); tr
tr.addElement( new TD().addElement( new Input( Input.TEXT, "field2", param2 ))); .addElement(new TD()
.addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2",
param2)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "Enter your three digit access code:" ) ); tr.addElement(new TD()
tr.addElement( new TD().addElement( new Input( Input.TEXT, "field1", param1 ))); .addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",
param1)));
t.addElement(tr); t.addElement(tr);
Element b = ECSFactory.makeButton("Purchase"); Element b = ECSFactory.makeButton("Purchase");
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( b ).setColSpan(2).setAlign("center")); tr.addElement(new TD().addElement(b).setColSpan(2).setAlign(
"center"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
@ -180,7 +236,6 @@ public class ReflectedXSS extends LessonAdapter
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
@ -189,17 +244,23 @@ public class ReflectedXSS extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "A simple script is &lt;SCRIPT&gt;alert('bang!');&lt;/SCRIPT&gt;." ); hints
.add("A simple script is &lt;SCRIPT&gt;alert('bang!');&lt;/SCRIPT&gt;.");
hints.add("Can you get the script to disclose the JSESSIONID cookie?"); hints.add("Can you get the script to disclose the JSESSIONID cookie?");
hints.add( "You can use &lt;SCRIPT&gt;alert(document.cookie);&lt;/SCRIPT&gt; to access the session id cookie" ); hints
hints.add( "Can you get the script to access the credit card form field?" ); .add("You can use &lt;SCRIPT&gt;alert(document.cookie);&lt;/SCRIPT&gt; to access the session id cookie");
hints.add( "Try a cross site trace (XST) Command:<br>" + hints
"&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)" + .add("Can you get the script to access the credit card form field?");
" {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"TRACE\", \"./\", false);" + hints
" xmlHttp.send();str1=xmlHttp.responseText; while (str1.indexOf(\"\\n\") > -1) str1 = str1.replace(\"\\n\",\"&lt;br&gt;\"); " + .add("Try a cross site trace (XST) Command:<br>"
"document.write(str1);}&lt;/script&gt;"); + "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)"
+ " {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"TRACE\", \"./\", false);"
+ " xmlHttp.send();str1=xmlHttp.responseText; while (str1.indexOf(\"\\n\") > -1) str1 = str1.replace(\"\\n\",\"&lt;br&gt;\"); "
+ "document.write(str1);}&lt;/script&gt;");
return hints; return hints;
} }
// <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false); xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script> // <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false); xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script>
/** /**
* Gets the instructions attribute of the WeakAccessControl object * Gets the instructions attribute of the WeakAccessControl object
@ -212,15 +273,15 @@ public class ReflectedXSS extends LessonAdapter
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
@ -231,5 +292,3 @@ public class ReflectedXSS extends LessonAdapter
return "How to Perform Reflected Cross Site Scripting (XSS) Attacks"; return "How to Perform Reflected Cross Site Scripting (XSS) Attacks";
} }
} }

View File

@ -7,11 +7,34 @@ import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -35,7 +58,8 @@ public class RemoteAdminFlaw extends LessonAdapter
} }
else else
{ {
ec.addElement( "WebGoat has an admin interface. To 'complete' this lesson you must figure " ec
.addElement("WebGoat has an admin interface. To 'complete' this lesson you must figure "
+ "out how to access the administrative interface for WebGoat."); + "out how to access the administrative interface for WebGoat.");
} }
return ec; return ec;
@ -54,6 +78,7 @@ public class RemoteAdminFlaw extends LessonAdapter
return AbstractLesson.A2; return AbstractLesson.A2;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
@ -63,22 +88,24 @@ public class RemoteAdminFlaw extends LessonAdapter
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("WebGoat has 2 admin interfaces."); hints.add("WebGoat has 2 admin interfaces.");
hints.add( "WebGoat has one admin interface that is controlled via a URL parameter and is 'hackable'" ); hints
hints.add( "WebGoat has one admin interface that is controlled via server side security constraints and should not be 'hackable'" ); .add("WebGoat has one admin interface that is controlled via a URL parameter and is 'hackable'");
hints
.add("WebGoat has one admin interface that is controlled via server side security constraints and should not be 'hackable'");
hints.add("Follow the Source!"); hints.add("Follow the Source!");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(15); private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -89,7 +116,4 @@ public class RemoteAdminFlaw extends LessonAdapter
return ("Remote Admin Access"); return ("Remote Admin Access");
} }
} }

View File

@ -13,23 +13,59 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class DeleteProfile extends DefaultLessonAction public class DeleteProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public DeleteProfile(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public DeleteProfile(AbstractLesson lesson, String lessonName,
String actionName, LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); + RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
@ -56,6 +92,7 @@ public class DeleteProfile extends DefaultLessonAction
updateLessonStatus(s); updateLessonStatus(s);
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.LISTSTAFF_ACTION; return RoleBasedAccessControl.LISTSTAFF_ACTION;
@ -72,7 +109,9 @@ public class DeleteProfile extends DefaultLessonAction
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.executeUpdate(query); statement.executeUpdate(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -88,8 +127,9 @@ public class DeleteProfile extends DefaultLessonAction
} }
} }
public void deleteEmployeeProfile_BACKUP(WebSession s, int userId, int employeeId)
throws UnauthorizedException public void deleteEmployeeProfile_BACKUP(WebSession s, int userId,
int employeeId) throws UnauthorizedException
{ {
try try
{ {
@ -98,7 +138,9 @@ public class DeleteProfile extends DefaultLessonAction
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.executeUpdate(query); statement.executeUpdate(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -115,23 +157,24 @@ public class DeleteProfile extends DefaultLessonAction
} }
private void updateLessonStatus(WebSession s) private void updateLessonStatus(WebSession s)
{ {
// If the logged in user is not authorized to be here, stage is complete. // If the logged in user is not authorized to be here, stage is complete.
try try
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
if (!isAuthorized(s, userId, RoleBasedAccessControl.DELETEPROFILE_ACTION)) if (!isAuthorized(s, userId,
RoleBasedAccessControl.DELETEPROFILE_ACTION))
{ {
s.setMessage( "Welcome to stage 2 -- protecting the business layer" ); s
.setMessage("Welcome to stage 2 -- protecting the business layer");
setStage(s, 2); setStage(s, 2);
} }
} }
catch (ParameterNotFoundException e) catch (ParameterNotFoundException e)
{ {}
}
} }
} }

View File

@ -12,38 +12,73 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class EditProfile extends DefaultLessonAction
{ {
public EditProfile(AbstractLesson lesson, String lessonName, String actionName)
public EditProfile(AbstractLesson lesson, String lessonName,
String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getUserId(s); int userId = getUserId(s);
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.EDITPROFILE_ACTION; return RoleBasedAccessControl.EDITPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) public Employee getEmployeeProfile(WebSession s, int userId,
throws UnauthorizedException int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
@ -54,28 +89,29 @@ public class EditProfile extends DefaultLessonAction
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); .getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +
@ -98,8 +134,9 @@ public class EditProfile extends DefaultLessonAction
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId)
throws UnauthorizedException 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 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 // Query the database for the profile data of the given employee if "owned" by the given user
@ -113,28 +150,29 @@ public class EditProfile extends DefaultLessonAction
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); .getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +

View File

@ -14,24 +14,60 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class FindProfile extends DefaultLessonAction public class FindProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public FindProfile(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public FindProfile(AbstractLesson lesson, String lessonName,
String actionName, LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
String pattern = s.getParser().getRawParameter(RoleBasedAccessControl.SEARCHNAME); String pattern = s.getParser().getRawParameter(
RoleBasedAccessControl.SEARCHNAME);
findEmployeeProfile(s, userId, pattern); findEmployeeProfile(s, userId, pattern);
@ -58,6 +94,7 @@ public class FindProfile extends DefaultLessonAction
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String page = RoleBasedAccessControl.SEARCHSTAFF_ACTION; String page = RoleBasedAccessControl.SEARCHSTAFF_ACTION;
@ -68,27 +105,30 @@ public class FindProfile extends DefaultLessonAction
return page; return page;
} }
private boolean foundEmployee(WebSession s) private boolean foundEmployee(WebSession s)
{ {
boolean found = false; boolean found = false;
try try
{ {
int id = getIntRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID); int id = getIntRequestAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ID);
found = true; found = true;
} }
catch (ParameterNotFoundException e) catch (ParameterNotFoundException e)
{ {}
}
return found; return found;
} }
public Employee findEmployeeProfile(WebSession s, int userId, String pattern) public Employee findEmployeeProfile(WebSession s, int userId, String pattern)
throws UnauthorizedException throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Clear any residual employee id's in the session now. // Clear any residual employee id's in the session now.
removeSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID); removeSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ID);
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
@ -97,8 +137,10 @@ public class FindProfile extends DefaultLessonAction
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); .getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
answer_statement.setString(1, "%" + pattern + "%"); answer_statement.setString(1, "%" + pattern + "%");
answer_statement.setString(2, "%" + pattern + "%"); answer_statement.setString(2, "%" + pattern + "%");
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
@ -108,21 +150,19 @@ public class FindProfile extends DefaultLessonAction
{ {
int id = answer_results.getInt("userid"); int id = answer_results.getInt("userid");
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(id, answer_results
id, .getString("first_name"), answer_results
answer_results.getString("first_name"), .getString("last_name"), answer_results
answer_results.getString("last_name"), .getString("ssn"), answer_results
answer_results.getString("ssn"), .getString("title"), answer_results
answer_results.getString("title"), .getString("phone"), answer_results
answer_results.getString("phone"), .getString("address1"), answer_results
answer_results.getString("address1"), .getString("address2"), answer_results
answer_results.getString("address2"), .getInt("manager"), answer_results
answer_results.getInt("manager"), .getString("start_date"), answer_results
answer_results.getString("start_date"), .getInt("salary"), answer_results.getString("ccn"),
answer_results.getInt("salary"), answer_results.getInt("ccn_limit"), answer_results
answer_results.getString("ccn"), .getString("disciplined_date"),
answer_results.getInt("ccn_limit"),
answer_results.getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
@ -130,7 +170,9 @@ public class FindProfile extends DefaultLessonAction
profile.getFirstName() + " " + profile.getLastName() + profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")"); " (" + profile.getId() + ")");
*/ */
setRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID, Integer.toString(id)); setRequestAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ID, Integer
.toString(id));
} }
} }
catch (SQLException sqle) catch (SQLException sqle)

View File

@ -14,29 +14,63 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class ListStaff extends DefaultLessonAction
{ {
public ListStaff(AbstractLesson lesson, String lessonName, String actionName) public ListStaff(AbstractLesson lesson, String lessonName, String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
List employees = getAllEmployees(s, userId); List employees = getAllEmployees(s, userId);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.STAFF_ATTRIBUTE_KEY, employees);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.LISTSTAFF_ACTION; return RoleBasedAccessControl.LISTSTAFF_ACTION;
@ -53,11 +87,14 @@ public class ListStaff extends DefaultLessonAction
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " 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 + ")"; + "(SELECT employee_id FROM ownership WHERE employer_id = "
+ userId + ")";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
@ -67,7 +104,8 @@ public class ListStaff extends DefaultLessonAction
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
//System.out.println("Retrieving employee stub for role " + role); //System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
employees.add(stub); employees.add(stub);
} }
} }
@ -83,10 +121,10 @@ public class ListStaff extends DefaultLessonAction
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
public List getAllEmployees_BACKUP(WebSession s, int userId) public List getAllEmployees_BACKUP(WebSession s, int userId)
throws UnauthorizedException throws UnauthorizedException
{ {
@ -97,11 +135,14 @@ public class ListStaff extends DefaultLessonAction
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " 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 + ")"; + "(SELECT employee_id FROM ownership WHERE employer_id = "
+ userId + ")";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
@ -111,7 +152,8 @@ public class ListStaff extends DefaultLessonAction
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
//System.out.println("Retrieving employee stub for role " + role); //System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
employees.add(stub); employees.add(stub);
} }
} }
@ -127,7 +169,6 @@ public class ListStaff extends DefaultLessonAction
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }

View File

@ -16,29 +16,66 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Login extends DefaultLessonAction public class Login extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public Login(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public Login(AbstractLesson lesson, String lessonName, String actionName,
LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s ) throws ParameterNotFoundException, ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException,
ValidationException
{ {
//System.out.println("Login.handleRequest()"); //System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s); List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.STAFF_ATTRIBUTE_KEY, employees);
int employeeId = -1; int employeeId = -1;
try try
{ {
employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); employeeId = s.getParser().getIntParameter(
String password = s.getParser().getStringParameter(RoleBasedAccessControl.PASSWORD); RoleBasedAccessControl.EMPLOYEE_ID);
String password = s.getParser().getStringParameter(
RoleBasedAccessControl.PASSWORD);
// Attempt authentication // Attempt authentication
if (login(s, employeeId, password)) if (login(s, employeeId, password))
@ -65,10 +102,12 @@ public class Login extends DefaultLessonAction
catch (ParameterNotFoundException pnfe) catch (ParameterNotFoundException pnfe)
{ {
// No credentials offered, so we log them out // No credentials offered, so we log them out
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); setSessionAttribute(s, getLessonName() + ".isAuthenticated",
Boolean.FALSE);
} }
} }
/** /**
* After this.handleRequest() is called, when the View asks for the current JSP to load, * After this.handleRequest() is called, when the View asks for the current JSP to load,
* it will get one initialized by this call. * it will get one initialized by this call.
@ -84,11 +123,13 @@ public class Login extends DefaultLessonAction
} }
public boolean requiresAuthentication() public boolean requiresAuthentication()
{ {
return false; return false;
} }
public boolean login(WebSession s, int userId, String password) public boolean login(WebSession s, int userId, String password)
{ {
//System.out.println("Logging in to lesson"); //System.out.println("Logging in to lesson");
@ -96,16 +137,22 @@ public class Login extends DefaultLessonAction
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; String query = "SELECT * FROM employee WHERE userid = " + userId
+ " and password = '" + password + "'";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first()) if (answer_results.first())
{ {
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); setSessionAttribute(s,
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID, Integer.toString(userId)); getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID, Integer
.toString(userId));
authenticated = true; authenticated = true;
} }
@ -126,6 +173,7 @@ public class Login extends DefaultLessonAction
return authenticated; return authenticated;
} }
public List getAllEmployees(WebSession s) public List getAllEmployees(WebSession s)
{ {
List employees = new Vector(); List employees = new Vector();
@ -135,12 +183,14 @@ public class Login extends DefaultLessonAction
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " + String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
"where employee.userid=roles.userid"; + "where employee.userid=roles.userid";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
@ -149,7 +199,8 @@ public class Login extends DefaultLessonAction
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
employees.add(stub); employees.add(stub);
} }
} }
@ -165,7 +216,6 @@ public class Login extends DefaultLessonAction
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }

View File

@ -9,21 +9,56 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Logout extends DefaultLessonAction public class Logout extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public Logout(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public Logout(AbstractLesson lesson, String lessonName, String actionName,
LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s ) throws ParameterNotFoundException, ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException,
ValidationException
{ {
//System.out.println("Logging out"); //System.out.println("Logging out");
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); setSessionAttribute(s, getLessonName() + ".isAuthenticated",
Boolean.FALSE);
// FIXME: Maybe we should forward to Login. // FIXME: Maybe we should forward to Login.
try try
@ -43,6 +78,7 @@ public class Logout extends DefaultLessonAction
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return chainedAction.getNextPage(s); return chainedAction.getNextPage(s);

View File

@ -19,52 +19,106 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute
* this software.
* *
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/ */
public class RoleBasedAccessControl extends LessonAdapter public class RoleBasedAccessControl extends LessonAdapter
{ {
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 String LESSON_NAME = "RoleBasedAccessControl"; private final static String LESSON_NAME = "RoleBasedAccessControl";
private final static String JSP_PATH = "/lessons/" + LESSON_NAME + "/"; private final static String JSP_PATH = "/lessons/" + LESSON_NAME + "/";
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
@ -73,6 +127,7 @@ public class RoleBasedAccessControl extends LessonAdapter
private Map lessonFunctions = new Hashtable(); private Map lessonFunctions = new Hashtable();
public static synchronized Connection getConnection(WebSession s) public static synchronized Connection getConnection(WebSession s)
throws SQLException, ClassNotFoundException throws SQLException, ClassNotFoundException
{ {
@ -84,6 +139,7 @@ public class RoleBasedAccessControl extends LessonAdapter
return connection; return connection;
} }
public RoleBasedAccessControl() public RoleBasedAccessControl()
{ {
String myClassName = parseClassName(this.getClass().getName()); String myClassName = parseClassName(this.getClass().getName());
@ -94,13 +150,19 @@ public class RoleBasedAccessControl extends LessonAdapter
registerAction(new EditProfile(this, myClassName, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, myClassName, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, myClassName, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); registerAction(new Login(this, myClassName, LOGIN_ACTION,
registerAction(new Logout(this, myClassName, LOGOUT_ACTION, getAction(LOGIN_ACTION))); getAction(LISTSTAFF_ACTION)));
registerAction(new FindProfile(this, myClassName, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new Logout(this, myClassName, LOGOUT_ACTION,
registerAction(new UpdateProfile(this, myClassName, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); getAction(LOGIN_ACTION)));
registerAction(new DeleteProfile(this, myClassName, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); registerAction(new FindProfile(this, myClassName, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, myClassName,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, myClassName,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
protected static String parseClassName(String fqcn) protected static String parseClassName(String fqcn)
{ {
String className = fqcn; String className = fqcn;
@ -112,11 +174,13 @@ public class RoleBasedAccessControl extends LessonAdapter
return className; return className;
} }
protected void registerAction(LessonAction action) protected void registerAction(LessonAction action)
{ {
lessonFunctions.put(action.getActionName(), action); lessonFunctions.put(action.getActionName(), action);
} }
/** /**
* Gets the category attribute of the CommandInjection object * Gets the category attribute of the CommandInjection object
* *
@ -136,20 +200,25 @@ public class RoleBasedAccessControl extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "Many sites attempt to restrict access to resources by role." ); hints
hints.add( "Developers frequently make mistakes implementing this scheme." ); .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."); hints.add("Attempt combinations of users, roles, and resources.");
// Stage 1 // Stage 1
hints.add( "How does the application know that the user selected the delete function?" ); hints
.add("How does the application know that the user selected the delete function?");
// Stage 2 // Stage 2
// Stage 3 // Stage 3
hints.add( "How does the application know that the user selected any particular employee to view?" ); hints
.add("How does the application know that the user selected any particular employee to view?");
// Stage 4 // Stage 4
hints.add( "Note that the contents of the staff listing change depending on who is logged in." ); hints
.add("Note that the contents of the staff listing change depending on who is logged in.");
return hints; return hints;
} }
@ -169,26 +238,34 @@ public class RoleBasedAccessControl extends LessonAdapter
switch (getStage(s)) switch (getStage(s))
{ {
case 1: case 1:
instructions = "Stage " + getStage(s) + ": Breaking functional access control.<br>" + instructions = "Stage "
"You should be able to login as a regular employee and delete another user's employee " + + getStage(s)
"profile, even though that is supposed to be an HR-only function."; + ": Breaking functional access control.<br>"
+ "You should be able to login as a regular employee and delete another user's employee "
+ "profile, even though that is supposed to be an HR-only function.";
break; break;
case 2: case 2:
instructions = "Stage " + getStage(s) + ": Implementing access control in the Business Layer<br>" instructions = "Stage "
+ "Access control has already been implemented in the Presentation Layer, but as we have just " + + getStage(s)
"seen, this is not enough. Implement access control in the Businesss Layer to verify " + + ": Implementing access control in the Business Layer<br>"
"authorization to use the Delete function before actually executing it."; + "Access control has already been implemented in the Presentation Layer, but as we have just "
+ "seen, this is not enough. Implement access control in the Businesss Layer to verify "
+ "authorization to use the Delete function before actually executing it.";
break; break;
case 3: case 3:
instructions = "Stage " + getStage(s) + ": Breaking data access control.<br>" + instructions = "Stage "
"Data Layer access control is being already done on the staff list, but it has not been " + + getStage(s)
"globally implemented. Take advantage of this to login as a regular employee and view the " + + ": Breaking data access control.<br>"
"CEO's employee profile."; + "Data Layer access control is being already done on the staff list, but it has not been "
+ "globally implemented. Take advantage of this to login as a regular employee and view the "
+ "CEO's employee profile.";
break; break;
case 4: case 4:
instructions = "Stage " + getStage(s) + ": Implementing access control in the Data Layer.<br>" + instructions = "Stage "
"Implement Data Layer access control to prevent unauthorized (and potentially career threatening) " + + getStage(s)
"access to employee personal data."; + ": Implementing access control in the Data Layer.<br>"
+ "Implement Data Layer access control to prevent unauthorized (and potentially career threatening) "
+ "access to employee personal data.";
break; break;
default: default:
// Illegal stage value // Illegal stage value
@ -206,7 +283,6 @@ public class RoleBasedAccessControl extends LessonAdapter
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
// Here is where dispatching to the various action handlers happens. // Here is where dispatching to the various action handlers happens.
@ -289,6 +365,7 @@ public class RoleBasedAccessControl extends LessonAdapter
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
public void handleRequest_BACKUP(WebSession s) public void handleRequest_BACKUP(WebSession s)
{ {
// Here is where dispatching to the various action handlers happens. // Here is where dispatching to the various action handlers happens.
@ -328,7 +405,8 @@ public class RoleBasedAccessControl extends LessonAdapter
if (action.isAuthenticated(s)) if (action.isAuthenticated(s))
{ {
int userId = action.getUserId(s); int userId = action.getUserId(s);
if (action.isAuthorized(s, userId, action.getActionName())) if (action.isAuthorized(s, userId, action
.getActionName()))
{ {
action.handleRequest(s); action.handleRequest(s);
} }
@ -382,30 +460,38 @@ public class RoleBasedAccessControl extends LessonAdapter
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
public boolean isAuthorized(WebSession s, int userId, String functionId) public boolean isAuthorized(WebSession s, int userId, String functionId)
{ {
//System.out.println("Checking authorization from " + getCurrentAction(s)); //System.out.println("Checking authorization from " + getCurrentAction(s));
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.isAuthorized(s, userId, functionId); return action.isAuthorized(s, userId, functionId);
} }
public int getUserId(WebSession s) throws ParameterNotFoundException public int getUserId(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.getUserId(s); return action.getUserId(s);
} }
public String getUserName(WebSession s) throws ParameterNotFoundException public String getUserName(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.getUserName(s); return action.getUserName(s);
} }
public String getTemplatePage(WebSession s) public String getTemplatePage(WebSession s)
{ {
return JSP_PATH + LESSON_NAME + ".jsp"; return JSP_PATH + LESSON_NAME + ".jsp";
} }
public String getPage(WebSession s) public String getPage(WebSession s)
{ {
String page = JSP_PATH + getCurrentAction(s) + ".jsp"; String page = JSP_PATH + getCurrentAction(s) + ".jsp";
@ -414,11 +500,13 @@ public class RoleBasedAccessControl extends LessonAdapter
return page; return page;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
@ -429,6 +517,7 @@ public class RoleBasedAccessControl extends LessonAdapter
return "LAB: Role Based Access Control"; return "LAB: Role Based Access Control";
} }
public String getSourceFileName() public String getSourceFileName()
{ {
// FIXME: Need to generalize findSourceResource() and use it on the currently active // FIXME: Need to generalize findSourceResource() and use it on the currently active

View File

@ -4,13 +4,45 @@ import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.DefaultLessonAction; import org.owasp.webgoat.lessons.DefaultLessonAction;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class SearchStaff extends DefaultLessonAction
{ {
public SearchStaff(AbstractLesson lesson, String lessonName, String actionName)
public SearchStaff(AbstractLesson lesson, String lessonName,
String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.SEARCHSTAFF_ACTION; return RoleBasedAccessControl.SEARCHSTAFF_ACTION;

View File

@ -14,50 +14,103 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class UpdateProfile extends DefaultLessonAction public class UpdateProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public UpdateProfile(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public UpdateProfile(AbstractLesson lesson, String lessonName,
String actionName, LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
int subjectId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID, 0); int subjectId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID, 0);
String firstName = s.getParser().getStringParameter(RoleBasedAccessControl.FIRST_NAME); String firstName = s.getParser().getStringParameter(
String lastName = s.getParser().getStringParameter(RoleBasedAccessControl.LAST_NAME); RoleBasedAccessControl.FIRST_NAME);
String ssn = s.getParser().getStringParameter(RoleBasedAccessControl.SSN); String lastName = s.getParser().getStringParameter(
String title = s.getParser().getStringParameter(RoleBasedAccessControl.TITLE); RoleBasedAccessControl.LAST_NAME);
String phone = s.getParser().getStringParameter(RoleBasedAccessControl.PHONE_NUMBER); String ssn = s.getParser().getStringParameter(
String address1 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS1); RoleBasedAccessControl.SSN);
String address2 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS2); String title = s.getParser().getStringParameter(
int manager = s.getParser().getIntParameter(RoleBasedAccessControl.MANAGER); RoleBasedAccessControl.TITLE);
String startDate = s.getParser().getStringParameter(RoleBasedAccessControl.START_DATE); String phone = s.getParser().getStringParameter(
int salary = s.getParser().getIntParameter(RoleBasedAccessControl.SALARY); RoleBasedAccessControl.PHONE_NUMBER);
String ccn = s.getParser().getStringParameter(RoleBasedAccessControl.CCN); String address1 = s.getParser().getStringParameter(
int ccnLimit = s.getParser().getIntParameter(RoleBasedAccessControl.CCN_LIMIT); RoleBasedAccessControl.ADDRESS1);
String disciplinaryActionDate = s.getParser().getStringParameter(RoleBasedAccessControl.DISCIPLINARY_DATE); String address2 = s.getParser().getStringParameter(
String disciplinaryActionNotes = s.getParser().getStringParameter(RoleBasedAccessControl.DISCIPLINARY_NOTES); RoleBasedAccessControl.ADDRESS2);
String personalDescription = s.getParser().getStringParameter(RoleBasedAccessControl.DESCRIPTION); int manager = s.getParser().getIntParameter(
RoleBasedAccessControl.MANAGER);
String startDate = s.getParser().getStringParameter(
RoleBasedAccessControl.START_DATE);
int salary = s.getParser().getIntParameter(
RoleBasedAccessControl.SALARY);
String ccn = s.getParser().getStringParameter(
RoleBasedAccessControl.CCN);
int ccnLimit = s.getParser().getIntParameter(
RoleBasedAccessControl.CCN_LIMIT);
String disciplinaryActionDate = s.getParser().getStringParameter(
RoleBasedAccessControl.DISCIPLINARY_DATE);
String disciplinaryActionNotes = s.getParser().getStringParameter(
RoleBasedAccessControl.DISCIPLINARY_NOTES);
String personalDescription = s.getParser().getStringParameter(
RoleBasedAccessControl.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, Employee employee = new Employee(subjectId, firstName, lastName,
address1, address2, manager, startDate, salary, ssn, title, phone, address1, address2, manager, startDate,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, salary, ccn, ccnLimit, disciplinaryActionDate,
personalDescription); disciplinaryActionNotes, personalDescription);
if (subjectId > 0) if (subjectId > 0)
{ {
this.changeEmployeeProfile(s, userId, subjectId, employee); this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID, Integer.toString(subjectId)); setRequestAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ID, Integer
.toString(subjectId));
} }
else else
this.createEmployeeProfile(s, userId, employee); this.createEmployeeProfile(s, userId, employee);
@ -81,37 +134,45 @@ public class UpdateProfile extends DefaultLessonAction
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.VIEWPROFILE_ACTION; return RoleBasedAccessControl.VIEWPROFILE_ACTION;
} }
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) public void changeEmployeeProfile(WebSession s, int userId, int subjectId,
throws UnauthorizedException Employee employee) throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = '" + employee.getFirstName() + String query = "UPDATE employee SET first_name = '"
"', last_name = '" + employee.getLastName() + + employee.getFirstName() + "', last_name = '"
"', ssn = '" + employee.getSsn() + + employee.getLastName() + "', ssn = '" + employee.getSsn()
"', title = '" + employee.getTitle() + + "', title = '" + employee.getTitle() + "', phone = '"
"', phone = '" + employee.getPhoneNumber() + + employee.getPhoneNumber() + "', address1 = '"
"', address1 = '" + employee.getAddress1() + + employee.getAddress1() + "', address2 = '"
"', address2 = '" + employee.getAddress2() + + employee.getAddress2() + "', manager = "
"', manager = " + employee.getManager() + + employee.getManager()
", start_date = '" + employee.getStartDate() + + ", start_date = '"
"', ccn = '" + employee.getCcn() + + employee.getStartDate()
"', ccn_limit = " + employee.getCcnLimit() + + "', ccn = '"
+ employee.getCcn()
+ "', ccn_limit = "
+ employee.getCcnLimit()
+
// "', disciplined_date = '" + employee.getDisciplinaryActionDate() + // "', disciplined_date = '" + employee.getDisciplinaryActionDate() +
// "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() + // "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() +
", personal_description = '" + employee.getPersonalDescription() + ", personal_description = '"
"' WHERE userid = " + subjectId; + employee.getPersonalDescription() + "' WHERE userid = "
+ subjectId;
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -128,31 +189,39 @@ public class UpdateProfile extends DefaultLessonAction
} }
} }
public void changeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException public void changeEmployeeProfile_BACKUP(WebSession s, int userId,
int subjectId, Employee employee) throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = '" + employee.getFirstName() + String query = "UPDATE employee SET first_name = '"
"', last_name = '" + employee.getLastName() + + employee.getFirstName() + "', last_name = '"
"', ssn = '" + employee.getSsn() + + employee.getLastName() + "', ssn = '" + employee.getSsn()
"', title = '" + employee.getTitle() + + "', title = '" + employee.getTitle() + "', phone = '"
"', phone = '" + employee.getPhoneNumber() + + employee.getPhoneNumber() + "', address1 = '"
"', address1 = '" + employee.getAddress1() + + employee.getAddress1() + "', address2 = '"
"', address2 = '" + employee.getAddress2() + + employee.getAddress2() + "', manager = "
"', manager = " + employee.getManager() + + employee.getManager()
", start_date = '" + employee.getStartDate() + + ", start_date = '"
"', ccn = '" + employee.getCcn() + + employee.getStartDate()
"', ccn_limit = " + employee.getCcnLimit() + + "', ccn = '"
+ employee.getCcn()
+ "', ccn_limit = "
+ employee.getCcnLimit()
+
// "', disciplined_date = '" + employee.getDisciplinaryActionDate() + // "', disciplined_date = '" + employee.getDisciplinaryActionDate() +
// "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() + // "', disciplined_notes = '" + employee.getDisciplinaryActionNotes() +
", personal_description = '" + employee.getPersonalDescription() + ", personal_description = '"
"' WHERE userid = " + subjectId; + employee.getPersonalDescription() + "' WHERE userid = "
+ subjectId;
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -175,8 +244,11 @@ public class UpdateProfile extends DefaultLessonAction
int uid = -1; int uid = -1;
try try
{ {
Statement statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); Statement statement = WebSession.getConnection(s).createStatement(
ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement
.executeQuery("select max(userid) as uid from employee");
results.first(); results.first();
uid = results.getInt("uid"); uid = results.getInt("uid");
} }
@ -184,7 +256,9 @@ public class UpdateProfile extends DefaultLessonAction
{ {
sqle.printStackTrace(); sqle.printStackTrace();
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
} catch (ClassNotFoundException e) { }
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
@ -192,36 +266,32 @@ public class UpdateProfile extends DefaultLessonAction
} }
public void createEmployeeProfile(WebSession s, int userId, Employee employee) public void createEmployeeProfile(WebSession s, int userId,
throws UnauthorizedException Employee employee) throws UnauthorizedException
{ {
try try
{ {
int newUID = getNextUID(s); int newUID = getNextUID(s);
// FIXME: This max() thing doesn't work on InstantDB. // FIXME: This max() thing doesn't work on InstantDB.
String query = "INSERT INTO employee VALUES (" + newUID + ", '" String query = "INSERT INTO employee VALUES (" + newUID + ", '"
+ employee.getFirstName() + "','" + employee.getFirstName() + "','" + employee.getLastName()
+ employee.getLastName() + "','" + "','" + employee.getSsn() + "','goober57x','"
+ employee.getSsn() + "','goober57x','" + employee.getTitle() + "','" + employee.getPhoneNumber()
+ employee.getTitle() + "','" + "','" + employee.getAddress1() + "','"
+ employee.getPhoneNumber() + "','" + employee.getAddress2() + "'," + employee.getManager()
+ employee.getAddress1() + "','" + ",'" + employee.getStartDate() + "',"
+ employee.getAddress2() + "'," + employee.getSalary() + ",'" + employee.getCcn() + "',"
+ employee.getManager() + ",'"
+ employee.getStartDate() + "',"
+ employee.getSalary() + ",'"
+ employee.getCcn() + "',"
+ employee.getCcnLimit() + ",'" + employee.getCcnLimit() + ",'"
+ employee.getDisciplinaryActionDate() + "','" + employee.getDisciplinaryActionDate() + "','"
+ employee.getDisciplinaryActionNotes() + "','" + employee.getDisciplinaryActionNotes() + "','"
+ employee.getPersonalDescription() + employee.getPersonalDescription() + "')";
+ "')";
//System.out.println("Query: " + query); //System.out.println("Query: " + query);
try try
{ {
Statement statement = WebSession.getConnection(s).createStatement(); Statement statement = WebSession.getConnection(s)
.createStatement();
statement.executeUpdate(query); statement.executeUpdate(query);
} }
catch (SQLException sqle) catch (SQLException sqle)
@ -236,7 +306,8 @@ public class UpdateProfile extends DefaultLessonAction
try try
{ {
Statement statement = WebSession.getConnection(s).createStatement(); Statement statement = WebSession.getConnection(s)
.createStatement();
statement.executeUpdate(query); statement.executeUpdate(query);
} }
catch (SQLException sqle) catch (SQLException sqle)

View File

@ -12,35 +12,71 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class ViewProfile extends DefaultLessonAction
{ {
public ViewProfile(AbstractLesson lesson, String lessonName, String actionName)
public ViewProfile(AbstractLesson lesson, String lessonName,
String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
int employeeId = -1; int employeeId = -1;
try try
{ {
// User selected employee // User selected employee
employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
} }
catch (ParameterNotFoundException e) catch (ParameterNotFoundException e)
{ {
// May be an internally selected employee // May be an internally selected employee
employeeId = getIntRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID); employeeId = getIntRequestAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ID);
} }
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
@ -48,62 +84,69 @@ public class ViewProfile extends DefaultLessonAction
updateLessonStatus(s); updateLessonStatus(s);
} }
private void updateLessonStatus(WebSession s) private void updateLessonStatus(WebSession s)
{ {
// If the logged in user is not authorized to see the given employee's data, stage is complete. // If the logged in user is not authorized to see the given employee's data, stage is complete.
try try
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); + RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
if (getStage(s) == 3 && !isAuthorizedForEmployee(s, userId, employeeId)) if (getStage(s) == 3
&& !isAuthorizedForEmployee(s, userId, employeeId))
{ {
s.setMessage("Welcome to stage 4 -- protecting the data layer"); s.setMessage("Welcome to stage 4 -- protecting the data layer");
setStage(s, 4); setStage(s, 4);
} }
} }
catch (ParameterNotFoundException e) catch (ParameterNotFoundException e)
{ {}
}
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.VIEWPROFILE_ACTION; return RoleBasedAccessControl.VIEWPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, int userId,
int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +
@ -126,8 +169,9 @@ public class ViewProfile extends DefaultLessonAction
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId)
throws UnauthorizedException public Employee getEmployeeProfile_BACKUP(WebSession s, int userId,
int subjectUserId) throws UnauthorizedException
{ {
// Query the database to determine if the given employee is owned by the given user // Query the database to determine if the given employee is owned by the given user
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
@ -137,30 +181,32 @@ public class ViewProfile extends DefaultLessonAction
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +

View File

@ -14,29 +14,63 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class ListStaff extends DefaultLessonAction
{ {
public ListStaff(AbstractLesson lesson, String lessonName, String actionName) public ListStaff(AbstractLesson lesson, String lessonName, String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID);
List employees = getAllEmployees(s, userId); List employees = getAllEmployees(s, userId);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return SQLInjection.LISTSTAFF_ACTION; return SQLInjection.LISTSTAFF_ACTION;
@ -53,11 +87,14 @@ public class ListStaff extends DefaultLessonAction
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " 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 + ")"; + "(SELECT employee_id FROM ownership WHERE employer_id = "
+ userId + ")";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
@ -67,7 +104,8 @@ public class ListStaff extends DefaultLessonAction
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
//System.out.println("Retrieving employee stub for role " + role); //System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
employees.add(stub); employees.add(stub);
} }
} }
@ -83,10 +121,10 @@ public class ListStaff extends DefaultLessonAction
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
public List getAllEmployees_BACKUP(WebSession s, int userId) public List getAllEmployees_BACKUP(WebSession s, int userId)
throws UnauthorizedException throws UnauthorizedException
{ {
@ -97,11 +135,14 @@ public class ListStaff extends DefaultLessonAction
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " 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 + ")"; + "(SELECT employee_id FROM ownership WHERE employer_id = "
+ userId + ")";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
@ -111,7 +152,8 @@ public class ListStaff extends DefaultLessonAction
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
//System.out.println("Retrieving employee stub for role " + role); //System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
employees.add(stub); employees.add(stub);
} }
} }
@ -127,7 +169,6 @@ public class ListStaff extends DefaultLessonAction
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }

View File

@ -16,29 +16,66 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Login extends DefaultLessonAction public class Login extends DefaultLessonAction
{ {
private LessonAction chainedAction; private LessonAction chainedAction;
public Login(AbstractLesson lesson, String lessonName, String actionName, LessonAction chainedAction)
public Login(AbstractLesson lesson, String lessonName, String actionName,
LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest( WebSession s ) throws ParameterNotFoundException, ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException,
ValidationException
{ {
//System.out.println("Login.handleRequest()"); //System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s); List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
String employeeId = null; String employeeId = null;
try try
{ {
employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID); employeeId = s.getParser().getStringParameter(
String password = s.getParser().getRawParameter(SQLInjection.PASSWORD); SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(
SQLInjection.PASSWORD);
// Attempt authentication // Attempt authentication
boolean authenticated = login(s, employeeId, password); boolean authenticated = login(s, employeeId, password);
@ -70,10 +107,12 @@ public class Login extends DefaultLessonAction
catch (ParameterNotFoundException pnfe) catch (ParameterNotFoundException pnfe)
{ {
// No credentials offered, so we log them out // No credentials offered, so we log them out
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); setSessionAttribute(s, getLessonName() + ".isAuthenticated",
Boolean.FALSE);
} }
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String nextPage = SQLInjection.LOGIN_ACTION; String nextPage = SQLInjection.LOGIN_ACTION;
@ -85,6 +124,7 @@ public class Login extends DefaultLessonAction
} }
public boolean requiresAuthentication() public boolean requiresAuthentication()
{ {
return false; return false;
@ -98,16 +138,21 @@ public class Login extends DefaultLessonAction
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; String query = "SELECT * FROM employee WHERE userid = " + userId
+ " and password = '" + password + "'";
//System.out.println("Query:" + query); //System.out.println("Query:" + query);
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first()) if (answer_results.first())
{ {
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); setSessionAttribute(s,
setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId); getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID, userId);
authenticated = true; authenticated = true;
} }
} }
@ -127,6 +172,7 @@ public class Login extends DefaultLessonAction
return authenticated; return authenticated;
} }
public boolean login_BACKUP(WebSession s, String userId, String password) public boolean login_BACKUP(WebSession s, String userId, String password)
{ {
//System.out.println("Logging in to lesson"); //System.out.println("Logging in to lesson");
@ -134,16 +180,21 @@ public class Login extends DefaultLessonAction
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; String query = "SELECT * FROM employee WHERE userid = " + userId
+ " and password = '" + password + "'";
//System.out.println("Query:" + query); //System.out.println("Query:" + query);
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first()) if (answer_results.first())
{ {
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); setSessionAttribute(s,
setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId); getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID, userId);
authenticated = true; authenticated = true;
} }
@ -164,6 +215,7 @@ public class Login extends DefaultLessonAction
return authenticated; return authenticated;
} }
public List getAllEmployees(WebSession s) public List getAllEmployees(WebSession s)
{ {
List<EmployeeStub> employees = new Vector<EmployeeStub>(); List<EmployeeStub> employees = new Vector<EmployeeStub>();
@ -173,12 +225,14 @@ public class Login extends DefaultLessonAction
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " + String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
"where employee.userid=roles.userid"; + "where employee.userid=roles.userid";
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
@ -187,7 +241,8 @@ public class Login extends DefaultLessonAction
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
employees.add(stub); employees.add(stub);
} }
} }
@ -203,22 +258,23 @@ public class Login extends DefaultLessonAction
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
private void updateLessonStatus(WebSession s) private void updateLessonStatus(WebSession s)
{ {
try try
{ {
String employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID); String employeeId = s.getParser().getStringParameter(
String password = s.getParser().getRawParameter(SQLInjection.PASSWORD); SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(
SQLInjection.PASSWORD);
switch (getStage(s)) switch (getStage(s))
{ {
case 1: case 1:
if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID && isAuthenticated(s)) if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID
&& isAuthenticated(s))
{ {
s.setMessage("Welcome to stage 2"); s.setMessage("Welcome to stage 2");
setStage(s, 2); setStage(s, 2);
@ -226,8 +282,9 @@ public class Login extends DefaultLessonAction
break; break;
case 2: case 2:
// This assumes the student hasn't modified login_BACKUP(). // This assumes the student hasn't modified login_BACKUP().
if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID && if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID
!isAuthenticated(s) && login_BACKUP(s, employeeId, password)) && !isAuthenticated(s)
&& login_BACKUP(s, employeeId, password))
{ {
s.setMessage("Welcome to stage 3"); s.setMessage("Welcome to stage 3");
setStage(s, 3); setStage(s, 3);
@ -238,8 +295,7 @@ public class Login extends DefaultLessonAction
} }
} }
catch (ParameterNotFoundException pnfe) catch (ParameterNotFoundException pnfe)
{ {}
}
} }
} }

View File

@ -25,63 +25,119 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute
* this software.
* *
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/ */
public class SQLInjection extends LessonAdapter public class SQLInjection extends LessonAdapter
{ {
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 String LESSON_NAME = "SQLInjection"; private final static String LESSON_NAME = "SQLInjection";
private final static String JSP_PATH = "/lessons/" + LESSON_NAME + "/"; private final static String JSP_PATH = "/lessons/" + LESSON_NAME + "/";
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";
private static Connection connection = null; private static Connection connection = null;
private Map lessonFunctions = new Hashtable(); private Map lessonFunctions = new Hashtable();
public static synchronized Connection getConnection(WebSession s) public static synchronized Connection getConnection(WebSession s)
throws SQLException, ClassNotFoundException throws SQLException, ClassNotFoundException
{ {
@ -93,6 +149,7 @@ public class SQLInjection extends LessonAdapter
return connection; return connection;
} }
public SQLInjection() public SQLInjection()
{ {
String myClassName = parseClassName(this.getClass().getName()); String myClassName = parseClassName(this.getClass().getName());
@ -103,13 +160,19 @@ public class SQLInjection extends LessonAdapter
registerAction(new EditProfile(this, myClassName, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, myClassName, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, myClassName, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); registerAction(new Login(this, myClassName, LOGIN_ACTION,
registerAction(new Logout(this, myClassName, LOGOUT_ACTION, getAction(LOGIN_ACTION))); getAction(LISTSTAFF_ACTION)));
registerAction(new FindProfile(this, myClassName, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new Logout(this, myClassName, LOGOUT_ACTION,
registerAction(new UpdateProfile(this, myClassName, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); getAction(LOGIN_ACTION)));
registerAction(new DeleteProfile(this, myClassName, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); registerAction(new FindProfile(this, myClassName, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, myClassName,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, myClassName,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
protected static String parseClassName(String fqcn) protected static String parseClassName(String fqcn)
{ {
String className = fqcn; String className = fqcn;
@ -121,11 +184,13 @@ public class SQLInjection extends LessonAdapter
return className; return className;
} }
protected void registerAction(LessonAction action) protected void registerAction(LessonAction action)
{ {
lessonFunctions.put(action.getActionName(), action); lessonFunctions.put(action.getActionName(), action);
} }
/** /**
* Gets the category attribute of the CrossSiteScripting object * Gets the category attribute of the CrossSiteScripting object
* *
@ -145,21 +210,27 @@ public class SQLInjection extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "The application is taking your input and inserting it at the end of a pre-formed SQL command." ); hints
hints.add( "This is the code for the query being built and issued by WebGoat:<br><br> " + .add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
"\"SELECT * FROM employee WHERE userid = \" + userId + \" and password = \" + password" ); hints
hints.add( "Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " + .add("This is the code for the query being built and issued by WebGoat:<br><br> "
"Try appending a SQL statement that always resolves to true"); + "\"SELECT * FROM employee WHERE userid = \" + userId + \" and password = \" + password");
hints
.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Try appending a SQL statement that always resolves to true");
// Stage 1 // Stage 1
hints.add( "You may need to use WebScarab to remove a field length limit to fit your attack." ); 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 [ smith' OR '1' = '1 ]."); hints.add("Try entering a password of [ smith' OR '1' = '1 ].");
// Stage 2 // Stage 2
hints.add( "Many of WebGoat's database queries are already parameterized. Search the project for PreparedStatement." ); hints
.add("Many of WebGoat's database queries are already parameterized. Search the project for PreparedStatement.");
// Stage 3 // Stage 3
hints.add( "Try entering a password of [ 101 OR 1=1 ORDER BY 'salary' ]." ); hints
.add("Try entering a password of [ 101 OR 1=1 ORDER BY 'salary' ].");
// Stage 4 // Stage 4
@ -181,27 +252,35 @@ public class SQLInjection extends LessonAdapter
switch (getStage(s)) switch (getStage(s))
{ {
case 1: case 1:
instructions = "Stage " + getStage(s) + ": Use String SQL Injection to bypass authentication. " instructions = "Stage "
+ getStage(s)
+ ": Use String SQL Injection to bypass authentication. "
+ "The goal here is to login as the user " + "The goal here is to login as the user "
+ PRIZE_EMPLOYEE_NAME + PRIZE_EMPLOYEE_NAME
+ ", who is in the Admin group. " + ", who is in the Admin group. "
+ "You do not have the password, but the form is SQL injectable."; + "You do not have the password, but the form is SQL injectable.";
break; break;
case 2: case 2:
instructions = "Stage " + getStage(s) + ": Use a parameterized query.<br>" + instructions = "Stage "
"A dynamic SQL query is not necessary for the login function to work. Change login " + + getStage(s)
"to use a parameterized query to protect against malicious SQL in the query parameters."; + ": Use a parameterized query.<br>"
+ "A dynamic SQL query is not necessary for the login function to work. Change login "
+ "to use a parameterized query to protect against malicious SQL in the query parameters.";
break; break;
case 3: case 3:
instructions = "Stage " + getStage(s) + ": Use Integer SQL Injection to bypass access control.<br>" + instructions = "Stage "
"The goal here is to view the CEO's employee profile, again, even with data access " + + getStage(s)
"control checks in place from a previous lesson. " + + ": Use Integer SQL Injection to bypass access control.<br>"
"As before, you do not have the password, but the form is SQL injectable."; + "The goal here is to view the CEO's employee profile, again, even with data access "
+ "control checks in place from a previous lesson. "
+ "As before, you do not have the password, but the form is SQL injectable.";
break; break;
case 4: case 4:
instructions = "Stage " + getStage(s) + ": Use a parameterized query again.<br>" + instructions = "Stage "
"Change the ViewProfile function to use a parameterized query to protect against " + + getStage(s)
"malicious SQL in the numeric query parameter."; + ": Use a parameterized query again.<br>"
+ "Change the ViewProfile function to use a parameterized query to protect against "
+ "malicious SQL in the numeric query parameter.";
break; break;
default: default:
// Illegal stage value // Illegal stage value
@ -218,6 +297,7 @@ public class SQLInjection extends LessonAdapter
return (LessonAction) lessonFunctions.get(actionName); return (LessonAction) lessonFunctions.get(actionName);
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if (s.getLessonSession(this) == null) if (s.getLessonSession(this) == null)
@ -242,7 +322,8 @@ public class SQLInjection extends LessonAdapter
if (action != null) if (action != null)
{ {
//System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + action.getActionName()); //System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + action.getActionName());
if (!action.requiresAuthentication() || action.isAuthenticated(s)) if (!action.requiresAuthentication()
|| action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
//setCurrentAction(s, action.getNextPage(s)); //setCurrentAction(s, action.getNextPage(s));
@ -288,30 +369,38 @@ public class SQLInjection extends LessonAdapter
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
public boolean isAuthorized(WebSession s, int userId, String functionId) public boolean isAuthorized(WebSession s, int userId, String functionId)
{ {
//System.out.println("Checking authorization from " + getCurrentAction(s)); //System.out.println("Checking authorization from " + getCurrentAction(s));
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.isAuthorized(s, userId, functionId); return action.isAuthorized(s, userId, functionId);
} }
public int getUserId(WebSession s) throws ParameterNotFoundException public int getUserId(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.getUserId(s); return action.getUserId(s);
} }
public String getUserName(WebSession s) throws ParameterNotFoundException public String getUserName(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = (LessonAction) lessonFunctions.get(getCurrentAction(s)); LessonAction action = (LessonAction) lessonFunctions
.get(getCurrentAction(s));
return action.getUserName(s); return action.getUserName(s);
} }
public String getTemplatePage(WebSession s) public String getTemplatePage(WebSession s)
{ {
return JSP_PATH + LESSON_NAME + ".jsp"; return JSP_PATH + LESSON_NAME + ".jsp";
} }
public String getPage(WebSession s) public String getPage(WebSession s)
{ {
String page = JSP_PATH + getCurrentAction(s) + ".jsp"; String page = JSP_PATH + getCurrentAction(s) + ".jsp";
@ -320,11 +409,13 @@ public class SQLInjection extends LessonAdapter
return page; return page;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CrossSiteScripting object * Gets the title attribute of the CrossSiteScripting object
* *
@ -335,6 +426,7 @@ public class SQLInjection extends LessonAdapter
return "LAB: SQL Injection"; return "LAB: SQL Injection";
} }
public String getSourceFileName() public String getSourceFileName()
{ {
// FIXME: Need to generalize findSourceResource() and use it on the currently active // FIXME: Need to generalize findSourceResource() and use it on the currently active

View File

@ -12,15 +12,47 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at 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 class ViewProfile extends DefaultLessonAction
{ {
public ViewProfile(AbstractLesson lesson, String lessonName, String actionName)
public ViewProfile(AbstractLesson lesson, String lessonName,
String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
@ -28,17 +60,20 @@ public class ViewProfile extends DefaultLessonAction
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID); String userId = getSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID);
String employeeId = null; String employeeId = null;
try try
{ {
// User selected employee // User selected employee
employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID); employeeId = s.getParser().getRawParameter(
SQLInjection.EMPLOYEE_ID);
} }
catch (ParameterNotFoundException e) catch (ParameterNotFoundException e)
{ {
// May be an internally selected employee // May be an internally selected employee
employeeId = getRequestAttribute(s, getLessonName() + "." + SQLInjection.EMPLOYEE_ID); employeeId = getRequestAttribute(s, getLessonName() + "."
+ SQLInjection.EMPLOYEE_ID);
} }
// FIXME: If this fails and returns null, ViewProfile.jsp will blow up as it expects an Employee. // FIXME: If this fails and returns null, ViewProfile.jsp will blow up as it expects an Employee.
@ -48,7 +83,8 @@ public class ViewProfile extends DefaultLessonAction
if (employee == null) if (employee == null)
getLesson().setCurrentAction(s, SQLInjection.ERROR_ACTION); getLesson().setCurrentAction(s, SQLInjection.ERROR_ACTION);
else else
setSessionAttribute(s, getLessonName() + "." + SQLInjection.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
@ -56,43 +92,47 @@ public class ViewProfile extends DefaultLessonAction
updateLessonStatus(s, employee); updateLessonStatus(s, employee);
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return SQLInjection.VIEWPROFILE_ACTION; return SQLInjection.VIEWPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, String userId, String subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, String userId,
String subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +
@ -115,8 +155,9 @@ public class ViewProfile extends DefaultLessonAction
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, String userId, String subjectUserId)
throws UnauthorizedException public Employee getEmployeeProfile_BACKUP(WebSession s, String userId,
String subjectUserId) throws UnauthorizedException
{ {
// Query the database to determine if this employee has access to this function // 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 // Query the database for the profile data of the given employee if "owned" by the given user
@ -126,30 +167,32 @@ public class ViewProfile extends DefaultLessonAction
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"),
answer_results.getInt("userid"),
answer_results.getString("first_name"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results.getString("ssn"), answer_results
answer_results.getString("title"), .getString("title"), answer_results
answer_results.getString("phone"), .getString("phone"), answer_results
answer_results.getString("address1"), .getString("address1"), answer_results
answer_results.getString("address2"), .getString("address2"), answer_results
answer_results.getInt("manager"), .getInt("manager"), answer_results
answer_results.getString("start_date"), .getString("start_date"), answer_results
answer_results.getInt("salary"), .getInt("salary"), answer_results
answer_results.getString("ccn"), .getString("ccn"), answer_results
answer_results.getInt("ccn_limit"), .getInt("ccn_limit"), answer_results
answer_results.getString("disciplined_date"), .getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description")); answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " + /* System.out.println("Retrieved employee from db: " +
@ -177,15 +220,19 @@ public class ViewProfile extends DefaultLessonAction
{ {
try try
{ {
String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID); String userId = getSessionAttribute(s, getLessonName() + "."
String employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID); + SQLInjection.USER_ID);
String employeeId = s.getParser().getRawParameter(
SQLInjection.EMPLOYEE_ID);
switch (getStage(s)) switch (getStage(s))
{ {
case 3: case 3:
// If the employee we are viewing is the prize and we are not authorized to have it, // If the employee we are viewing is the prize and we are not authorized to have it,
// the stage is completed // the stage is completed
if (employee != null && employee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID && if (employee != null
!isAuthorizedForEmployee(s, Integer.parseInt(userId), employee.getId())) && employee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID
&& !isAuthorizedForEmployee(s, Integer
.parseInt(userId), employee.getId()))
{ {
s.setMessage("Welcome to stage 4"); s.setMessage("Welcome to stage 4");
setStage(s, 4); setStage(s, 4);
@ -200,14 +247,16 @@ public class ViewProfile extends DefaultLessonAction
Employee targetEmployee = null; Employee targetEmployee = null;
try try
{ {
targetEmployee = getEmployeeProfile_BACKUP(s, userId, employeeId); targetEmployee = getEmployeeProfile_BACKUP(s,
userId, employeeId);
} }
catch (UnauthorizedException e) catch (UnauthorizedException e)
{}
if (targetEmployee != null
&& targetEmployee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID)
{ {
} s
if (targetEmployee != null && targetEmployee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID) .setMessage("Congratulations. You have successfully completed this lesson");
{
s.setMessage("Congratulations. You have successfully completed this lesson");
getLesson().getLessonTracker(s).setCompleted(true); getLesson().getLessonTracker(s).setCompleted(true);
} }
} }
@ -217,8 +266,7 @@ public class ViewProfile extends DefaultLessonAction
} }
} }
catch (ParameterNotFoundException pnfe) catch (ParameterNotFoundException pnfe)
{ {}
}
} }
} }

View File

@ -19,54 +19,90 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
public class SilentTransactions extends LessonAdapter { /*******************************************************************************
private final static Integer DEFAULT_RANKING = new Integer(40);
private final static Double CURRENT_BALANCE = 11987.09;
/**
* Copyright (c) 2002 Free Software Foundation developed under the
* custody of the Open Web Application Security Project
* (http://www.owasp.org) This software package is published by OWASP
* under the GPL. You should read and accept the LICENSE before you
* use, modify and/or redistribute this software.
* *
* @author sherif@macadamian.com *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Sherif Koussa <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created December 26, 2006 * @created December 26, 2006
*/ */
public void handleRequest(WebSession s) { public class SilentTransactions extends LessonAdapter
{
private final static Integer DEFAULT_RANKING = new Integer(40);
private final static Double CURRENT_BALANCE = 11987.09;
public void handleRequest(WebSession s)
{
try try
{ {
if (s.getParser().getRawParameter("from", "").equals("ajax")) if (s.getParser().getRawParameter("from", "").equals("ajax"))
{ {
if (s.getParser().getRawParameter( "confirm", "").equals("Confirm")) if (s.getParser().getRawParameter("confirm", "").equals(
"Confirm"))
{ {
String amount = s.getParser().getRawParameter("amount", ""); String amount = s.getParser().getRawParameter("amount", "");
s.getResponse().setContentType("text/html"); s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse()
.getOutputStream());
StringBuffer result = new StringBuffer(); StringBuffer result = new StringBuffer();
result.append("<br><br>* Congratulations. You have successfully completed this lesson.<br>"); result
.append("<br><br>* Congratulations. You have successfully completed this lesson.<br>");
if (!amount.equals("")) if (!amount.equals(""))
{ {
result.append("You have just silently authorized "); result.append("You have just silently authorized ");
result.append(amount); result.append(amount);
result.append("$ without the user interaction.<br>"); result.append("$ without the user interaction.<br>");
} }
result.append("Now you can send out a spam email containing this link and whoever clicks on it<br>"); result
result.append(" and happens to be logged in the same time will loose their money !!"); .append("Now you can send out a spam email containing this link and whoever clicks on it<br>");
result
.append(" and happens to be logged in the same time will loose their money !!");
out.print(result.toString()); out.print(result.toString());
out.flush(); out.flush();
out.close(); out.close();
getLessonTracker(s).setCompleted(true); getLessonTracker(s).setCompleted(true);
return; return;
} }
else if (s.getParser().getRawParameter( "confirm", "").equals("Transferring")) else if (s.getParser().getRawParameter("confirm", "").equals(
"Transferring"))
{ {
s.getResponse().setContentType("text/html"); s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse()
out.print("<br><br>The Transaction has Completed Successfully."); .getOutputStream());
out
.print("<br><br>The Transaction has Completed Successfully.");
out.flush(); out.flush();
out.close(); out.close();
return; return;
@ -78,7 +114,8 @@ public class SilentTransactions extends LessonAdapter {
ex.printStackTrace(); ex.printStackTrace();
} }
Form form = new Form( getFormAction(), Form.POST ).setName( "form" ).setEncType( "" ); Form form = new Form(getFormAction(), Form.POST).setName("form")
.setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
@ -86,6 +123,7 @@ public class SilentTransactions extends LessonAdapter {
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -96,64 +134,92 @@ public class SilentTransactions extends LessonAdapter {
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep + String script = "<script>"
"function processData(){" + lineSep + + lineSep
" var accountNo = document.getElementById('newAccount').value;" + lineSep + + "function processData(){"
" var amount = document.getElementById('amount').value;" + lineSep + + lineSep
" if ( accountNo == ''){" + lineSep + + " var accountNo = document.getElementById('newAccount').value;"
" alert('Please enter a valid account number to transfer to.')" + lineSep + + lineSep
" return;" + lineSep + + " var amount = document.getElementById('amount').value;"
"}" + lineSep + + lineSep
" else if ( amount == ''){" + lineSep + + " if ( accountNo == ''){"
" alert('Please enter a valid amount to transfer.')" + lineSep + + lineSep
" return;" + lineSep + + " alert('Please enter a valid account number to transfer to.')"
"}" + lineSep + + lineSep
" var balanceValue = document.getElementById('balanceID').innerText;" + lineSep + + " return;"
" balanceValue = balanceValue.replace( new RegExp('$') , '');" + lineSep + + lineSep
" if ( parseFloat(amount) > parseFloat(balanceValue) ) {" + lineSep + + "}"
" alert('You can not transfer more funds than what is available in your balance.')" + lineSep + + lineSep
" return;" + lineSep + + " else if ( amount == ''){"
"}" + lineSep + + lineSep
" document.getElementById('confirm').value = 'Transferring'" + lineSep + + " alert('Please enter a valid amount to transfer.')"
"submitData(accountNo, amount);" + lineSep + + lineSep
" document.getElementById('confirm').value = 'Confirm'" + lineSep + + " return;"
"balanceValue = parseFloat(balanceValue) - parseFloat(amount);" + lineSep + + lineSep
"balanceValue = balanceValue.toFixed(2);" + lineSep + + "}"
"document.getElementById('balanceID').innerText = balanceValue + '$';" + lineSep + + lineSep
"}" + lineSep + + " var balanceValue = document.getElementById('balanceID').innerText;"
"function submitData(accountNo, balance) {" + lineSep + + lineSep
"var url = '/WebGoat/attack?Screen=" + String.valueOf(getScreenId()) + + " balanceValue = balanceValue.replace( new RegExp('$') , '');"
"&menu=" + getDefaultCategory().getRanking().toString() + + lineSep
"&from=ajax&newAccount='+ accountNo+ '&amount=' + balance +'&confirm=' + document.getElementById('confirm').value; " + lineSep + + " if ( parseFloat(amount) > parseFloat(balanceValue) ) {"
"if (typeof XMLHttpRequest != 'undefined') {" + lineSep + + lineSep
"req = new XMLHttpRequest();" + lineSep + + " alert('You can not transfer more funds than what is available in your balance.')"
"} else if (window.ActiveXObject) {" + lineSep + + lineSep
"req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep + + " return;"
" }" + lineSep + + lineSep
" req.open('GET', url, true);" + lineSep + + "}"
" req.onreadystatechange = callback;" + lineSep + + lineSep
" req.send(null);" + lineSep + + " document.getElementById('confirm').value = 'Transferring'"
"}" + lineSep + + lineSep
"function callback() {" + lineSep + + "submitData(accountNo, amount);"
" if (req.readyState == 4) { " + lineSep + + lineSep
" if (req.status == 200) { " + lineSep + + " document.getElementById('confirm').value = 'Confirm'"
" var result = req.responseText ;" + lineSep + + lineSep
" var resultsDiv = document.getElementById('resultsDiv');" + lineSep + + "balanceValue = parseFloat(balanceValue) - parseFloat(amount);"
" resultsDiv.innerHTML = '';" + lineSep + + lineSep
" resultsDiv.innerHTML = result;" + lineSep + + "balanceValue = balanceValue.toFixed(2);"
" }}}" + lineSep + + lineSep
"</script>" + lineSep; + "document.getElementById('balanceID').innerText = balanceValue + '$';"
+ lineSep
+ "}"
+ lineSep
+ "function submitData(accountNo, balance) {"
+ lineSep
+ "var url = '/WebGoat/attack?Screen="
+ String.valueOf(getScreenId())
+ "&menu="
+ getDefaultCategory().getRanking().toString()
+ "&from=ajax&newAccount='+ accountNo+ '&amount=' + balance +'&confirm=' + document.getElementById('confirm').value; "
+ lineSep + "if (typeof XMLHttpRequest != 'undefined') {"
+ lineSep + "req = new XMLHttpRequest();" + lineSep
+ "} else if (window.ActiveXObject) {" + lineSep
+ "req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep
+ " }" + lineSep + " req.open('GET', url, true);" + lineSep
+ " req.onreadystatechange = callback;" + lineSep
+ " req.send(null);" + lineSep + "}" + lineSep
+ "function callback() {" + lineSep
+ " if (req.readyState == 4) { " + lineSep
+ " if (req.status == 200) { " + lineSep
+ " var result = req.responseText ;"
+ lineSep
+ " var resultsDiv = document.getElementById('resultsDiv');"
+ lineSep + " resultsDiv.innerHTML = '';" + lineSep
+ " resultsDiv.innerHTML = result;" + lineSep
+ " }}}" + lineSep + "</script>" + lineSep;
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
ec.addElement(new H1("Welcome to WebGoat Banking System")); ec.addElement(new H1("Welcome to WebGoat Banking System"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new H3("Account Summary:")); ec.addElement(new H3("Account Summary:"));
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(1).setWidth("70%").setAlign("left"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(1)
.setWidth("70%").setAlign("left");
ec.addElement(new BR()); ec.addElement(new BR());
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD(new StringElement("Account Balance:"))); tr.addElement(new TD(new StringElement("Account Balance:")));
tr.addElement( new TD( new StringElement( "<div id='balanceID'>" + CURRENT_BALANCE.toString() + "$</div>") )); tr.addElement(new TD(new StringElement("<div id='balanceID'>"
+ CURRENT_BALANCE.toString() + "$</div>")));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
@ -196,29 +262,37 @@ public class SilentTransactions extends LessonAdapter {
return ec; return ec;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.AJAX_SECURITY; return AbstractLesson.AJAX_SECURITY;
} }
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Check the javascript in the HTML source."); hints.add("Check the javascript in the HTML source.");
hints.add("Check how the application calls a specific javascript function to execute the transaction."); hints
hints.add("Check the javascript functions processData and submitData()"); .add("Check how the application calls a specific javascript function to execute the transaction.");
hints.add("Function submitData() is the one responsible for actually ececuting the transaction."); hints
hints.add("Check if your browser supports running javascript from the address bar."); .add("Check the javascript functions processData and submitData()");
hints
.add("Function submitData() is the one responsible for actually ececuting the transaction.");
hints
.add("Check if your browser supports running javascript from the address bar.");
hints.add("Try to navigate to 'javascript:submitData(1234556,11000);'"); hints.add("Try to navigate to 'javascript:submitData(1234556,11000);'");
return hints; return hints;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
@ -229,7 +303,9 @@ public class SilentTransactions extends LessonAdapter {
return ("Silent Transactions Attacks"); return ("Silent Transactions Attacks");
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }

View File

@ -27,13 +27,43 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.ParameterNotFoundException; import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author asmolen * @author asmolen
* *
* TODO To change the template for this generated type comment go to * TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates * Window - Preferences - Java - Code Style - Code Templates
*/ */
public class SoapRequest extends LessonAdapter { public class SoapRequest extends LessonAdapter
{
/* TEST CODE /* TEST CODE
private final static String ACCT_NUM = "account_number"; private final static String ACCT_NUM = "account_number";
private static Connection connection = null; private static Connection connection = null;
@ -42,59 +72,71 @@ public class SoapRequest extends LessonAdapter {
//static boolean completed; //static boolean completed;
public static Connection connection = null; public static Connection connection = null;
public final static String firstName = "getFirstName"; public final static String firstName = "getFirstName";
public final static String lastName = "getLastName"; public final static String lastName = "getLastName";
public final static String loginCount = "getLoginCount"; public final static String loginCount = "getLoginCount";
public final static String ccNumber = "getCreditCard"; public final static String ccNumber = "getCreditCard";
//int instead of boolean to keep track of method invocation count //int instead of boolean to keep track of method invocation count
static int accessFirstName; static int accessFirstName;
static int accessLastName; static int accessLastName;
static int accessCreditCard; static int accessCreditCard;
static int accessLoginCount; static int accessLoginCount;
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.WEB_SERVICES; return AbstractLesson.WEB_SERVICES;
} }
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Accessible operations are delimited by the &lt;operation&gt; tag contained within the &lt;portType&gt; section of the WSDL. <BR> Below is an example of a typical operation (getFirstName): <br><br>" + hints
"&lt;wsdl:portType name=\"SoapRequest\"&gt; <br>" + .add("Accessible operations are delimited by the &lt;operation&gt; tag contained within the &lt;portType&gt; section of the WSDL. <BR> Below is an example of a typical operation (getFirstName): <br><br>"
"&lt;wsdl:<strong>operation name=\"getFirstName\"</strong>&gt;<br>" + + "&lt;wsdl:portType name=\"SoapRequest\"&gt; <br>"
"&lt;wsdl:input message=\"impl:getFirstNameRequest\" name=\"getFirstNameRequest\" /&gt;<br>" + + "&lt;wsdl:<strong>operation name=\"getFirstName\"</strong>&gt;<br>"
"&lt;wsdl:output message=\"impl:getFirstNameResponse\" name=\"getFirstNameResponse\" /&gt;<br>" + + "&lt;wsdl:input message=\"impl:getFirstNameRequest\" name=\"getFirstNameRequest\" /&gt;<br>"
"&lt;wsdlsoap:operation soapAction=\"\" /&gt;" + + "&lt;wsdl:output message=\"impl:getFirstNameResponse\" name=\"getFirstNameResponse\" /&gt;<br>"
"&lt;/wsdl:portType&gt;<br><br>" + + "&lt;wsdlsoap:operation soapAction=\"\" /&gt;"
"The methods invoked are defined by the input and output message attributes. " + + "&lt;/wsdl:portType&gt;<br><br>"
"Example: <strong>\"getFirstNameRequest\"</strong>"); + "The methods invoked are defined by the input and output message attributes. "
hints.add("There are several tags within a SOAP envelope. " + + "Example: <strong>\"getFirstNameRequest\"</strong>");
"Each namespace is defined in the &lt;definitions&gt; section of the WSDL, and is declared using the (xmlns:namespace_name_here=\"namespace_reference_location_here\") format.<br><br>" + hints
"The following example defines a tag \"&lt;xsd:\", whose attribute structure will reference the namespace location assigned to it in the declaration:<br>" + .add("There are several tags within a SOAP envelope. "
"<strong>xmlns:xsd=\"http://www.w3.org/2001/XMLSchema</strong>"); + "Each namespace is defined in the &lt;definitions&gt; section of the WSDL, and is declared using the (xmlns:namespace_name_here=\"namespace_reference_location_here\") format.<br><br>"
hints.add("Determine what parameters and types are required by the message definition corresponding to the operation's request method. " + + "The following example defines a tag \"&lt;xsd:\", whose attribute structure will reference the namespace location assigned to it in the declaration:<br>"
"This example defines a parameter (id) of type (int) in the namespace (xsd) for the method (getFirstNameRequest):<br>" + + "<strong>xmlns:xsd=\"http://www.w3.org/2001/XMLSchema</strong>");
"&lt;wsdl:message name=\"getFirstNameRequest\"<br><br>" + hints
"&lt;wsdl:<strong>part name=\"id\" type=\"xsd:int\"</strong> /&gt;<br>" + .add("Determine what parameters and types are required by the message definition corresponding to the operation's request method. "
"&lt;/wsdl:message&gt;<br><br>" + + "This example defines a parameter (id) of type (int) in the namespace (xsd) for the method (getFirstNameRequest):<br>"
"Examples of other types:<br>" + + "&lt;wsdl:message name=\"getFirstNameRequest\"<br><br>"
"{boolean, byte, base64Binary, double, float, int, long, short, unsignedInt, unsignedLong, unsignedShort, string}.<br>"); + "&lt;wsdl:<strong>part name=\"id\" type=\"xsd:int\"</strong> /&gt;<br>"
String soapEnv = "A SOAP request uses the following HTTP header: <br><br> " + + "&lt;/wsdl:message&gt;<br><br>"
"SOAPAction: some action header, can be &quot;&quot; <br><br>" + + "Examples of other types:<br>"
"The SOAP message body has the following format:<br>" + + "{boolean, byte, base64Binary, double, float, int, long, short, unsignedInt, unsignedLong, unsignedShort, string}.<br>");
"&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; <br>" + String soapEnv = "A SOAP request uses the following HTTP header: <br><br> "
"&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" <br>" + + "SOAPAction: some action header, can be &quot;&quot; <br><br>"
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" <br>" + + "The SOAP message body has the following format:<br>"
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"&gt; <br>" + + "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; <br>"
"&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>" + + "&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" <br>"
"&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:getFirstName SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:ns1=\"http://lessons\"&gt; <br>" + + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" <br>"
"&nbsp;&nbsp;&nbsp;&nbsp;&lt;id xsi:type=\"xsd:int\"&gt;101&lt;/id&gt; <br>"+ + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"&gt; <br>"
"&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:getFirstName&gt; <br>" + + "&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>"
"&nbsp;&nbsp;&lt;/SOAP-ENV:Body&gt; <br>" + + "&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:getFirstName SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:ns1=\"http://lessons\"&gt; <br>"
"&lt;/SOAP-ENV:Envelope&gt; <br><br>" + + "&nbsp;&nbsp;&nbsp;&nbsp;&lt;id xsi:type=\"xsd:int\"&gt;101&lt;/id&gt; <br>"
"Intercept the HTTP request and try to create a SOAP request."; + "&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:getFirstName&gt; <br>"
+ "&nbsp;&nbsp;&lt;/SOAP-ENV:Body&gt; <br>"
+ "&lt;/SOAP-ENV:Envelope&gt; <br><br>"
+ "Intercept the HTTP request and try to create a SOAP request.";
soapEnv.replaceAll("(?s) ", "&nbsp;"); soapEnv.replaceAll("(?s) ", "&nbsp;");
hints.add(soapEnv); hints.add(soapEnv);
@ -103,16 +145,19 @@ public class SoapRequest extends LessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return "How to Create a SOAP Request"; return "How to Create a SOAP Request";
} }
protected Element makeOperationsLine(WebSession s) protected Element makeOperationsLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -125,7 +170,8 @@ public class SoapRequest extends LessonAdapter {
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement( "How many operations are defined in the WSDL: " )); tr.addElement(new TD()
.addElement("How many operations are defined in the WSDL: "));
tr.addElement(new TD(new Input(Input.TEXT, "count", ""))); tr.addElement(new TD(new Input(Input.TEXT, "count", "")));
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
tr.addElement(new TD(b).setAlign("LEFT")); tr.addElement(new TD(b).setAlign("LEFT"));
@ -136,6 +182,7 @@ public class SoapRequest extends LessonAdapter {
return ec; return ec;
} }
protected Element makeTypeLine(WebSession s) protected Element makeTypeLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -148,7 +195,9 @@ public class SoapRequest extends LessonAdapter {
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement( "Now, what is the type of the (id) parameter in the \"getFirstNameRequest\" method: " )); tr
.addElement(new TD()
.addElement("Now, what is the type of the (id) parameter in the \"getFirstNameRequest\" method: "));
tr.addElement(new TD(new Input(Input.TEXT, "type", ""))); tr.addElement(new TD(new Input(Input.TEXT, "type", "")));
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
tr.addElement(new TD(b).setAlign("LEFT")); tr.addElement(new TD(b).setAlign("LEFT"));
@ -159,26 +208,31 @@ public class SoapRequest extends LessonAdapter {
return ec; return ec;
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return viewWsdl(s); return viewWsdl(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return determineType(s); return determineType(s);
} }
protected Element doStage3(WebSession s) throws Exception protected Element doStage3(WebSession s) throws Exception
{ {
return createSoapEnvelope(s); return createSoapEnvelope(s);
} }
protected Element viewWsdl(WebSession s) protected Element viewWsdl(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -227,7 +281,9 @@ public class SoapRequest extends LessonAdapter {
ec.addElement(makeOperationsLine(s)); ec.addElement(makeOperationsLine(s));
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL"); A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL");
ec.addElement(new P().addElement("View the following WSDL and count available operations:")); ec
.addElement(new P()
.addElement("View the following WSDL and count available operations:"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(a); ec.addElement(a);
} }
@ -237,6 +293,7 @@ public class SoapRequest extends LessonAdapter {
return (ec); return (ec);
} }
protected Element determineType(WebSession s) protected Element determineType(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -281,7 +338,9 @@ public class SoapRequest extends LessonAdapter {
ec.addElement(makeTypeLine(s)); ec.addElement(makeTypeLine(s));
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL"); A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL");
ec.addElement(new P().addElement("View the following WSDL and count available operations:")); ec
.addElement(new P()
.addElement("View the following WSDL and count available operations:"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(a); ec.addElement(a);
} }
@ -291,6 +350,7 @@ public class SoapRequest extends LessonAdapter {
return (ec); return (ec);
} }
protected Element createSoapEnvelope(WebSession s) protected Element createSoapEnvelope(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -308,8 +368,11 @@ public class SoapRequest extends LessonAdapter {
{ {
// display Stage2 content // display Stage2 content
ec.addElement(new P().addElement( "Intercept the request and invoke any method by sending a valid SOAP request for a valid account. <br>" )); ec
Element b = ECSFactory.makeButton( "Press to generate an HTTP request" ); .addElement(new P()
.addElement("Intercept the request and invoke any method by sending a valid SOAP request for a valid account. <br>"));
Element b = ECSFactory
.makeButton("Press to generate an HTTP request");
ec.addElement(b); ec.addElement(b);
// conditionally display invoked methods // conditionally display invoked methods
@ -341,14 +404,18 @@ public class SoapRequest extends LessonAdapter {
return (ec); return (ec);
} }
public String getResults(int id, String field) {
public String getResults(int id, String field)
{
try try
{ {
Connection connection = DatabaseUtilities.makeConnection(); Connection connection = DatabaseUtilities.makeConnection();
if (connection == null) { if (connection == null)
{
return null; return null;
} }
PreparedStatement ps = connection.prepareStatement("SELECT * FROM user_data WHERE userid = ?"); PreparedStatement ps = connection
.prepareStatement("SELECT * FROM user_data WHERE userid = ?");
ps.setInt(1, id); ps.setInt(1, id);
try try
{ {
@ -359,16 +426,16 @@ public class SoapRequest extends LessonAdapter {
} }
} }
catch (SQLException sqle) catch (SQLException sqle)
{ {}
}
} }
catch (Exception e) catch (Exception e)
{ {}
}
return null; return null;
} }
public String getCreditCard(int id) {
public String getCreditCard(int id)
{
String result = getResults(id, "cc_number"); String result = getResults(id, "cc_number");
//SoapRequest.completed = true; //SoapRequest.completed = true;
@ -382,7 +449,9 @@ public class SoapRequest extends LessonAdapter {
return null; return null;
} }
public String getFirstName(int id) {
public String getFirstName(int id)
{
String result = getResults(id, "first_name"); String result = getResults(id, "first_name");
if (result != null) if (result != null)
{ {
@ -394,7 +463,9 @@ public class SoapRequest extends LessonAdapter {
return null; return null;
} }
public String getLastName(int id) {
public String getLastName(int id)
{
String result = getResults(id, "last_name"); String result = getResults(id, "last_name");
if (result != null) if (result != null)
{ {
@ -406,7 +477,9 @@ public class SoapRequest extends LessonAdapter {
return null; return null;
} }
public String getLoginCount(int id) {
public String getLoginCount(int id)
{
String result = getResults(id, "login_count"); String result = getResults(id, "login_count");
if (result != null) if (result != null)
{ {

View File

@ -23,12 +23,34 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -39,8 +61,10 @@ public class SqlNumericInjection extends LessonAdapter
private final static String STATION_ID = "station"; private final static String STATION_ID = "station";
private static Connection connection = null; private static Connection connection = null;
private String station; private String station;
/** /**
* Description of the Method * Description of the Method
* *
@ -53,18 +77,19 @@ public class SqlNumericInjection extends LessonAdapter
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return injectableQuery(s); return injectableQuery(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return parameterizedQuery(s); return parameterizedQuery(s);
} }
protected Element injectableQuery(WebSession s) protected Element injectableQuery(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -78,9 +103,12 @@ public class SqlNumericInjection extends LessonAdapter
station = s.getParser().getRawParameter(STATION_ID, null); station = s.getParser().getRawParameter(STATION_ID, null);
if (station == null){ if (station == null)
{
query = "SELECT * FROM weather_data WHERE station = [station]"; query = "SELECT * FROM weather_data WHERE station = [station]";
} else { }
else
{
query = "SELECT * FROM weather_data WHERE station = " + station; query = "SELECT * FROM weather_data WHERE station = " + station;
} }
@ -96,13 +124,16 @@ public class SqlNumericInjection extends LessonAdapter
try try
{ {
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
results.last(); results.last();
// If they get back more than one row they succeeded // If they get back more than one row they succeeded
@ -110,7 +141,8 @@ public class SqlNumericInjection extends LessonAdapter
{ {
makeSuccess(s); makeSuccess(s);
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
s.setMessage("Start this lesson over to attack a parameterized query."); s
.setMessage("Start this lesson over to attack a parameterized query.");
} }
} }
else else
@ -133,12 +165,14 @@ public class SqlNumericInjection extends LessonAdapter
return (ec); return (ec);
} }
protected Element parameterizedQuery(WebSession s) protected Element parameterizedQuery(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Now that you have successfully performed an SQL injection, try the same " + ec
" type of attack on a parameterized query."); .addElement("Now that you have successfully performed an SQL injection, try the same "
+ " type of attack on a parameterized query.");
// if ( s.getParser().getRawParameter( ACCT_NUM, "101" ).equals("restart")) // if ( s.getParser().getRawParameter( ACCT_NUM, "101" ).equals("restart"))
// { // {
// getLessonTracker(s).setStage(1); // getLessonTracker(s).setStage(1);
@ -167,14 +201,17 @@ public class SqlNumericInjection extends LessonAdapter
try try
{ {
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, Integer.parseInt(station)); statement.setInt(1, Integer.parseInt(station));
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
results.last(); results.last();
// If they get back more than one row they succeeded // If they get back more than one row they succeeded
@ -194,7 +231,9 @@ public class SqlNumericInjection extends LessonAdapter
} }
catch (NumberFormatException npe) catch (NumberFormatException npe)
{ {
ec.addElement( new P().addElement( "Error parsing station as a number: " + npe.getMessage() ) ); ec.addElement(new P()
.addElement("Error parsing station as a number: "
+ npe.getMessage()));
} }
} }
catch (Exception e) catch (Exception e)
@ -206,18 +245,24 @@ public class SqlNumericInjection extends LessonAdapter
return (ec); return (ec);
} }
protected Element makeStationList( WebSession s ) throws SQLException, ClassNotFoundException
protected Element makeStationList(WebSession s) throws SQLException,
ClassNotFoundException
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement( new P().addElement( "Select your local weather station: " ) ); ec
.addElement(new P()
.addElement("Select your local weather station: "));
Map stations = getStations(s); Map stations = getStations(s);
Select select = new Select(STATION_ID); Select select = new Select(STATION_ID);
Iterator it = stations.keySet().iterator(); Iterator it = stations.keySet().iterator();
while (it.hasNext()) { while (it.hasNext())
{
String key = (String) it.next(); String key = (String) it.next();
select.addElement(new Option(key).addElement((String)stations.get(key))); select.addElement(new Option(key).addElement((String) stations
.get(key)));
} }
ec.addElement(select); ec.addElement(select);
ec.addElement(new P()); ec.addElement(new P());
@ -228,12 +273,14 @@ public class SqlNumericInjection extends LessonAdapter
return ec; return ec;
} }
/** /**
* Gets the stations from the db * Gets the stations from the db
* *
* @return A map containing each station, indexed by station number * @return A map containing each station, indexed by station number
*/ */
protected Map getStations( WebSession s ) throws SQLException, ClassNotFoundException protected Map getStations(WebSession s) throws SQLException,
ClassNotFoundException
{ {
if (connection == null) if (connection == null)
@ -246,19 +293,23 @@ public class SqlNumericInjection extends LessonAdapter
try try
{ {
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
results.beforeFirst(); results.beforeFirst();
while(results.next()) { while (results.next())
{
String station = results.getString("station"); String station = results.getString("station");
String name = results.getString("name"); String name = results.getString("name");
//<START_OMIT_SOURCE> //<START_OMIT_SOURCE>
if(!station.equals("10001") && !station.equals("11001")) { if (!station.equals("10001") && !station.equals("11001"))
{
stations.put(station, name); stations.put(station, name);
} }
//<END_OMIT_SOURCE> //<END_OMIT_SOURCE>
@ -275,6 +326,7 @@ public class SqlNumericInjection extends LessonAdapter
return stations; return stations;
} }
/** /**
* Gets the category attribute of the SqNumericInjection object * Gets the category attribute of the SqNumericInjection object
* *
@ -294,11 +346,14 @@ public class SqlNumericInjection extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "The application is taking your input and inserting it at the end of a pre-formed SQL command." ); hints
hints.add( "This is the code for the query being built and issued by WebGoat:<br><br> " + .add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
"\"SELECT * FROM weather_data WHERE station = \" + station " ); hints
hints.add( "Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " + .add("This is the code for the query being built and issued by WebGoat:<br><br> "
"Try appending a SQL statement that always resolves to true."); + "\"SELECT * FROM weather_data WHERE station = \" + station ");
hints
.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Try appending a SQL statement that always resolves to true.");
hints.add("Try entering [ 101 OR 1 = 1 ]."); hints.add("Try entering [ 101 OR 1 = 1 ].");
return hints; return hints;
@ -306,11 +361,13 @@ public class SqlNumericInjection extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(70); private final static Integer DEFAULT_RANKING = new Integer(70);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DatabaseFieldScreen object * Gets the title attribute of the DatabaseFieldScreen object
* *
@ -345,4 +402,3 @@ public class SqlNumericInjection extends LessonAdapter
} }
} }
} }

View File

@ -19,23 +19,50 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class SqlStringInjection extends LessonAdapter public class SqlStringInjection extends LessonAdapter
{ {
private final static String ACCT_NAME = "account_name"; private final static String ACCT_NAME = "account_name";
private static Connection connection = null; private static Connection connection = null;
private static String STAGE = "stage"; private static String STAGE = "stage";
private String accountName; private String accountName;
/** /**
* Description of the Method * Description of the Method
* *
@ -47,11 +74,13 @@ public class SqlStringInjection extends LessonAdapter
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return injectableQuery(s); return injectableQuery(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return parameterizedQuery(s); return parameterizedQuery(s);
@ -71,18 +100,22 @@ public class SqlStringInjection extends LessonAdapter
ec.addElement(makeAccountLine(s)); ec.addElement(makeAccountLine(s));
String query = "SELECT * FROM user_data WHERE last_name = '" + accountName +"'"; String query = "SELECT * FROM user_data WHERE last_name = '"
+ accountName + "'";
ec.addElement(new PRE(query)); ec.addElement(new PRE(query));
try try
{ {
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
@ -94,9 +127,11 @@ public class SqlStringInjection extends LessonAdapter
StringBuffer msg = new StringBuffer(); StringBuffer msg = new StringBuffer();
msg.append("Bet you can't do it again! "); msg.append("Bet you can't do it again! ");
msg.append("This lesson has detected your successfull attack "); msg
.append("This lesson has detected your successfull attack ");
msg.append("and has now switch to a defensive mode. "); msg.append("and has now switch to a defensive mode. ");
msg.append("Try again to attack a parameterized query."); msg
.append("Try again to attack a parameterized query.");
s.setMessage(msg.toString()); s.setMessage(msg.toString());
} }
@ -125,10 +160,12 @@ public class SqlStringInjection extends LessonAdapter
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Now that you have successfully performed an SQL injection, try the same " + ec
" type of attack on a parameterized query. Type 'restart' in the input field if you wish to " + .addElement("Now that you have successfully performed an SQL injection, try the same "
" to return to the injectable query"); + " type of attack on a parameterized query. Type 'restart' in the input field if you wish to "
if ( s.getParser().getRawParameter( ACCT_NAME, "YOUR_NAME" ).equals("restart")) + " to return to the injectable query");
if (s.getParser().getRawParameter(ACCT_NAME, "YOUR_NAME").equals(
"restart"))
{ {
getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1"); getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1");
return (injectableQuery(s)); return (injectableQuery(s));
@ -150,14 +187,17 @@ public class SqlStringInjection extends LessonAdapter
try try
{ {
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.setString(1, accountName); statement.setString(1, accountName);
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
@ -185,6 +225,7 @@ public class SqlStringInjection extends LessonAdapter
return (ec); return (ec);
} }
protected Element makeAccountLine(WebSession s) protected Element makeAccountLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -221,11 +262,14 @@ public class SqlStringInjection extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "The application is taking your input and inserting it at the end of a pre-formed SQL command." ); hints
hints.add( "This is the code for the query being built and issued by WebGoat:<br><br> " + .add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
"\"SELECT * FROM user_data WHERE last_name = \" + accountName " ); hints
hints.add( "Compound SQL statements can be made by joining multiple tests with keywords like AND and OR." + .add("This is the code for the query being built and issued by WebGoat:<br><br> "
"Try appending a SQL statement that always resolves to true"); + "\"SELECT * FROM user_data WHERE last_name = \" + accountName ");
hints
.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR."
+ "Try appending a SQL statement that always resolves to true");
hints.add("Try entering [ smith' OR '1' = '1 ]."); hints.add("Try entering [ smith' OR '1' = '1 ].");
return hints; return hints;
@ -233,11 +277,13 @@ public class SqlStringInjection extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(75); private final static Integer DEFAULT_RANKING = new Integer(75);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DatabaseFieldScreen object * Gets the title attribute of the DatabaseFieldScreen object
* *
@ -272,4 +318,3 @@ public class SqlStringInjection extends LessonAdapter
} }
} }
} }

View File

@ -22,27 +22,59 @@ import org.apache.ecs.html.TextArea;
import org.owasp.webgoat.session.*; import org.owasp.webgoat.session.*;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class StoredXss extends LessonAdapter public class StoredXss extends LessonAdapter
{ {
private final static String MESSAGE = "message"; private final static String MESSAGE = "message";
private final static int MESSAGE_COL = 3; private final static int MESSAGE_COL = 3;
private final static String NUMBER = "Num"; private final static String NUMBER = "Num";
private final static int NUM_COL = 1; private final static int NUM_COL = 1;
private final static String STANDARD_QUERY = "SELECT * FROM messages"; private final static String STANDARD_QUERY = "SELECT * FROM messages";
private final static String TITLE = "title"; private final static String TITLE = "title";
private final static int TITLE_COL = 2; private final static int TITLE_COL = 2;
private static Connection connection = null; private static Connection connection = null;
private static int count = 1; 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 int USER_COL = 4; // Added by Chuck Willis - used to show user who posted message
@ -55,7 +87,8 @@ public class StoredXss extends LessonAdapter
{ {
try try
{ {
String title = HtmlEncoder.encode( s.getParser().getRawParameter( TITLE, "" ) ); String title = HtmlEncoder.encode(s.getParser().getRawParameter(
TITLE, ""));
String message = s.getParser().getRawParameter(MESSAGE, ""); String message = s.getParser().getRawParameter(MESSAGE, "");
if (connection == null) if (connection == null)
@ -65,7 +98,9 @@ public class StoredXss extends LessonAdapter
String query = "INSERT INTO messages VALUES (?, ?, ?, ? )"; 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.setInt(1, count++);
statement.setString(2, title); statement.setString(2, title);
statement.setString(3, message); statement.setString(3, message);
@ -84,6 +119,7 @@ public class StoredXss extends LessonAdapter
} }
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -125,23 +161,25 @@ public class StoredXss extends LessonAdapter
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("You can put HTML tags in your message."); hints.add("You can put HTML tags in your message.");
hints.add( "Bury a SCRIPT tag in the message to attack anyone who reads it." ); hints
hints.add( "Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in the message field." ); .add("Bury a SCRIPT tag in the message to attack anyone who reads it.");
hints.add( "Enter this: &lt;script&gtalert(\"document.cookie\");&lt;/script&gt; in the message field." ); hints
.add("Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in the message field.");
hints
.add("Enter this: &lt;script&gtalert(\"document.cookie\");&lt;/script&gt; in the message field.");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the MessageBoardScreen object * Gets the title attribute of the MessageBoardScreen object
* *
@ -178,17 +216,22 @@ public class StoredXss extends LessonAdapter
// cookies, but not get confused by other users scripts // cookies, but not get confused by other users scripts
String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ?"; String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ?";
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.setString(1, getNameroot(s.getUserName()) + "%"); statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setInt(2, messageNum); statement.setInt(2, messageNum);
ResultSet results = statement.executeQuery(); 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 )) ); ec.addElement(new H1("Message Contents For: "
Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 ); + 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:")))); TR row1 = new TR(new TD(new B(new StringElement("Title:"))));
row1.addElement( new TD( new StringElement( results.getString( TITLE_COL ) ) ) ); row1.addElement(new TD(new StringElement(results
.getString(TITLE_COL))));
t.addElement(row1); t.addElement(row1);
String messageData = results.getString(MESSAGE_COL); String messageData = results.getString(MESSAGE_COL);
@ -201,15 +244,16 @@ public class StoredXss extends LessonAdapter
// they can see that the message is attributed to that user // they can see that the message is attributed to that user
TR row3 = new TR(new TD(new StringElement("Posted By:"))); TR row3 = new TR(new TD(new StringElement("Posted By:")));
row3.addElement( new TD( new StringElement( results.getString( USER_COL ) ) ) ); row3.addElement(new TD(new StringElement(results
.getString(USER_COL))));
t.addElement(row3); t.addElement(row3);
ec.addElement(t); ec.addElement(t);
// Some sanity checks that the script may be correct // Some sanity checks that the script may be correct
if ( messageData.toLowerCase().indexOf( "<script>" ) != -1 && if (messageData.toLowerCase().indexOf("<script>") != -1
messageData.toLowerCase().indexOf( "</script>" ) != -1 && && messageData.toLowerCase().indexOf("</script>") != -1
messageData.toLowerCase().indexOf( "alert" ) != -1 ) && messageData.toLowerCase().indexOf("alert") != -1)
{ {
makeSuccess(s); makeSuccess(s);
} }
@ -219,7 +263,8 @@ public class StoredXss extends LessonAdapter
{ {
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));
} }
} }
} }
@ -287,13 +332,17 @@ public class StoredXss extends LessonAdapter
connection = DatabaseUtilities.makeConnection(s); connection = DatabaseUtilities.makeConnection(s);
} }
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
// edit by Chuck Willis - Added logic to associate similar usernames // edit by Chuck Willis - Added logic to associate similar usernames
// The idea is that users chuck-1, chuck-2, etc will see each other's messages // The idea is that users chuck-1, chuck-2, etc will see each other's messages
// but not anyone elses. This allows users to try out XSS to grab another user's // but not anyone elses. This allows users to try out XSS to grab another user's
// cookies, but not get confused by other users scripts // cookies, but not get confused by other users scripts
ResultSet results = statement.executeQuery( STANDARD_QUERY + " WHERE user_name LIKE '" + getNameroot( s.getUserName() ) + "%'" ); ResultSet results = statement.executeQuery(STANDARD_QUERY
+ " WHERE user_name LIKE '" + getNameroot(s.getUserName())
+ "%'");
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
@ -301,7 +350,8 @@ public class StoredXss extends LessonAdapter
for (int i = 0; results.next(); i++) for (int i = 0; results.next(); i++)
{ {
A a = ECSFactory.makeLink( results.getString( TITLE_COL ), NUMBER, results.getInt( NUM_COL ) ); A a = ECSFactory.makeLink(results.getString(TITLE_COL),
NUMBER, results.getInt(NUM_COL));
TD td = new TD().addElement(a); TD td = new TD().addElement(a);
TR tr = new TR().addElement(td); TR tr = new TR().addElement(td);
t.addElement(tr); t.addElement(tr);
@ -320,6 +370,7 @@ public class StoredXss extends LessonAdapter
return (ec); return (ec);
} }
private static String getNameroot(String name) private static String getNameroot(String name)
{ {
String nameroot = name; String nameroot = name;
@ -330,4 +381,3 @@ public class StoredXss extends LessonAdapter
return nameroot; return nameroot;
} }
} }

View File

@ -14,21 +14,47 @@ import org.apache.ecs.html.P;
import org.owasp.webgoat.session.*; import org.owasp.webgoat.session.*;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class ThreadSafetyProblem extends LessonAdapter public class ThreadSafetyProblem extends LessonAdapter
{ {
private final static String USER_NAME = "username"; private final static String USER_NAME = "username";
private Connection connection = null; private Connection connection = null;
private static String currentUser; private static String currentUser;
private String originalUser; private String originalUser;
@ -66,19 +92,25 @@ public class ThreadSafetyProblem extends LessonAdapter
Thread.sleep(1500); Thread.sleep(1500);
// Get the users info from the DB // Get the users info from the DB
String query = "SELECT * FROM user_system_data WHERE user_name = '" + currentUser + "'"; String query = "SELECT * FROM user_system_data WHERE user_name = '"
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); + currentUser + "'";
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ec.addElement("Account information for user: " + originalUser + "<br><br>"); ec.addElement("Account information for user: "
+ originalUser + "<br><br>");
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
} }
else else
{ {
s.setMessage("'" + currentUser + "' is not a user in the WebGoat database."); s.setMessage("'" + currentUser
+ "' is not a user in the WebGoat database.");
} }
} }
if (!user1.equals(currentUser)) if (!user1.equals(currentUser))
@ -105,10 +137,13 @@ public class ThreadSafetyProblem extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "Web applications handle many HTTP requests at the same time." ); hints
.add("Web applications handle many HTTP requests at the same time.");
hints.add("Developers use variables that are not thread safe."); hints.add("Developers use variables that are not thread safe.");
hints.add( "Show the Java source code and trace the 'currentUser' variable" ); hints
hints.add( "Open two browsers and send 'jeff' in one and 'dave' in the other." ); .add("Show the Java source code and trace the 'currentUser' variable");
hints
.add("Open two browsers and send 'jeff' in one and 'dave' in the other.");
return hints; return hints;
} }
@ -122,28 +157,30 @@ public class ThreadSafetyProblem extends LessonAdapter
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The user should be able to exploit the concurrency error in this web application " + String instructions = "The user should be able to exploit the concurrency error in this web application "
"and view login information for another user that is attempting the same function " + + "and view login information for another user that is attempting the same function "
"at the same time. <b>This will require the use of two browsers</b>. Valid user " + + "at the same time. <b>This will require the use of two browsers</b>. Valid user "
"names are 'jeff' and 'dave'." + + "names are 'jeff' and 'dave'."
"<p>Please enter your username to access your account."; + "<p>Please enter your username to access your account.";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(80); private final static Integer DEFAULT_RANKING = new Integer(80);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.GENERAL; return AbstractLesson.GENERAL;
} }
/** /**
* Gets the title attribute of the ConcurrencyScreen object * Gets the title attribute of the ConcurrencyScreen object
* *
@ -178,4 +215,3 @@ public class ThreadSafetyProblem extends LessonAdapter
} }
} }
} }

View File

@ -19,12 +19,34 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -50,7 +72,8 @@ public class TraceXSS extends LessonAdapter
try try
{ {
String param1 = s.getParser().getRawParameter("field1", "111"); String param1 = s.getParser().getRawParameter("field1", "111");
String param2 = HtmlEncoder.encode( s.getParser().getRawParameter( "field2", "4128 3214 0002 1999" ) ); String param2 = HtmlEncoder.encode(s.getParser().getRawParameter(
"field2", "4128 3214 0002 1999"));
float quantity = 1.0f; float quantity = 1.0f;
float total = 0.0f; float total = 0.0f;
float runningTotal = 0.0f; float runningTotal = 0.0f;
@ -58,19 +81,25 @@ public class TraceXSS extends LessonAdapter
// test input field1 // test input field1
if (!pattern1.matcher(param1).matches()) if (!pattern1.matcher(param1).matches())
{ {
if ( param1.toLowerCase().indexOf( "script" ) != -1 && param1.toLowerCase().indexOf( "trace" ) != -1) if (param1.toLowerCase().indexOf("script") != -1
&& param1.toLowerCase().indexOf("trace") != -1)
{ {
makeSuccess(s); makeSuccess(s);
} }
s.setMessage( "Whoops! You entered " + param1 + " instead of your three digit code. Please try again." ); s
.setMessage("Whoops! You entered "
+ param1
+ " instead of your three digit code. Please try again.");
} }
// FIXME: encode output of field2, then s.setMessage( field2 ); // FIXME: encode output of field2, then s.setMessage( field2 );
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement( new Center().addElement( new H1().addElement( "Shopping Cart " ))); ec.addElement(new Center().addElement(new H1()
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 2 ).setBorder( 1 ).setWidth("90%").setAlign("center"); .addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
@ -78,44 +107,64 @@ public class TraceXSS extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); tr.addElement(new TH().addElement(
"Shopping Cart Items -- To Buy Now").setWidth("80%"));
tr.addElement(new TH().addElement("Price:").setWidth("10%")); tr.addElement(new TH().addElement("Price:").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity:").setWidth("3%")); tr.addElement(new TH().addElement("Quantity:").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%")); tr.addElement(new TH().addElement("Total").setWidth("7%"));
t.addElement(tr); t.addElement(tr);
tr = new 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("69.99").setAlign("right")); tr.addElement(new TD().addElement("69.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY1", s.getParser()
.getStringParameter("QTY1", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY1", 1.0f); quantity = s.getParser().getFloatParameter("QTY1", 1.0f);
total = quantity * 69.99f; total = quantity * 69.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement("Dynex - Traditional Notebook Case")); tr.addElement(new TD()
.addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement("27.99").setAlign("right")); tr.addElement(new TD().addElement("27.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY2", s.getParser()
.getStringParameter("QTY2", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY2", 1.0f); quantity = s.getParser().getFloatParameter("QTY2", 1.0f);
total = quantity * 27.99f; total = quantity * 27.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new 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("1599.99").setAlign("right")); tr.addElement(new TD().addElement("1599.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY3", s.getParser()
.getStringParameter("QTY3", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY3", 1.0f); quantity = s.getParser().getFloatParameter("QTY3", 1.0f);
total = quantity * 1599.99f; total = quantity * 1599.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new 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("299.99").setAlign("right")); tr.addElement(new TD().addElement("299.99").setAlign("right"));
tr.addElement( new TD().addElement(new Input( Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "1") )).setAlign( "right" )); tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY4", s.getParser()
.getStringParameter("QTY4", "1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY4", 1.0f); quantity = s.getParser().getFloatParameter("QTY4", 1.0f);
total = quantity * 299.99f; total = quantity * 299.99f;
runningTotal += total; runningTotal += total;
@ -124,7 +173,8 @@ public class TraceXSS extends LessonAdapter
ec.addElement(t); 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()) if (s.isColor())
{ {
@ -134,25 +184,33 @@ public class TraceXSS extends LessonAdapter
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "The total charged to your credit card:" ) ); tr.addElement(new TD()
.addElement("The total charged to your credit card:"));
tr.addElement(new TD().addElement("$" + runningTotal)); tr.addElement(new TD().addElement("$" + runningTotal));
tr.addElement( new TD().addElement( ECSFactory.makeButton( "Update Cart" ))); tr.addElement(new TD().addElement(ECSFactory
.makeButton("Update Cart")));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "Enter your credit card number:" ) ); tr
tr.addElement( new TD().addElement( new Input( Input.TEXT, "field2", param2 ))); .addElement(new TD()
.addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2",
param2)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( "Enter your three digit access code:" ) ); tr.addElement(new TD()
tr.addElement( new TD().addElement( new Input( Input.TEXT, "field1", param1 ))); .addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",
param1)));
t.addElement(tr); t.addElement(tr);
Element b = ECSFactory.makeButton("Purchase"); Element b = ECSFactory.makeButton("Purchase");
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement( b ).setColSpan(2).setAlign("center")); tr.addElement(new TD().addElement(b).setColSpan(2).setAlign(
"center"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
@ -179,7 +237,6 @@ public class TraceXSS extends LessonAdapter
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
@ -188,29 +245,35 @@ public class TraceXSS extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "Most web servers support GET/POST. Many default installations also support TRACE"); hints
hints.add( "JavaScript has the ability to post a URL:<br>" + .add("Most web servers support GET/POST. Many default installations also support TRACE");
"&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)" + hints
" {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"GET\", \"./\", false);" + .add("JavaScript has the ability to post a URL:<br>"
" xmlHttp.send();str1=xmlHttp.responseText; " + + "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)"
"document.write(str1);&lt;/script&gt;"); + " {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"GET\", \"./\", false);"
+ " xmlHttp.send();str1=xmlHttp.responseText; "
+ "document.write(str1);&lt;/script&gt;");
hints.add("Try changing the HTTP GET to a HTTP TRACE"); hints.add("Try changing the HTTP GET to a HTTP TRACE");
hints.add( "Try a cross site trace (XST) Command:<br>" + hints
"&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)" + .add("Try a cross site trace (XST) Command:<br>"
" {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"TRACE\", \"./\", false);" + + "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)"
" xmlHttp.send();str1=xmlHttp.responseText; while (str1.indexOf(\"\\n\") > -1) str1 = str1.replace(\"\\n\",\"&lt;br&gt;\"); " + + " {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"TRACE\", \"./\", false);"
"document.write(str1);}&lt;/script&gt;"); + " xmlHttp.send();str1=xmlHttp.responseText; while (str1.indexOf(\"\\n\") > -1) str1 = str1.replace(\"\\n\",\"&lt;br&gt;\"); "
+ "document.write(str1);}&lt;/script&gt;");
return hints; return hints;
} }
// <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false); xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script> // <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false); xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script>
private final static Integer DEFAULT_RANKING = new Integer(130); private final static Integer DEFAULT_RANKING = new Integer(130);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
@ -221,5 +284,3 @@ public class TraceXSS extends LessonAdapter
return ("How to Perform Cross Site Trace Attacks"); return ("How to Perform Cross Site Trace Attacks");
} }
} }

View File

@ -25,11 +25,34 @@ import org.apache.ecs.html.TextArea;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
@ -39,6 +62,7 @@ public class UncheckedEmail extends LessonAdapter
{ {
private final static String MESSAGE = "msg"; private final static String MESSAGE = "msg";
private final static String TO = "to"; private final static String TO = "to";
@ -57,7 +81,8 @@ public class UncheckedEmail extends LessonAdapter
{ {
String to = s.getParser().getRawParameter(TO, ""); String to = s.getParser().getRawParameter(TO, "");
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())
{ {
@ -65,7 +90,8 @@ public class UncheckedEmail extends LessonAdapter
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Send OWASP your Comments<BR>").setAlign("left").setColSpan(3)); tr.addElement(new TH().addElement("Send OWASP your Comments<BR>")
.setAlign("left").setColSpan(3));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
@ -73,24 +99,25 @@ public class UncheckedEmail extends LessonAdapter
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TH().addElement(new H1("Contact Us")).setAlign("left").setWidth("55%").setVAlign("BOTTOM")); tr.addElement(new TH().addElement(new H1("Contact Us")).setAlign(
"left").setWidth("55%").setVAlign("BOTTOM"));
tr.addElement(new TH().addElement("&nbsp;")); tr.addElement(new TH().addElement("&nbsp;"));
tr.addElement( new TH().addElement(new H3("Contact Information:")).setAlign("left").setVAlign("BOTTOM")); tr.addElement(new TH().addElement(new H3("Contact Information:"))
.setAlign("left").setVAlign("BOTTOM"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement("We value your comments. To send OWASP your questions or comments regarding the " + tr
"WebGoat tool, please enter your comments below. The information you provide will be handled according " + .addElement(new TD()
"to our <U>Privacy Policy</U>.")); .addElement("We value your comments. To send OWASP your questions or comments regarding the "
+ "WebGoat tool, please enter your comments below. The information you provide will be handled according "
+ "to our <U>Privacy Policy</U>."));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement( new TD().addElement("<b>OWASP</B><BR>" + tr.addElement(new TD().addElement(
"9175 Guilford Rd <BR> Suite 300 <BR>" + "<b>OWASP</B><BR>" + "9175 Guilford Rd <BR> Suite 300 <BR>"
"Columbia, MD. 21046").setVAlign("top")); + "Columbia, MD. 21046").setVAlign("top"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(3)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(3));
t.addElement(tr); t.addElement(tr);
@ -102,13 +129,13 @@ public class UncheckedEmail extends LessonAdapter
tr.addElement(new TD().setAlign("LEFT").addElement(input)); tr.addElement(new TD().setAlign("LEFT").addElement(input));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
String message = s.getParser().getRawParameter(MESSAGE, ""); String message = s.getParser().getRawParameter(MESSAGE, "");
TextArea ta = new TextArea(MESSAGE, 5, 40); TextArea ta = new TextArea(MESSAGE, 5, 40);
ta.addElement(new StringElement(convertMetachars(message))); ta.addElement(new StringElement(convertMetachars(message)));
tr.addElement(new TD().setAlign("LEFT").addElement(ta)); tr.addElement(new TD().setAlign("LEFT").addElement(ta));
tr.addElement( new TD().setAlign( "LEFT" ).setVAlign( "MIDDLE" ).addElement( ECSFactory.makeButton( "Send!" ) ) ); tr.addElement(new TD().setAlign("LEFT").setVAlign("MIDDLE")
.addElement(ECSFactory.makeButton("Send!")));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
@ -126,21 +153,32 @@ public class UncheckedEmail extends LessonAdapter
// Tue, 09 Jan 2002 22:14:02 -0500 // Tue, 09 Jan 2002 22:14:02 -0500
ec.addElement(new HR()); ec.addElement(new HR());
ec.addElement( new Center().addElement( new B().addElement( "You sent the following message to: " + to ) ) ); ec
.addElement(new Center()
.addElement(new B()
.addElement("You sent the following message to: "
+ to)));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement( new StringElement("<b>Return-Path:</b> &lt;webgoat@owasp.org&gt;")); ec.addElement(new StringElement(
"<b>Return-Path:</b> &lt;webgoat@owasp.org&gt;"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Delivered-To:</b> " + to)); ec.addElement(new StringElement("<b>Delivered-To:</b> " + to));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement( new StringElement("<b>Received:</b> (qmail 614458 invoked by uid 239); " + today)); ec.addElement(new StringElement(
"<b>Received:</b> (qmail 614458 invoked by uid 239); "
+ today));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement( new StringElement("for &lt;" + to+"&gt;; " + today )); ec.addElement(new StringElement("for &lt;" + to + "&gt;; "
+ today));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>To:</b> " + to)); ec.addElement(new StringElement("<b>To:</b> " + to));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement( new StringElement("<b>From:</b> Blame it on the Goat &lt;webgoat@owasp.org&gt;")); ec
.addElement(new StringElement(
"<b>From:</b> Blame it on the Goat &lt;webgoat@owasp.org&gt;"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement( new StringElement("<b>Subject:</b> OWASP security issues")); ec.addElement(new StringElement(
"<b>Subject:</b> OWASP security issues"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement(message)); ec.addElement(new StringElement(message));
@ -181,10 +219,13 @@ public class UncheckedEmail extends LessonAdapter
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Try sending an anonymous message to yourself."); hints.add("Try sending an anonymous message to yourself.");
hints.add( "Try inserting some html or javascript code in the message field" ); hints
.add("Try inserting some html or javascript code in the message field");
hints.add("Look at the hidden fields in the HTML."); hints.add("Look at the hidden fields in the HTML.");
hints.add( "Insert &lt;A href=\"http://www.aspectsecurity.com/webgoat.html\"&gt;Click here for Aspect&lt;/A&gt in the message field" ); hints
hints.add( "Insert &lt;script&gt;alert(\"Bad Stuff\");&lt;/script&gt; in the message field" ); .add("Insert &lt;A href=\"http://www.aspectsecurity.com/webgoat.html\"&gt;Click here for Aspect&lt;/A&gt in the message field");
hints
.add("Insert &lt;script&gt;alert(\"Bad Stuff\");&lt;/script&gt; in the message field");
return hints; return hints;
} }
@ -202,16 +243,15 @@ public class UncheckedEmail extends LessonAdapter
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(55); private final static Integer DEFAULT_RANKING = new Integer(55);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the EmailScreen object * Gets the title attribute of the EmailScreen object
* *
@ -222,5 +262,3 @@ public class UncheckedEmail extends LessonAdapter
return ("How to Exploit Unchecked Email"); return ("How to Exploit Unchecked Email");
} }
} }

View File

@ -38,53 +38,104 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author asmolen * @author asmolen
* *
* TODO To change the template for this generated type comment go to * TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates * Window - Preferences - Java - Code Style - Code Templates
*/ */
public class WSDLScanning extends LessonAdapter { public class WSDLScanning extends LessonAdapter
{
static boolean completed = false; static boolean completed = false;
static boolean beenRestartedYet = false; static boolean beenRestartedYet = false;
public static Connection connection = null; public static Connection connection = null;
public final static String firstName = "getFirstName"; public final static String firstName = "getFirstName";
public final static String lastName = "getLastName"; public final static String lastName = "getLastName";
public final static String loginCount = "getLoginCount"; public final static String loginCount = "getLoginCount";
public final static String ccNumber = "getCreditCard"; public final static String ccNumber = "getCreditCard";
final static IMG CREDITS_LOGO = new IMG( "images/logos/parasoft.jpg" ).setAlt( "Parasoft" ).setBorder( 0 ).setHspace( 0 ).setVspace( 0 );
final static IMG CREDITS_LOGO = new IMG("images/logos/parasoft.jpg")
.setAlt("Parasoft").setBorder(0).setHspace(0).setVspace(0);
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.WEB_SERVICES; return AbstractLesson.WEB_SERVICES;
} }
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "Try connecting to the WSDL with a browser or Web Service tool." ); hints
hints.add( "Sometimes the WSDL will define methods that are not available through a web API. " + .add("Try connecting to the WSDL with a browser or Web Service tool.");
"Try to find operations that are in the WSDL, but not part of this API"); hints
hints.add( "The URL for the web service is: http://localost/WebGoat/services/WSDLScanning <br>" + .add("Sometimes the WSDL will define methods that are not available through a web API. "
"The WSDL can usually be viewed by adding a ?WSDL on the end of the request."); + "Try to find operations that are in the WSDL, but not part of this API");
hints.add( "Look in the WSDL for the getCreditCard operation and insert the field in an intercepted request."); hints
.add("The URL for the web service is: http://localost/WebGoat/services/WSDLScanning <br>"
+ "The WSDL can usually be viewed by adding a ?WSDL on the end of the request.");
hints
.add("Look in the WSDL for the getCreditCard operation and insert the field in an intercepted request.");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return "WSDL Scanning"; return "WSDL Scanning";
} }
public Object accessWGService(String serv, String proc, String parameterName, Object parameterValue) {
public Object accessWGService(String serv, String proc,
String parameterName, Object parameterValue)
{
String targetNamespace = "WebGoat"; String targetNamespace = "WebGoat";
try { try
{
QName serviceName = new QName(targetNamespace, serv); QName serviceName = new QName(targetNamespace, serv);
QName operationName = new QName(targetNamespace, proc); QName operationName = new QName(targetNamespace, proc);
Service service = new Service(); Service service = new Service();
@ -94,24 +145,31 @@ public class WSDLScanning extends LessonAdapter {
call.setReturnType(XMLType.XSD_STRING); call.setReturnType(XMLType.XSD_STRING);
call.setUsername("guest"); call.setUsername("guest");
call.setPassword("guest"); call.setPassword("guest");
call.setTargetEndpointAddress( call.setTargetEndpointAddress("http://localhost/WebGoat/services/"
"http://localhost/WebGoat/services/" + serv); + serv);
Object result = call.invoke(new Object[] { parameterValue }); Object result = call.invoke(new Object[] { parameterValue });
return result; return result;
} catch (RemoteException e) { }
catch (RemoteException e)
{
e.printStackTrace(); e.printStackTrace();
} catch (ServiceException e) { }
catch (ServiceException e)
{
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { }
catch (Exception e)
{
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Table t1 = new Table().setCellSpacing(0).setCellPadding(2); Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) if (s.isColor())
@ -125,10 +183,10 @@ public class WSDLScanning extends LessonAdapter {
tr = new TR(); tr = new TR();
tr.addElement(new TD("Select the fields to return: ")); tr.addElement(new TD("Select the fields to return: "));
tr.addElement(new TD( new Select("field").setMultiple(true) tr.addElement(new TD(new Select("field").setMultiple(true).addElement(
.addElement(new Option(firstName).addElement("First Name")) new Option(firstName).addElement("First Name")).addElement(
.addElement(new Option(lastName).addElement("Last Name")) new Option(lastName).addElement("Last Name")).addElement(
.addElement(new Option(loginCount).addElement("Login Count")))); new Option(loginCount).addElement("Login Count"))));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
@ -138,7 +196,8 @@ public class WSDLScanning extends LessonAdapter {
ec.addElement(t1); ec.addElement(t1);
try { try
{
String[] fields = s.getParser().getParameterValues("field"); String[] fields = s.getParser().getParameterValues("field");
int id = s.getParser().getIntParameter("id"); int id = s.getParser().getIntParameter("id");
if (connection == null) if (connection == null)
@ -146,7 +205,8 @@ public class WSDLScanning extends LessonAdapter {
connection = DatabaseUtilities.makeConnection(s); connection = DatabaseUtilities.makeConnection(s);
} }
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 2 ).setBorder( 1 ); Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1);
if (s.isColor()) if (s.isColor())
{ {
@ -154,9 +214,12 @@ public class WSDLScanning extends LessonAdapter {
} }
TR header = new TR(); TR header = new TR();
TR results = new TR(); TR results = new TR();
for (int i=0; i<fields.length;i++) { for (int i = 0; i < fields.length; i++)
{
header.addElement(new TD().addElement(fields[i])); header.addElement(new TD().addElement(fields[i]));
results.addElement(new TD().addElement((String) accessWGService("WSDLScanning", fields[i], "acct_num", new Integer(id)))); results.addElement(new TD()
.addElement((String) accessWGService("WSDLScanning",
fields[i], "acct_num", new Integer(id))));
} }
if (fields.length == 0) if (fields.length == 0)
{ {
@ -165,21 +228,30 @@ public class WSDLScanning extends LessonAdapter {
t.addElement(header); t.addElement(header);
t.addElement(results); t.addElement(results);
ec.addElement(new P().addElement(t)); ec.addElement(new P().addElement(t));
} catch (Exception e) { }
catch (Exception e)
{
} }
try try
{ {
A a = new A("services/WSDLScanning?WSDL", "WebGoat WSDL"); A a = new A("services/WSDLScanning?WSDL", "WebGoat WSDL");
ec.addElement(new P().addElement("View the web services definition language (WSDL) to see the complete API:")); ec
.addElement(new P()
.addElement("View the web services definition language (WSDL) to see the complete API:"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(a); ec.addElement(a);
//getLessonTracker( s ).setCompleted( completed ); //getLessonTracker( s ).setCompleted( completed );
if ( completed && ! getLessonTracker( s ).getCompleted() && ! beenRestartedYet ) { if (completed && !getLessonTracker(s).getCompleted()
&& !beenRestartedYet)
{
makeSuccess(s); makeSuccess(s);
beenRestartedYet = true; beenRestartedYet = true;
} else if ( completed && ! getLessonTracker(s).getCompleted() && beenRestartedYet) { }
else if (completed && !getLessonTracker(s).getCompleted()
&& beenRestartedYet)
{
completed = false; completed = false;
beenRestartedYet = false; beenRestartedYet = false;
} }
@ -193,14 +265,19 @@ public class WSDLScanning extends LessonAdapter {
} }
return (ec); return (ec);
} }
public String getResults(int id, String field) {
public String getResults(int id, String field)
{
try try
{ {
Connection connection = DatabaseUtilities.makeConnection(); Connection connection = DatabaseUtilities.makeConnection();
if (connection == null) { if (connection == null)
{
return null; return null;
} }
PreparedStatement ps = connection.prepareStatement("SELECT * FROM user_data WHERE userid = ?"); PreparedStatement ps = connection
.prepareStatement("SELECT * FROM user_data WHERE userid = ?");
ps.setInt(1, id); ps.setInt(1, id);
try try
{ {
@ -211,15 +288,16 @@ public class WSDLScanning extends LessonAdapter {
} }
} }
catch (SQLException sqle) catch (SQLException sqle)
{ {}
}
} }
catch (Exception e) catch (Exception e)
{ {}
}
return null; return null;
} }
public String getCreditCard(int id) {
public String getCreditCard(int id)
{
String result = getResults(id, "cc_number"); String result = getResults(id, "cc_number");
if (result != null) if (result != null)
{ {
@ -228,7 +306,10 @@ public class WSDLScanning extends LessonAdapter {
} }
return null; return null;
} }
public String getFirstName(int id) {
public String getFirstName(int id)
{
String result = getResults(id, "first_name"); String result = getResults(id, "first_name");
if (result != null) if (result != null)
{ {
@ -236,7 +317,10 @@ public class WSDLScanning extends LessonAdapter {
} }
return null; return null;
} }
public String getLastName(int id) {
public String getLastName(int id)
{
String result = getResults(id, "last_name"); String result = getResults(id, "last_name");
if (result != null) if (result != null)
{ {
@ -244,7 +328,10 @@ public class WSDLScanning extends LessonAdapter {
} }
return null; return null;
} }
public String getLoginCount(int id) {
public String getLoginCount(int id)
{
String result = getResults(id, "login_count"); String result = getResults(id, "login_count");
if (result != null) if (result != null)
{ {
@ -253,10 +340,10 @@ public class WSDLScanning extends LessonAdapter {
return null; return null;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO); return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO);
} }
} }

View File

@ -16,30 +16,56 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.*; import org.owasp.webgoat.session.*;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class WeakAuthenticationCookie extends LessonAdapter public class WeakAuthenticationCookie extends LessonAdapter
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String AUTHCOOKIE = "AuthCookie"; protected final static String AUTHCOOKIE = "AuthCookie";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String LOGOUT = "WACLogout"; protected final static String LOGOUT = "WACLogout";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String PASSWORD = "Password"; protected final static String PASSWORD = "Password";
/** /**
* Description of the Field * Description of the Field
*/ */
@ -84,6 +110,7 @@ public class WeakAuthenticationCookie extends LessonAdapter
return (null); return (null);
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -233,9 +260,12 @@ public class WeakAuthenticationCookie extends LessonAdapter
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "The server skips authentication if you send the right cookie." ); hints
hints.add( "Is the AuthCookie value guessable knowing the username and password?" ); .add("The server skips authentication if you send the right cookie.");
hints.add( "Add 'AuthCookie=********;' to the Cookie: header using <A href=\"http://www.owasp.org/development/webscarab\">WebScarab</A>." ); hints
.add("Is the AuthCookie value guessable knowing the username and password?");
hints
.add("Add 'AuthCookie=********;' to the Cookie: header using <A href=\"http://www.owasp.org/development/webscarab\">WebScarab</A>.");
return hints; return hints;
} }
@ -253,16 +283,15 @@ public class WeakAuthenticationCookie extends LessonAdapter
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(90); private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CookieScreen object * Gets the title attribute of the CookieScreen object
* *
@ -285,7 +314,8 @@ public class WeakAuthenticationCookie extends LessonAdapter
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Sign In ")); 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()) if (s.isColor())
{ {
@ -293,7 +323,10 @@ public class WeakAuthenticationCookie extends LessonAdapter
} }
TR tr = new TR(); 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.") 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")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
@ -334,15 +367,18 @@ public class WeakAuthenticationCookie extends LessonAdapter
* @return Description of the Return Value * @return Description of the Return Value
* @exception Exception Description of the Exception * @exception Exception Description of the Exception
*/ */
protected Element makeUser( WebSession s, String user, String method ) throws Exception protected Element makeUser(WebSession s, String user, String method)
throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement("Welcome, " + user)); ec.addElement(new P().addElement("Welcome, " + user));
ec.addElement( new P().addElement( "You have been authenticated with " + method ) ); ec.addElement(new P().addElement("You have been authenticated with "
ec.addElement( new P().addElement( ECSFactory.makeLink( "Logout", LOGOUT, true ) ) ); + method));
ec.addElement( new P().addElement( ECSFactory.makeLink( "Refresh", "", "" ) ) ); ec.addElement(new P().addElement(ECSFactory.makeLink("Logout", LOGOUT,
true)));
ec.addElement(new P()
.addElement(ECSFactory.makeLink("Refresh", "", "")));
return (ec); return (ec);
} }
} }

View File

@ -20,17 +20,41 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.ParameterNotFoundException; import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Rogan Dawes <a href="http://dawes.za.net/rogan">Rogan Dawes</a> * @author Rogan Dawes <a href="http://dawes.za.net/rogan">Rogan Dawes</a>
* @created March 30, 2005 * @created March 30, 2005
*/ */
public class WeakSessionID extends LessonAdapter { public class WeakSessionID extends LessonAdapter
{
/** /**
* Description of the Field * Description of the Field
*/ */
@ -47,22 +71,29 @@ public class WeakSessionID extends LessonAdapter {
protected final static String USERNAME = "Username"; protected final static String USERNAME = "Username";
protected static List<String> sessionList = new ArrayList<String>(); protected static List<String> sessionList = new ArrayList<String>();
protected static long seq = Math.round(Math.random() * 10240) + 10000; protected static long seq = Math.round(Math.random() * 10240) + 10000;
protected static long lastTime = System.currentTimeMillis(); protected static long lastTime = System.currentTimeMillis();
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
* *
* @return The credits value * @return The credits value
*/ */
public Element getCredits() { public Element getCredits()
{
return new StringElement("By Rogan Dawes"); return new StringElement("By Rogan Dawes");
} }
protected String newCookie() {
protected String newCookie()
{
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
seq++; seq++;
if (seq % 29 == 0) { if (seq % 29 == 0)
{
String target = encode(seq++, lastTime + (now - lastTime) / 2); String target = encode(seq++, lastTime + (now - lastTime) / 2);
sessionList.add(target); sessionList.add(target);
if (sessionList.size() > 100) if (sessionList.size() > 100)
@ -72,27 +103,35 @@ public class WeakSessionID extends LessonAdapter {
return encode(seq, now); return encode(seq, now);
} }
private String encode(long seq, long time) {
private String encode(long seq, long time)
{
return new String(Long.toString(seq) + "-" + Long.toString(time)); return new String(Long.toString(seq) + "-" + Long.toString(time));
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s Description of the Parameter * @param s Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent( WebSession s ) { protected Element createContent(WebSession s)
try { {
try
{
String sessionid = s.getCookie(SESSIONID); String sessionid = s.getCookie(SESSIONID);
if ( sessionid != null && sessionList.indexOf(sessionid) > -1) { if (sessionid != null && sessionList.indexOf(sessionid) > -1)
{
return makeSuccess(s); return makeSuccess(s);
} }
else { else
{
return makeLogin(s); return makeLogin(s);
} }
} }
catch ( Exception e ) { catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
@ -106,21 +145,24 @@ public class WeakSessionID extends LessonAdapter {
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() { protected Category getDefaultCategory()
{
return AbstractLesson.A3; return AbstractLesson.A3;
} }
/** /**
* Gets the hints attribute of the CookieScreen object * Gets the hints attribute of the CookieScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List getHints() { protected List getHints()
{
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "The server skips authentication if you send the right cookie." ); hints
hints.add( "Is the cookie value predictable? Can you see gaps where someone else has acquired a cookie?" ); .add("The server skips authentication if you send the right cookie.");
hints
.add("Is the cookie value predictable? Can you see gaps where someone else has acquired a cookie?");
hints.add("Try harder, you brute!"); hints.add("Try harder, you brute!");
return hints; return hints;
@ -128,17 +170,20 @@ public class WeakSessionID extends LessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(90); private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CookieScreen object * Gets the title attribute of the CookieScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() { public String getTitle()
{
return ("How to hijack a session"); return ("How to hijack a session");
} }
@ -149,35 +194,46 @@ public class WeakSessionID extends LessonAdapter {
* @param s Description of the Parameter * @param s Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeLogin( WebSession s ) { protected Element makeLogin(WebSession s)
{
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String weakid = s.getCookie(SESSIONID); String weakid = s.getCookie(SESSIONID);
if (weakid == null) { if (weakid == null)
{
weakid = newCookie(); weakid = newCookie();
Cookie cookie = new Cookie(SESSIONID, weakid); Cookie cookie = new Cookie(SESSIONID, weakid);
s.getResponse().addCookie(cookie); s.getResponse().addCookie(cookie);
} }
ec.addElement(new H1().addElement("Sign In ")); 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() ) { if (s.isColor())
{
t.setBorder(1); t.setBorder(1);
} }
String username = null; String username = null;
String password = null; String password = null;
try { try
{
username = s.getParser().getStringParameter(USERNAME); username = s.getParser().getStringParameter(USERNAME);
} catch (ParameterNotFoundException pnfe) {} }
try { catch (ParameterNotFoundException pnfe)
{}
try
{
password = s.getParser().getStringParameter(PASSWORD); password = s.getParser().getStringParameter(PASSWORD);
} catch (ParameterNotFoundException pnfe) {} }
catch (ParameterNotFoundException pnfe)
{}
if (username != null || password != null) { if (username != null || password != null)
{
s.setMessage("Invalid username or password."); s.setMessage("Invalid username or password.");
} }
@ -215,4 +271,3 @@ public class WeakSessionID extends LessonAdapter {
return (ec); return (ec);
} }
} }

View File

@ -11,18 +11,41 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.*; import org.owasp.webgoat.session.*;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class WelcomeScreen extends Screen public class WelcomeScreen extends Screen
{ {
/** /**
* Constructor for the WelcomeScreen object * Constructor for the WelcomeScreen object
* *
@ -33,29 +56,35 @@ public class WelcomeScreen extends Screen
setup(s); setup(s);
} }
/** /**
* Constructor for the WelcomeScreen object * Constructor for the WelcomeScreen object
*/ */
public WelcomeScreen() { } public WelcomeScreen()
{}
public void setup(WebSession s) public void setup(WebSession s)
{ {
// call createContent first so messages will go somewhere // call createContent first so messages will go somewhere
Form form = new Form( "attack", Form.POST ).setName( "form" ).setEncType( "" ); Form form = new Form("attack", Form.POST).setName("form")
.setEncType("");
form.addElement(wrapForm(s)); form.addElement(wrapForm(s));
TD lowerright = new TD().setHeight( "100%" ).setVAlign( "top" ).setAlign( "left" ).addElement( form ); TD lowerright = new TD().setHeight("100%").setVAlign("top").setAlign(
"left").addElement(form);
TR row = new TR().addElement(lowerright); TR row = new TR().addElement(lowerright);
Table layout = new Table().setBgColor( HtmlColor.WHITE ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 ); Table layout = new Table().setBgColor(HtmlColor.WHITE)
.setCellSpacing(0).setCellPadding(0).setBorder(0);
layout.addElement(row); layout.addElement(row);
setContent(layout); setContent(layout);
} }
protected Element wrapForm(WebSession s) protected Element wrapForm(WebSession s)
{ {
if (s == null) if (s == null)
@ -63,18 +92,21 @@ public class WelcomeScreen extends Screen
return new StringElement("Invalid Session"); return new StringElement("Invalid Session");
} }
Table container = new Table().setWidth( "100%" ).setCellSpacing( 10 ).setCellPadding( 0 ).setBorder( 0 ); Table container = new Table().setWidth("100%").setCellSpacing(10)
.setCellPadding(0).setBorder(0);
// CreateContent can generate error messages so you MUST call it before makeMessages() // CreateContent can generate error messages so you MUST call it before makeMessages()
Element content = createContent(s); Element content = createContent(s);
container.addElement( new TR().addElement( new TD().setColSpan( 2 ).setVAlign( "TOP" ).addElement( container.addElement(new TR().addElement(new TD().setColSpan(2)
makeMessages( s ) ) ) ); .setVAlign("TOP").addElement(makeMessages(s))));
container.addElement( new TR().addElement( new TD().setColSpan( 2 ).addElement( content ) ) ); container.addElement(new TR().addElement(new TD().setColSpan(2)
.addElement(content)));
container.addElement(new TR()); container.addElement(new TR());
return (container); return (container);
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -90,11 +122,13 @@ public class WelcomeScreen extends Screen
return (ec); return (ec);
} }
public Element getCredits() public Element getCredits()
{ {
return new ElementContainer(); return new ElementContainer();
} }
/** /**
* Gets the instructions attribute of the WelcomeScreen object * Gets the instructions attribute of the WelcomeScreen object
* *
@ -118,11 +152,12 @@ public class WelcomeScreen extends Screen
return ("Welcome to the Penetration Testing Course"); return ("Welcome to the Penetration Testing Course");
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see session.Screen#getRole() * @see session.Screen#getRole()
*/ */
public String getRole() { public String getRole()
{
return AbstractLesson.USER_ROLE; return AbstractLesson.USER_ROLE;
} }
} }

View File

@ -29,13 +29,43 @@ import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory; import org.xml.sax.helpers.XMLReaderFactory;
/** /*******************************************************************************
*
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author rdawes * @author rdawes
* *
* TODO To change the template for this generated type comment go to Window - * TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates * Preferences - Java - Code Style - Code Templates
*/ */
public class WsSAXInjection extends LessonAdapter { public class WsSAXInjection extends LessonAdapter
{
private final static String PASSWORD = "password"; private final static String PASSWORD = "password";
private String password; private String password;
@ -57,32 +87,44 @@ public class WsSAXInjection extends LessonAdapter {
static boolean completed; static boolean completed;
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return AbstractLesson.WEB_SERVICES; return AbstractLesson.WEB_SERVICES;
} }
protected List getHints() {
protected List getHints()
{
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("The backend parses the XML received using a SAX parser."); hints.add("The backend parses the XML received using a SAX parser.");
hints.add("SAX parsers often don't care if an element is repeated."); hints.add("SAX parsers often don't care if an element is repeated.");
hints.add("If there are repeated elements, the last one is the one that is effective"); hints
hints.add("Try injecting matching 'close' tags, and creating your own XML elements"); .add("If there are repeated elements, the last one is the one that is effective");
hints
.add("Try injecting matching 'close' tags, and creating your own XML elements");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(150); private final static Integer DEFAULT_RANKING = new Integer(150);
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() {
public String getTitle()
{
return "Web Service SAX Injection"; return "Web Service SAX Injection";
} }
protected Element makeInputLine(WebSession s) {
protected Element makeInputLine(WebSession s)
{
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement("Please change your password: ")); ec.addElement(new P().addElement("Please change your password: "));
@ -96,9 +138,12 @@ public class WsSAXInjection extends LessonAdapter {
return ec; return ec;
} }
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try { try
{
ec.addElement(makeInputLine(s)); ec.addElement(makeInputLine(s));
password = s.getParser().getRawParameter(PASSWORD, null); password = s.getParser().getRawParameter(PASSWORD, null);
@ -110,53 +155,84 @@ public class WsSAXInjection extends LessonAdapter {
pre.addElement(HtmlEncoder.encode(xml)); pre.addElement(HtmlEncoder.encode(xml));
ec.addElement(pre); ec.addElement(pre);
if (password != null) { if (password != null)
{
ec.addElement(checkXML(s, xml)); ec.addElement(checkXML(s, xml));
} }
} catch (Exception e) { }
catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
private Element checkXML(WebSession s, String xml) {
try { private Element checkXML(WebSession s, String xml)
{
try
{
XMLReader reader = XMLReaderFactory.createXMLReader(); XMLReader reader = XMLReaderFactory.createXMLReader();
PasswordChanger changer = new PasswordChanger(); PasswordChanger changer = new PasswordChanger();
reader.setContentHandler(changer); reader.setContentHandler(changer);
reader.parse(new InputSource(new StringReader(xml))); reader.parse(new InputSource(new StringReader(xml)));
if (!"101".equals(changer.getId())) { if (!"101".equals(changer.getId()))
{
makeSuccess(s); makeSuccess(s);
return new B(HtmlEncoder.encode("You have changed the passsword for userid " + changer.getId() + " to '" + changer.getPassword() + "'")); return new B(HtmlEncoder
} else { .encode("You have changed the passsword for userid "
return new StringElement("You changed the password for userid 101. Try again."); + changer.getId() + " to '"
+ changer.getPassword() + "'"));
} }
} catch (SAXException saxe) { else
return new StringElement("The XML was not well formed: " + saxe.getLocalizedMessage()); {
} catch (IOException ioe) { return new StringElement(
"You changed the password for userid 101. Try again.");
}
}
catch (SAXException saxe)
{
return new StringElement("The XML was not well formed: "
+ saxe.getLocalizedMessage());
}
catch (IOException ioe)
{
return new StringElement(ioe.getLocalizedMessage()); return new StringElement(ioe.getLocalizedMessage());
} }
} }
private static class PasswordChanger extends DefaultHandler { private static class PasswordChanger extends DefaultHandler
{
private static String PASSWORD_TAG = "password"; private static String PASSWORD_TAG = "password";
private static String ID_TAG = "id"; private static String ID_TAG = "id";
private String id = null; private String id = null;
private String password = null; private String password = null;
private StringBuffer text = new StringBuffer(); private StringBuffer text = new StringBuffer();
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException
{
text.delete(0, text.length()); text.delete(0, text.length());
} }
public void characters(char[] ch, int start, int length) throws SAXException {
public void characters(char[] ch, int start, int length)
throws SAXException
{
text.append(ch, start, length); text.append(ch, start, length);
} }
public void endElement(String uri, String localName, String qName) throws SAXException {
public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (localName.equals(ID_TAG)) if (localName.equals(ID_TAG))
id = text.toString(); id = text.toString();
if (localName.equals(PASSWORD_TAG)) if (localName.equals(PASSWORD_TAG))
@ -164,15 +240,22 @@ public class WsSAXInjection extends LessonAdapter {
text.delete(0, text.length()); text.delete(0, text.length());
} }
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException
{
text.append(ch, start, length); text.append(ch, start, length);
} }
public String getId() {
public String getId()
{
return id; return id;
} }
public String getPassword() {
public String getPassword()
{
return password; return password;
} }

View File

@ -27,50 +27,92 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author asmolen * @author asmolen
* *
* TODO To change the template for this generated type comment go to * TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates * Window - Preferences - Java - Code Style - Code Templates
*/ */
public class WsSqlInjection extends LessonAdapter { public class WsSqlInjection extends LessonAdapter
{
public final static String ccNumber = "cc_number"; public final static String ccNumber = "cc_number";
private final static String ACCT_NUM = "account_number"; private final static String ACCT_NUM = "account_number";
private String accountNumber; private String accountNumber;
final static IMG CREDITS_LOGO = new IMG( "images/logos/parasoft.jpg" ).setAlt( "Parasoft" ).setBorder( 0 ).setHspace( 0 ).setVspace( 0 );
final static IMG CREDITS_LOGO = new IMG("images/logos/parasoft.jpg")
.setAlt("Parasoft").setBorder(0).setHspace(0).setVspace(0);
private static Connection connection = null; private static Connection connection = null;
/* (non-Javadoc) /* (non-Javadoc)
* @see lessons.AbstractLesson#getMenuItem() * @see lessons.AbstractLesson#getMenuItem()
*/ */
static boolean completed; static boolean completed;
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return AbstractLesson.WEB_SERVICES; return AbstractLesson.WEB_SERVICES;
} }
protected List getHints() protected List getHints()
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add( "Try connecting to the WSDL with a browser or Web Service tool." ); hints
hints.add( "Sometimes the server side code will perform input validation before issuing " + .add("Try connecting to the WSDL with a browser or Web Service tool.");
"the request to the web service operation. Try to bypass this check by " + hints
"accessing the web service directly"); .add("Sometimes the server side code will perform input validation before issuing "
hints.add( "The URL for the web service is: http://localhost/WebGoat/services/WsSqlInjection?WSDL <br>" + + "the request to the web service operation. Try to bypass this check by "
"The WSDL can usually be viewed by adding a ?WSDL on the end of the request."); + "accessing the web service directly");
hints.add( "Create a new soap request for the getCreditCard(String id) operation."); hints
hints.add("A soap request uses the following HTTP header: <br> " + .add("The URL for the web service is: http://localhost/WebGoat/services/WsSqlInjection?WSDL <br>"
"SOAPAction: some action header, can be &quot;&quot;<br><br>" + + "The WSDL can usually be viewed by adding a ?WSDL on the end of the request.");
"The soap message body has the following format:<br>" + hints
"&lt;?xml version='1.0' encoding='UTF-8'?&gt; <br>" + .add("Create a new soap request for the getCreditCard(String id) operation.");
"&nbsp;&nbsp;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'&gt; <br>" + hints
"&nbsp;&nbsp;&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>" + .add("A soap request uses the following HTTP header: <br> "
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:getCreditCard SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:ns1='http://lessons'&gt; <br>" + + "SOAPAction: some action header, can be &quot;&quot;<br><br>"
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;id xsi:type='xsd:string'&gt;101&lt;/id&gt; <br>" + + "The soap message body has the following format:<br>"
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:getCreditCard&gt; <br>" + + "&lt;?xml version='1.0' encoding='UTF-8'?&gt; <br>"
"&nbsp;&nbsp;&nbsp;&nbsp;&lt;/SOAP-ENV:Body&gt; <br>" + + "&nbsp;&nbsp;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'&gt; <br>"
"&nbsp;&nbsp;&lt;/SOAP-ENV:Envelope&gt; <br>" + + "&nbsp;&nbsp;&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>"
""); + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:getCreditCard SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:ns1='http://lessons'&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;id xsi:type='xsd:string'&gt;101&lt;/id&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:getCreditCard&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;/SOAP-ENV:Body&gt; <br>"
+ "&nbsp;&nbsp;&lt;/SOAP-ENV:Envelope&gt; <br>" + "");
/* "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; <br>" + /* "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; <br>" +
" &lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" <br>" + " &lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" <br>" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" <br>" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" <br>" +
@ -87,15 +129,19 @@ public class WsSqlInjection extends LessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(150); private final static Integer DEFAULT_RANKING = new Integer(150);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return "Web Service SQL Injection"; return "Web Service SQL Injection";
} }
protected Element makeAccountLine(WebSession s) protected Element makeAccountLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -111,6 +157,8 @@ public class WsSqlInjection extends LessonAdapter {
return ec; return ec;
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -122,11 +170,14 @@ public class WsSqlInjection extends LessonAdapter {
} }
ec.addElement(makeAccountLine(s)); ec.addElement(makeAccountLine(s));
String query = "SELECT * FROM user_data WHERE userid = " + accountNumber ; String query = "SELECT * FROM user_data WHERE userid = "
+ accountNumber;
ec.addElement(new PRE(query)); ec.addElement(new PRE(query));
for (int i=0; i<accountNumber.length(); i++) { for (int i = 0; i < accountNumber.length(); i++)
{
char c = accountNumber.charAt(i); char c = accountNumber.charAt(i);
if (c < '0' || c > '9') { if (c < '0' || c > '9')
{
ec.addElement("Invalid account number. "); ec.addElement("Invalid account number. ");
accountNumber = "0"; accountNumber = "0";
} }
@ -137,7 +188,8 @@ public class WsSqlInjection extends LessonAdapter {
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
results.last(); results.last();
if (results.getRow() >= 6) if (results.getRow() >= 6)
{ {
@ -154,7 +206,9 @@ public class WsSqlInjection extends LessonAdapter {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
} }
A a = new A("services/WsSqlInjection?WSDL", "WebGoat WSDL"); A a = new A("services/WsSqlInjection?WSDL", "WebGoat WSDL");
ec.addElement(new P().addElement("Exploit the following WSDL to access sensitive data:")); ec
.addElement(new P()
.addElement("Exploit the following WSDL to access sensitive data:"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(a); ec.addElement(a);
getLessonTracker(s).setCompleted(completed); getLessonTracker(s).setCompleted(completed);
@ -166,50 +220,63 @@ public class WsSqlInjection extends LessonAdapter {
} }
return (ec); return (ec);
} }
public ResultSet getResults (String id) {
public ResultSet getResults(String id)
{
try try
{ {
Connection connection = DatabaseUtilities.makeConnection(); Connection connection = DatabaseUtilities.makeConnection();
if (connection == null) { if (connection == null)
{
return null; return null;
} }
String query = "SELECT * FROM user_data WHERE userid = " + id; String query = "SELECT * FROM user_data WHERE userid = " + id;
try try
{ {
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
return results; return results;
} }
catch (SQLException sqle) catch (SQLException sqle)
{ {}
}
} }
catch (Exception e) catch (Exception e)
{ {}
}
return null; return null;
} }
public String[] getCreditCard(String id) {
public String[] getCreditCard(String id)
{
ResultSet results = getResults(id); ResultSet results = getResults(id);
if ((results != null)) { if ((results != null))
try { {
try
{
results.last(); results.last();
String[] users = new String[results.getRow()]; String[] users = new String[results.getRow()];
if (users.length > 4) { if (users.length > 4)
{
completed = true; completed = true;
} }
results.beforeFirst(); results.beforeFirst();
while (results.next() == true) { while (results.next() == true)
{
int i = results.getRow(); int i = results.getRow();
users[i - 1] = results.getString(ccNumber); users[i - 1] = results.getString(ccNumber);
} }
return users; return users;
} catch (SQLException sqle) {
} }
catch (SQLException sqle)
{}
} }
return null; return null;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO); return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO);

View File

@ -21,16 +21,47 @@ import org.apache.ecs.html.Div;
import org.apache.ecs.vxml.Initial; import org.apache.ecs.vxml.Initial;
import org.apache.ecs.StringElement; import org.apache.ecs.StringElement;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
public class XMLInjection extends LessonAdapter { /*******************************************************************************
*
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class XMLInjection extends LessonAdapter
{
private final static Integer DEFAULT_RANKING = new Integer(20); private final static Integer DEFAULT_RANKING = new Integer(20);
private final static String ACCOUNTID = "accountID"; private final static String ACCOUNTID = "accountID";
public static HashMap rewardsMap = new HashMap(); public static HashMap rewardsMap = new HashMap();
protected static HashMap init() protected static HashMap init()
{ {
Reward r = new Reward(); Reward r = new Reward();
@ -62,23 +93,28 @@ public class XMLInjection extends LessonAdapter {
return rewardsMap; return rewardsMap;
} }
public void handleRequest(WebSession s) {
public void handleRequest(WebSession s)
{
try try
{ {
if (s.getParser().getRawParameter("from", "").equals("ajax")) if (s.getParser().getRawParameter("from", "").equals("ajax"))
{ {
if(s.getParser().getRawParameter(ACCOUNTID, "").equals("836239")) if (s.getParser().getRawParameter(ACCOUNTID, "").equals(
"836239"))
{ {
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String xmlStr = "<root>" + lineSep + String xmlStr = "<root>" + lineSep
"<reward>WebGoat t-shirt 20 Pts</reward>" + lineSep + + "<reward>WebGoat t-shirt 20 Pts</reward>"
"<reward>WebGoat Secure Kettle 50 Pts</reward>" + lineSep + + lineSep
"<reward>WebGoat Mug 30 Pts</reward>" + lineSep + + "<reward>WebGoat Secure Kettle 50 Pts</reward>"
"</root>"; + lineSep + "<reward>WebGoat Mug 30 Pts</reward>"
+ lineSep + "</root>";
s.getResponse().setContentType("text/xml"); s.getResponse().setContentType("text/xml");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse()
.getOutputStream());
out.print(xmlStr); out.print(xmlStr);
out.flush(); out.flush();
out.close(); out.close();
@ -91,7 +127,8 @@ public class XMLInjection extends LessonAdapter {
ex.printStackTrace(); ex.printStackTrace();
} }
Form form = new Form( getFormAction(), Form.POST ).setName( "form" ).setEncType( "" ); Form form = new Form(getFormAction(), Form.POST).setName("form")
.setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
@ -99,7 +136,9 @@ public class XMLInjection extends LessonAdapter {
} }
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
boolean isDone = false; boolean isDone = false;
init(); init();
@ -109,58 +148,95 @@ public class XMLInjection extends LessonAdapter {
isDone = true; isDone = true;
} }
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep + String script = "<script>"
"function getRewards() {" + lineSep + + lineSep
"var accountIDField = document.getElementById('" + ACCOUNTID + "');" + lineSep + + "function getRewards() {"
"if (accountIDField.value.length < 6 ) { return; }" + lineSep + + lineSep
"var url = '/WebGoat/attack?Screen=" + String.valueOf(getScreenId()) + + "var accountIDField = document.getElementById('"
"&menu=" + getDefaultCategory().getRanking().toString() + + ACCOUNTID
"&from=ajax&" + ACCOUNTID + "=' + encodeURIComponent(accountIDField.value);" + lineSep + + "');"
"if (typeof XMLHttpRequest != 'undefined') {" + lineSep + + lineSep
"req = new XMLHttpRequest();" + lineSep + + "if (accountIDField.value.length < 6 ) { return; }"
"} else if (window.ActiveXObject) {" + lineSep + + lineSep
"req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep + + "var url = '/WebGoat/attack?Screen="
" }" + lineSep + + String.valueOf(getScreenId())
" req.open('GET', url, true);" + lineSep + + "&menu="
" req.onreadystatechange = callback;" + lineSep + + getDefaultCategory().getRanking().toString()
" req.send(null);" + lineSep + + "&from=ajax&"
"}" + lineSep + + ACCOUNTID
"function callback() {" + lineSep + + "=' + encodeURIComponent(accountIDField.value);"
" if (req.readyState == 4) { " + lineSep + + lineSep
" if (req.status == 200) { " + lineSep + + "if (typeof XMLHttpRequest != 'undefined') {"
" var rewards = req.responseXML.getElementsByTagName('root')[0];" + lineSep + + lineSep
" var rewardsDiv = document.getElementById('rewardsDiv');" + lineSep + + "req = new XMLHttpRequest();"
" rewardsDiv.innerHTML = '';" + lineSep + + lineSep
" var strHTML='';"+ lineSep + + "} else if (window.ActiveXObject) {"
" strHTML = '<tr><td>&nbsp;</td><td><b>Rewards</b></td></tr>';" + lineSep + + lineSep
" for(var i=0; i< rewards.childNodes.length; i++){" + lineSep + + "req = new ActiveXObject('Microsoft.XMLHTTP');"
" var node = rewards.childNodes[i];" + lineSep + + lineSep
" strHTML = strHTML + '<tr><td><input name=\"check' + (i+1001) +'\" type=\"checkbox\"></td><td>';" + lineSep + + " }"
" strHTML = strHTML + node.childNodes[0].nodeValue + '</td></tr>';" + lineSep + + lineSep
" }" + lineSep + + " req.open('GET', url, true);"
" strHTML = '<table>' + strHTML + '</table>';" + lineSep + + lineSep
" strHTML = 'Your account balance is now 100 points<br><br>' + strHTML;" + lineSep + + " req.onreadystatechange = callback;"
" rewardsDiv.innerHTML = strHTML;"+ lineSep + + lineSep
" }}}" + lineSep + + " req.send(null);"
"</script>" + lineSep; + lineSep
+ "}"
+ lineSep
+ "function callback() {"
+ lineSep
+ " if (req.readyState == 4) { "
+ lineSep
+ " if (req.status == 200) { "
+ lineSep
+ " var rewards = req.responseXML.getElementsByTagName('root')[0];"
+ lineSep
+ " var rewardsDiv = document.getElementById('rewardsDiv');"
+ lineSep
+ " rewardsDiv.innerHTML = '';"
+ lineSep
+ " var strHTML='';"
+ lineSep
+ " strHTML = '<tr><td>&nbsp;</td><td><b>Rewards</b></td></tr>';"
+ lineSep
+ " for(var i=0; i< rewards.childNodes.length; i++){"
+ lineSep
+ " var node = rewards.childNodes[i];"
+ lineSep
+ " strHTML = strHTML + '<tr><td><input name=\"check' + (i+1001) +'\" type=\"checkbox\"></td><td>';"
+ lineSep
+ " strHTML = strHTML + node.childNodes[0].nodeValue + '</td></tr>';"
+ lineSep
+ " }"
+ lineSep
+ " strHTML = '<table>' + strHTML + '</table>';"
+ lineSep
+ " strHTML = 'Your account balance is now 100 points<br><br>' + strHTML;"
+ lineSep + " rewardsDiv.innerHTML = strHTML;"
+ lineSep + " }}}" + lineSep + "</script>" + lineSep;
if (!isDone) if (!isDone)
{ {
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
} }
ec.addElement( new BR().addElement (new H1().addElement( "Welcome to WebGoat-Miles Reward Miles Program."))); ec.addElement(new BR().addElement(new H1()
.addElement("Welcome to WebGoat-Miles Reward Miles Program.")));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement( new BR().addElement (new H3().addElement( "Rewards available through the program:"))); ec.addElement(new BR().addElement(new H3()
.addElement("Rewards available through the program:")));
ec.addElement(new BR()); ec.addElement(new BR());
Table t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
.setWidth("90%").setAlign("center");
TR trRewards = null; TR trRewards = null;
for (int i = 1001; i < 1001 + rewardsMap.size(); i++) for (int i = 1001; i < 1001 + rewardsMap.size(); i++)
{ {
trRewards = new TR(); trRewards = new TR();
Reward r = (Reward) rewardsMap.get(i); Reward r = (Reward) rewardsMap.get(i);
trRewards.addElement( new TD("-" + r.getName() + r.getPoints() + " Pts") ); trRewards.addElement(new TD("-" + r.getName() + r.getPoints()
+ " Pts"));
t2.addElement(trRewards); t2.addElement(trRewards);
} }
@ -171,7 +247,8 @@ public class XMLInjection extends LessonAdapter {
ec.addElement(new H3().addElement("Redeem your points:")); ec.addElement(new H3().addElement("Redeem your points:"));
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
.setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
@ -213,10 +290,13 @@ public class XMLInjection extends LessonAdapter {
if (s.getParser().getRawParameter("check" + i, "") != "") if (s.getParser().getRawParameter("check" + i, "") != "")
{ {
shipment.append( ((Reward)rewardsMap.get(i)).getName() + "<br>" ); shipment.append(((Reward) rewardsMap.get(i)).getName()
+ "<br>");
} }
} }
shipment.insert(0, "<br><br><b>The following items will be shipped to your address:</b><br>"); shipment
.insert(0,
"<br><br><b>The following items will be shipped to your address:</b><br>");
ec.addElement(new StringElement(shipment.toString())); ec.addElement(new StringElement(shipment.toString()));
} }
@ -225,57 +305,84 @@ public class XMLInjection extends LessonAdapter {
return ec; return ec;
} }
protected Element makeSuccess(WebSession s) protected Element makeSuccess(WebSession s)
{ {
getLessonTracker(s).setCompleted(true); getLessonTracker(s).setCompleted(true);
s.setMessage("Congratulations. You have successfully completed this lesson."); s
.setMessage("Congratulations. You have successfully completed this lesson.");
return (null); return (null);
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return AJAX_SECURITY; return AJAX_SECURITY;
} }
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected List getHints() {
protected List getHints()
{
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("This page is using XMLHTTP to comunicate with the server."); hints.add("This page is using XMLHTTP to comunicate with the server.");
hints.add("Try to intercept the reply and check the reply."); hints.add("Try to intercept the reply and check the reply.");
hints.add( "Intercept the reply and try to inject some XML to add more rewards to yourself." ); hints
.add("Intercept the reply and try to inject some XML to add more rewards to yourself.");
return hints; return hints;
} }
public String getTitle() {
public String getTitle()
{
return "XML Injection"; return "XML Injection";
} }
static class Reward static class Reward
{ {
private String name; private String name;
private int points; private int points;
public String getName() {
public String getName()
{
return name; return name;
} }
public void setName(String name) {
public void setName(String name)
{
this.name = name; this.name = name;
} }
public int getPoints() {
public int getPoints()
{
return points; return points;
} }
public void setPoints(int points) {
public void setPoints(int points)
{
this.points = points; this.points = points;
} }

View File

@ -35,36 +35,79 @@ import org.apache.ecs.HtmlColor;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ECSFactory;
/** /*******************************************************************************
* @author sherif
* *
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Sherif Koussa <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created November 28, 2006
*/ */
public class XPATHInjection extends LessonAdapter {
public class XPATHInjection extends LessonAdapter
{
private final static Integer DEFAULT_RANKING = new Integer(74); private final static Integer DEFAULT_RANKING = new Integer(74);
private final static String USERNAME = "Username"; private final static String USERNAME = "Username";
private final static String PASSWORD = "Password"; private final static String PASSWORD = "Password";
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
NodeList nodes = null; NodeList nodes = null;
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try{ try
ec.addElement( new BR().addElement (new H1().addElement( "Welcome to WebGoat employee intranet"))); {
ec.addElement(new BR().addElement(new H1()
.addElement("Welcome to WebGoat employee intranet")));
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0)
.setBorder(0).setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement( new TH().addElement("Please confirm your username and password before viewing your profile.").setColSpan(2).setAlign("left")); tr
.addElement(new TH()
.addElement(
"Please confirm your username and password before viewing your profile.")
.setColSpan(2).setAlign("left"));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement("*Required Fields").setWidth("30%").setColSpan(2).setAlign("left")); tr.addElement(new TD().addElement("*Required Fields").setWidth(
"30%").setColSpan(2).setAlign("left"));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().addElement("&nbsp").setWidth("30%").setColSpan(2).setAlign("left")); tr.addElement(new TD().addElement("&nbsp").setWidth("30%")
.setColSpan(2).setAlign("left"));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
@ -88,30 +131,36 @@ public class XPATHInjection extends LessonAdapter {
String username = s.getParser().getRawParameter(USERNAME, ""); String username = s.getParser().getRawParameter(USERNAME, "");
if (username == null || username.length() == 0) if (username == null || username.length() == 0)
{ {
ec.addElement( new P().addElement( new StringElement("Username is a required field"))); ec.addElement(new P().addElement(new StringElement(
"Username is a required field")));
return ec; return ec;
} }
String password = s.getParser().getRawParameter(PASSWORD, ""); String password = s.getParser().getRawParameter(PASSWORD, "");
if (password == null || password.length() == 0) if (password == null || password.length() == 0)
{ {
ec.addElement( new P().addElement( new StringElement("Password is a required field"))); ec.addElement(new P().addElement(new StringElement(
"Password is a required field")));
return ec; return ec;
} }
String dir = s.getContext().getRealPath( "/lessons/XPATHInjection/EmployeesData.xml" ); String dir = s.getContext().getRealPath(
"/lessons/XPATHInjection/EmployeesData.xml");
File d = new File(dir); File d = new File(dir);
XPathFactory factory = XPathFactory.newInstance(); XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath(); XPath xPath = factory.newXPath();
InputSource inputSource = new InputSource(new FileInputStream(d)); InputSource inputSource = new InputSource(new FileInputStream(d));
String expression = "/employees/employee[loginID/text()='" + username + "' and passwd/text()='" + password + "']"; String expression = "/employees/employee[loginID/text()='"
nodes = (NodeList)xPath.evaluate(expression, inputSource, XPathConstants.NODESET); + username + "' and passwd/text()='" + password + "']";
nodes = (NodeList) xPath.evaluate(expression, inputSource,
XPathConstants.NODESET);
int nodesLength = nodes.getLength(); int nodesLength = nodes.getLength();
Table t2 = null; Table t2 = null;
if (nodesLength > 0) if (nodesLength > 0)
{ {
t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(1).setWidth("90%").setAlign("center"); t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(
1).setWidth("90%").setAlign("center");
tr = new TR(); tr = new TR();
tr.setBgColor(HtmlColor.GRAY); tr.setBgColor(HtmlColor.GRAY);
tr.addElement(new TD().addElement("Username")); tr.addElement(new TD().addElement("Username"));
@ -123,7 +172,8 @@ public class XPATHInjection extends LessonAdapter {
for (int i = 0; i < nodesLength; i++) for (int i = 0; i < nodesLength; i++)
{ {
Node node = nodes.item(i); Node node = nodes.item(i);
String[] arrTokens = node.getTextContent().split("[\\t\\s\\n]+"); String[] arrTokens = node.getTextContent()
.split("[\\t\\s\\n]+");
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(arrTokens[1])); tr.addElement(new TD().addElement(arrTokens[1]));
@ -131,7 +181,6 @@ public class XPATHInjection extends LessonAdapter {
tr.addElement(new TD().addElement(arrTokens[4])); tr.addElement(new TD().addElement(arrTokens[4]));
t2.addElement(tr); t2.addElement(tr);
} }
if (nodes.getLength() > 1) if (nodes.getLength() > 1)
{ {
@ -162,36 +211,50 @@ public class XPATHInjection extends LessonAdapter {
return ec; return ec;
} }
public Element getCredits() {
public Element getCredits()
{
return new StringElement("Created by Sherif Koussa"); return new StringElement("Created by Sherif Koussa");
} }
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return AbstractLesson.A6; return AbstractLesson.A6;
} }
protected boolean getDefaultHidden() {
protected boolean getDefaultHidden()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected List getHints() {
protected List getHints()
{
// TODO Auto-generated method stub // TODO Auto-generated method stub
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Remember that the data is stored in XML format."); hints.add("Remember that the data is stored in XML format.");
hints.add("The system is using XPath to query."); hints.add("The system is using XPath to query.");
hints.add( "XPath is almost the same thing as SQL, the same hacking techniques apply too." ); hints
hints.add( "Try username: Smith' or 1=1 or 'a'='a and a password: anything " ); .add("XPath is almost the same thing as SQL, the same hacking techniques apply too.");
hints
.add("Try username: Smith' or 1=1 or 'a'='a and a password: anything ");
return hints; return hints;
} }
public String getTitle() {
public String getTitle()
{
return "How to Perform XPATH Injection"; return "How to Perform XPATH Injection";
} }

View File

@ -1,19 +1,44 @@
package org.owasp.webgoat.lessons.admin; package org.owasp.webgoat.lessons.admin;
import org.owasp.webgoat.lessons.AbstractLesson; import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Screen; import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public abstract class AdminScreen extends Screen public abstract class AdminScreen extends Screen
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
@ -39,13 +64,15 @@ public abstract class AdminScreen extends Screen
* *
* @param s Description of the Parameter * @param s Description of the Parameter
*/ */
public AdminScreen( WebSession s ) { } public AdminScreen(WebSession s)
{}
/** /**
* Constructor for the AdminScreen object * Constructor for the AdminScreen object
*/ */
public AdminScreen() { } public AdminScreen()
{}
/** /**
@ -59,10 +86,12 @@ public abstract class AdminScreen extends Screen
} }
public String getRole() { public String getRole()
{
return AbstractLesson.ADMIN_ROLE; return AbstractLesson.ADMIN_ROLE;
} }
/** /**
* Sets the query attribute of the AdminScreen object * Sets the query attribute of the AdminScreen object
* *
@ -73,4 +102,3 @@ public abstract class AdminScreen extends Screen
query = q; query = q;
} }
} }

View File

@ -12,18 +12,43 @@ import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class ProductsAdminScreen extends LessonAdapter public class ProductsAdminScreen extends LessonAdapter
{ {
private final static String QUERY = "SELECT * FROM product_system_data"; private final static String QUERY = "SELECT * FROM product_system_data";
private static Connection connection = null; private static Connection connection = null;
@ -44,14 +69,17 @@ public class ProductsAdminScreen extends LessonAdapter
connection = DatabaseUtilities.makeConnection(s); connection = DatabaseUtilities.makeConnection(s);
} }
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(QUERY); ResultSet results = statement.executeQuery(QUERY);
if (results != null) if (results != null)
{ {
makeSuccess(s); makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
} }
} }
catch (Exception e) catch (Exception e)
@ -74,6 +102,7 @@ public class ProductsAdminScreen extends LessonAdapter
return ADMIN_FUNCTIONS; return ADMIN_FUNCTIONS;
} }
/** /**
* Gets the role attribute of the ProductsAdminScreen object * Gets the role attribute of the ProductsAdminScreen object
* *
@ -97,9 +126,9 @@ public class ProductsAdminScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
} }

View File

@ -12,18 +12,43 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.*; import org.owasp.webgoat.session.*;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class RefreshDBScreen extends LessonAdapter public class RefreshDBScreen extends LessonAdapter
{ {
private final static String REFRESH = "Refresh"; private final static String REFRESH = "Refresh";
private static Connection connection = null; private static Connection connection = null;
@ -44,7 +69,8 @@ public class RefreshDBScreen extends LessonAdapter
if (refresh) if (refresh)
{ {
refreshDB(s); refreshDB(s);
ec.addElement( new StringElement( "Successfully refreshed the database." ) ); ec.addElement(new StringElement(
"Successfully refreshed the database."));
} }
else else
{ {
@ -54,7 +80,8 @@ public class RefreshDBScreen extends LessonAdapter
TD td1 = new TD().addElement(label); TD td1 = new TD().addElement(label);
TD td2 = new TD().addElement(link1); TD td2 = new TD().addElement(link1);
TD td3 = new TD().addElement(link2); TD td3 = new TD().addElement(link2);
TR row = new TR().addElement( td1 ).addElement( td2 ).addElement( td3 ); TR row = new TR().addElement(td1).addElement(td2).addElement(
td3);
Table t = new Table().setCellSpacing(40).setWidth("50%"); Table t = new Table().setCellSpacing(40).setWidth("50%");
if (s.isColor()) if (s.isColor())
@ -88,11 +115,13 @@ public class RefreshDBScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the role attribute of the RefreshDBScreen object * Gets the role attribute of the RefreshDBScreen object
* *
@ -135,9 +164,9 @@ public class RefreshDBScreen extends LessonAdapter
} }
catch (Exception e) catch (Exception e)
{ {
s.setMessage( "Error refreshing database " + this.getClass().getName() ); s.setMessage("Error refreshing database "
+ this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -20,14 +20,36 @@ import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker; import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/**
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute
* this software.
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class ReportCardScreen extends LessonAdapter public class ReportCardScreen extends LessonAdapter
@ -63,8 +85,7 @@ public class ReportCardScreen extends LessonAdapter
} }
} }
catch (Exception e) catch (Exception e)
{ {}
}
if (user == null) if (user == null)
{ {
@ -81,10 +102,14 @@ public class ReportCardScreen extends LessonAdapter
private Element makeFeedback(WebSession s) private Element makeFeedback(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement( new Center( new StringElement( "Comments and suggestions are welcome. " + s.getFeedbackAddress() )) ); ec.addElement(new Center(new StringElement(
"Comments and suggestions are welcome. "
+ s.getFeedbackAddress())));
return ec; return ec;
} }
/** /**
* Gets the category attribute of the UserAdminScreen object * Gets the category attribute of the UserAdminScreen object
* *
@ -97,11 +122,13 @@ public class ReportCardScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the role attribute of the UserAdminScreen object * Gets the role attribute of the UserAdminScreen object
* *
@ -134,7 +161,8 @@ public class ReportCardScreen extends LessonAdapter
*/ */
private TR makeLessonRow(WebSession s, String user, Screen screen) private TR makeLessonRow(WebSession s, String user, Screen screen)
{ {
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker( s, user, screen ); LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(
s, user, screen);
TR tr = new TR(); TR tr = new TR();
if (lessonTracker.getCompleted()) if (lessonTracker.getCompleted())
{ {
@ -144,7 +172,8 @@ public class ReportCardScreen extends LessonAdapter
{ {
tr.setBgColor(HtmlColor.LIGHTBLUE); tr.setBgColor(HtmlColor.LIGHTBLUE);
} }
else if ( !lessonTracker.getCompleted() && lessonTracker.getNumVisits() > 10 ) else if (!lessonTracker.getCompleted()
&& lessonTracker.getNumVisits() > 10)
{ {
tr.setBgColor(HtmlColor.RED); tr.setBgColor(HtmlColor.RED);
} }
@ -153,14 +182,22 @@ public class ReportCardScreen extends LessonAdapter
tr.setBgColor(HtmlColor.YELLOW); tr.setBgColor(HtmlColor.YELLOW);
} }
tr.addElement(new TD().addElement(screen.getTitle())); tr.addElement(new TD().addElement(screen.getTitle()));
tr.addElement( new TD().setAlign( "CENTER" ).addElement( lessonTracker.getCompleted() ? "Y" : "N" ) ); tr.addElement(new TD().setAlign("CENTER").addElement(
tr.addElement( new TD().setAlign( "CENTER" ).addElement( Integer.toString( lessonTracker.getNumVisits() ) ) ); lessonTracker.getCompleted() ? "Y" : "N"));
tr.addElement( new TD().setAlign( "CENTER" ).addElement( Integer.toString( lessonTracker.getMaxHintLevel() ) ) ); tr.addElement(new TD().setAlign("CENTER").addElement(
tr.addElement( new TD().setAlign( "CENTER" ).addElement( lessonTracker.getViewedCookies() ? "Y" : "N" ) ); Integer.toString(lessonTracker.getNumVisits())));
tr.addElement( new TD().setAlign( "CENTER" ).addElement( lessonTracker.getViewedHtml() ? "Y" : "N" ) ); tr.addElement(new TD().setAlign("CENTER").addElement(
tr.addElement( new TD().setAlign( "CENTER" ).addElement( lessonTracker.getViewedLessonPlan() ? "Y" : "N" ) ); Integer.toString(lessonTracker.getMaxHintLevel())));
tr.addElement( new TD().setAlign( "CENTER" ).addElement( lessonTracker.getViewedParameters() ? "Y" : "N" ) ); tr.addElement(new TD().setAlign("CENTER").addElement(
tr.addElement( new TD().setAlign( "CENTER" ).addElement( lessonTracker.getViewedSource() ? "Y" : "N" ) ); lessonTracker.getViewedCookies() ? "Y" : "N"));
tr.addElement(new TD().setAlign("CENTER").addElement(
lessonTracker.getViewedHtml() ? "Y" : "N"));
tr.addElement(new TD().setAlign("CENTER").addElement(
lessonTracker.getViewedLessonPlan() ? "Y" : "N"));
tr.addElement(new TD().setAlign("CENTER").addElement(
lessonTracker.getViewedParameters() ? "Y" : "N"));
tr.addElement(new TD().setAlign("CENTER").addElement(
lessonTracker.getViewedSource() ? "Y" : "N"));
return tr; return tr;
} }
@ -202,9 +239,11 @@ public class ReportCardScreen extends LessonAdapter
// These are all the user lesson // These are all the user lesson
tr = new TR(); tr = new TR();
tr.addElement( new TD().setAlign( "CENTER" ).setColSpan( 9 ).addElement( "Normal user lessons" ) ); tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement(
"Normal user lessons"));
t.addElement(tr); t.addElement(tr);
for ( Iterator lessonIter = s.getCourse().getLessons( s, AbstractLesson.USER_ROLE ).iterator(); lessonIter.hasNext(); ) for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.USER_ROLE).iterator(); lessonIter.hasNext();)
{ {
Screen screen = (Screen) lessonIter.next(); Screen screen = (Screen) lessonIter.next();
t.addElement(makeLessonRow(s, user, screen)); t.addElement(makeLessonRow(s, user, screen));
@ -212,9 +251,12 @@ public class ReportCardScreen extends LessonAdapter
// The user figured out there was a hackable admin acocunt // The user figured out there was a hackable admin acocunt
tr = new TR(); tr = new TR();
tr.addElement( new TD().setAlign( "CENTER" ).setColSpan( 9 ).addElement( "Hackable Admin Screens" ) ); tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement(
"Hackable Admin Screens"));
t.addElement(tr); t.addElement(tr);
for ( Iterator lessonIter = s.getCourse().getLessons( s, AbstractLesson.HACKED_ADMIN_ROLE ).iterator(); lessonIter.hasNext(); ) for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{ {
Screen screen = (Screen) lessonIter.next(); Screen screen = (Screen) lessonIter.next();
t.addElement(makeLessonRow(s, user, screen)); t.addElement(makeLessonRow(s, user, screen));
@ -222,9 +264,11 @@ public class ReportCardScreen extends LessonAdapter
// The user figured out how to actually hack the admin acocunt // The user figured out how to actually hack the admin acocunt
tr = new TR(); tr = new TR();
tr.addElement( new TD().setAlign( "CENTER" ).setColSpan( 9 ).addElement( "Actual Admin Screens" ) ); tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement(
"Actual Admin Screens"));
t.addElement(tr); t.addElement(tr);
for ( Iterator lessonIter = s.getCourse().getLessons( s, AbstractLesson.ADMIN_ROLE ).iterator(); lessonIter.hasNext(); ) for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.ADMIN_ROLE).iterator(); lessonIter.hasNext();)
{ {
Screen screen = (Screen) lessonIter.next(); Screen screen = (Screen) lessonIter.next();
t.addElement(makeLessonRow(s, user, screen)); t.addElement(makeLessonRow(s, user, screen));
@ -275,4 +319,3 @@ public class ReportCardScreen extends LessonAdapter
return tr; return tr;
} }
} }

View File

@ -21,22 +21,46 @@ import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker; import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/**
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute
* this software.
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Bruce mayhew <a href="http://code.google.com">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class SummaryReportCardScreen extends LessonAdapter public class SummaryReportCardScreen extends LessonAdapter
{ {
private int totalUsersNormalComplete = 0; private int totalUsersNormalComplete = 0;
private int totalUsersAdminComplete = 0; private int totalUsersAdminComplete = 0;
/** /**
* Description of the Method * Description of the Method
* *
@ -81,14 +105,16 @@ public class SummaryReportCardScreen extends LessonAdapter
ec.addElement(new P()); ec.addElement(new P());
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 4 ).setBorder( 1 ).setWidth("100%"); Table t = new Table().setCellSpacing(0).setCellPadding(4).setBorder(1)
.setWidth("100%");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
t.addElement(makeUserSummaryHeader()); t.addElement(makeUserSummaryHeader());
for ( Iterator userIter = UserTracker.instance().getAllUsers(WebSession.WEBGOAT_USER).iterator(); userIter.hasNext(); ) for (Iterator userIter = UserTracker.instance().getAllUsers(
WebSession.WEBGOAT_USER).iterator(); userIter.hasNext();)
{ {
String user = (String) userIter.next(); String user = (String) userIter.next();
@ -103,7 +129,8 @@ public class SummaryReportCardScreen extends LessonAdapter
protected Element makeSummary(WebSession s) protected Element makeSummary(WebSession s)
{ {
Table t = new Table().setCellSpacing( 0 ).setCellPadding( 2 ).setBorder( 0 ).setWidth("100%"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
.setWidth("100%");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
@ -113,27 +140,36 @@ public class SummaryReportCardScreen extends LessonAdapter
//t.addElement( tr ); //t.addElement( tr );
tr = new TR(); tr = new TR();
tr.addElement( new TD().setWidth("60%").addElement( "Total number of users")); tr.addElement(new TD().setWidth("60%").addElement(
tr.addElement( new TD().setAlign("LEFT").addElement(Integer.toString( UserTracker.instance().getAllUsers(WebSession.WEBGOAT_USER).size() ))); "Total number of users"));
tr.addElement(new TD().setAlign("LEFT").addElement(
Integer.toString(UserTracker.instance().getAllUsers(
WebSession.WEBGOAT_USER).size())));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().setWidth("60%").addElement( "Total number of users that completed all normal lessons")); tr.addElement(new TD().setWidth("60%").addElement(
tr.addElement( new TD().setAlign("LEFT").addElement(Integer.toString( totalUsersNormalComplete ))); "Total number of users that completed all normal lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(
Integer.toString(totalUsersNormalComplete)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement( new TD().setWidth("60%").addElement( "Total number of users that completed all admin lessons")); tr.addElement(new TD().setWidth("60%").addElement(
tr.addElement( new TD().setAlign("LEFT").addElement(Integer.toString( totalUsersAdminComplete ))); "Total number of users that completed all admin lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(
Integer.toString(totalUsersAdminComplete)));
t.addElement(tr); t.addElement(tr);
return t; return t;
} }
private void deleteUser(String user) private void deleteUser(String user)
{ {
UserTracker.instance().deleteUser(user); UserTracker.instance().deleteUser(user);
} }
/** /**
* Gets the category attribute of the UserAdminScreen object * Gets the category attribute of the UserAdminScreen object
* *
@ -146,11 +182,13 @@ public class SummaryReportCardScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the role attribute of the UserAdminScreen object * Gets the role attribute of the UserAdminScreen object
* *
@ -187,8 +225,6 @@ public class SummaryReportCardScreen extends LessonAdapter
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -225,12 +261,14 @@ public class SummaryReportCardScreen extends LessonAdapter
boolean normalComplete = false; boolean normalComplete = false;
boolean adminComplete = false; boolean adminComplete = false;
for ( Iterator lessonIter = s.getCourse().getLessons( s, AbstractLesson.USER_ROLE ).iterator(); lessonIter.hasNext(); ) for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.USER_ROLE).iterator(); lessonIter.hasNext();)
{ {
lessonCount++; lessonCount++;
Screen screen = (Screen) lessonIter.next(); Screen screen = (Screen) lessonIter.next();
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker( s, user, screen ); LessonTracker lessonTracker = UserTracker.instance()
.getLessonTracker(s, user, screen);
if (lessonTracker.getCompleted()) if (lessonTracker.getCompleted())
{ {
passedCount++; passedCount++;
@ -241,17 +279,21 @@ public class SummaryReportCardScreen extends LessonAdapter
normalComplete = true; normalComplete = true;
totalUsersNormalComplete++; totalUsersNormalComplete++;
} }
String text = Integer.toString( passedCount ) + " of " + Integer.toString( lessonCount ); String text = Integer.toString(passedCount) + " of "
+ Integer.toString(lessonCount);
tr.addElement(new TD().setAlign("CENTER").addElement(text)); tr.addElement(new TD().setAlign("CENTER").addElement(text));
lessonCount = 0; lessonCount = 0;
passedCount = 0; passedCount = 0;
for ( Iterator lessonIter = s.getCourse().getLessons( s, AbstractLesson.HACKED_ADMIN_ROLE ).iterator(); lessonIter.hasNext(); ) for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{ {
lessonCount++; lessonCount++;
Screen screen = (Screen) lessonIter.next(); Screen screen = (Screen) lessonIter.next();
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker( s, user, screen ); LessonTracker lessonTracker = UserTracker.instance()
.getLessonTracker(s, user, screen);
if (lessonTracker.getCompleted()) if (lessonTracker.getCompleted())
{ {
passedCount++; passedCount++;
@ -262,11 +304,14 @@ public class SummaryReportCardScreen extends LessonAdapter
adminComplete = true; adminComplete = true;
totalUsersAdminComplete++; totalUsersAdminComplete++;
} }
text = Integer.toString( passedCount ) + " of " + Integer.toString( lessonCount ); text = Integer.toString(passedCount) + " of "
+ Integer.toString(lessonCount);
tr.addElement(new TD().setAlign("CENTER").addElement(text)); tr.addElement(new TD().setAlign("CENTER").addElement(text));
tr.addElement( new TD().setAlign( "CENTER" ).addElement( new Input( Input.SUBMIT, "View_" + user, "View" ) ) ); tr.addElement(new TD().setAlign("CENTER").addElement(
tr.addElement( new TD().setAlign( "CENTER" ).addElement( new Input( Input.SUBMIT, "Delete_" + user, "Delete" ) ) ); new Input(Input.SUBMIT, "View_" + user, "View")));
tr.addElement(new TD().setAlign("CENTER").addElement(
new Input(Input.SUBMIT, "Delete_" + user, "Delete")));
if (normalComplete && adminComplete) if (normalComplete && adminComplete)
{ {
@ -284,9 +329,9 @@ public class SummaryReportCardScreen extends LessonAdapter
return (tr); return (tr);
} }
public boolean isEnterprise() public boolean isEnterprise()
{ {
return true; return true;
} }
} }

View File

@ -12,19 +12,43 @@ import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class UserAdminScreen extends LessonAdapter public class UserAdminScreen extends LessonAdapter
{ {
private final static String QUERY = "SELECT * FROM user_system_data"; private final static String QUERY = "SELECT * FROM user_system_data";
private static Connection connection = null; private static Connection connection = null;
@ -45,14 +69,17 @@ public class UserAdminScreen extends LessonAdapter
connection = DatabaseUtilities.makeConnection(s); connection = DatabaseUtilities.makeConnection(s);
} }
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(QUERY); ResultSet results = statement.executeQuery(QUERY);
if (results != null) if (results != null)
{ {
makeSuccess(s); makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
} }
} }
catch (Exception e) catch (Exception e)
@ -77,11 +104,13 @@ public class UserAdminScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the role attribute of the UserAdminScreen object * Gets the role attribute of the UserAdminScreen object
* *
@ -103,4 +132,3 @@ public class UserAdminScreen extends LessonAdapter
return ("User Information"); return ("User Information");
} }
} }

View File

@ -13,19 +13,43 @@ import org.apache.ecs.StringElement;
import org.apache.ecs.html.Input; import org.apache.ecs.html.Input;
import org.owasp.webgoat.session.*; import org.owasp.webgoat.session.*;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class ViewDatabase extends LessonAdapter public class ViewDatabase extends LessonAdapter
{ {
private final static String SQL = "sql"; private final static String SQL = "sql";
private static Connection connection = null; private static Connection connection = null;
@ -43,7 +67,8 @@ public class ViewDatabase extends LessonAdapter
{ {
ec.addElement(new StringElement("Enter a SQL statement: ")); ec.addElement(new StringElement("Enter a SQL statement: "));
StringBuffer sqlStatement = new StringBuffer( s.getParser().getRawParameter( SQL, "" ) ); StringBuffer sqlStatement = new StringBuffer(s.getParser()
.getRawParameter(SQL, ""));
Input input = new Input(Input.TEXT, SQL, sqlStatement.toString()); Input input = new Input(Input.TEXT, SQL, sqlStatement.toString());
ec.addElement(input); ec.addElement(input);
@ -58,14 +83,18 @@ public class ViewDatabase extends LessonAdapter
if (sqlStatement.length() > 0) if (sqlStatement.length() > 0)
{ {
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement statement = connection.createStatement(
ResultSet results = statement.executeQuery( sqlStatement.toString() ); ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(sqlStatement
.toString());
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
makeSuccess(s); makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement( DatabaseUtilities.writeTable( results, resultsMetaData ) ); ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
} }
} }
@ -79,6 +108,7 @@ public class ViewDatabase extends LessonAdapter
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the DatabaseScreen object * Gets the category attribute of the DatabaseScreen object
* *
@ -91,11 +121,13 @@ public class ViewDatabase extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the hints attribute of the DatabaseScreen object * Gets the hints attribute of the DatabaseScreen object
* *
@ -144,4 +176,3 @@ public class ViewDatabase extends LessonAdapter
return ("Database Dump"); return ("Database Dump");
} }
} }

View File

@ -8,17 +8,41 @@ import org.apache.ecs.html.Center;
import org.apache.ecs.html.H1; import org.apache.ecs.html.H1;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class WelcomeAdminScreen extends WelcomeScreen public class WelcomeAdminScreen extends WelcomeScreen
{ {
/** /**
* Constructor for the WelcomeAdminScreen object * Constructor for the WelcomeAdminScreen object
* *
@ -33,8 +57,8 @@ public class WelcomeAdminScreen extends WelcomeScreen
/** /**
* Constructor for the WelcomeAdminScreen object * Constructor for the WelcomeAdminScreen object
*/ */
public WelcomeAdminScreen() { } public WelcomeAdminScreen()
{}
/** /**
@ -47,7 +71,8 @@ public class WelcomeAdminScreen extends WelcomeScreen
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement( new Center( new H1( "You are logged on as an administrator" ) ) ); ec.addElement(new Center(
new H1("You are logged on as an administrator")));
ec.addElement(super.createContent(s)); ec.addElement(super.createContent(s));
return (ec); return (ec);
@ -64,4 +89,3 @@ public class WelcomeAdminScreen extends WelcomeScreen
return ("Admin Welcome"); return ("Admin Welcome");
} }
} }

View File

@ -1,32 +1 @@
package org.owasp.webgoat.servlets; package org.owasp.webgoat.servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /******************************************************************************* * * * This file is part of WebGoat, an Open Web Application Security Project * utility. For details, please see http://www.owasp.org/ * * Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307, USA. * * Getting Source ============== * * Source for this application is maintained at code.google.com, a repository * for free software projects. * * For details, please see http://code.google.com/p/webgoat/ */ public class Controller extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userAgent = request.getHeader("user-agent"); String clientBrowser = "Not known!"; if (userAgent != null) { clientBrowser = userAgent; } request.setAttribute("client.browser", clientBrowser); request.getRequestDispatcher("/view.jsp").forward(request, response); } }
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Controller extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String userAgent = request.getHeader("user-agent");
String clientBrowser = "Not known!";
if (userAgent != null)
{
clientBrowser = userAgent;
}
request.setAttribute("client.browser", clientBrowser);
request.getRequestDispatcher("/view.jsp").forward(request, response);
}
}

View File

@ -3,22 +3,53 @@ package org.owasp.webgoat.session;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Map; import java.util.Map;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Authorization public class Authorization
{ {
Map permissions = new Hashtable(); Map permissions = new Hashtable();
public Authorization() public Authorization()
{ {}
}
public void setPermission(int userId, int functionId) public void setPermission(int userId, int functionId)
{ {
permissions.put(new Integer(userId), new Integer(functionId)); permissions.put(new Integer(userId), new Integer(functionId));
} }
public boolean isAllowed(int userId, int functionId) public boolean isAllowed(int userId, int functionId)
{ {
return (permissions.get(new Integer(userId)) != null); return (permissions.get(new Integer(userId)) != null);
} }
} }

View File

@ -14,21 +14,48 @@ import org.owasp.webgoat.HammerHead;
import org.owasp.webgoat.lessons.AbstractLesson; import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category; import org.owasp.webgoat.lessons.Category;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class Course public class Course
{ {
private List lessons = new ArrayList(); private List lessons = new ArrayList();
private final static String PROPERTIES_FILENAME = HammerHead.propertiesPath; private final static String PROPERTIES_FILENAME = HammerHead.propertiesPath;
private WebgoatProperties properties = null; private WebgoatProperties properties = null;
public Course() public Course()
{ {
try try
@ -71,14 +98,16 @@ public class Course
int index = fileName.indexOf("/WEB-INF/classes/"); int index = fileName.indexOf("/WEB-INF/classes/");
if (index != -1) if (index != -1)
{ {
fileName = fileName.substring( index + "/WEB-INF/classes/".length(), fileName.length() - ext.length() ); fileName = fileName.substring(index + "/WEB-INF/classes/".length(),
fileName.length() - ext.length());
fileName = fileName.replace('/', '.'); fileName = fileName.replace('/', '.');
fileName = fileName.replace('\\', '.'); fileName = fileName.replace('\\', '.');
} }
else else
{ {
// Strip off the leading path info // Strip off the leading path info
fileName = fileName.substring( path.length(), fileName.length() - ext.length() ); fileName = fileName.substring(path.length(), fileName.length()
- ext.length());
} }
return fileName; return fileName;
@ -93,7 +122,9 @@ public class Course
* @param courseName Description of the Parameter * @param courseName Description of the Parameter
* @param extension TODO * @param extension TODO
*/ */
private void findSourceResource( AbstractLesson lesson, ServletContext context, String path, String className, String extension ) private void findSourceResource(AbstractLesson lesson,
ServletContext context, String path, String className,
String extension)
{ {
//System.out.println("findSourceResource() looking for source files in: " + path); //System.out.println("findSourceResource() looking for source files in: " + path);
//System.out.println("findSourceResource() looking for source files for class: " + className); //System.out.println("findSourceResource() looking for source files for class: " + className);
@ -121,7 +152,8 @@ public class Course
// A subdirectory // A subdirectory
else if ((lessonName.length() != 1) && lessonName.endsWith("/")) else if ((lessonName.length() != 1) && lessonName.endsWith("/"))
{ {
findSourceResource( lesson, context, lessonName, className, extension ); findSourceResource(lesson, context, lessonName, className,
extension);
} }
// A source file // A source file
else else
@ -162,7 +194,9 @@ public class Course
* @param courseName Description of the Parameter * @param courseName Description of the Parameter
* @param extension TODO * @param extension TODO
*/ */
private void findLessonPlanResource( AbstractLesson lesson, ServletContext context, String path, String courseName, String extension ) private void findLessonPlanResource(AbstractLesson lesson,
ServletContext context, String path, String courseName,
String extension)
{ {
Set files = context.getResourcePaths(path); Set files = context.getResourcePaths(path);
Iterator fileIter = files.iterator(); Iterator fileIter = files.iterator();
@ -184,7 +218,8 @@ public class Course
} }
else if ((className.length() != 1) && className.endsWith("/")) else if ((className.length() != 1) && className.endsWith("/"))
{ {
findLessonPlanResource( lesson, context, className, courseName, extension ); findLessonPlanResource(lesson, context, className, courseName,
extension);
} }
else else
{ {
@ -253,7 +288,8 @@ public class Course
roles.add(AbstractLesson.USER_ROLE); roles.add(AbstractLesson.USER_ROLE);
// Category 0 is the admin function. We want the first real category // Category 0 is the admin function. We want the first real category
// to be returned. This is noramally the General category and the Http Basics lesson // to be returned. This is noramally the General category and the Http Basics lesson
return ((AbstractLesson)getLessons( (Category)getCategories().get(1), roles).get(0)); return ((AbstractLesson) getLessons((Category) getCategories().get(1),
roles).get(0));
} }
@ -278,7 +314,8 @@ public class Course
AbstractLesson lesson = (AbstractLesson) iter.next(); AbstractLesson lesson = (AbstractLesson) iter.next();
//System.out.println("getLesson() at role: " + lesson.getRole()); //System.out.println("getLesson() at role: " + lesson.getRole());
if ( lesson.getScreenId() == lessonId && roles.contains(lesson.getRole()) ) if (lesson.getScreenId() == lessonId
&& roles.contains(lesson.getRole()))
{ {
return lesson; return lesson;
} }
@ -287,6 +324,7 @@ public class Course
return null; return null;
} }
public AbstractLesson getLesson(WebSession s, int lessonId, String role) public AbstractLesson getLesson(WebSession s, int lessonId, String role)
{ {
List roles = new Vector(); List roles = new Vector();
@ -294,6 +332,7 @@ public class Course
return getLesson(s, lessonId, roles); return getLesson(s, lessonId, roles);
} }
public List getLessons(WebSession s, String role) public List getLessons(WebSession s, String role)
{ {
List roles = new Vector(); List roles = new Vector();
@ -301,6 +340,7 @@ public class Course
return getLessons(s, roles); return getLessons(s, roles);
} }
/** /**
* Gets the lessons attribute of the Course object * Gets the lessons attribute of the Course object
* *
@ -318,7 +358,8 @@ public class Course
while (categoryIter.hasNext()) while (categoryIter.hasNext())
{ {
lessonList.addAll( getLessons( s, (Category) categoryIter.next(), roles ) ); lessonList.addAll(getLessons(s, (Category) categoryIter.next(),
roles));
} }
return lessonList; return lessonList;
} }
@ -340,7 +381,8 @@ public class Course
{ {
AbstractLesson lesson = (AbstractLesson) iter.next(); AbstractLesson lesson = (AbstractLesson) iter.next();
if ( lesson.getCategory().equals( category ) && roles.contains(lesson.getRole()) ) if (lesson.getCategory().equals(category)
&& roles.contains(lesson.getRole()))
{ {
lessonList.add(lesson); lessonList.add(lesson);
} }
@ -351,6 +393,7 @@ public class Course
return lessonList; return lessonList;
} }
public List getLessons(WebSession s, Category category, String role) public List getLessons(WebSession s, Category category, String role)
{ {
List roles = new Vector(); List roles = new Vector();
@ -358,6 +401,7 @@ public class Course
return getLessons(s, category, roles); return getLessons(s, category, roles);
} }
public List getLessons(WebSession s, Category category, List roles) public List getLessons(WebSession s, Category category, List roles)
{ {
if (s.isHackedAdmin()) if (s.isHackedAdmin())
@ -367,13 +411,15 @@ public class Course
return getLessons(category, roles); return getLessons(category, roles);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param path Description of the Parameter * @param path Description of the Parameter
* @param context Description of the Parameter * @param context Description of the Parameter
*/ */
public void loadCourses( boolean enterprise, ServletContext context, String path ) public void loadCourses(boolean enterprise, ServletContext context,
String path)
{ {
Set files = context.getResourcePaths(path); Set files = context.getResourcePaths(path);
Iterator fileIter = files.iterator(); Iterator fileIter = files.iterator();
@ -425,8 +471,10 @@ public class Course
// There are two methods instead of one because the developer was not // There are two methods instead of one because the developer was not
// smart enough to figure out the recursive return value // smart enough to figure out the recursive return value
findSourceResource( lesson, context, "/", className, ".java" ); findSourceResource(lesson, context, "/", className,
findLessonPlanResource( lesson, context, "/", className, ".html" ); ".java");
findLessonPlanResource(lesson, context, "/", className,
".html");
// Override lesson attributes based on properties. // Override lesson attributes based on properties.
lesson.update(properties); lesson.update(properties);
@ -445,4 +493,3 @@ public class Course
} }
} }
} }

View File

@ -8,18 +8,40 @@ import java.sql.Statement;
import org.owasp.webgoat.lessons.AbstractLesson; import org.owasp.webgoat.lessons.AbstractLesson;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of *
* the Open Web Application Security Project (http://www.owasp.org) This * This file is part of WebGoat, an Open Web Application Security Project
* software package org.owasp.webgoat.is published by OWASP under the GPL. You should read and * utility. For details, please see http://www.owasp.org/
* accept the LICENSE before you use, modify and/or redistribute this *
* software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/ */
public class CreateDB public class CreateDB
{ {
/** /**
* The main program for the AccessSqlInjection class * The main program for the AccessSqlInjection class
* *
@ -44,7 +66,10 @@ public class CreateDB
try try
{ {
connection = DriverManager.getConnection("jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=c:/webgoat.mdb;PWD=webgoat", "webgoat", "webgoat"); connection = DriverManager
.getConnection(
"jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=c:/webgoat.mdb;PWD=webgoat",
"webgoat", "webgoat");
db.makeDB(connection); db.makeDB(connection);
} }
catch (Exception e) catch (Exception e)
@ -60,13 +85,16 @@ public class CreateDB
try try
{ {
Statement answer_statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.first(); answer_results.first();
int employeeId = answer_results.getInt("userid"); int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
System.out.println("Query 1 Results: " + firstName + " " + lastName + " " + employeeId); System.out.println("Query 1 Results: " + firstName + " " + lastName
+ " " + employeeId);
} }
catch (SQLException sqle) catch (SQLException sqle)
{ {
@ -81,7 +109,9 @@ public class CreateDB
try try
{ {
Statement answer_statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query); ResultSet answer_results = answer_statement.executeQuery(query);
boolean allowed = answer_results.first(); boolean allowed = answer_results.first();
//boolean allowed = answer_results.next(); //boolean allowed = answer_results.next();
@ -124,11 +154,9 @@ public class CreateDB
try try
{ {
String createTableStatement = "CREATE TABLE messages (" String createTableStatement = "CREATE TABLE messages ("
+ "num int not null," + "num int not null," + "title varchar(50),"
+ "title varchar(50),"
+ "message varchar(200)," + "message varchar(200),"
+ "user_name varchar(50) not null " + "user_name varchar(50) not null " + ")";
+ ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} }
catch (SQLException e) catch (SQLException e)
@ -166,8 +194,7 @@ public class CreateDB
{ {
String createTableStatement = "CREATE TABLE product_system_data (" String createTableStatement = "CREATE TABLE product_system_data ("
+ "productid varchar(6) not null primary key," + "productid varchar(6) not null primary key,"
+ "product_name varchar(20)," + "product_name varchar(20)," + "price varchar(10)" + ")";
+ "price varchar(10)" + ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} }
catch (SQLException e) catch (SQLException e)
@ -197,7 +224,8 @@ public class CreateDB
* *
* @exception SQLException Description of the Exception * @exception SQLException Description of the Exception
*/ */
private void createUserAdminTable(Connection connection) throws SQLException private void createUserAdminTable(Connection connection)
throws SQLException
{ {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@ -217,10 +245,8 @@ public class CreateDB
{ {
String createTableStatement = "CREATE TABLE user_system_data (" String createTableStatement = "CREATE TABLE user_system_data ("
+ "userid varchar(5) not null primary key," + "userid varchar(5) not null primary key,"
+ "user_name varchar(12)," + "user_name varchar(12)," + "password varchar(10),"
+ "password varchar(10)," + "cookie varchar(30)" + ")";
+ "cookie varchar(30)"
+ ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} }
catch (SQLException e) catch (SQLException e)
@ -269,14 +295,10 @@ public class CreateDB
try try
{ {
String createTableStatement = "CREATE TABLE user_data (" String createTableStatement = "CREATE TABLE user_data ("
+ "userid int not null," + "userid int not null," + "first_name varchar(20),"
+ "first_name varchar(20)," + "last_name varchar(20)," + "cc_number varchar(30),"
+ "last_name varchar(20)," + "cc_type varchar(10)," + "cookie varchar(20),"
+ "cc_number varchar(30)," + "login_count int" + ")";
+ "cc_type varchar(10),"
+ "cookie varchar(20),"
+ "login_count int"
+ ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} }
catch (SQLException e) catch (SQLException e)
@ -314,6 +336,7 @@ public class CreateDB
statement.executeUpdate(insertData13); statement.executeUpdate(insertData13);
} }
private void createLoginTable(Connection connection) throws SQLException private void createLoginTable(Connection connection) throws SQLException
{ {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@ -333,9 +356,7 @@ public class CreateDB
try try
{ {
String createTableStatement = "CREATE TABLE user_login (" String createTableStatement = "CREATE TABLE user_login ("
+ "userid varchar(5)," + "userid varchar(5)," + "webgoat_user varchar(20)" + ")";
+ "webgoat_user varchar(20)"
+ ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} }
catch (SQLException e) catch (SQLException e)
@ -346,6 +367,7 @@ public class CreateDB
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -353,7 +375,8 @@ public class CreateDB
* *
* @exception SQLException Description of the Exception * @exception SQLException Description of the Exception
*/ */
private void createWeatherDataTable(Connection connection) throws SQLException private void createWeatherDataTable(Connection connection)
throws SQLException
{ {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@ -372,12 +395,9 @@ public class CreateDB
try try
{ {
String createTableStatement = "CREATE TABLE weather_data (" String createTableStatement = "CREATE TABLE weather_data ("
+ "station int not null," + "station int not null," + "name varchar(20) not null,"
+ "name varchar(20) not null," + "state char(2) not null," + "min_temp int not null,"
+ "state char(2) not null," + "max_temp int not null" + ")";
+ "min_temp int not null,"
+ "max_temp int not null"
+ ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} }
catch (SQLException e) catch (SQLException e)
@ -401,6 +421,7 @@ public class CreateDB
statement.executeUpdate(insertData6); statement.executeUpdate(insertData6);
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// //
@ -412,7 +433,6 @@ public class CreateDB
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
private void createEmployeeTable(Connection connection) throws SQLException private void createEmployeeTable(Connection connection) throws SQLException
{ {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@ -433,19 +453,12 @@ public class CreateDB
String createTable = "CREATE TABLE employee (" String createTable = "CREATE TABLE employee ("
//+ "userid INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY," //+ "userid INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,"
+ "userid INT NOT NULL PRIMARY KEY," + "userid INT NOT NULL PRIMARY KEY,"
+ "first_name VARCHAR(20)," + "first_name VARCHAR(20)," + "last_name VARCHAR(20),"
+ "last_name VARCHAR(20)," + "ssn VARCHAR(12)," + "password VARCHAR(10),"
+ "ssn VARCHAR(12)," + "title VARCHAR(20)," + "phone VARCHAR(13),"
+ "password VARCHAR(10)," + "address1 VARCHAR(80)," + "address2 VARCHAR(80),"
+ "title VARCHAR(20)," + "manager INT," + "start_date CHAR(8)," + "salary INT,"
+ "phone VARCHAR(13)," + "ccn VARCHAR(30)," + "ccn_limit INT,"
+ "address1 VARCHAR(80),"
+ "address2 VARCHAR(80),"
+ "manager INT,"
+ "start_date CHAR(8),"
+ "salary INT,"
+ "ccn VARCHAR(30),"
+ "ccn_limit INT,"
+ "disciplined_date CHAR(8)," // date of write up, NA otherwise + "disciplined_date CHAR(8)," // date of write up, NA otherwise
+ "disciplined_notes VARCHAR(60)," // reason for the recent write-up + "disciplined_notes VARCHAR(60)," // reason for the recent write-up
+ "personal_description VARCHAR(60)" // We can be rude here + "personal_description VARCHAR(60)" // We can be rude here
@ -459,52 +472,52 @@ public class CreateDB
System.out.println("Error: unable to create employee table"); System.out.println("Error: unable to create employee table");
} }
String insertData1 = "INSERT INTO employee VALUES (101, 'Larry', 'Stooge', '386-09-5451', 'larry'," + String insertData1 = "INSERT INTO employee VALUES (101, 'Larry', 'Stooge', '386-09-5451', 'larry',"
"'Technician','443-689-0192','9175 Guilford Rd','New York, NY', 102, 01012000,55000,'2578546969853547'," + + "'Technician','443-689-0192','9175 Guilford Rd','New York, NY', 102, 01012000,55000,'2578546969853547',"
"5000,010106,'Constantly harrassing coworkers','Does not work well with others')"; + "5000,010106,'Constantly harrassing coworkers','Does not work well with others')";
String insertData2 = "INSERT INTO employee VALUES (102, 'Moe', 'Stooge', '936-18-4524','moe'," + String insertData2 = "INSERT INTO employee VALUES (102, 'Moe', 'Stooge', '936-18-4524','moe',"
"'CSO','443-938-5301', '3013 AMD Ave', 'New York, NY', 112, 03082003, 140000, 'NA', 0, 0101013, " + + "'CSO','443-938-5301', '3013 AMD Ave', 'New York, NY', 112, 03082003, 140000, 'NA', 0, 0101013, "
"'Hit Curly over head', 'Very dominating over Larry and Curly')"; + "'Hit Curly over head', 'Very dominating over Larry and Curly')";
String insertData3 = "INSERT INTO employee VALUES (103, 'Curly', 'Stooge', '961-08-0047','curly'," + String insertData3 = "INSERT INTO employee VALUES (103, 'Curly', 'Stooge', '961-08-0047','curly',"
"'Technician','410-667-6654', '1112 Crusoe Lane', 'New York, NY', 102, 02122001, 50000, 'NA', 0, 0101014, " + + "'Technician','410-667-6654', '1112 Crusoe Lane', 'New York, NY', 102, 02122001, 50000, 'NA', 0, 0101014, "
"'Hit Moe back', 'Owes three-thousand to company for fradulent purchases')"; + "'Hit Moe back', 'Owes three-thousand to company for fradulent purchases')";
String insertData4 = "INSERT INTO employee VALUES (104, 'Eric', 'Walker', '445-66-5565','eric'," + String insertData4 = "INSERT INTO employee VALUES (104, 'Eric', 'Walker', '445-66-5565','eric',"
"'Engineer','410-887-1193', '1160 Prescott Rd', 'New York, NY', 107, 12152005, 13000, 'NA', 0, 0101013, " + + "'Engineer','410-887-1193', '1160 Prescott Rd', 'New York, NY', 107, 12152005, 13000, 'NA', 0, 0101013, "
"'Bothering Larry about webgoat problems', 'Late. Always needs help. Too intern-ish.')"; + "'Bothering Larry about webgoat problems', 'Late. Always needs help. Too intern-ish.')";
String insertData5 = "INSERT INTO employee VALUES (105, 'Tom', 'Cat', '792-14-6364','tom'," + String insertData5 = "INSERT INTO employee VALUES (105, 'Tom', 'Cat', '792-14-6364','tom',"
"'Engineer','443-599-0762', '2211 HyperThread Rd.', 'New York, NY', 106, 01011999, 80000, '5481360857968521', 30000, 0, " + + "'Engineer','443-599-0762', '2211 HyperThread Rd.', 'New York, NY', 106, 01011999, 80000, '5481360857968521', 30000, 0, "
"'NA', 'Co-Owner.')"; + "'NA', 'Co-Owner.')";
String insertData6 = "INSERT INTO employee VALUES (106, 'Jerry', 'Mouse', '858-55-4452','jerry'," + String insertData6 = "INSERT INTO employee VALUES (106, 'Jerry', 'Mouse', '858-55-4452','jerry',"
"'Human Resources','443-699-3366', '3011 Unix Drive', 'New York, NY', 102, 01011999, 70000, '6981754825013564', 20000, 0, " + + "'Human Resources','443-699-3366', '3011 Unix Drive', 'New York, NY', 102, 01011999, 70000, '6981754825013564', 20000, 0, "
"'NA', 'Co-Owner.')"; + "'NA', 'Co-Owner.')";
String insertData7 = "INSERT INTO employee VALUES (107, 'David', 'Giambi', '439-20-9405','david'," + String insertData7 = "INSERT INTO employee VALUES (107, 'David', 'Giambi', '439-20-9405','david',"
"'Human Resources','610-521-8413', '5132 DIMM Avenue', 'New York, NY', 102, 05011999, 100000, '6981754825018101', 10000, 061402, " + + "'Human Resources','610-521-8413', '5132 DIMM Avenue', 'New York, NY', 102, 05011999, 100000, '6981754825018101', 10000, 061402, "
"'Hacked into accounting server. Modified personal pay.', 'Strong work habbit. Questionable ethics.')"; + "'Hacked into accounting server. Modified personal pay.', 'Strong work habbit. Questionable ethics.')";
String insertData8 = "INSERT INTO employee VALUES (108, 'Bruce', 'McGuirre', '707-95-9482','bruce'," + String insertData8 = "INSERT INTO employee VALUES (108, 'Bruce', 'McGuirre', '707-95-9482','bruce',"
"'Engineer','610-282-1103', '8899 FreeBSD Drive<script>alert(document.cookie)</script> ', 'New York, NY', 107, 03012000, 110000, '6981754825854136', 30000, 061502, " + + "'Engineer','610-282-1103', '8899 FreeBSD Drive<script>alert(document.cookie)</script> ', 'New York, NY', 107, 03012000, 110000, '6981754825854136', 30000, 061502, "
"'Tortuous Boot Camp workout at 5am. Employees felt sick.', 'Enjoys watching others struggle in exercises.')"; + "'Tortuous Boot Camp workout at 5am. Employees felt sick.', 'Enjoys watching others struggle in exercises.')";
String insertData9 = "INSERT INTO employee VALUES (109, 'Sean', 'Livingston', '136-55-1046','sean'," + String insertData9 = "INSERT INTO employee VALUES (109, 'Sean', 'Livingston', '136-55-1046','sean',"
"'Engineer','610-878-9549', '6422 dFlyBSD Road', 'New York, NY', 107, 06012003, 130000, '6981754825014510', 5000, 072804, " + + "'Engineer','610-878-9549', '6422 dFlyBSD Road', 'New York, NY', 107, 06012003, 130000, '6981754825014510', 5000, 072804, "
"'Late to work 30 days in row due to excessive Halo 2', 'Has some fascination with Steelers. Go Ravens.')"; + "'Late to work 30 days in row due to excessive Halo 2', 'Has some fascination with Steelers. Go Ravens.')";
String insertData10 = "INSERT INTO employee VALUES (110, 'Joanne', 'McDougal', '789-54-2413','joanne'," + String insertData10 = "INSERT INTO employee VALUES (110, 'Joanne', 'McDougal', '789-54-2413','joanne',"
"'Human Resources','610-213-6341', '5567 Broadband Lane', 'New York, NY', 106, 01012001, 90000, '6981754825081054', 300, 112005, " + + "'Human Resources','610-213-6341', '5567 Broadband Lane', 'New York, NY', 106, 01012001, 90000, '6981754825081054', 300, 112005, "
"'Used company cc to purchase new car. Limit adjusted.', 'Finds it necessary to leave early every day.')"; + "'Used company cc to purchase new car. Limit adjusted.', 'Finds it necessary to leave early every day.')";
String insertData11 = "INSERT INTO employee VALUES (111, 'John', 'Wayne', '129-69-4572', 'john'," + String insertData11 = "INSERT INTO employee VALUES (111, 'John', 'Wayne', '129-69-4572', 'john',"
"'CTO','610-213-1134', '129 Third St', 'New York, NY', 112, 01012001, 200000, '4437334565679921', 300, 112005, " + + "'CTO','610-213-1134', '129 Third St', 'New York, NY', 112, 01012001, 200000, '4437334565679921', 300, 112005, "
"'', '')"; + "'', '')";
String insertData12 = "INSERT INTO employee VALUES (112, 'Neville', 'Bartholomew', '111-111-1111', 'socks'," + String insertData12 = "INSERT INTO employee VALUES (112, 'Neville', 'Bartholomew', '111-111-1111', 'socks',"
"'CEO','408-587-0024', '1 Corporate Headquarters', 'San Jose, CA', 112, 03012000, 450000, '4803389267684109', 300, 112005, " + + "'CEO','408-587-0024', '1 Corporate Headquarters', 'San Jose, CA', 112, 03012000, 450000, '4803389267684109', 300, 112005, "
"'', '')"; + "'', '')";
statement.executeUpdate(insertData1); statement.executeUpdate(insertData1);
statement.executeUpdate(insertData2); statement.executeUpdate(insertData2);
@ -521,6 +534,7 @@ public class CreateDB
} }
private void createRolesTable(Connection connection) throws SQLException private void createRolesTable(Connection connection) throws SQLException
{ {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@ -538,10 +552,8 @@ public class CreateDB
try try
{ {
String createTable = "CREATE TABLE roles (" String createTable = "CREATE TABLE roles ("
+ "userid INT NOT NULL," + "userid INT NOT NULL," + "role VARCHAR(10) NOT NULL,"
+ "role VARCHAR(10) NOT NULL," + "PRIMARY KEY (userid, role)" + ")";
+ "PRIMARY KEY (userid, role)"
+ ")";
statement.executeUpdate(createTable); statement.executeUpdate(createTable);
} }
@ -577,6 +589,7 @@ public class CreateDB
statement.executeUpdate(insertData12); statement.executeUpdate(insertData12);
} }
private void createAuthTable(Connection connection) throws SQLException private void createAuthTable(Connection connection) throws SQLException
{ {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@ -596,8 +609,7 @@ public class CreateDB
String createTable = "CREATE TABLE auth (" String createTable = "CREATE TABLE auth ("
+ "role VARCHAR(10) NOT NULL," + "role VARCHAR(10) NOT NULL,"
+ "functionid VARCHAR(20) NOT NULL," + "functionid VARCHAR(20) NOT NULL,"
+ "PRIMARY KEY (role, functionid)" + "PRIMARY KEY (role, functionid)" + ")";
+ ")";
statement.executeUpdate(createTable); statement.executeUpdate(createTable);
} }
@ -642,8 +654,12 @@ public class CreateDB
// Add a permission for the webgoat role to see the source. // Add a permission for the webgoat role to see the source.
// The challenge(s) will change the default role to "challenge" // The challenge(s) will change the default role to "challenge"
String insertData26 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOURCE +"')"; String insertData26 = "INSERT INTO auth VALUES('"
String insertData27 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWHINTS + "')"; + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOURCE
+ "')";
String insertData27 = "INSERT INTO auth VALUES('"
+ AbstractLesson.USER_ROLE + "','" + WebSession.SHOWHINTS
+ "')";
statement.executeUpdate(insertData1); statement.executeUpdate(insertData1);
statement.executeUpdate(insertData2); statement.executeUpdate(insertData2);
@ -682,7 +698,9 @@ public class CreateDB
statement.executeUpdate(insertData27); statement.executeUpdate(insertData27);
} }
private void createOwnershipTable(Connection connection) throws SQLException
private void createOwnershipTable(Connection connection)
throws SQLException
{ {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
@ -699,10 +717,8 @@ public class CreateDB
try try
{ {
String createTable = "CREATE TABLE ownership (" String createTable = "CREATE TABLE ownership ("
+ "employer_id INT NOT NULL," + "employer_id INT NOT NULL," + "employee_id INT NOT NULL,"
+ "employee_id INT NOT NULL," + "PRIMARY KEY (employee_id, employer_id)" + ")";
+ "PRIMARY KEY (employee_id, employer_id)"
+ ")";
statement.executeUpdate(createTable); statement.executeUpdate(createTable);
} }
@ -821,6 +837,7 @@ public class CreateDB
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
// //
// End of WebGoat Financials // End of WebGoat Financials

View File

@ -13,19 +13,43 @@ import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR; import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of *
* the Open Web Application Security Project (http://www.owasp.org) This * This file is part of WebGoat, an Open Web Application Security Project
* software package org.owasp.webgoat.is published by OWASP under the GPL. You should read and * utility. For details, please see http://www.owasp.org/
* accept the LICENSE before you use, modify and/or redistribute this *
* software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/ */
public class DatabaseUtilities public class DatabaseUtilities
{ {
public static String servletContextRealPath = null; public static String servletContextRealPath = null;
/** /**
* Description of the Method * Description of the Method
* *
@ -36,22 +60,27 @@ public class DatabaseUtilities
* @exception ClassNotFoundException Description of the Exception * @exception ClassNotFoundException Description of the Exception
* @exception SQLException Description of the Exception * @exception SQLException Description of the Exception
*/ */
public static Connection makeConnection(WebSession s) throws ClassNotFoundException, SQLException public static Connection makeConnection(WebSession s)
throws ClassNotFoundException, SQLException
{ {
Class.forName(s.getDatabaseDriver()); Class.forName(s.getDatabaseDriver());
return (DriverManager.getConnection(s.getDatabaseConnectionString())); return (DriverManager.getConnection(s.getDatabaseConnectionString()));
} }
public static Connection makeConnection(String driverName, String connectionString)
throws ClassNotFoundException, SQLException public static Connection makeConnection(String driverName,
String connectionString) throws ClassNotFoundException,
SQLException
{ {
Class.forName(driverName); Class.forName(driverName);
return (DriverManager.getConnection(connectionString)); return (DriverManager.getConnection(connectionString));
} }
public static Connection makeConnection() {
public static Connection makeConnection()
{
try try
{ {
// FIXME: Work around for not having a session object with the web service lessons // FIXME: Work around for not having a session object with the web service lessons
@ -65,7 +94,9 @@ public class DatabaseUtilities
dbName = dbName.concat("webgoat.mdb"); dbName = dbName.concat("webgoat.mdb");
System.out.println("DBName: " + dbName); System.out.println("DBName: " + dbName);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
return DriverManager.getConnection("jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=" + dbName + ";PWD=webgoat"); return DriverManager
.getConnection("jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ="
+ dbName + ";PWD=webgoat");
} }
else else
{ {
@ -93,7 +124,8 @@ public class DatabaseUtilities
* @exception IOException Description of the Exception * @exception IOException Description of the Exception
* @exception SQLException Description of the Exception * @exception SQLException Description of the Exception
*/ */
public static MultiPartElement writeTable(ResultSet results, ResultSetMetaData resultsMetaData) throws IOException, SQLException public static MultiPartElement writeTable(ResultSet results,
ResultSetMetaData resultsMetaData) throws IOException, SQLException
{ {
int numColumns = resultsMetaData.getColumnCount(); int numColumns = resultsMetaData.getColumnCount();
results.beforeFirst(); results.beforeFirst();
@ -119,7 +151,8 @@ public class DatabaseUtilities
for (int i = 1; i < (numColumns + 1); i++) for (int i = 1; i < (numColumns + 1); i++)
{ {
row.addElement(new TD(results.getString(i).replaceAll(" ", "&nbsp;"))); row.addElement(new TD(results.getString(i).replaceAll(" ",
"&nbsp;")));
} }
t.addElement(row); t.addElement(row);
@ -129,7 +162,8 @@ public class DatabaseUtilities
} }
else else
{ {
return (new B("Query Successful; however no data was returned from this query.")); return (new B(
"Query Successful; however no data was returned from this query."));
} }
} }
} }

View File

@ -21,12 +21,34 @@ import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR; import org.apache.ecs.html.TR;
import org.apache.ecs.html.U; import org.apache.ecs.html.U;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams (jeff.williams@aspectsecurity.com) * @author Jeff Williams (jeff.williams@aspectsecurity.com)
* @created October 29, 2003 * @created October 29, 2003
@ -48,13 +70,12 @@ public class ECSFactory
public final static String PASSWORD = "Password"; public final static String PASSWORD = "Password";
/** /**
* Don't let anyone instantiate this class * Don't let anyone instantiate this class
*/ */
private ECSFactory() { } private ECSFactory()
{}
/** /**
@ -76,7 +97,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -97,7 +117,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -130,7 +149,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -141,10 +159,12 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static TR makeField( String labeltext, String name, String value, int size ) public static TR makeField(String labeltext, String name, String value,
int size)
{ {
Input field = new Input().setName( name ).setValue( value ).setSize( size ).setMaxlength( size ); Input field = new Input().setName(name).setValue(value).setSize(size)
.setMaxlength(size);
// double check in case someone means to make a * starred out password field // double check in case someone means to make a * starred out password field
@ -159,7 +179,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -172,14 +191,15 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Element makeInput( String label, String type, String name, boolean value, boolean selected, String alignment ) public static Element makeInput(String label, String type, String name,
boolean value, boolean selected, String alignment)
{ {
return makeInput( label, type, name, new Boolean( value ).toString(), selected, alignment ); return makeInput(label, type, name, new Boolean(value).toString(),
selected, alignment);
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -190,14 +210,15 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Element makeInput( String label, String type, String name, String value ) public static Element makeInput(String label, String type, String name,
String value)
{ {
return makeInput( label, type, name, value, new Boolean( value ).booleanValue(), "RIGHT" ); return makeInput(label, type, name, value, new Boolean(value)
.booleanValue(), "RIGHT");
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -210,7 +231,8 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Element makeInput( String label, String type, String name, String value, boolean selected, String alignment ) public static Element makeInput(String label, String type, String name,
String value, boolean selected, String alignment)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -244,7 +266,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -276,7 +297,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -293,7 +313,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -310,7 +329,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -320,7 +338,8 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Input makeOnClickInput( String text, String clickAction, String type ) public static Input makeOnClickInput(String text, String clickAction,
String type)
{ {
Input b = new Input(); Input b = new Input();
@ -335,7 +354,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -368,7 +386,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -388,7 +405,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -418,7 +434,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -438,7 +453,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -474,7 +488,6 @@ public class ECSFactory
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -485,7 +498,8 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Select makePulldown( String name, Object[] list, String selected, int rowsShowing ) public static Select makePulldown(String name, Object[] list,
String selected, int rowsShowing)
{ {
Select select = new Select(name); Select select = new Select(name);
@ -495,7 +509,8 @@ public class ECSFactory
String value = list[loop].toString(); String value = list[loop].toString();
org.apache.ecs.html.Option o = new org.apache.ecs.html.Option( value, value, value ); org.apache.ecs.html.Option o = new org.apache.ecs.html.Option(
value, value, value);
if (value.equals(selected)) if (value.equals(selected))
{ {
@ -514,7 +529,6 @@ public class ECSFactory
} }
/** /**
* Default size of 1 for rows showing in select box. * Default size of 1 for rows showing in select box.
* *
@ -527,14 +541,14 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Element makeSelect( boolean diffNames, Select select, String name, Vector options, String[] list, String selected ) public static Element makeSelect(boolean diffNames, Select select,
String name, Vector options, String[] list, String selected)
{ {
return makeSelect(diffNames, select, name, options, list, selected, 1); return makeSelect(diffNames, select, name, options, list, selected, 1);
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -548,7 +562,9 @@ public class ECSFactory
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static Select makeSelect( boolean diffNames, Select select, String name, Vector options, String[] list, String selected, int rowsShowing ) public static Select makeSelect(boolean diffNames, Select select,
String name, Vector options, String[] list, String selected,
int rowsShowing)
{ {
if (select == null) if (select == null)
@ -566,7 +582,8 @@ public class ECSFactory
String label = list[loop + 1]; String label = list[loop + 1];
org.apache.ecs.html.Option o = new org.apache.ecs.html.Option( value ); org.apache.ecs.html.Option o = new org.apache.ecs.html.Option(
value);
if (loop == 0) if (loop == 0)
{ {
@ -593,7 +610,8 @@ public class ECSFactory
String value = list[loop]; String value = list[loop];
org.apache.ecs.html.Option o = new org.apache.ecs.html.Option( value ); org.apache.ecs.html.Option o = new org.apache.ecs.html.Option(
value);
if (loop == 0) if (loop == 0)
{ {
@ -621,7 +639,8 @@ public class ECSFactory
while (i.hasNext()) while (i.hasNext())
{ {
org.apache.ecs.html.Option o = (org.apache.ecs.html.Option) i.next(); org.apache.ecs.html.Option o = (org.apache.ecs.html.Option) i
.next();
if (selected.equalsIgnoreCase(o.getAttribute("value"))) if (selected.equalsIgnoreCase(o.getAttribute("value")))
{ {
@ -675,7 +694,8 @@ public class ECSFactory
ec.addElement(new P()); ec.addElement(new P());
ec.addElement( "<CENTER><TEXTAREA ROWS=10 COLS=90 READONLY>" + text + "</TEXTAREA></CENTER>" ); ec.addElement("<CENTER><TEXTAREA ROWS=10 COLS=90 READONLY>" + text
+ "</TEXTAREA></CENTER>");
ec.addElement(new BR()); ec.addElement(new BR());
@ -685,4 +705,3 @@ public class ECSFactory
} }
} }

View File

@ -2,10 +2,42 @@ package org.owasp.webgoat.session;
import java.io.Serializable; import java.io.Serializable;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Employee implements Serializable public class Employee implements Serializable
{ {
public final static String EMPLOYEE_ROLE = "employee"; public final static String EMPLOYEE_ROLE = "employee";
public final static String MANAGER_ROLE = "manager"; public final static String MANAGER_ROLE = "manager";
public final static String HR_ROLE = "hr"; public final static String HR_ROLE = "hr";
private int id; private int id;
@ -40,28 +72,17 @@ public class Employee implements Serializable
private String personalDescription; private String personalDescription;
// FIXME: To be deleted // FIXME: To be deleted
public Employee() public Employee()
{ {}
}
public Employee(
int id, public Employee(int id, String firstName, String lastName, String ssn,
String firstName, String title, String phone, String address1, String address2,
String lastName, int manager, String startDate, int salary, String ccn,
String ssn, int ccnLimit, String disciplinaryActionDate,
String title, String disciplinaryActionNotes, String personalDescription)
String phone,
String address1,
String address2,
int manager,
String startDate,
int salary,
String ccn,
int ccnLimit,
String disciplinaryActionDate,
String disciplinaryActionNotes,
String personalDescription)
{ {
this.id = id; this.id = id;
this.firstName = firstName; this.firstName = firstName;
@ -81,136 +102,163 @@ public class Employee implements Serializable
this.personalDescription = personalDescription; this.personalDescription = personalDescription;
} }
public String getAddress1() public String getAddress1()
{ {
return address1; return address1;
} }
public void setAddress1(String address1) public void setAddress1(String address1)
{ {
this.address1 = address1; this.address1 = address1;
} }
public String getAddress2() public String getAddress2()
{ {
return address2; return address2;
} }
public void setAddress2(String address2) public void setAddress2(String address2)
{ {
this.address2 = address2; this.address2 = address2;
} }
public String getCcn() public String getCcn()
{ {
return ccn; return ccn;
} }
public void setCcn(String ccn) public void setCcn(String ccn)
{ {
this.ccn = ccn; this.ccn = ccn;
} }
public int getCcnLimit() public int getCcnLimit()
{ {
return ccnLimit; return ccnLimit;
} }
public void setCcnLimit(int ccnLimit) public void setCcnLimit(int ccnLimit)
{ {
this.ccnLimit = ccnLimit; this.ccnLimit = ccnLimit;
} }
public String getFirstName() public String getFirstName()
{ {
return firstName; return firstName;
} }
public void setFirstName(String firstName) public void setFirstName(String firstName)
{ {
this.firstName = firstName; this.firstName = firstName;
} }
public String getLastName() public String getLastName()
{ {
return lastName; return lastName;
} }
public void setLastName(String lastName) public void setLastName(String lastName)
{ {
this.lastName = lastName; this.lastName = lastName;
} }
public String getPhoneNumber() public String getPhoneNumber()
{ {
return phone; return phone;
} }
public void setPhoneNumber(String phone) public void setPhoneNumber(String phone)
{ {
this.phone = phone; this.phone = phone;
} }
public int getSalary() public int getSalary()
{ {
return salary; return salary;
} }
public void setSalary(int salary) public void setSalary(int salary)
{ {
this.salary = salary; this.salary = salary;
} }
public String getSsn() public String getSsn()
{ {
return ssn; return ssn;
} }
public void setSsn(String ssn) public void setSsn(String ssn)
{ {
this.ssn = ssn; this.ssn = ssn;
} }
public String getStartDate() public String getStartDate()
{ {
return startDate; return startDate;
} }
public void setStartDate(String startDate) public void setStartDate(String startDate)
{ {
this.startDate = startDate; this.startDate = startDate;
} }
public int getId() public int getId()
{ {
return id; return id;
} }
public void setId(int id) public void setId(int id)
{ {
this.id = id; this.id = id;
} }
public String getTitle() public String getTitle()
{ {
return this.title; return this.title;
} }
public int getManager() public int getManager()
{ {
return this.manager; return this.manager;
} }
public String getDisciplinaryActionDate() public String getDisciplinaryActionDate()
{ {
return this.disciplinaryActionDate; return this.disciplinaryActionDate;
} }
public String getDisciplinaryActionNotes() public String getDisciplinaryActionNotes()
{ {
return this.disciplinaryActionNotes; return this.disciplinaryActionNotes;
} }
public String getPersonalDescription() public String getPersonalDescription()
{ {
return this.personalDescription; return this.personalDescription;

View File

@ -2,18 +2,53 @@ package org.owasp.webgoat.session;
import java.io.Serializable; import java.io.Serializable;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class EmployeeStub implements Serializable public class EmployeeStub implements Serializable
{ {
private int id; private int id;
private String firstName; private String firstName;
private String lastName; private String lastName;
private String role; private String role;
public EmployeeStub(int id, String firstName, String lastName) public EmployeeStub(int id, String firstName, String lastName)
{ {
this(id, firstName, lastName, Employee.EMPLOYEE_ROLE); this(id, firstName, lastName, Employee.EMPLOYEE_ROLE);
} }
public EmployeeStub(int id, String firstName, String lastName, String role) public EmployeeStub(int id, String firstName, String lastName, String role)
{ {
this.id = id; this.id = id;
@ -22,21 +57,25 @@ public class EmployeeStub implements Serializable
this.role = role; this.role = role;
} }
public String getFirstName() public String getFirstName()
{ {
return firstName; return firstName;
} }
public int getId() public int getId()
{ {
return id; return id;
} }
public String getLastName() public String getLastName()
{ {
return lastName; return lastName;
} }
public String getRole() public String getRole()
{ {
return role; return role;

View File

@ -20,11 +20,34 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table; import org.apache.ecs.html.Table;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * This file is part of WebGoat, an Open Web Application Security Project
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created November 4, 2003 * @created November 4, 2003

View File

@ -1,6 +1,34 @@
package org.owasp.webgoat.session; package org.owasp.webgoat.session;
/** /*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* Represents a virtual session for a lesson. Lesson-specific session data may * Represents a virtual session for a lesson. Lesson-specific session data may
* be stored here. * be stored here.
* *
@ -9,25 +37,30 @@ package org.owasp.webgoat.session;
*/ */
public class LessonSession public class LessonSession
{ {
private boolean isAuthenticated = false; private boolean isAuthenticated = false;
private String currentLessonScreen; private String currentLessonScreen;
public void setAuthenticated(boolean isAuthenticated) public void setAuthenticated(boolean isAuthenticated)
{ {
this.isAuthenticated = isAuthenticated; this.isAuthenticated = isAuthenticated;
} }
public boolean isAuthenticated() public boolean isAuthenticated()
{ {
return this.isAuthenticated; return this.isAuthenticated;
} }
public void setCurrentLessonScreen(String currentLessonScreen) public void setCurrentLessonScreen(String currentLessonScreen)
{ {
this.currentLessonScreen = currentLessonScreen; this.currentLessonScreen = currentLessonScreen;
} }
public String getCurrentLessonScreen() public String getCurrentLessonScreen()
{ {
return this.currentLessonScreen; return this.currentLessonScreen;

View File

@ -5,24 +5,57 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.util.Properties; import java.util.Properties;
/*******************************************************************************
/** *
* Description of the Class *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 29, 2003 * @created October 29, 2003
*/ */
public class LessonTracker public class LessonTracker
{ {
private boolean completed = false; private boolean completed = false;
private int currentStage = 1; private int currentStage = 1;
private int maxHintLevel = 0; private int maxHintLevel = 0;
private int numVisits = 0; private int numVisits = 0;
private boolean viewedCookies = false; private boolean viewedCookies = false;
private boolean viewedHtml = false; private boolean viewedHtml = false;
private boolean viewedLessonPlan = false; private boolean viewedLessonPlan = false;
private boolean viewedParameters = false; private boolean viewedParameters = false;
private boolean viewedSource = false; private boolean viewedSource = false;
Properties lessonProperties = new Properties(); Properties lessonProperties = new Properties();
@ -44,11 +77,13 @@ public class LessonTracker
return currentStage; return currentStage;
} }
public void setStage(int stage) public void setStage(int stage)
{ {
currentStage = stage; currentStage = stage;
} }
/** /**
* Gets the maxHintLevel attribute of the LessonTracker object * Gets the maxHintLevel attribute of the LessonTracker object
* *
@ -93,7 +128,6 @@ public class LessonTracker
} }
/** /**
* Gets the viewedLessonPlan attribute of the LessonTracker object * Gets the viewedLessonPlan attribute of the LessonTracker object
* *
@ -143,15 +177,30 @@ public class LessonTracker
*/ */
private void setProperties(Properties props, Screen screen) private void setProperties(Properties props, Screen screen)
{ {
completed = Boolean.valueOf( props.getProperty( screen.getTitle() + ".completed" ) ).booleanValue(); completed = Boolean.valueOf(
maxHintLevel = Integer.parseInt( props.getProperty( screen.getTitle() + ".maxHintLevel" ) ); props.getProperty(screen.getTitle() + ".completed"))
currentStage = Integer.parseInt( props.getProperty( screen.getTitle() + ".currentStage" ) ); .booleanValue();
numVisits = Integer.parseInt( props.getProperty( screen.getTitle() + ".numVisits" ) ); maxHintLevel = Integer.parseInt(props.getProperty(screen.getTitle()
viewedCookies = Boolean.valueOf( props.getProperty( screen.getTitle() + ".viewedCookies" ) ).booleanValue(); + ".maxHintLevel"));
viewedHtml = Boolean.valueOf( props.getProperty( screen.getTitle() + ".viewedHtml" ) ).booleanValue(); currentStage = Integer.parseInt(props.getProperty(screen.getTitle()
viewedLessonPlan = Boolean.valueOf( props.getProperty( screen.getTitle() + ".viewedLessonPlan" ) ).booleanValue(); + ".currentStage"));
viewedParameters = Boolean.valueOf( props.getProperty( screen.getTitle() + ".viewedParameters" ) ).booleanValue(); numVisits = Integer.parseInt(props.getProperty(screen.getTitle()
viewedSource = Boolean.valueOf( props.getProperty( screen.getTitle() + ".viewedSource" ) ).booleanValue(); + ".numVisits"));
viewedCookies = Boolean.valueOf(
props.getProperty(screen.getTitle() + ".viewedCookies"))
.booleanValue();
viewedHtml = Boolean.valueOf(
props.getProperty(screen.getTitle() + ".viewedHtml"))
.booleanValue();
viewedLessonPlan = Boolean.valueOf(
props.getProperty(screen.getTitle() + ".viewedLessonPlan"))
.booleanValue();
viewedParameters = Boolean.valueOf(
props.getProperty(screen.getTitle() + ".viewedParameters"))
.booleanValue();
viewedSource = Boolean.valueOf(
props.getProperty(screen.getTitle() + ".viewedSource"))
.booleanValue();
} }
@ -160,9 +209,12 @@ public class LessonTracker
return s.getContext().getRealPath("users") + "/"; return s.getContext().getRealPath("users") + "/";
} }
private static String getTrackerFile( WebSession s, String user, Screen screen )
private static String getTrackerFile(WebSession s, String user,
Screen screen)
{ {
return getUserDir( s ) + user + "." + screen.getClass().getName() + ".props"; return getUserDir(s) + user + "." + screen.getClass().getName()
+ ".props";
} }
@ -186,7 +238,8 @@ public class LessonTracker
in = new FileInputStream(fileName); in = new FileInputStream(fileName);
tempProps.load(in); tempProps.load(in);
// allow the screen to use any custom properties it may have set // allow the screen to use any custom properties it may have set
LessonTracker tempLessonTracker = screen.createLessonTracker( tempProps ); LessonTracker tempLessonTracker = screen
.createLessonTracker(tempProps);
tempLessonTracker.setProperties(tempProps, screen); tempLessonTracker.setProperties(tempProps, screen);
return tempLessonTracker; return tempLessonTracker;
} }
@ -206,7 +259,8 @@ public class LessonTracker
{ {
in.close(); in.close();
} }
catch (Exception e) {} catch (Exception e)
{}
} }
return screen.createLessonTracker(); return screen.createLessonTracker();
@ -224,7 +278,6 @@ public class LessonTracker
} }
/** /**
* Sets the maxHintLevel attribute of the LessonTracker object * Sets the maxHintLevel attribute of the LessonTracker object
* *
@ -258,7 +311,6 @@ public class LessonTracker
} }
/** /**
* Sets the viewedLessonPlan attribute of the LessonTracker object * Sets the viewedLessonPlan attribute of the LessonTracker object
* *
@ -302,6 +354,7 @@ public class LessonTracker
store(s, screen, s.getUserName()); store(s, screen, s.getUserName());
} }
/** /**
* Allows the storing of properties for a user and a screen. * Allows the storing of properties for a user and a screen.
* *
@ -312,15 +365,24 @@ public class LessonTracker
FileOutputStream out = null; FileOutputStream out = null;
String fileName = getTrackerFile(s, user, screen); String fileName = getTrackerFile(s, user, screen);
//System.out.println( "Storing data to" + fileName ); //System.out.println( "Storing data to" + fileName );
lessonProperties.setProperty( screen.getTitle() + ".completed", Boolean.toString( completed ) ); lessonProperties.setProperty(screen.getTitle() + ".completed", Boolean
lessonProperties.setProperty( screen.getTitle() + ".currentStage", Integer.toString( currentStage ) ); .toString(completed));
lessonProperties.setProperty( screen.getTitle() + ".maxHintLevel", Integer.toString( maxHintLevel ) ); lessonProperties.setProperty(screen.getTitle() + ".currentStage",
lessonProperties.setProperty( screen.getTitle() + ".numVisits", Integer.toString( numVisits ) ); Integer.toString(currentStage));
lessonProperties.setProperty( screen.getTitle() + ".viewedCookies", Boolean.toString( viewedCookies ) ); lessonProperties.setProperty(screen.getTitle() + ".maxHintLevel",
lessonProperties.setProperty( screen.getTitle() + ".viewedHtml", Boolean.toString( viewedHtml ) ); Integer.toString(maxHintLevel));
lessonProperties.setProperty( screen.getTitle() + ".viewedLessonPlan", Boolean.toString( viewedLessonPlan ) ); lessonProperties.setProperty(screen.getTitle() + ".numVisits", Integer
lessonProperties.setProperty( screen.getTitle() + ".viewedParameters", Boolean.toString( viewedParameters ) ); .toString(numVisits));
lessonProperties.setProperty( screen.getTitle() + ".viewedSource", Boolean.toString( viewedSource ) ); lessonProperties.setProperty(screen.getTitle() + ".viewedCookies",
Boolean.toString(viewedCookies));
lessonProperties.setProperty(screen.getTitle() + ".viewedHtml", Boolean
.toString(viewedHtml));
lessonProperties.setProperty(screen.getTitle() + ".viewedLessonPlan",
Boolean.toString(viewedLessonPlan));
lessonProperties.setProperty(screen.getTitle() + ".viewedParameters",
Boolean.toString(viewedParameters));
lessonProperties.setProperty(screen.getTitle() + ".viewedSource",
Boolean.toString(viewedSource));
try try
{ {
out = new FileOutputStream(fileName); out = new FileOutputStream(fileName);
@ -329,7 +391,8 @@ public class LessonTracker
catch (Exception e) catch (Exception e)
{ {
// what do we want to do, I think nothing. // what do we want to do, I think nothing.
System.out.println( "Warning User data for " + s.getUserName() + " will not persist" ); System.out.println("Warning User data for " + s.getUserName()
+ " will not persist");
} }
finally finally
{ {
@ -337,7 +400,8 @@ public class LessonTracker
{ {
out.close(); out.close();
} }
catch (Exception e) {} catch (Exception e)
{}
} }
} }
@ -364,6 +428,7 @@ public class LessonTracker
return buff.toString(); return buff.toString();
} }
/** /**
* @return Returns the lessonProperties. * @return Returns the lessonProperties.
*/ */
@ -372,6 +437,7 @@ public class LessonTracker
return lessonProperties; return lessonProperties;
} }
/** /**
* @param lessonProperties The lessonProperties to set. * @param lessonProperties The lessonProperties to set.
*/ */
@ -380,4 +446,3 @@ public class LessonTracker
this.lessonProperties = lessonProperties; this.lessonProperties = lessonProperties;
} }
} }

View File

@ -1,46 +1,90 @@
package org.owasp.webgoat.session; package org.owasp.webgoat.session;
public class Parameter implements Comparable { /*******************************************************************************
*
*
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class Parameter implements Comparable
{
String name; String name;
String value; String value;
public Parameter(String name, String value) {
public Parameter(String name, String value)
{
this.name = name; this.name = name;
this.value = value; this.value = value;
} }
public String getName() public String getName()
{ {
return name; return name;
} }
public String getValue() public String getValue()
{ {
return value; return value;
} }
//@Override //@Override
public boolean equals(Object obj) { public boolean equals(Object obj)
{
if (obj instanceof Parameter) if (obj instanceof Parameter)
{ {
Parameter other = (Parameter) obj; Parameter other = (Parameter) obj;
return ( name.equals( other.getName() ) && value.equals( other.getValue() ) ); return (name.equals(other.getName()) && value.equals(other
.getValue()));
} }
return false; return false;
} }
//@Override //@Override
public int hashCode() { public int hashCode()
{
return toString().hashCode(); return toString().hashCode();
} }
//@Override //@Override
public String toString() { public String toString()
{
return (name + "=" + value); return (name + "=" + value);
} }
public int compareTo(Object o) {
public int compareTo(Object o)
{
return toString().compareTo(o.toString()); return toString().compareTo(o.toString());
} }
} }

View File

@ -1,15 +1,39 @@
package org.owasp.webgoat.session; package org.owasp.webgoat.session;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of *
* the Open Web Application Security Project (http://www.owasp.org) This *
* software package org.owasp.webgoat.is published by OWASP under the GPL. You should read and * This file is part of WebGoat, an Open Web Application Security Project
* accept the LICENSE before you use, modify and/or redistribute this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/ */
public class ParameterNotFoundException extends Exception public class ParameterNotFoundException extends Exception
{ {
/** /**
* Constructs a new ParameterNotFoundException with no detail message. * Constructs a new ParameterNotFoundException with no detail message.
*/ */

View File

@ -9,20 +9,45 @@ import javax.servlet.ServletRequest;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/** *
* Copyright (c) 2002-2004 Free Software Foundation developed under the custody of *
* the Open Web Application Security Project (http://www.owasp.org) This * This file is part of WebGoat, an Open Web Application Security Project
* software package org.owasp.webgoat.is published by OWASP under the GPL. You should read and * utility. For details, please see http://www.owasp.org/
* accept the LICENSE before you use, modify and/or redistribute this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/ */
public class ParameterParser public class ParameterParser
{ {
private final static String ALLOWED_CHARACTERS = "$()-?.@!,:;=//+"; // Don't allow #& specifically private final static String ALLOWED_CHARACTERS = "$()-?.@!,:;=//+"; // Don't allow #& specifically
private ServletRequest request; private ServletRequest request;
/** /**
* Constructs a new ParameterParser to handle the parameters of the given * Constructs a new ParameterParser to handle the parameters of the given
* request. * request.
@ -34,6 +59,7 @@ public class ParameterParser
this.request = request; this.request = request;
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -48,7 +74,8 @@ public class ParameterParser
{ {
char c = s.charAt(loop); char c = s.charAt(loop);
if (Character.isLetterOrDigit(c) || Character.isWhitespace(c) || (ALLOWED_CHARACTERS.indexOf(c) != -1)) if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)
|| (ALLOWED_CHARACTERS.indexOf(c) != -1))
{ {
clean.append(c); clean.append(c);
} }
@ -69,7 +96,8 @@ public class ParameterParser
*@return the parameter value as a boolean *@return the parameter value as a boolean
*@exception ParameterNotFoundException if the parameter was not found *@exception ParameterNotFoundException if the parameter was not found
*/ */
public boolean getBooleanParameter(String name) throws ParameterNotFoundException public boolean getBooleanParameter(String name)
throws ParameterNotFoundException
{ {
return new Boolean(getStringParameter(name)).booleanValue(); return new Boolean(getStringParameter(name)).booleanValue();
} }
@ -126,7 +154,8 @@ public class ParameterParser
*@exception NumberFormatException if the parameter value could not be *@exception NumberFormatException if the parameter value could not be
* converted to a byte * converted to a byte
*/ */
public byte getByteParameter(String name) throws ParameterNotFoundException, NumberFormatException public byte getByteParameter(String name)
throws ParameterNotFoundException, NumberFormatException
{ {
return Byte.parseByte(getStringParameter(name)); return Byte.parseByte(getStringParameter(name));
} }
@ -204,7 +233,8 @@ public class ParameterParser
*@param name Description of the Parameter *@param name Description of the Parameter
*@return The classNameParameter value *@return The classNameParameter value
*/ */
public String getClassNameParameter(String name) throws ParameterNotFoundException public String getClassNameParameter(String name)
throws ParameterNotFoundException
{ {
String p = getStringParameter(name); String p = getStringParameter(name);
StringTokenizer st = new StringTokenizer(p); StringTokenizer st = new StringTokenizer(p);
@ -244,7 +274,8 @@ public class ParameterParser
*@exception NumberFormatException if the parameter could not be *@exception NumberFormatException if the parameter could not be
* converted to a double * converted to a double
*/ */
public double getDoubleParameter(String name) throws ParameterNotFoundException, NumberFormatException public double getDoubleParameter(String name)
throws ParameterNotFoundException, NumberFormatException
{ {
return new Double(getStringParameter(name)).doubleValue(); return new Double(getStringParameter(name)).doubleValue();
} }
@ -280,7 +311,8 @@ public class ParameterParser
*@exception NumberFormatException if the parameter could not be *@exception NumberFormatException if the parameter could not be
* converted to a float * converted to a float
*/ */
public float getFloatParameter(String name) throws ParameterNotFoundException, NumberFormatException public float getFloatParameter(String name)
throws ParameterNotFoundException, NumberFormatException
{ {
return new Float(getStringParameter(name)).floatValue(); return new Float(getStringParameter(name)).floatValue();
} }
@ -428,7 +460,8 @@ public class ParameterParser
*@exception NumberFormatException if the parameter could not be *@exception NumberFormatException if the parameter could not be
* converted to a int * converted to a int
*/ */
public int getIntParameter(String name) throws ParameterNotFoundException, NumberFormatException public int getIntParameter(String name) throws ParameterNotFoundException,
NumberFormatException
{ {
return Integer.parseInt(getStringParameter(name)); return Integer.parseInt(getStringParameter(name));
} }
@ -464,7 +497,8 @@ public class ParameterParser
*@exception NumberFormatException if the parameter could not be *@exception NumberFormatException if the parameter could not be
* converted to a long * converted to a long
*/ */
public long getLongParameter(String name) throws ParameterNotFoundException, NumberFormatException public long getLongParameter(String name)
throws ParameterNotFoundException, NumberFormatException
{ {
return Long.parseLong(getStringParameter(name)); return Long.parseLong(getStringParameter(name));
} }
@ -587,7 +621,8 @@ public class ParameterParser
*@return The rawParameter value *@return The rawParameter value
*@exception ParameterNotFoundException Description of the Exception *@exception ParameterNotFoundException Description of the Exception
*/ */
public String getRawParameter(String name) throws ParameterNotFoundException public String getRawParameter(String name)
throws ParameterNotFoundException
{ {
String[] values = request.getParameterValues(name); String[] values = request.getParameterValues(name);
@ -613,7 +648,8 @@ public class ParameterParser
*@exception NumberFormatException if the parameter could not be *@exception NumberFormatException if the parameter could not be
* converted to a short * converted to a short
*/ */
public short getShortParameter(String name) throws ParameterNotFoundException, NumberFormatException public short getShortParameter(String name)
throws ParameterNotFoundException, NumberFormatException
{ {
return Short.parseShort(getStringParameter(name)); return Short.parseShort(getStringParameter(name));
} }
@ -648,7 +684,8 @@ public class ParameterParser
*@exception ParameterNotFoundException if the parameter was not found or was *@exception ParameterNotFoundException if the parameter was not found or was
* the empty string * the empty string
*/ */
public String getStringParameter(String name) throws ParameterNotFoundException public String getStringParameter(String name)
throws ParameterNotFoundException
{ {
String[] values = request.getParameterValues(name); String[] values = request.getParameterValues(name);
String value; String value;
@ -728,7 +765,8 @@ public class ParameterParser
*@return The subParameter value *@return The subParameter value
*@exception ParameterNotFoundException Description of the Exception *@exception ParameterNotFoundException Description of the Exception
*/ */
public String getSubParameter(String first, String next) throws ParameterNotFoundException public String getSubParameter(String first, String next)
throws ParameterNotFoundException
{ {
String[] values = request.getParameterValues(first); String[] values = request.getParameterValues(first);
String value; String value;
@ -793,7 +831,8 @@ public class ParameterParser
*@param name Description of the Parameter *@param name Description of the Parameter
*@return The wordParameter value *@return The wordParameter value
*/ */
public String getWordParameter(String name) throws ParameterNotFoundException public String getWordParameter(String name)
throws ParameterNotFoundException
{ {
String p = getStringParameter(name); String p = getStringParameter(name);
StringTokenizer st = new StringTokenizer(p); StringTokenizer st = new StringTokenizer(p);
@ -823,6 +862,7 @@ public class ParameterParser
} }
} }
/** /**
* Gets the specified parameter from the request and validates it against the provided regular expression. * Gets the specified parameter from the request and validates it against the provided regular expression.
* If the regular expression check fails, the default value is returned instead. * If the regular expression check fails, the default value is returned instead.
@ -832,7 +872,8 @@ public class ParameterParser
*@param regexpattern The precompiled regular expression to be used to validate the parameter. *@param regexpattern The precompiled regular expression to be used to validate the parameter.
*@return The validated parameter value, or the default value if validation failed. *@return The validated parameter value, or the default value if validation failed.
*/ */
private String getRegexParameter(String name, String def, Pattern regexpattern) throws ValidationException private String getRegexParameter(String name, String def,
Pattern regexpattern) throws ValidationException
{ {
try try
{ {
@ -846,6 +887,7 @@ public class ParameterParser
} }
} }
/** /**
* Gets the specified parameter from the request and validates it against the provided regular expression. * Gets the specified parameter from the request and validates it against the provided regular expression.
* If the regular expression check fails, the default value is returned instead. * If the regular expression check fails, the default value is returned instead.
@ -872,7 +914,6 @@ public class ParameterParser
} }
public String getStrictAlphaParameter(String name, int maxLength) public String getStrictAlphaParameter(String name, int maxLength)
throws ParameterNotFoundException, ValidationException throws ParameterNotFoundException, ValidationException
{ {
@ -883,7 +924,6 @@ public class ParameterParser
} }
public String getStrictNumericParameter(String name, int maxLength) public String getStrictNumericParameter(String name, int maxLength)
throws ParameterNotFoundException, ValidationException throws ParameterNotFoundException, ValidationException
{ {
@ -893,95 +933,118 @@ public class ParameterParser
return getRegexParameter(name, numericPattern); return getRegexParameter(name, numericPattern);
} }
private static final String SSNREGEX = "^\\d{3}-\\d{2}-\\d{4}$"; private static final String SSNREGEX = "^\\d{3}-\\d{2}-\\d{4}$";
private static final Pattern Ssnpattern = Pattern.compile(SSNREGEX); private static final Pattern Ssnpattern = Pattern.compile(SSNREGEX);
public String getSsnParameter(String name) throws ParameterNotFoundException, ValidationException
public String getSsnParameter(String name)
throws ParameterNotFoundException, ValidationException
{ {
return getRegexParameter(name, Ssnpattern); return getRegexParameter(name, Ssnpattern);
} }
// Validates format for major brands of credit card. // Validates format for major brands of credit card.
//private static final String CCNREGEX = "^(?:(?<Visa>4\\d{3})|(?<Mastercard>5[1-5]\\d{2})|(?<Discover>6011)|(?<DinersClub>(?:3[68]\\d{2})|(?:30[0-5]\\d))|(?<AmericanExpress>3[47]\\d{2}))([ -]?)(?(DinersClub)(?:\\d{6}\\1\\d{4})|(?(AmericanExpress)(?:\\d{6}\\1\\d{5})|(?:\\d{4}\\1\\d{4}\\1\\d{4})))$"; //private static final String CCNREGEX = "^(?:(?<Visa>4\\d{3})|(?<Mastercard>5[1-5]\\d{2})|(?<Discover>6011)|(?<DinersClub>(?:3[68]\\d{2})|(?:30[0-5]\\d))|(?<AmericanExpress>3[47]\\d{2}))([ -]?)(?(DinersClub)(?:\\d{6}\\1\\d{4})|(?(AmericanExpress)(?:\\d{6}\\1\\d{5})|(?:\\d{4}\\1\\d{4}\\1\\d{4})))$";
private static final String CCNREGEX = "^\\d{16}$"; private static final String CCNREGEX = "^\\d{16}$";
private static final Pattern Ccnpattern = Pattern.compile(CCNREGEX); private static final Pattern Ccnpattern = Pattern.compile(CCNREGEX);
public String getCcnParameter(String name) throws ParameterNotFoundException, ValidationException
public String getCcnParameter(String name)
throws ParameterNotFoundException, ValidationException
{ {
return getRegexParameter(name, Ccnpattern); return getRegexParameter(name, Ccnpattern);
} }
private static final String ZIPREGEX = "^\\d{5}(-\\d{4})?$"; private static final String ZIPREGEX = "^\\d{5}(-\\d{4})?$";
private static final Pattern Zippattern = Pattern.compile(ZIPREGEX); private static final Pattern Zippattern = Pattern.compile(ZIPREGEX);
public String getZipParameter(String name) throws ParameterNotFoundException, ValidationException
public String getZipParameter(String name)
throws ParameterNotFoundException, ValidationException
{ {
return getZipParameter(name, null); return getZipParameter(name, null);
} }
public String getZipParameter(String name, String def) throws ValidationException
public String getZipParameter(String name, String def)
throws ValidationException
{ {
return getRegexParameter(name, def, Zippattern); return getRegexParameter(name, def, Zippattern);
} }
private static final String PHONEREGEX = "^\\(?[\\d]{3}\\)?[\\s-]?[\\d]{3}[\\s-]?[\\d]{4}$"; private static final String PHONEREGEX = "^\\(?[\\d]{3}\\)?[\\s-]?[\\d]{3}[\\s-]?[\\d]{4}$";
// Or this more forgiving pattern: // Or this more forgiving pattern:
//private static final String PHONEREGEX = "^([\\-()+ 0-9x])+$"; //private static final String PHONEREGEX = "^([\\-()+ 0-9x])+$";
private static final Pattern phonepattern = Pattern.compile(PHONEREGEX); private static final Pattern phonepattern = Pattern.compile(PHONEREGEX);
public String getPhoneParameter(String name) throws ParameterNotFoundException, ValidationException
public String getPhoneParameter(String name)
throws ParameterNotFoundException, ValidationException
{ {
return getPhoneParameter(name, null); return getPhoneParameter(name, null);
} }
public String getPhoneParameter(String name, String def) throws ValidationException
public String getPhoneParameter(String name, String def)
throws ValidationException
{ {
return getRegexParameter(name, def, phonepattern); return getRegexParameter(name, def, phonepattern);
} }
private static final String EMAILREGEX = "^[\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}$"; private static final String EMAILREGEX = "^[\\w-]+(?:\\.[\\w-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}$";
private static final Pattern emailpattern = Pattern.compile(EMAILREGEX); private static final Pattern emailpattern = Pattern.compile(EMAILREGEX);
public String getEMailParameter(String name) throws ParameterNotFoundException, ValidationException
public String getEMailParameter(String name)
throws ParameterNotFoundException, ValidationException
{ {
return getEMailParameter(name, null); return getEMailParameter(name, null);
} }
public String getEMailParameter(String name, String def) throws ValidationException
public String getEMailParameter(String name, String def)
throws ValidationException
{ {
return getRegexParameter(name, def, emailpattern); return getRegexParameter(name, def, emailpattern);
} }
private static final String DATEREGEX = "([\\/ .,:0-9a-zA-Z])+$"; private static final String DATEREGEX = "([\\/ .,:0-9a-zA-Z])+$";
private static final Pattern datepattern = Pattern.compile(DATEREGEX); private static final Pattern datepattern = Pattern.compile(DATEREGEX);
public String getDateParameter(String name) throws ParameterNotFoundException, ValidationException
public String getDateParameter(String name)
throws ParameterNotFoundException, ValidationException
{ {
return getDateParameter(name, null); return getDateParameter(name, null);
} }
public String getDateParameter(String name, String def) throws ValidationException
public String getDateParameter(String name, String def)
throws ValidationException
{ {
return getRegexParameter(name, def, datepattern); return getRegexParameter(name, def, datepattern);
} }
private static final String URLREGEX = "^(((https?)://)([-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$"; private static final String URLREGEX = "^(((https?)://)([-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$";
private static final Pattern URLpattern = Pattern.compile(URLREGEX); private static final Pattern URLpattern = Pattern.compile(URLREGEX);
public String getURLParameter(String name) throws ParameterNotFoundException, ValidationException
public String getURLParameter(String name)
throws ParameterNotFoundException, ValidationException
{ {
return getURLParameter(name, null); return getURLParameter(name, null);
} }
public String getURLParameter(String name, String def) throws ValidationException
public String getURLParameter(String name, String def)
throws ValidationException
{ {
return getRegexParameter(name, def, URLpattern); return getRegexParameter(name, def, URLpattern);
} }
@ -992,6 +1055,7 @@ public class ParameterParser
return HtmlEncoder.encode(s); return HtmlEncoder.encode(s);
} }
/** /**
* Description of the Method * Description of the Method
* *

View File

@ -13,35 +13,61 @@ import org.apache.ecs.html.IMG;
import org.apache.ecs.html.TD; import org.apache.ecs.html.TD;
import org.owasp.webgoat.lessons.AbstractLesson; import org.owasp.webgoat.lessons.AbstractLesson;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public abstract class Screen public abstract class Screen
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
public static int MAIN_SIZE = 375; public static int MAIN_SIZE = 375;
//private Head head; //private Head head;
private Element content; private Element content;
private LessonTracker lessonTracker; private LessonTracker lessonTracker;
final static IMG logo = new IMG( "images/aspectlogo-horizontal-small.jpg" ).setAlt( "Aspect Security" ).setBorder( 0 ).setHspace( 0 ).setVspace( 0 );
final static IMG logo = new IMG("images/aspectlogo-horizontal-small.jpg")
.setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0);
/** /**
* Constructor for the Screen object * Constructor for the Screen object
*/ */
public Screen() { } public Screen()
{}
// FIXME: Each lesson should have a role assigned to it. Each user/student // FIXME: Each lesson should have a role assigned to it. Each user/student
@ -52,6 +78,7 @@ public abstract class Screen
// see the admin screens, once they figure out how to turn the admin switch on. // see the admin screens, once they figure out how to turn the admin switch on.
public abstract String getRole(); public abstract String getRole();
/** /**
* Description of the Method * Description of the Method
* *
@ -62,7 +89,6 @@ public abstract class Screen
protected abstract Element createContent(WebSession s); protected abstract Element createContent(WebSession s);
/** /**
* Gets the credits attribute of the Screen object * Gets the credits attribute of the Screen object
* *
@ -101,7 +127,6 @@ public abstract class Screen
} }
/** /**
* Gets the lessonTracker attribute of the AbstractLesson object * Gets the lessonTracker attribute of the AbstractLesson object
* *
@ -115,6 +140,7 @@ public abstract class Screen
return userTracker.getLessonTracker(s, this); return userTracker.getLessonTracker(s, this);
} }
public LessonTracker getLessonTracker(WebSession s, String userNameOverride) public LessonTracker getLessonTracker(WebSession s, String userNameOverride)
{ {
UserTracker userTracker = UserTracker.instance(); UserTracker userTracker = UserTracker.instance();
@ -128,6 +154,7 @@ public abstract class Screen
return userTracker.getLessonTracker(s, lesson); return userTracker.getLessonTracker(s, lesson);
} }
/** /**
* Fill in a descriptive title for this lesson * Fill in a descriptive title for this lesson
* *
@ -141,6 +168,7 @@ public abstract class Screen
this.content = content; this.content = content;
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -153,11 +181,13 @@ public abstract class Screen
return new A("http://www.aspectsecurity.com/webgoat.html", logo); return new A("http://www.aspectsecurity.com/webgoat.html", logo);
} }
public String getSponsor() public String getSponsor()
{ {
return "Aspect Security"; return "Aspect Security";
} }
public String getSponsorLogoResource() public String getSponsorLogoResource()
{ {
return "images/aspectlogo-horizontal-small.jpg"; return "images/aspectlogo-horizontal-small.jpg";
@ -173,11 +203,11 @@ public abstract class Screen
protected TD makeMenuCategory_DELETE_ME(String text) protected TD makeMenuCategory_DELETE_ME(String text)
{ {
return ( new TD().setWidth( "100%" ).addElement( new Font().setColor( HtmlColor.WHITE ).addElement( new B().addElement( text ) ) ) ); return (new TD().setWidth("100%").addElement(new Font().setColor(
HtmlColor.WHITE).addElement(new B().addElement(text))));
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -204,7 +234,6 @@ public abstract class Screen
} }
/** /**
* Returns the content length of the the html. * Returns the content length of the the html.
* *
@ -233,6 +262,7 @@ public abstract class Screen
} }
public String getContent() public String getContent()
{ {
return (content == null) ? "" : content.toString(); return (content == null) ? "" : content.toString();
@ -290,18 +320,21 @@ public abstract class Screen
* length checking and only do "&nbsp" conversion in lines that won't exceed * length checking and only do "&nbsp" conversion in lines that won't exceed
* screen size, say less than 80 characters. * screen size, say less than 80 characters.
*/ */
String[] metaChar = {"&", "<", ">", "\"", "\t", System.getProperty("line.separator")}; String[] metaChar = { "&", "<", ">", "\"", "\t",
System.getProperty("line.separator") };
String[] htmlCode = { "&amp;", "&lt;", "&gt;", "&quot;", " ", "<br>" }; String[] htmlCode = { "&amp;", "&lt;", "&gt;", "&quot;", " ", "<br>" };
String replacedString = token; String replacedString = token;
for (; mci < metaChar.length; mci += 1) for (; mci < metaChar.length; mci += 1)
{ {
replacedString = replacedString.replaceAll( metaChar[mci], htmlCode[mci] ); replacedString = replacedString.replaceAll(metaChar[mci],
htmlCode[mci]);
} }
return (replacedString); return (replacedString);
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -313,7 +346,6 @@ public abstract class Screen
return (convertMetachars(token).replaceAll(" ", "&nbsp;")); return (convertMetachars(token).replaceAll(" ", "&nbsp;"));
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -322,7 +354,4 @@ public abstract class Screen
*/ */
//protected abstract Element wrapForm( WebSession s ); //protected abstract Element wrapForm( WebSession s );
} }

View File

@ -1,5 +1,34 @@
package org.owasp.webgoat.session; package org.owasp.webgoat.session;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class UnauthenticatedException extends Exception public class UnauthenticatedException extends Exception
{ {

View File

@ -1,5 +1,34 @@
package org.owasp.webgoat.session; package org.owasp.webgoat.session;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class UnauthorizedException extends Exception public class UnauthorizedException extends Exception
{ {

View File

@ -9,11 +9,35 @@ import java.util.Map;
import org.apache.catalina.Role; import org.apache.catalina.Role;
import org.apache.catalina.User; import org.apache.catalina.User;
import org.apache.catalina.users.MemoryUserDatabase; import org.apache.catalina.users.MemoryUserDatabase;
/**
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web /*******************************************************************************
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP *
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute *
* this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a> * @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 29, 2003 * @created October 29, 2003
@ -34,8 +58,8 @@ public class UserTracker
/** /**
* Constructor for the UserTracker object * Constructor for the UserTracker object
*/ */
private UserTracker() { } private UserTracker()
{}
/** /**
@ -81,11 +105,14 @@ public class UserTracker
return storage.keySet(); return storage.keySet();
} }
public Collection getAllUsers(String roleName) public Collection getAllUsers(String roleName)
{ {
synchronized ( usersDB ) { synchronized (usersDB)
{
Collection allUsers = new ArrayList(); Collection allUsers = new ArrayList();
try { try
{
usersDB.open(); usersDB.open();
Iterator users = usersDB.getUsers(); Iterator users = usersDB.getUsers();
while (users.hasNext()) while (users.hasNext())
@ -109,9 +136,11 @@ public class UserTracker
} }
} }
public void deleteUser(String user) public void deleteUser(String user)
{ {
synchronized ( usersDB ) { synchronized (usersDB)
{
try try
{ {
usersDB.open(); usersDB.open();
@ -134,6 +163,7 @@ public class UserTracker
} }
} }
/** /**
* Gets the lessonTracker attribute of the UserTracker object * Gets the lessonTracker attribute of the UserTracker object
* *
@ -146,7 +176,9 @@ public class UserTracker
return getLessonTracker(s, s.getUserName(), screen); return getLessonTracker(s, s.getUserName(), screen);
} }
public LessonTracker getLessonTracker( WebSession s, String user, Screen screen )
public LessonTracker getLessonTracker(WebSession s, String user,
Screen screen)
{ {
HashMap usermap = getUserMap(user); HashMap usermap = getUserMap(user);
LessonTracker tracker = (LessonTracker) usermap.get(screen.getTitle()); LessonTracker tracker = (LessonTracker) usermap.get(screen.getTitle());
@ -170,11 +202,12 @@ public class UserTracker
*/ */
public String getStatus(WebSession s, Screen screen) public String getStatus(WebSession s, Screen screen)
{ {
return ( "User [" + s.getUserName() + "] has accessed " + screen + " UserTracker:getStatus()LTH = " + getLessonTracker( s, screen ).hashCode() ); return ("User [" + s.getUserName() + "] has accessed " + screen
+ " UserTracker:getStatus()LTH = " + getLessonTracker(s, screen)
.hashCode());
} }
/** /**
* Gets the userMap attribute of the UserTracker object * Gets the userMap attribute of the UserTracker object
* *
@ -199,7 +232,6 @@ public class UserTracker
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -219,7 +251,6 @@ public class UserTracker
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -240,4 +271,3 @@ public class UserTracker
} }
} }

View File

@ -1,12 +1,43 @@
package org.owasp.webgoat.session; package org.owasp.webgoat.session;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ValidationException extends Exception public class ValidationException extends Exception
{ {
public ValidationException() public ValidationException()
{ {
super(); super();
} }
public ValidationException(String message) public ValidationException(String message)
{ {
super(message); super(message);

View File

@ -25,13 +25,38 @@ import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category; import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.admin.RefreshDBScreen; import org.owasp.webgoat.lessons.admin.RefreshDBScreen;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is *
* published by OWASP under the GPL. You should read and accept the LICENSE before you use, modify * This file is part of WebGoat, an Open Web Application Security Project
* and/or redistribute this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
*
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class WebSession public class WebSession

View File

@ -4,8 +4,38 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Properties; import java.util.Properties;
/*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
*
* Copyright (c) 2002 - 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class WebgoatProperties extends Properties public class WebgoatProperties extends Properties
{ {
public WebgoatProperties(String propertiesFileName) throws IOException public WebgoatProperties(String propertiesFileName) throws IOException
{ {
try try
@ -15,10 +45,12 @@ public class WebgoatProperties extends Properties
} }
catch (IOException e) catch (IOException e)
{ {
System.out.println("Warning: Unable to open webgoat.properties file"); System.out
.println("Warning: Unable to open webgoat.properties file");
} }
} }
public int getIntProperty(String key, int defaultValue) public int getIntProperty(String key, int defaultValue)
{ {
int value = defaultValue; int value = defaultValue;
@ -32,6 +64,7 @@ public class WebgoatProperties extends Properties
return value; return value;
} }
public boolean getBooleanProperty(String key, boolean defaultValue) public boolean getBooleanProperty(String key, boolean defaultValue)
{ {
boolean value = defaultValue; boolean value = defaultValue;
@ -57,13 +90,15 @@ public class WebgoatProperties extends Properties
return value; return value;
} }
private String trimLesson(String lesson) private String trimLesson(String lesson)
{ {
String result = ""; String result = "";
if (lesson.startsWith("org.owasp.webgoat.lessons.")) if (lesson.startsWith("org.owasp.webgoat.lessons."))
{ {
result = lesson.substring("org.owasp.webgoat.lessons.".length(), lesson.length()); result = lesson.substring("org.owasp.webgoat.lessons.".length(),
lesson.length());
} }
else else
{ {
@ -73,6 +108,7 @@ public class WebgoatProperties extends Properties
return result; return result;
} }
public static void main(String[] args) public static void main(String[] args)
{ {
WebgoatProperties properties = null; WebgoatProperties properties = null;

View File

@ -6,18 +6,41 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.BitSet; import java.util.BitSet;
/*******************************************************************************
/** *
* Copyright (c) 2002 Free Software Foundation developed under the custody of the Open Web *
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * This file is part of WebGoat, an Open Web Application Security Project
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * utility. For details, please see http://www.owasp.org/
* this software. *
* 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @created October 28, 2003 * @created October 28, 2003
*/ */
public class Exec public class Exec
{ {
/** /**
* Description of the Method * Description of the Method
* *
@ -62,12 +85,14 @@ public class Exec
* @param lazy Description of the Parameter * @param lazy Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static ExecResults execOptions( String[] command, String input, int successCode, int timeout, boolean lazy ) public static ExecResults execOptions(String[] command, String input,
int successCode, int timeout, boolean lazy)
{ {
Process child = null; Process child = null;
ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream(); ByteArrayOutputStream errors = new ByteArrayOutputStream();
ExecResults results = new ExecResults( command[0], input, successCode, timeout ); ExecResults results = new ExecResults(command[0], input, successCode,
timeout);
BitSet interrupted = new BitSet(1); BitSet interrupted = new BitSet(1);
boolean lazyQuit = false; boolean lazyQuit = false;
ThreadWatcher watcher; ThreadWatcher watcher;
@ -249,12 +274,14 @@ public class Exec
* @param lazy Description of the Parameter * @param lazy Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public static ExecResults execOptions( String command, String input, int successCode, int timeout, boolean lazy ) public static ExecResults execOptions(String command, String input,
int successCode, int timeout, boolean lazy)
{ {
Process child = null; Process child = null;
ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errors = new ByteArrayOutputStream(); ByteArrayOutputStream errors = new ByteArrayOutputStream();
ExecResults results = new ExecResults( command, input, successCode, timeout ); ExecResults results = new ExecResults(command, input, successCode,
timeout);
BitSet interrupted = new BitSet(1); BitSet interrupted = new BitSet(1);
boolean lazyQuit = false; boolean lazyQuit = false;
ThreadWatcher watcher; ThreadWatcher watcher;
@ -476,10 +503,12 @@ public class Exec
{ {
ExecResults results; ExecResults results;
String sep = System.getProperty("line.separator"); String sep = System.getProperty("line.separator");
System.out.println( "-------------------------------------------" + sep + "TEST 1: execSimple" ); System.out.println("-------------------------------------------" + sep
+ "TEST 1: execSimple");
results = Exec.execSimple("c:/swarm-2.1.1/bin/whoami.exe"); results = Exec.execSimple("c:/swarm-2.1.1/bin/whoami.exe");
System.out.println(results); System.out.println(results);
System.out.println( "-------------------------------------------" + sep + "TEST 2: execSimple (with search)" ); System.out.println("-------------------------------------------" + sep
+ "TEST 2: execSimple (with search)");
results = Exec.execSimple("netstat -r"); results = Exec.execSimple("netstat -r");
System.out.println(results); System.out.println(results);
@ -488,21 +517,26 @@ public class Exec
System.out.println("ERROR: listening on 1031"); System.out.println("ERROR: listening on 1031");
} }
System.out.println( "-------------------------------------------" + sep + "TEST 3: execInput" ); System.out.println("-------------------------------------------" + sep
results = Exec.execInput( "find \"cde\"", "abcdefg1\nhijklmnop\nqrstuv\nabcdefg2" ); + "TEST 3: execInput");
results = Exec.execInput("find \"cde\"",
"abcdefg1\nhijklmnop\nqrstuv\nabcdefg2");
System.out.println(results); System.out.println(results);
System.out.println( "-------------------------------------------" + sep + "TEST 4:execTimeout" ); System.out.println("-------------------------------------------" + sep
+ "TEST 4:execTimeout");
results = Exec.execTimeout("ping -t 127.0.0.1", 5 * 1000); results = Exec.execTimeout("ping -t 127.0.0.1", 5 * 1000);
System.out.println(results); System.out.println(results);
System.out.println( "-------------------------------------------" + sep + "TEST 5:execLazy" ); System.out.println("-------------------------------------------" + sep
+ "TEST 5:execLazy");
results = Exec.execLazy("ping -t 127.0.0.1"); results = Exec.execLazy("ping -t 127.0.0.1");
System.out.println(results); System.out.println(results);
System.out.println( "-------------------------------------------" + sep + "TEST 6:ExecTimeout process never outputs" ); System.out.println("-------------------------------------------" + sep
+ "TEST 6:ExecTimeout process never outputs");
results = Exec.execTimeout("c:/swarm-2.1.1/bin/sleep.exe 20", 5 * 1000); results = Exec.execTimeout("c:/swarm-2.1.1/bin/sleep.exe 20", 5 * 1000);
System.out.println(results); System.out.println(results);
System.out.println( "-------------------------------------------" + sep + "TEST 7:ExecTimeout process waits for input" ); System.out.println("-------------------------------------------" + sep
+ "TEST 7:ExecTimeout process waits for input");
results = Exec.execTimeout("c:/swarm-2.1.1/bin/cat", 5 * 1000); results = Exec.execTimeout("c:/swarm-2.1.1/bin/cat", 5 * 1000);
System.out.println(results); System.out.println(results);
} }
} }

View File

@ -1,15 +1,39 @@
package org.owasp.webgoat.util; package org.owasp.webgoat.util;
/** /*******************************************************************************
* Copyright (c) 2002 Free Software Foundation developed under the custody of *
* the Open Web Application Security Project (http://www.owasp.org) This *
* software package org.owasp.webgoat.is published by OWASP under the GPL. You should read and * This file is part of WebGoat, an Open Web Application Security Project
* accept the LICENSE before you use, modify and/or redistribute this software. * 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 distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
*
* For details, please see http://code.google.com/p/webgoat/
* *
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a> * @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
*/ */
public class ExecResults public class ExecResults
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
@ -19,18 +43,30 @@ public class ExecResults
* Description of the Field * Description of the Field
*/ */
public final static int THROWABLE = 1; public final static int THROWABLE = 1;
private String myCommand; private String myCommand;
private boolean myError = false; private boolean myError = false;
private int myErrorType = 0; private int myErrorType = 0;
private String myErrors = null; private String myErrors = null;
private String myInput; private String myInput;
private boolean myInterrupted = false; private boolean myInterrupted = false;
private String myOutput = null; private String myOutput = null;
private int myReturnCode = 0; private int myReturnCode = 0;
private int mySuccessCode; private int mySuccessCode;
private Throwable myThrowable = null; private Throwable myThrowable = null;
private int myTimeout; private int myTimeout;
/** /**
* Constructor for the ExecResults object * Constructor for the ExecResults object
* *
@ -39,7 +75,8 @@ public class ExecResults
*@param successCode Description of the Parameter *@param successCode Description of the Parameter
*@param timeout Description of the Parameter *@param timeout Description of the Parameter
*/ */
public ExecResults(String command, String input, int successCode, int timeout) public ExecResults(String command, String input, int successCode,
int timeout)
{ {
myCommand = command.trim(); myCommand = command.trim();
myInput = input.trim(); myInput = input.trim();
@ -47,6 +84,7 @@ public class ExecResults
myTimeout = timeout; myTimeout = timeout;
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -57,7 +95,8 @@ public class ExecResults
*/ */
private boolean contains(String haystack, String needle, int fromIndex) private boolean contains(String haystack, String needle, int fromIndex)
{ {
return (haystack.trim().toLowerCase().indexOf(needle.trim().toLowerCase(), fromIndex) != -1); return (haystack.trim().toLowerCase().indexOf(
needle.trim().toLowerCase(), fromIndex) != -1);
} }
@ -305,7 +344,8 @@ public class ExecResults
if (myInterrupted) if (myInterrupted)
{ {
value.append("Command timed out after " + (myTimeout / 1000) + " seconds " + sep); value.append("Command timed out after " + (myTimeout / 1000)
+ " seconds " + sep);
} }
value.append("Returncode: " + myReturnCode + sep); value.append("Returncode: " + myReturnCode + sep);

Some files were not shown because too many files have changed in this diff Show More