From 05c0c0342ededd9b749de5741636b2b6c4fe3c46 Mon Sep 17 00:00:00 2001 From: David Touzet Date: Fri, 26 Sep 2014 08:12:44 -0400 Subject: [PATCH] Internationalization refactoring pass 2 : removing dependencies to previous implentation --- .../owasp/webgoat/lessons/AbstractLesson.java | 1606 ++++++------- .../webgoat/lessons/BasicAuthentication.java | 45 +- .../lessons/BypassHtmlFieldRestrictions.java | 14 +- .../webgoat/lessons/CommandInjection.java | 23 +- .../webgoat/lessons/HiddenFieldTampering.java | 29 +- .../org/owasp/webgoat/lessons/HtmlClues.java | 23 +- .../org/owasp/webgoat/lessons/HttpBasics.java | 6 +- .../webgoat/lessons/JavaScriptValidation.java | 37 +- .../owasp/webgoat/lessons/LessonAdapter.java | 3 +- .../owasp/webgoat/lessons/LogSpoofing.java | 17 +- .../lessons/PathBasedAccessControl.java | 51 +- .../owasp/webgoat/lessons/ReflectedXSS.java | 35 +- .../webgoat/lessons/RemoteAdminFlaw.java | 11 +- .../org/owasp/webgoat/lessons/SqlAddData.java | 19 +- .../owasp/webgoat/lessons/SqlModifyData.java | 19 +- .../webgoat/lessons/SqlNumericInjection.java | 25 +- .../webgoat/lessons/SqlStringInjection.java | 25 +- .../org/owasp/webgoat/lessons/StoredXss.java | 33 +- .../lessons/WeakAuthenticationCookie.java | 39 +- .../org/owasp/webgoat/session/Course.java | 795 ++++--- .../org/owasp/webgoat/session/WebSession.java | 2091 +++++++++-------- .../owasp/webgoat/session/WebgoatContext.java | 447 ++-- .../org/owasp/webgoat/util/BeanProvider.java | 63 + .../org/owasp/webgoat/util/LabelManager.java | 41 + .../owasp/webgoat/util/LabelManagerImpl.java | 61 + .../org/owasp/webgoat/util/LabelProvider.java | 67 + .../org/owasp/webgoat/util/WebGoatI18N.java | 67 +- ...sh.properties => WebGoatLabels.properties} | 0 ...properties => WebGoatLabels_de.properties} | 0 .../resources/WebGoatLabels_fr.properties | 222 ++ ...properties => WebGoatLabels_ru.properties} | 0 .../webapp/WEB-INF/mvc-dispatcher-servlet.xml | 116 +- src/main/webapp/WEB-INF/web.xml | 582 ++--- src/main/webapp/main.jsp | 589 ++--- 34 files changed, 3829 insertions(+), 3372 deletions(-) create mode 100644 src/main/java/org/owasp/webgoat/util/BeanProvider.java create mode 100644 src/main/java/org/owasp/webgoat/util/LabelManager.java create mode 100644 src/main/java/org/owasp/webgoat/util/LabelManagerImpl.java create mode 100644 src/main/java/org/owasp/webgoat/util/LabelProvider.java rename src/main/resources/{WebGoatLabels_english.properties => WebGoatLabels.properties} (100%) rename src/main/resources/{WebGoatLabels_german.properties => WebGoatLabels_de.properties} (100%) create mode 100644 src/main/resources/WebGoatLabels_fr.properties rename src/main/resources/{WebGoatLabels_russian.properties => WebGoatLabels_ru.properties} (100%) diff --git a/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java b/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java index 07e556bb3..e689f7d1f 100644 --- a/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java +++ b/src/main/java/org/owasp/webgoat/lessons/AbstractLesson.java @@ -1,798 +1,808 @@ -package org.owasp.webgoat.lessons; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.ecs.Element; -import org.apache.ecs.ElementContainer; -import org.apache.ecs.StringElement; -import org.apache.ecs.html.Body; -import org.apache.ecs.html.Form; -import org.apache.ecs.html.Head; -import org.apache.ecs.html.Html; -import org.apache.ecs.html.IMG; -import org.apache.ecs.html.PRE; -import org.apache.ecs.html.Title; -import org.owasp.webgoat.session.ParameterNotFoundException; -import org.owasp.webgoat.session.Screen; -import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.session.WebgoatContext; -import org.owasp.webgoat.session.WebgoatProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ************************************************************************************************* - * - * - * This file is part of WebGoat, an Open Web Application Security Project - * utility. For details, please see http://www.owasp.org/ - * - * Copyright (c) 2002 - 20014 Bruce Mayhew - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; either version 2 of the License, or (at your option) any later - * version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place - Suite 330, Boston, MA 02111-1307, USA. - * - * Getting Source ============== - * - * Source for this application is maintained at - * https://github.com/WebGoat/WebGoat, a repository for free software projects. - * - * For details, please see http://webgoat.github.io - * - * @author Bruce Mayhew WebGoat - * @created October 28, 2003 - */ -public abstract class AbstractLesson extends Screen implements Comparable { - - private static final Logger logger = LoggerFactory.getLogger(AbstractLesson.class); - - /** - * Description of the Field - */ - public final static String ADMIN_ROLE = "admin"; - - public final static String CHALLENGE_ROLE = "challenge"; - - /** - * Description of the Field - */ - public final static String HACKED_ADMIN_ROLE = "hacked_admin"; - - /** - * Description of the Field - */ - public final static String USER_ROLE = "user"; - - private static int count = 1; - - private Integer id = null; - - final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next").setBorder(0).setHspace(0).setVspace(0); - - final static IMG previousGrey = new IMG("images/left14.gif").setAlt("Previous").setBorder(0).setHspace(0) - .setVspace(0); - - private Integer ranking; - - private Category category; - - private boolean hidden; - - private String sourceFileName; - - private Map lessonPlanFileName = new HashMap(); - - private String lessonSolutionFileName; - - private WebgoatContext webgoatContext; - - private LinkedList availableLanguages = new LinkedList(); - - private String defaultLanguage = "en"; - - /** - * Constructor for the Lesson object - */ - public AbstractLesson() { - id = new Integer(++count); - } - - public String getName() { - String className = getClass().getName(); - return className.substring(className.lastIndexOf('.') + 1); - } - - public void setRanking(Integer ranking) { - this.ranking = ranking; - } - - public void setHidden(boolean hidden) { - this.hidden = hidden; - } - - public void update(WebgoatProperties properties) { - String className = getClass().getName(); - className = className.substring(className.lastIndexOf(".") + 1); - setRanking(new Integer(properties.getIntProperty("lesson." + className + ".ranking", getDefaultRanking() - .intValue()))); - String categoryRankingKey = "category." + getDefaultCategory().getName() + ".ranking"; - // System.out.println("Category ranking key: " + categoryRankingKey); - Category tempCategory = Category.getCategory(getDefaultCategory().getName()); - tempCategory.setRanking(new Integer(properties.getIntProperty(categoryRankingKey, getDefaultCategory() - .getRanking().intValue()))); - category = tempCategory; - setHidden(properties.getBooleanProperty("lesson." + className + ".hidden", getDefaultHidden())); - // System.out.println(className + " in " + tempCategory.getName() + " - // (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking: - // " + getRanking() + ", hidden:" + hidden +")"); - } - - public boolean isCompleted(WebSession s) { - return getLessonTracker(s, this).getCompleted(); - } - - /** - * Gets the credits attribute of the AbstractLesson object - * - * @return The credits value - */ - public abstract Element getCredits(); - - /** - * Description of the Method - * - * @param obj Description of the Parameter - * @return Description of the Return Value - */ - public int compareTo(Object obj) { - return this.getRanking().compareTo(((AbstractLesson) obj).getRanking()); - } - - /** - * Description of the Method - * - * @param obj Description of the Parameter - * @return Description of the Return Value - */ - public boolean equals(Object obj) { - return this.getScreenId() == ((AbstractLesson) obj).getScreenId(); - } - - /** - * Gets the category attribute of the Lesson object - * - * @return The category value - */ - public Category getCategory() { - return category; - } - - protected abstract Integer getDefaultRanking(); - - protected abstract Category getDefaultCategory(); - - protected abstract boolean getDefaultHidden(); - - /** - * Gets the fileMethod attribute of the Lesson class - * - * @param reader Description of the Parameter - * @param methodName Description of the Parameter - * @param numbers Description of the Parameter - * @return The fileMethod value - */ - public static String getFileMethod(BufferedReader reader, String methodName, boolean numbers) { - int count = 0; - StringBuffer sb = new StringBuffer(); - boolean echo = false; - boolean startCount = false; - int parenCount = 0; - - try { - String line; - - while ((line = reader.readLine()) != null) { - if ((line.indexOf(methodName) != -1) - && ((line.indexOf("public") != -1) || (line.indexOf("protected") != -1) || (line - .indexOf("private") != -1))) { - echo = true; - startCount = true; - } - - if (echo && startCount) { - if (numbers) { - sb.append(pad(++count) + " "); - } - - sb.append(line + "\n"); - } - - if (echo && (line.indexOf("{") != -1)) { - parenCount++; - } - - if (echo && (line.indexOf("}") != -1)) { - parenCount--; - - if (parenCount == 0) { - startCount = false; - echo = false; - } - } - } - - reader.close(); - } catch (Exception e) { - System.out.println(e); - e.printStackTrace(); - } - - return (sb.toString()); - } - - /** - * Reads text from a file into an ElementContainer. Each line in the file is - * represented in the ElementContainer by a StringElement. Each - * StringElement is appended with a new-line character. - * - * @param reader Description of the Parameter - * @param numbers Description of the Parameter - * @return Description of the Return Value - */ - public static String readFromFile(BufferedReader reader, boolean numbers) { - return (getFileText(reader, numbers)); - } - - /** - * Gets the fileText attribute of the Screen class - * - * @param reader Description of the Parameter - * @param numbers Description of the Parameter - * @return The fileText value - */ - public static String getFileText(BufferedReader reader, boolean numbers) { - int count = 0; - StringBuffer sb = new StringBuffer(); - - try { - String line; - - while ((line = reader.readLine()) != null) { - if (numbers) { - sb.append(pad(++count) + " "); - } - sb.append(line + System.getProperty("line.separator")); - } - - reader.close(); - } catch (Exception e) { - System.out.println(e); - e.printStackTrace(); - } - - return (sb.toString()); - } - - /** - * Will this screen be included in an enterprise edition. - * - * @return The ranking value - */ - public boolean isEnterprise() { - return false; - } - - /** - * Gets the hintCount attribute of the Lesson object - * - * @param s The user's WebSession - * - * @return The hintCount value - */ - public int getHintCount(WebSession s) { - return getHints(s).size(); - } - - protected abstract List getHints(WebSession s); - - // @TODO we need to restrict access at the service layer - // rather than passing session object around - public List getHintsPublic(WebSession s) { - List hints = getHints(s); - return hints; - } - - /** - * Fill in a minor hint that will help people who basically get it, but are - * stuck on somthing silly. - * - * @param s The users WebSession - * - * @return The hint1 value - */ - public String getHint(WebSession s, int hintNumber) { - return "Hint: " + getHints(s).get(hintNumber); - } - - /** - * Gets the instructions attribute of the AbstractLesson object - * - * @return The instructions value - */ - public abstract String getInstructions(WebSession s); - - /** - * Gets the lessonPlan attribute of the Lesson object - * - * @return The lessonPlan value - */ - protected String getLessonName() { - int index = this.getClass().getName().indexOf("lessons."); - return this.getClass().getName().substring(index + "lessons.".length()); - } - - /** - * Gets the title attribute of the HelloScreen object - * - * @return The title value - */ - public abstract String getTitle(); - - /** - * Gets the content of lessonPlanURL - * - * @param s The user's WebSession - * - * @return The HTML content of the current lesson plan - */ - public String getLessonPlan(WebSession s) { - StringBuffer src = new StringBuffer(); - String lang = s.getCurrrentLanguage(); - - try { - // System.out.println("Loading lesson plan file: " + - // getLessonPlanFileName()); - String filename = getLessonPlanFileName(lang); - if (filename == null) { - filename = getLessonPlanFileName(getDefaultLanguage()); - - } - - src.append(readFromFile(new BufferedReader(new FileReader(s.getWebResource(filename))), false)); - - } catch (Exception e) { - // s.setMessage( "Could not find lesson plan for " + - // getLessonName()); - src = new StringBuffer("Could not find lesson plan for: " + getLessonName() + " and language " + lang); - - } - return src.toString(); - } - - /** - * Gets the ranking attribute of the Lesson object - * - * @return The ranking value - */ - public Integer getRanking() { - if (ranking != null) { - return ranking; - } else { - return getDefaultRanking(); - } - } - - /** - * Gets the hidden value of the Lesson Object - * - * @return The hidden value - */ - public boolean getHidden() { - return this.hidden; - } - - /** - * Gets the role attribute of the AbstractLesson object - * - * @return The role value - */ - public String getRole() { - // FIXME: Each lesson should have a role assigned to it. Each - // user/student - // should also have a role(s) assigned. The user would only be allowed - // to see lessons that correspond to their role. Eventually these roles - // will be stored in the internal database. The user will be able to - // hack - // into the database and change their role. This will allow the user to - // see the admin screens, once they figure out how to turn the admin - // switch on. - return USER_ROLE; - } - - /** - * Gets the uniqueID attribute of the AbstractLesson object - * - * @return The uniqueID value - */ - public int getScreenId() { - return id.intValue(); - } - - public String getHtml_DELETE_ME(WebSession s) { - String html = null; - - // FIXME: This doesn't work for the labs since they do not implement - // createContent(). - String rawHtml = createContent(s).toString(); - // System.out.println("Getting raw html content: " + - // rawHtml.substring(0, Math.min(rawHtml.length(), 100))); - html = convertMetachars(AbstractLesson.readFromFile(new BufferedReader(new StringReader(rawHtml)), true)); - // System.out.println("Getting encoded html content: " + - // html.substring(0, Math.min(html.length(), 100))); - - return html; - } - - public String getSource(WebSession s) { - String source = null; - String src = null; - - try { - // System.out.println("Loading source file: " + - // getSourceFileName()); - src = convertMetacharsJavaCode(readFromFile(new BufferedReader(new FileReader(s - .getWebResource(getSourceFileName()))), true)); - - // TODO: For styled line numbers and better memory efficiency, - // use a custom FilterReader - // that performs the convertMetacharsJavaCode() transform plus - // optionally adds a styled - // line number. Wouldn't color syntax be great too? - } catch (Exception e) { - s.setMessage("Could not find source file"); - src = ("Could not find the source file or source file does not exist.
" - + "Send this message to: " + s.getWebgoatContext().getFeedbackAddress() + ""); - } - - Html html = new Html(); - - Head head = new Head(); - head.addElement(new Title(getSourceFileName())); - - Body body = new Body(); - body.addElement(new StringElement(src)); - - html.addElement(head); - html.addElement(body); - - source = html.toString(); - - return source; - } - - public String getRawSource(WebSession s) { - String src; - - try { - logger.debug("Loading source file: " + getSourceFileName()); - src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getSourceFileName()))), false); - - } catch (FileNotFoundException e) { - s.setMessage("Could not find source file"); - src = ("Could not find the source file or source file does not exist.
" - + "Send this message to: " + s.getWebgoatContext().getFeedbackAddress() + ""); - } - - return src; - } - - public String getSolution(WebSession s) { - String src = null; - - try { - // System.out.println("Solution: " + getLessonSolutionFileName()); - src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName()))), false); - } catch (Exception e) { - s.setMessage("Could not find the solution file"); - src = ("Could not find the solution file or solution file does not exist.
" - + "Send this message to: " + s.getWebgoatContext().getFeedbackAddress() + ""); - } - - // Solutions are html files - return src; - } - - /** - *

- * Returns the default "path" portion of a lesson's URL.

- * - *

- * Legacy webgoat lesson links are of the form - * "attack?Screen=Xmenu=Ystage=Z". This method returns the path portion of - * the url, i.e., "attack" in the string above.

- * - *

- * Newer, Spring-Controller-based classes will override this method to - * return "*.do"-styled paths.

- */ - protected String getPath() { - return "attack"; - } - - /** - * Get the link that can be used to request this screen. - * - * @return - */ - public String getLink() { - StringBuffer link = new StringBuffer(); - - // mvc update: - link.append(getPath()).append("?"); - link.append(WebSession.SCREEN); - link.append("="); - link.append(getScreenId()); - link.append("&"); - link.append(WebSession.MENU); - link.append("="); - link.append(getCategory().getRanking()); - return link.toString(); - } - - /** - * Get the link to the jsp page used to render this screen. - * - * @return - */ - public String getPage(WebSession s) { - return null; - } - - /** - * Get the link to the jsp template page used to render this screen. - * - * @return - */ - public String getTemplatePage(WebSession s) { - return null; - } - - public abstract String getCurrentAction(WebSession s); - - public abstract void setCurrentAction(WebSession s, String lessonScreen); - - /** - * Override this method to implement accesss control in a lesson. - * - * @param s - * @param functionId - * @return - */ - public boolean isAuthorized(WebSession s, int employeeId, String functionId) { - return false; - } - - /** - * Override this method to implement accesss control in a lesson. - * - * @param s - * @param functionId - * @return - */ - public boolean isAuthorized(WebSession s, String role, String functionId) { - logger.info("Checking if " + role + " authorized for: " + functionId); - boolean authorized = false; - try { - String query = "SELECT * FROM auth WHERE role = '" + role + "' and functionid = '" + functionId + "'"; - try { - Statement answer_statement = WebSession.getConnection(s) - .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - ResultSet answer_results = answer_statement.executeQuery(query); - authorized = answer_results.first(); - logger.info("authorized: "+ authorized); - } catch (SQLException sqle) { - s.setMessage("Error authorizing"); - logger.error("Error authorizing", sqle); - } - } catch (Exception e) { - s.setMessage("Error authorizing"); - logger.error("Error authorizing", e); - } - return authorized; - } - - public int getUserId(WebSession s) throws ParameterNotFoundException { - return -1; - } - - public String getUserName(WebSession s) throws ParameterNotFoundException { - return null; - } - - /** - * Description of the Method - * - * @param windowName Description of the Parameter - * @return Description of the Return Value - */ - public static String makeWindowScript(String windowName) { - // FIXME: make this string static - StringBuffer script = new StringBuffer(); - script.append("\n"); - - return script.toString(); - } - - /** - * Simply reads a url into an Element for display. CAUTION: you might want - * to tinker with any non-https links (href) - * - * @param url Description of the Parameter - * @return Description of the Return Value - */ - public static Element readFromURL(String url) { - ElementContainer ec = new ElementContainer(); - - try { - URL u = new URL(url); - HttpURLConnection huc = (HttpURLConnection) u.openConnection(); - BufferedReader reader = new BufferedReader(new InputStreamReader(huc.getInputStream())); - String line; - - while ((line = reader.readLine()) != null) { - ec.addElement(new StringElement(line)); - } - - reader.close(); - } catch (Exception e) { - System.out.println(e); - e.printStackTrace(); - } - - return (ec); - } - - /** - * Description of the Method - * - * @param reader Description of the Parameter - * @param numbers Description of the Parameter - * @param methodName Description of the Parameter - * @return Description of the Return Value - */ - public static Element readMethodFromFile(BufferedReader reader, String methodName, boolean numbers) { - PRE pre = new PRE().addElement(getFileMethod(reader, methodName, numbers)); - - return (pre); - } - - /** - * Description of the Method - * - * @param s Description of the Parameter - */ - public void handleRequest(WebSession s) { - // call createContent first so messages will go somewhere - Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); - form.addElement(createContent(s)); - setContent(form); - } - - public String getFormAction() { - return getLink(); - } - - /** - * Description of the Method - * - * @param s Description of the Parameter - * @return Description of the Return Value - */ - public String toString() { - return getTitle(); - } - - public String getDefaultLanguage() { - return this.defaultLanguage; - } - - public String getLessonPlanFileName(String lang) { - String ret = lessonPlanFileName.get(lang); - if (ret == null) { - ret = lessonPlanFileName.get(getDefaultLanguage()); - } - return ret; - } - - public void setLessonPlanFileName(String lang, String lessonPlanFileName) { - this.lessonPlanFileName.put(lang, lessonPlanFileName); - this.availableLanguages.add(lang); - } - - public List getAvailableLanguages() { - return this.availableLanguages; - } - - public String getLessonSolutionFileName() { - return lessonSolutionFileName; - } - - public void setLessonSolutionFileName(String lessonSolutionFileName) { - this.lessonSolutionFileName = lessonSolutionFileName; - } - - public String getSourceFileName() { - return sourceFileName; - } - - public void setSourceFileName(String sourceFileName) { - logger.debug("Setting source file of lesson " + this + " to: " + sourceFileName); - this.sourceFileName = sourceFileName; - } - - public WebgoatContext getWebgoatContext() { - return webgoatContext; - } - - public void setWebgoatContext(WebgoatContext webgoatContext) { - this.webgoatContext = webgoatContext; - } -} +package org.owasp.webgoat.lessons; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import org.apache.ecs.Element; +import org.apache.ecs.ElementContainer; +import org.apache.ecs.StringElement; +import org.apache.ecs.html.Body; +import org.apache.ecs.html.Form; +import org.apache.ecs.html.Head; +import org.apache.ecs.html.Html; +import org.apache.ecs.html.IMG; +import org.apache.ecs.html.PRE; +import org.apache.ecs.html.Title; +import org.owasp.webgoat.session.ParameterNotFoundException; +import org.owasp.webgoat.session.Screen; +import org.owasp.webgoat.session.WebSession; +import org.owasp.webgoat.session.WebgoatContext; +import org.owasp.webgoat.session.WebgoatProperties; +import org.owasp.webgoat.util.BeanProvider; +import org.owasp.webgoat.util.LabelManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ************************************************************************************************* + * + * + * This file is part of WebGoat, an Open Web Application Security Project + * utility. For details, please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 59 Temple + * Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Getting Source ============== + * + * Source for this application is maintained at + * https://github.com/WebGoat/WebGoat, a repository for free software projects. + * + * For details, please see http://webgoat.github.io + * + * @author Bruce Mayhew WebGoat + * @created October 28, 2003 + */ +public abstract class AbstractLesson extends Screen implements Comparable { + + private static final Logger logger = LoggerFactory.getLogger(AbstractLesson.class); + + /** + * Description of the Field + */ + public final static String ADMIN_ROLE = "admin"; + + public final static String CHALLENGE_ROLE = "challenge"; + + /** + * Description of the Field + */ + public final static String HACKED_ADMIN_ROLE = "hacked_admin"; + + /** + * Description of the Field + */ + public final static String USER_ROLE = "user"; + + private static int count = 1; + + private Integer id = null; + + final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next").setBorder(0).setHspace(0).setVspace(0); + + final static IMG previousGrey = new IMG("images/left14.gif").setAlt("Previous").setBorder(0).setHspace(0) + .setVspace(0); + + private Integer ranking; + + private Category category; + + private boolean hidden; + + private String sourceFileName; + + private Map lessonPlanFileName = new HashMap(); + + private String lessonSolutionFileName; + + private WebgoatContext webgoatContext; + + private LinkedList availableLanguages = new LinkedList(); + + private String defaultLanguage = "en"; + + private LabelManager labelManager = null; + + /** + * Constructor for the Lesson object + */ + public AbstractLesson() { + id = new Integer(++count); + } + + public String getName() { + String className = getClass().getName(); + return className.substring(className.lastIndexOf('.') + 1); + } + + public void setRanking(Integer ranking) { + this.ranking = ranking; + } + + public void setHidden(boolean hidden) { + this.hidden = hidden; + } + + public void update(WebgoatProperties properties) { + String className = getClass().getName(); + className = className.substring(className.lastIndexOf(".") + 1); + setRanking(new Integer(properties.getIntProperty("lesson." + className + ".ranking", getDefaultRanking() + .intValue()))); + String categoryRankingKey = "category." + getDefaultCategory().getName() + ".ranking"; + // System.out.println("Category ranking key: " + categoryRankingKey); + Category tempCategory = Category.getCategory(getDefaultCategory().getName()); + tempCategory.setRanking(new Integer(properties.getIntProperty(categoryRankingKey, getDefaultCategory() + .getRanking().intValue()))); + category = tempCategory; + setHidden(properties.getBooleanProperty("lesson." + className + ".hidden", getDefaultHidden())); + // System.out.println(className + " in " + tempCategory.getName() + " + // (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking: + // " + getRanking() + ", hidden:" + hidden +")"); + } + + public boolean isCompleted(WebSession s) { + return getLessonTracker(s, this).getCompleted(); + } + + /** + * Gets the credits attribute of the AbstractLesson object + * + * @return The credits value + */ + public abstract Element getCredits(); + + /** + * Description of the Method + * + * @param obj Description of the Parameter + * @return Description of the Return Value + */ + public int compareTo(Object obj) { + return this.getRanking().compareTo(((AbstractLesson) obj).getRanking()); + } + + /** + * Description of the Method + * + * @param obj Description of the Parameter + * @return Description of the Return Value + */ + public boolean equals(Object obj) { + return this.getScreenId() == ((AbstractLesson) obj).getScreenId(); + } + + /** + * Gets the category attribute of the Lesson object + * + * @return The category value + */ + public Category getCategory() { + return category; + } + + protected abstract Integer getDefaultRanking(); + + protected abstract Category getDefaultCategory(); + + protected abstract boolean getDefaultHidden(); + + /** + * Gets the fileMethod attribute of the Lesson class + * + * @param reader Description of the Parameter + * @param methodName Description of the Parameter + * @param numbers Description of the Parameter + * @return The fileMethod value + */ + public static String getFileMethod(BufferedReader reader, String methodName, boolean numbers) { + int count = 0; + StringBuffer sb = new StringBuffer(); + boolean echo = false; + boolean startCount = false; + int parenCount = 0; + + try { + String line; + + while ((line = reader.readLine()) != null) { + if ((line.indexOf(methodName) != -1) + && ((line.indexOf("public") != -1) || (line.indexOf("protected") != -1) || (line + .indexOf("private") != -1))) { + echo = true; + startCount = true; + } + + if (echo && startCount) { + if (numbers) { + sb.append(pad(++count) + " "); + } + + sb.append(line + "\n"); + } + + if (echo && (line.indexOf("{") != -1)) { + parenCount++; + } + + if (echo && (line.indexOf("}") != -1)) { + parenCount--; + + if (parenCount == 0) { + startCount = false; + echo = false; + } + } + } + + reader.close(); + } catch (Exception e) { + System.out.println(e); + e.printStackTrace(); + } + + return (sb.toString()); + } + + /** + * Reads text from a file into an ElementContainer. Each line in the file is + * represented in the ElementContainer by a StringElement. Each + * StringElement is appended with a new-line character. + * + * @param reader Description of the Parameter + * @param numbers Description of the Parameter + * @return Description of the Return Value + */ + public static String readFromFile(BufferedReader reader, boolean numbers) { + return (getFileText(reader, numbers)); + } + + /** + * Gets the fileText attribute of the Screen class + * + * @param reader Description of the Parameter + * @param numbers Description of the Parameter + * @return The fileText value + */ + public static String getFileText(BufferedReader reader, boolean numbers) { + int count = 0; + StringBuffer sb = new StringBuffer(); + + try { + String line; + + while ((line = reader.readLine()) != null) { + if (numbers) { + sb.append(pad(++count) + " "); + } + sb.append(line + System.getProperty("line.separator")); + } + + reader.close(); + } catch (Exception e) { + System.out.println(e); + e.printStackTrace(); + } + + return (sb.toString()); + } + + /** + * Will this screen be included in an enterprise edition. + * + * @return The ranking value + */ + public boolean isEnterprise() { + return false; + } + + /** + * Gets the hintCount attribute of the Lesson object + * + * @param s The user's WebSession + * + * @return The hintCount value + */ + public int getHintCount(WebSession s) { + return getHints(s).size(); + } + + protected abstract List getHints(WebSession s); + + // @TODO we need to restrict access at the service layer + // rather than passing session object around + public List getHintsPublic(WebSession s) { + List hints = getHints(s); + return hints; + } + + /** + * Fill in a minor hint that will help people who basically get it, but are + * stuck on somthing silly. + * + * @param s The users WebSession + * + * @return The hint1 value + */ + public String getHint(WebSession s, int hintNumber) { + return "Hint: " + getHints(s).get(hintNumber); + } + + /** + * Gets the instructions attribute of the AbstractLesson object + * + * @return The instructions value + */ + public abstract String getInstructions(WebSession s); + + /** + * Gets the lessonPlan attribute of the Lesson object + * + * @return The lessonPlan value + */ + protected String getLessonName() { + int index = this.getClass().getName().indexOf("lessons."); + return this.getClass().getName().substring(index + "lessons.".length()); + } + + /** + * Gets the title attribute of the HelloScreen object + * + * @return The title value + */ + public abstract String getTitle(); + + /** + * Gets the content of lessonPlanURL + * + * @param s The user's WebSession + * + * @return The HTML content of the current lesson plan + */ + public String getLessonPlan(WebSession s) { + StringBuffer src = new StringBuffer(); + String lang = s.getCurrrentLanguage(); + + try { + // System.out.println("Loading lesson plan file: " + + // getLessonPlanFileName()); + String filename = getLessonPlanFileName(lang); + if (filename == null) { + filename = getLessonPlanFileName(getDefaultLanguage()); + + } + + src.append(readFromFile(new BufferedReader(new FileReader(s.getWebResource(filename))), false)); + + } catch (Exception e) { + // s.setMessage( "Could not find lesson plan for " + + // getLessonName()); + src = new StringBuffer("Could not find lesson plan for: " + getLessonName() + " and language " + lang); + + } + return src.toString(); + } + + /** + * Gets the ranking attribute of the Lesson object + * + * @return The ranking value + */ + public Integer getRanking() { + if (ranking != null) { + return ranking; + } else { + return getDefaultRanking(); + } + } + + /** + * Gets the hidden value of the Lesson Object + * + * @return The hidden value + */ + public boolean getHidden() { + return this.hidden; + } + + /** + * Gets the role attribute of the AbstractLesson object + * + * @return The role value + */ + public String getRole() { + // FIXME: Each lesson should have a role assigned to it. Each + // user/student + // should also have a role(s) assigned. The user would only be allowed + // to see lessons that correspond to their role. Eventually these roles + // will be stored in the internal database. The user will be able to + // hack + // into the database and change their role. This will allow the user to + // see the admin screens, once they figure out how to turn the admin + // switch on. + return USER_ROLE; + } + + /** + * Gets the uniqueID attribute of the AbstractLesson object + * + * @return The uniqueID value + */ + public int getScreenId() { + return id.intValue(); + } + + public String getHtml_DELETE_ME(WebSession s) { + String html = null; + + // FIXME: This doesn't work for the labs since they do not implement + // createContent(). + String rawHtml = createContent(s).toString(); + // System.out.println("Getting raw html content: " + + // rawHtml.substring(0, Math.min(rawHtml.length(), 100))); + html = convertMetachars(AbstractLesson.readFromFile(new BufferedReader(new StringReader(rawHtml)), true)); + // System.out.println("Getting encoded html content: " + + // html.substring(0, Math.min(html.length(), 100))); + + return html; + } + + public String getSource(WebSession s) { + String source = null; + String src = null; + + try { + // System.out.println("Loading source file: " + + // getSourceFileName()); + src = convertMetacharsJavaCode(readFromFile(new BufferedReader(new FileReader(s + .getWebResource(getSourceFileName()))), true)); + + // TODO: For styled line numbers and better memory efficiency, + // use a custom FilterReader + // that performs the convertMetacharsJavaCode() transform plus + // optionally adds a styled + // line number. Wouldn't color syntax be great too? + } catch (Exception e) { + s.setMessage("Could not find source file"); + src = ("Could not find the source file or source file does not exist.
" + + "Send this message to: " + s.getWebgoatContext().getFeedbackAddress() + ""); + } + + Html html = new Html(); + + Head head = new Head(); + head.addElement(new Title(getSourceFileName())); + + Body body = new Body(); + body.addElement(new StringElement(src)); + + html.addElement(head); + html.addElement(body); + + source = html.toString(); + + return source; + } + + public String getRawSource(WebSession s) { + String src; + + try { + logger.debug("Loading source file: " + getSourceFileName()); + src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getSourceFileName()))), false); + + } catch (FileNotFoundException e) { + s.setMessage("Could not find source file"); + src = ("Could not find the source file or source file does not exist.
" + + "Send this message to: " + s.getWebgoatContext().getFeedbackAddress() + ""); + } + + return src; + } + + public String getSolution(WebSession s) { + String src = null; + + try { + // System.out.println("Solution: " + getLessonSolutionFileName()); + src = readFromFile(new BufferedReader(new FileReader(s.getWebResource(getLessonSolutionFileName()))), false); + } catch (Exception e) { + s.setMessage("Could not find the solution file"); + src = ("Could not find the solution file or solution file does not exist.
" + + "Send this message to: " + s.getWebgoatContext().getFeedbackAddress() + ""); + } + + // Solutions are html files + return src; + } + + /** + *

+ * Returns the default "path" portion of a lesson's URL.

+ * + *

+ * Legacy webgoat lesson links are of the form + * "attack?Screen=Xmenu=Ystage=Z". This method returns the path portion of + * the url, i.e., "attack" in the string above.

+ * + *

+ * Newer, Spring-Controller-based classes will override this method to + * return "*.do"-styled paths.

+ */ + protected String getPath() { + return "attack"; + } + + /** + * Get the link that can be used to request this screen. + * + * @return + */ + public String getLink() { + StringBuffer link = new StringBuffer(); + + // mvc update: + link.append(getPath()).append("?"); + link.append(WebSession.SCREEN); + link.append("="); + link.append(getScreenId()); + link.append("&"); + link.append(WebSession.MENU); + link.append("="); + link.append(getCategory().getRanking()); + return link.toString(); + } + + /** + * Get the link to the jsp page used to render this screen. + * + * @return + */ + public String getPage(WebSession s) { + return null; + } + + /** + * Get the link to the jsp template page used to render this screen. + * + * @return + */ + public String getTemplatePage(WebSession s) { + return null; + } + + public abstract String getCurrentAction(WebSession s); + + public abstract void setCurrentAction(WebSession s, String lessonScreen); + + /** + * Override this method to implement accesss control in a lesson. + * + * @param s + * @param functionId + * @return + */ + public boolean isAuthorized(WebSession s, int employeeId, String functionId) { + return false; + } + + /** + * Override this method to implement accesss control in a lesson. + * + * @param s + * @param functionId + * @return + */ + public boolean isAuthorized(WebSession s, String role, String functionId) { + logger.info("Checking if " + role + " authorized for: " + functionId); + boolean authorized = false; + try { + String query = "SELECT * FROM auth WHERE role = '" + role + "' and functionid = '" + functionId + "'"; + try { + Statement answer_statement = WebSession.getConnection(s) + .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + ResultSet answer_results = answer_statement.executeQuery(query); + authorized = answer_results.first(); + logger.info("authorized: "+ authorized); + } catch (SQLException sqle) { + s.setMessage("Error authorizing"); + logger.error("Error authorizing", sqle); + } + } catch (Exception e) { + s.setMessage("Error authorizing"); + logger.error("Error authorizing", e); + } + return authorized; + } + + public int getUserId(WebSession s) throws ParameterNotFoundException { + return -1; + } + + public String getUserName(WebSession s) throws ParameterNotFoundException { + return null; + } + + /** + * Description of the Method + * + * @param windowName Description of the Parameter + * @return Description of the Return Value + */ + public static String makeWindowScript(String windowName) { + // FIXME: make this string static + StringBuffer script = new StringBuffer(); + script.append("\n"); + + return script.toString(); + } + + /** + * Simply reads a url into an Element for display. CAUTION: you might want + * to tinker with any non-https links (href) + * + * @param url Description of the Parameter + * @return Description of the Return Value + */ + public static Element readFromURL(String url) { + ElementContainer ec = new ElementContainer(); + + try { + URL u = new URL(url); + HttpURLConnection huc = (HttpURLConnection) u.openConnection(); + BufferedReader reader = new BufferedReader(new InputStreamReader(huc.getInputStream())); + String line; + + while ((line = reader.readLine()) != null) { + ec.addElement(new StringElement(line)); + } + + reader.close(); + } catch (Exception e) { + System.out.println(e); + e.printStackTrace(); + } + + return (ec); + } + + /** + * Description of the Method + * + * @param reader Description of the Parameter + * @param numbers Description of the Parameter + * @param methodName Description of the Parameter + * @return Description of the Return Value + */ + public static Element readMethodFromFile(BufferedReader reader, String methodName, boolean numbers) { + PRE pre = new PRE().addElement(getFileMethod(reader, methodName, numbers)); + + return (pre); + } + + /** + * Description of the Method + * + * @param s Description of the Parameter + */ + public void handleRequest(WebSession s) { + // call createContent first so messages will go somewhere + Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType(""); + form.addElement(createContent(s)); + setContent(form); + } + + public String getFormAction() { + return getLink(); + } + + /** + * Description of the Method + * + * @param s Description of the Parameter + * @return Description of the Return Value + */ + public String toString() { + return getTitle(); + } + + public String getDefaultLanguage() { + return this.defaultLanguage; + } + + public String getLessonPlanFileName(String lang) { + String ret = lessonPlanFileName.get(lang); + if (ret == null) { + ret = lessonPlanFileName.get(getDefaultLanguage()); + } + return ret; + } + + public void setLessonPlanFileName(String lang, String lessonPlanFileName) { + this.lessonPlanFileName.put(lang, lessonPlanFileName); + this.availableLanguages.add(lang); + } + + public List getAvailableLanguages() { + return this.availableLanguages; + } + + public String getLessonSolutionFileName() { + return lessonSolutionFileName; + } + + public void setLessonSolutionFileName(String lessonSolutionFileName) { + this.lessonSolutionFileName = lessonSolutionFileName; + } + + public String getSourceFileName() { + return sourceFileName; + } + + public void setSourceFileName(String sourceFileName) { + logger.debug("Setting source file of lesson " + this + " to: " + sourceFileName); + this.sourceFileName = sourceFileName; + } + + public WebgoatContext getWebgoatContext() { + return webgoatContext; + } + + public void setWebgoatContext(WebgoatContext webgoatContext) { + this.webgoatContext = webgoatContext; + } + + protected LabelManager getLabelManager() { + if(labelManager == null) { + labelManager = BeanProvider.getBean("labelManager", LabelManager.class); + } + return labelManager; + } +} diff --git a/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java b/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java index d76e60d85..2bf3fb87d 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java +++ b/src/main/java/org/owasp/webgoat/lessons/BasicAuthentication.java @@ -13,7 +13,6 @@ import org.apache.ecs.html.TR; import org.apache.ecs.html.Table; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -102,12 +101,12 @@ public class BasicAuthentication extends SequentialLessonAdapter { if (headerName.length() > 0 && !headerName.equalsIgnoreCase(AUTHORIZATION)) { - s.setMessage(WebGoatI18N.get("BasicAuthHeaderNameIncorrect")); + s.setMessage(getLabelManager().get("BasicAuthHeaderNameIncorrect")); } if (headerValue.length() > 0 && !(headerValue.equals("guest:guest") || headerValue.equals("webgoat:webgoat"))) { - s.setMessage(WebGoatI18N.get("BasicAuthHeaderValueIncorrect")); + s.setMessage(getLabelManager().get("BasicAuthHeaderValueIncorrect")); } } @@ -121,8 +120,8 @@ public class BasicAuthentication extends SequentialLessonAdapter 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 StringElement(getLabelManager().get("BasicAuthenticationWhatIsNameOfHeader")))); + row2.addElement(new TD(new StringElement(getLabelManager().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()))); @@ -133,7 +132,7 @@ public class BasicAuthentication extends SequentialLessonAdapter ec.addElement(t); ec.addElement(new P()); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit")); + Element b = ECSFactory.makeButton(getLabelManager().get("Submit")); ec.addElement(b); } catch (Exception e) @@ -159,7 +158,7 @@ public class BasicAuthentication extends SequentialLessonAdapter getLessonTracker(s, originalUser).setStage(1); getLessonTracker(s, originalUser).store(s, this); makeSuccess(s); - s.setMessage(WebGoatI18N.get("BasicAuthenticiationGreenStars1")+ originalUser + WebGoatI18N.get("BasicAuthenticationGreenStars2")); + s.setMessage(getLabelManager().get("BasicAuthenticiationGreenStars1")+ originalUser + getLabelManager().get("BasicAuthenticationGreenStars2")); return ec; } else @@ -185,7 +184,7 @@ public class BasicAuthentication extends SequentialLessonAdapter getLessonTracker(s, BASIC).store(s, this, BASIC); } - s.setMessage(WebGoatI18N.get("BasicAuthenticationStage1Completed")); + s.setMessage(getLabelManager().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 @@ -193,28 +192,28 @@ public class BasicAuthentication extends SequentialLessonAdapter if (!originalAuth.equals("") && !originalAuth.equals(s.getHeader(AUTHORIZATION))) { ec - .addElement(WebGoatI18N.get("BasicAuthenticationAlmostThere1") + .addElement(getLabelManager().get("BasicAuthenticationAlmostThere1") + AUTHORIZATION - + WebGoatI18N.get("BasicAuthenticationAlmostThere2") + + getLabelManager().get("BasicAuthenticationAlmostThere2") + s.getUserName() - + WebGoatI18N.get("BasicAuthenticationAlmostThere3")); + + getLabelManager().get("BasicAuthenticationAlmostThere3")); } else if (!originalSessionId.equals(s.getCookie(JSESSIONID))) { ec - .addElement(WebGoatI18N.get("BasicAuthenticationReallyClose")); + .addElement(getLabelManager().get("BasicAuthenticationReallyClose")); } else { - ec.addElement(WebGoatI18N.get("BasicAuthenticationUseTheHints")); + ec.addElement(getLabelManager().get("BasicAuthenticationUseTheHints")); } } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -245,18 +244,18 @@ public class BasicAuthentication extends SequentialLessonAdapter // switch ( stage ) // { // case 1: - hints.add(WebGoatI18N.get("BasicAuthenticationHint1")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint2")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint3")); - hints.add(WebGoatI18N.get("BasicAuthenticationHint4")); + hints.add(getLabelManager().get("BasicAuthenticationHint1")); + hints.add(getLabelManager().get("BasicAuthenticationHint2")); + hints.add(getLabelManager().get("BasicAuthenticationHint3")); + hints.add(getLabelManager().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")); + hints.add(getLabelManager().get("BasicAuthenticationHint5")); + hints.add(getLabelManager().get("BasicAuthenticationHint6")); + hints.add(getLabelManager().get("BasicAuthenticationHint7")); + hints.add(getLabelManager().get("BasicAuthenticationHint8")); + hints.add(getLabelManager().get("BasicAuthenticationHint9")); // break; // } diff --git a/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java b/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java index 28149fb43..7294e2539 100644 --- a/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java +++ b/src/main/java/org/owasp/webgoat/lessons/BypassHtmlFieldRestrictions.java @@ -1,11 +1,6 @@ package org.owasp.webgoat.lessons; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.apache.ecs.Element; @@ -17,12 +12,9 @@ import org.apache.ecs.html.Div; import org.apache.ecs.html.IMG; import org.apache.ecs.html.Input; import org.apache.ecs.html.P; -import org.apache.ecs.html.PRE; -import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.ParameterNotFoundException; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -197,9 +189,9 @@ public class BypassHtmlFieldRestrictions extends SequentialLessonAdapter { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint1")); - hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint2")); - hints.add(WebGoatI18N.get("BypassHtmlFieldRestrictionsHint3")); + hints.add(getLabelManager().get("BypassHtmlFieldRestrictionsHint1")); + hints.add(getLabelManager().get("BypassHtmlFieldRestrictionsHint2")); + hints.add(getLabelManager().get("BypassHtmlFieldRestrictionsHint3")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java b/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java index 265e9e835..921918c85 100644 --- a/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/CommandInjection.java @@ -16,7 +16,6 @@ import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.util.Exec; import org.owasp.webgoat.util.ExecResults; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -79,7 +78,7 @@ public class CommandInjection extends LessonAdapter } 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() + "]"); + System.out.println(getLabelManager().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") @@ -97,7 +96,7 @@ public class CommandInjection extends LessonAdapter } else { - s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack1")); + s.setMessage(getLabelManager().get("CommandInjectionRightTrack1")); } } @@ -114,7 +113,7 @@ public class CommandInjection extends LessonAdapter } else { - s.setMessage(WebGoatI18N.get("CommandInjectionRightTrack2")); + s.setMessage(getLabelManager().get("CommandInjectionRightTrack2")); } } else @@ -125,8 +124,8 @@ public class CommandInjection extends LessonAdapter } File safeDir = new File(s.getContext().getRealPath("/lesson_plans/en")); - ec.addElement(new StringElement(WebGoatI18N.get("YouAreCurrentlyViewing")+"" - + (helpFile.toString().length() == 0 ? "<"+WebGoatI18N.get("SelectFileFromListBelow")+">" : helpFile.toString()) + ec.addElement(new StringElement(getLabelManager().get("YouAreCurrentlyViewing")+"" + + (helpFile.toString().length() == 0 ? "<"+getLabelManager().get("SelectFileFromListBelow")+">" : helpFile.toString()) + "")); if (!illegalCommand) @@ -151,11 +150,11 @@ public class CommandInjection extends LessonAdapter fileData = exec(s, cmd2); } - ec.addElement(new P().addElement(WebGoatI18N.get("SelectLessonPlanToView"))); + ec.addElement(new P().addElement(getLabelManager().get("SelectLessonPlanToView"))); ec.addElement(ECSFactory.makePulldown(HELP_FILE, parseResults(results.replaceAll("(?s)\\.html", "\\.help")))); // ec.addElement( results ); - Element b = ECSFactory.makeButton(WebGoatI18N.get("View")); + Element b = ECSFactory.makeButton(getLabelManager().get("View")); ec.addElement(b); // Strip out some of the extra html from the "help" file ec.addElement(new BR()); @@ -271,10 +270,10 @@ public class CommandInjection extends LessonAdapter 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")); + hints.add(getLabelManager().get("CommandInjectionHint1")); + hints.add(getLabelManager().get("CommandInjectionHint2")); + hints.add(getLabelManager().get("CommandInjectionHint3")); + hints.add(getLabelManager().get("CommandInjectionHint4")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java b/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java index 7b4161f26..9a8bc1823 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java +++ b/src/main/java/org/owasp/webgoat/lessons/HiddenFieldTampering.java @@ -22,7 +22,6 @@ import org.apache.ecs.html.TR; import org.apache.ecs.html.Table; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -107,7 +106,7 @@ public class HiddenFieldTampering extends LessonAdapter total = quantity * Float.parseFloat(price); } catch (Exception e) { - s.setMessage(WebGoatI18N.get("Invaild data") + this.getClass().getName()); + s.setMessage(getLabelManager().get("Invaild data") + this.getClass().getName()); price = PRICE_TV; quantity = 1.0f; total = quantity * Float.parseFloat(PRICE_TV); @@ -116,7 +115,7 @@ public class HiddenFieldTampering extends LessonAdapter if (price.equals(PRICE_TV)) { - ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart")))); + ec.addElement(new Center().addElement(new H1().addElement(getLabelManager().get("ShoppingCart")))); ec.addElement(new BR()); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); @@ -126,10 +125,10 @@ public class HiddenFieldTampering extends LessonAdapter } 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%")); + tr.addElement(new TH().addElement(getLabelManager().get("ShoppingCartItems")).setWidth("80%")); + tr.addElement(new TH().addElement(getLabelManager().get("Price")).setWidth("10%")); + tr.addElement(new TH().addElement(getLabelManager().get("Quantity")).setWidth("3%")); + tr.addElement(new TH().addElement(getLabelManager().get("Total")).setWidth("7%")); t.addElement(tr); tr = new TR(); @@ -150,10 +149,10 @@ public class HiddenFieldTampering extends LessonAdapter ec.addElement(new BR()); tr = new TR(); - tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":")); + tr.addElement(new TD().addElement(getLabelManager().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()"))); + tr.addElement(new TD().addElement(ECSFactory.makeButton(getLabelManager().get("UpdateCart")))); + tr.addElement(new TD().addElement(ECSFactory.makeButton(getLabelManager().get("Purchase"), "validate()"))); t.addElement(tr); ec.addElement(t); @@ -170,10 +169,10 @@ public class HiddenFieldTampering extends LessonAdapter makeSuccess(s); } - ec.addElement(new P().addElement(WebGoatI18N.get("TotalPriceIs")+":")); + ec.addElement(new P().addElement(getLabelManager().get("TotalPriceIs")+":")); ec.addElement(new B("$" + total)); ec.addElement(new BR()); - ec.addElement(new P().addElement(WebGoatI18N.get("ThisAmountCharged"))); + ec.addElement(new P().addElement(getLabelManager().get("ThisAmountCharged"))); } return (ec); @@ -198,9 +197,9 @@ public class HiddenFieldTampering extends LessonAdapter { 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 ); + hints.add(getLabelManager().get("HiddenFieldTamperingHint1")); + hints.add(getLabelManager().get("HiddenFieldTamperingHint2")); + hints.add(getLabelManager().get("HiddenFieldTamperingHint3")+ PRICE_TV +getLabelManager().get("HiddenFieldTamperingHint32") + PRICE_TV_HACKED ); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java b/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java index 85c3bebda..d04be31f0 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java +++ b/src/main/java/org/owasp/webgoat/lessons/HtmlClues.java @@ -19,7 +19,6 @@ import org.apache.ecs.html.TR; import org.apache.ecs.html.Table; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -108,7 +107,7 @@ public class HtmlClues extends LessonAdapter { makeSuccess(s); - s.setMessage(WebGoatI18N.get("HtmlCluesBINGO")); + s.setMessage(getLabelManager().get("HtmlCluesBINGO")); ec.addElement(makeUser(s, "admin", "CREDENTIALS")); } else @@ -139,8 +138,8 @@ public class HtmlClues extends LessonAdapter 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)); + ec.addElement(new P().addElement(getLabelManager().get("WelcomeUser")+ user)); + ec.addElement(new P().addElement(getLabelManager().get("YouHaveBeenAuthenticatedWith") + method)); return (ec); } @@ -159,12 +158,12 @@ public class HtmlClues extends LessonAdapter TR tr = new TR(); tr.addElement(new TH() - .addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn")) + .addElement(getLabelManager().get("WeakAuthenticationCookiePleaseSignIn")) .setColSpan(2).setAlign("left")); t.addElement(tr); tr = new TR(); - tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%")); + tr.addElement(new TD().addElement("*"+getLabelManager().get("RequiredFields")).setWidth("30%")); t.addElement(tr); tr = new TR(); @@ -173,8 +172,8 @@ public class HtmlClues extends LessonAdapter 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")+": ")))); + row1.addElement(new TD(new B(new StringElement("*"+getLabelManager().get("UserName")+": ")))); + row2.addElement(new TD(new B(new StringElement("*"+getLabelManager().get("Password")+": ")))); Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); @@ -183,7 +182,7 @@ public class HtmlClues extends LessonAdapter t.addElement(row1); t.addElement(row2); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); + Element b = ECSFactory.makeButton(getLabelManager().get("Login")); t.addElement(new TR(new TD(b))); ec.addElement(t); @@ -198,9 +197,9 @@ public class HtmlClues extends LessonAdapter protected List getHints(WebSession s) { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("HtmlCluesHint1")); - hints.add(WebGoatI18N.get("HtmlCluesHint2")); - hints.add(WebGoatI18N.get("HtmlCluesHint3")); + hints.add(getLabelManager().get("HtmlCluesHint1")); + hints.add(getLabelManager().get("HtmlCluesHint2")); + hints.add(getLabelManager().get("HtmlCluesHint3")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java b/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java index 32e7f09d3..c5be5587d 100644 --- a/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java +++ b/src/main/java/org/owasp/webgoat/lessons/HttpBasics.java @@ -2,7 +2,6 @@ package org.owasp.webgoat.lessons; import java.util.ArrayList; import java.util.List; - import org.apache.ecs.Element; import org.apache.ecs.ElementContainer; import org.apache.ecs.StringElement; @@ -10,7 +9,6 @@ import org.apache.ecs.html.BR; import org.apache.ecs.html.Input; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /** * ************************************************************************************************* @@ -61,7 +59,7 @@ public class HttpBasics extends LessonAdapter { StringBuffer person = null; try { ec.addElement(new BR()); - ec.addElement(new StringElement(WebGoatI18N.get("EnterYourName") + ": ")); + ec.addElement(new StringElement(getLabelManager().get("EnterYourName") + ": ")); person = new StringBuffer(s.getParser().getStringParameter(PERSON, "")); person.reverse(); @@ -69,7 +67,7 @@ public class HttpBasics extends LessonAdapter { Input input = new Input(Input.TEXT, PERSON, person.toString()); ec.addElement(input); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); + Element b = ECSFactory.makeButton(getLabelManager().get("Go!")); ec.addElement(b); } catch (Exception e) { s.setMessage("Error generating " + this.getClass().getName()); diff --git a/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java b/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java index 55bae2956..726971e98 100644 --- a/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java +++ b/src/main/java/org/owasp/webgoat/lessons/JavaScriptValidation.java @@ -14,7 +14,6 @@ import org.apache.ecs.html.Input; import org.apache.ecs.html.P; import org.apache.ecs.html.TextArea; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -125,28 +124,28 @@ public class JavaScriptValidation extends LessonAdapter b.setType(Input.BUTTON); b.setValue("Submit"); b.addAttribute("onclick", "validate();"); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("3LowerCase")+"(" + ec.addElement(new Div().addElement(new StringElement(getLabelManager().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(new StringElement(getLabelManager().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(new StringElement(getLabelManager().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(new StringElement(getLabelManager().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(new StringElement(getLabelManager().get("SimpleZipCode")+ " (" + regex5 + ")"))); ec.addElement(new Div().addElement(input5)); ec.addElement(new P()); ec.addElement(new Div() - .addElement(new StringElement(WebGoatI18N.get("ZIPDashFour")+" (" + regex6 + ")"))); + .addElement(new StringElement(getLabelManager().get("ZIPDashFour")+" (" + regex6 + ")"))); ec.addElement(new Div().addElement(input6)); ec.addElement(new P()); - ec.addElement(new Div().addElement(new StringElement(WebGoatI18N.get("USPhoneNumber")+ " (" + ec.addElement(new Div().addElement(new StringElement(getLabelManager().get("USPhoneNumber")+ " (" + regex7 + ")"))); ec.addElement(new Div().addElement(input7)); ec.addElement(new P()); @@ -161,43 +160,43 @@ public class JavaScriptValidation extends LessonAdapter if (!pattern1.matcher(param1).matches()) { err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+" Field1."; + msg += "
"+getLabelManager().get("ServerSideValidationViolation")+" Field1."; } if (!pattern2.matcher(param2).matches()) { err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+" Field2."; + msg += "
"+getLabelManager().get("ServerSideValidationViolation")+" Field2."; } if (!pattern3.matcher(param3).matches()) { err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field3."; + msg += "
"+getLabelManager().get("ServerSideValidationViolation")+"Field3."; } if (!pattern4.matcher(param4).matches()) { err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field4."; + msg += "
"+getLabelManager().get("ServerSideValidationViolation")+"Field4."; } if (!pattern5.matcher(param5).matches()) { err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field5."; + msg += "
"+getLabelManager().get("ServerSideValidationViolation")+"Field5."; } if (!pattern6.matcher(param6).matches()) { err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field6."; + msg += "
"+getLabelManager().get("ServerSideValidationViolation")+"Field6."; } if (!pattern7.matcher(param7).matches()) { err++; - msg += "
"+WebGoatI18N.get("ServerSideValidationViolation")+"Field7."; + msg += "
"+getLabelManager().get("ServerSideValidationViolation")+"Field7."; } if (err > 0) @@ -213,7 +212,7 @@ public class JavaScriptValidation extends LessonAdapter catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -238,9 +237,9 @@ public class JavaScriptValidation extends LessonAdapter protected List getHints(WebSession s) { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("JavaScriptValidationHint1")); - hints.add(WebGoatI18N.get("JavaScriptValidationHint2")); - hints.add(WebGoatI18N.get("JavaScriptValidationHint3")); + hints.add(getLabelManager().get("JavaScriptValidationHint1")); + hints.add(getLabelManager().get("JavaScriptValidationHint2")); + hints.add(getLabelManager().get("JavaScriptValidationHint3")); return hints; diff --git a/src/main/java/org/owasp/webgoat/lessons/LessonAdapter.java b/src/main/java/org/owasp/webgoat/lessons/LessonAdapter.java index 27463727d..56c2bcba1 100644 --- a/src/main/java/org/owasp/webgoat/lessons/LessonAdapter.java +++ b/src/main/java/org/owasp/webgoat/lessons/LessonAdapter.java @@ -15,7 +15,6 @@ import org.apache.ecs.html.TD; import org.apache.ecs.html.TR; import org.apache.ecs.html.Table; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /** * ************************************************************************************************* @@ -220,7 +219,7 @@ public abstract class LessonAdapter extends AbstractLesson { protected Element makeSuccess(WebSession s) { getLessonTracker(s).setCompleted(true); - s.setMessage(WebGoatI18N.get("LessonCompleted")); + s.setMessage(getLabelManager().get("LessonCompleted")); return (null); } diff --git a/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java b/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java index 8e9ac7eff..c143c07b6 100644 --- a/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java +++ b/src/main/java/org/owasp/webgoat/lessons/LogSpoofing.java @@ -18,7 +18,6 @@ import org.apache.ecs.html.TR; import org.apache.ecs.html.Table; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -75,15 +74,15 @@ public class LogSpoofing extends LessonAdapter TR row2 = new TR(); TR row3 = new TR(); - row1.addElement(new TD(new StringElement(WebGoatI18N.get("UserName")+":"))); + row1.addElement(new TD(new StringElement(getLabelManager().get("UserName")+":"))); Input username = new Input(Input.TEXT, USERNAME, ""); row1.addElement(new TD(username)); - row2.addElement(new TD(new StringElement(WebGoatI18N.get("Password")+": "))); + row2.addElement(new TD(new StringElement(getLabelManager().get("Password")+": "))); Input password = new Input(Input.PASSWORD, PASSWORD, ""); row2.addElement(new TD(password)); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); + Element b = ECSFactory.makeButton(getLabelManager().get("Login")); row3.addElement(new TD(new StringElement("  "))); row3.addElement(new TD(b)).setAlign("right"); @@ -105,7 +104,7 @@ public class LogSpoofing extends LessonAdapter 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); + row4.addElement(new TD(new PRE(getLabelManager().get("LoginFailedForUserName")+": " + inputUsername))).setBgColor(HtmlColor.GRAY); t2.addElement(row4); @@ -134,10 +133,10 @@ public class LogSpoofing extends LessonAdapter 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")); + hints.add(getLabelManager().get("LogSpoofingHint1")); + hints.add(getLabelManager().get("LogSpoofingHint2")); + hints.add(getLabelManager().get("LogSpoofingHint3")); + hints.add(getLabelManager().get("LogSpoofingHint4")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java b/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java index dc5a229aa..93fbe421a 100644 --- a/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java +++ b/src/main/java/org/owasp/webgoat/lessons/PathBasedAccessControl.java @@ -16,7 +16,6 @@ import org.apache.ecs.html.TR; import org.apache.ecs.html.Table; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -78,8 +77,8 @@ public class PathBasedAccessControl extends LessonAdapter } String[] list = d.list(); - String listing = "

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

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

"; + String listing = "

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

"+getLabelManager().get("ChooseFileToView")+"

"; TR tr = new TR(); tr.addElement(new TD().setColSpan(2).addElement(new StringElement(listing))); @@ -87,7 +86,7 @@ public class PathBasedAccessControl extends LessonAdapter 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")))); + tr.addElement(new TD().addElement(ECSFactory.makeButton(getLabelManager().get("ViewFile")))); t.addElement(tr); ec.addElement(t); @@ -106,13 +105,13 @@ public class PathBasedAccessControl extends LessonAdapter // file if (upDirCount(file) == 3 && !file.endsWith("LICENSE")) { - s.setMessage(WebGoatI18N.get("AccessDenied")); - s.setMessage(WebGoatI18N.get("ItAppears1")); + s.setMessage(getLabelManager().get("AccessDenied")); + s.setMessage(getLabelManager().get("ItAppears1")); } else if (upDirCount(file) > 3) { - s.setMessage(WebGoatI18N.get("AccessDenied")); - s.setMessage(WebGoatI18N.get("ItAppears2")); + s.setMessage(getLabelManager().get("AccessDenied")); + s.setMessage(getLabelManager().get("ItAppears2")); } else { @@ -131,13 +130,13 @@ public class PathBasedAccessControl extends LessonAdapter if (s.isDebug()) { - s.setMessage(WebGoatI18N.get("File") + file); - s.setMessage(WebGoatI18N.get("Dir")+ dir); + s.setMessage(getLabelManager().get("File") + file); + s.setMessage(getLabelManager().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()); + s.setMessage(getLabelManager().get("IsFile")+ f.isFile()); + s.setMessage(getLabelManager().get("Exists") + f.exists()); } if (!illegalCommand) { @@ -147,21 +146,21 @@ public class PathBasedAccessControl extends LessonAdapter // directory listing we gave them. if (upDirCount(file) >= 1) { - s.setMessage(WebGoatI18N.get("CongratsAccessToFileAllowed")); + s.setMessage(getLabelManager().get("CongratsAccessToFileAllowed")); s.setMessage(" ==> " + Encoding.urlDecode(f.getCanonicalPath())); makeSuccess(s); } else { - s.setMessage(WebGoatI18N.get("FileInAllowedDirectory")); + s.setMessage(getLabelManager().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")); + .setMessage(getLabelManager().get("AccessToFileDenied1") + Encoding.urlDecode(f.getCanonicalPath()) + + getLabelManager().get("AccessToFileDenied2")); } else { @@ -175,11 +174,11 @@ public class PathBasedAccessControl extends LessonAdapter ec.addElement(new BR()); ec.addElement(new BR()); ec.addElement(new HR().setWidth("100%")); - ec.addElement(WebGoatI18N.get("ViewingFile")+ f.getCanonicalPath()); + ec.addElement(getLabelManager().get("ViewingFile")+ f.getCanonicalPath()); ec.addElement(new HR().setWidth("100%")); - if (f.length() > 80000) { throw new Exception(WebGoatI18N.get("FileTooLarge")); } + if (f.length() > 80000) { throw new Exception(getLabelManager().get("FileTooLarge")); } String fileData = getFileText(new BufferedReader(new FileReader(f)), false); - if (fileData.indexOf(0x00) != -1) { throw new Exception(WebGoatI18N.get("FileBinary")); } + if (fileData.indexOf(0x00) != -1) { throw new Exception(getLabelManager().get("FileBinary")); } ec.addElement(new StringElement(fileData.replaceAll(System.getProperty("line.separator"), "
") .replaceAll("(?s)", "").replaceAll("

", "
") .replaceAll("
\\s
", "
").replaceAll("<\\?", "<").replaceAll("<(r|u|t)", @@ -187,13 +186,13 @@ public class PathBasedAccessControl extends LessonAdapter } catch (Exception e) { ec.addElement(new BR()); - ec.addElement(WebGoatI18N.get("TheFollowingError")); + ec.addElement(getLabelManager().get("TheFollowingError")); ec.addElement(e.getMessage()); } } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating")+ this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating")+ this.getClass().getName()); e.printStackTrace(); } @@ -230,10 +229,10 @@ public class PathBasedAccessControl extends LessonAdapter 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")); + hints.add(getLabelManager().get("PathBasedAccessControlHint1")); + hints.add(getLabelManager().get("PathBasedAccessControlHint2")); + hints.add(getLabelManager().get("PathBasedAccessControlHint3")); + hints.add(getLabelManager().get("PathBasedAccessControlHint4")); return hints; } @@ -245,7 +244,7 @@ public class PathBasedAccessControl extends LessonAdapter */ public String getInstructions(WebSession s) { - String instructions = WebGoatI18N.get("PathBasedAccessControlInstr1")+ s.getUserName() + WebGoatI18N.get("PathBasedAccessControlInstr2"); + String instructions = getLabelManager().get("PathBasedAccessControlInstr1")+ s.getUserName() + getLabelManager().get("PathBasedAccessControlInstr2"); return (instructions); } diff --git a/src/main/java/org/owasp/webgoat/lessons/ReflectedXSS.java b/src/main/java/org/owasp/webgoat/lessons/ReflectedXSS.java index a74631278..9fb3115ac 100644 --- a/src/main/java/org/owasp/webgoat/lessons/ReflectedXSS.java +++ b/src/main/java/org/owasp/webgoat/lessons/ReflectedXSS.java @@ -19,7 +19,6 @@ import org.apache.ecs.html.Table; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; import org.owasp.webgoat.util.HtmlEncoder; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -88,13 +87,13 @@ public class ReflectedXSS extends LessonAdapter makeSuccess(s); } - s.setMessage(WebGoatI18N.get("ReflectedXSSWhoops1")+ param1 + WebGoatI18N.get("ReflectedXSSWhoops2")); + s.setMessage(getLabelManager().get("ReflectedXSSWhoops1")+ param1 + getLabelManager().get("ReflectedXSSWhoops2")); } // FIXME: encode output of field2, then s.setMessage( field2 ); ec.addElement(new HR().setWidth("90%")); - ec.addElement(new Center().addElement(new H1().addElement(WebGoatI18N.get("ShoppingCart")))); + ec.addElement(new Center().addElement(new H1().addElement(getLabelManager().get("ShoppingCart")))); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1).setWidth("90%").setAlign("center"); if (s.isColor()) @@ -103,10 +102,10 @@ public class ReflectedXSS extends LessonAdapter } 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%")); + tr.addElement(new TH().addElement(getLabelManager().get("ShoppingCartItems")).setWidth("80%")); + tr.addElement(new TH().addElement(getLabelManager().get("Price")).setWidth("10%")); + tr.addElement(new TH().addElement(getLabelManager().get("Quantity")).setWidth("3%")); + tr.addElement(new TH().addElement(getLabelManager().get("Total")).setWidth("7%")); t.addElement(tr); tr = new TR(); @@ -171,24 +170,24 @@ public class ReflectedXSS extends LessonAdapter ec.addElement(new BR()); tr = new TR(); - tr.addElement(new TD().addElement(WebGoatI18N.get("TotalChargedCreditCard")+":")); + tr.addElement(new TD().addElement(getLabelManager().get("TotalChargedCreditCard")+":")); tr.addElement(new TD().addElement(money.format(runningTotal))); - tr.addElement(new TD().addElement(ECSFactory.makeButton(WebGoatI18N.get("UpdateCart")))); + tr.addElement(new TD().addElement(ECSFactory.makeButton(getLabelManager().get("UpdateCart")))); t.addElement(tr); tr = new TR(); tr.addElement(new TD().addElement(" ").setColSpan(2)); t.addElement(tr); tr = new TR(); - tr.addElement(new TD().addElement(WebGoatI18N.get("EnterCreditCard")+":")); + tr.addElement(new TD().addElement(getLabelManager().get("EnterCreditCard")+":")); tr.addElement(new TD().addElement(new Input(Input.TEXT, "field2", param2))); t.addElement(tr); tr = new TR(); - tr.addElement(new TD().addElement(WebGoatI18N.get("Enter3DigitCode")+":")); + tr.addElement(new TD().addElement(getLabelManager().get("Enter3DigitCode")+":")); tr.addElement(new TD().addElement("")); // tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1))); t.addElement(tr); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Purchase")); + Element b = ECSFactory.makeButton(getLabelManager().get("Purchase")); tr = new TR(); tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("center")); t.addElement(tr); @@ -198,7 +197,7 @@ public class ReflectedXSS extends LessonAdapter ec.addElement(new HR().setWidth("90%")); } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } return (ec); @@ -222,11 +221,11 @@ public class ReflectedXSS extends LessonAdapter protected List getHints(WebSession s) { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("ReflectedXSSHint1")); - hints.add(WebGoatI18N.get("ReflectedXSSHint2")); - hints.add(WebGoatI18N.get("ReflectedXSSHint3")); - hints.add(WebGoatI18N.get("ReflectedXSSHint4")); - hints.add(WebGoatI18N.get("ReflectedXSSHint5")); + hints.add(getLabelManager().get("ReflectedXSSHint1")); + hints.add(getLabelManager().get("ReflectedXSSHint2")); + hints.add(getLabelManager().get("ReflectedXSSHint3")); + hints.add(getLabelManager().get("ReflectedXSSHint4")); + hints.add(getLabelManager().get("ReflectedXSSHint5")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/RemoteAdminFlaw.java b/src/main/java/org/owasp/webgoat/lessons/RemoteAdminFlaw.java index 93f3b8658..49cb27d78 100644 --- a/src/main/java/org/owasp/webgoat/lessons/RemoteAdminFlaw.java +++ b/src/main/java/org/owasp/webgoat/lessons/RemoteAdminFlaw.java @@ -6,7 +6,6 @@ import java.util.List; import org.apache.ecs.Element; import org.apache.ecs.ElementContainer; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -79,11 +78,11 @@ public class RemoteAdminFlaw extends LessonAdapter public List getHints(WebSession s) { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("RemoteAdminFlawHint1")); - hints.add(WebGoatI18N.get("RemoteAdminFlawHint2")); - hints.add(WebGoatI18N.get("RemoteAdminFlawHint3")); - hints.add(WebGoatI18N.get("RemoteAdminFlawHint4")); - hints.add(WebGoatI18N.get("RemoteAdminFlawHint5")); + hints.add(getLabelManager().get("RemoteAdminFlawHint1")); + hints.add(getLabelManager().get("RemoteAdminFlawHint2")); + hints.add(getLabelManager().get("RemoteAdminFlawHint3")); + hints.add(getLabelManager().get("RemoteAdminFlawHint4")); + hints.add(getLabelManager().get("RemoteAdminFlawHint5")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/SqlAddData.java b/src/main/java/org/owasp/webgoat/lessons/SqlAddData.java index 17308fad2..468b9c60d 100644 --- a/src/main/java/org/owasp/webgoat/lessons/SqlAddData.java +++ b/src/main/java/org/owasp/webgoat/lessons/SqlAddData.java @@ -19,7 +19,6 @@ import org.apache.ecs.html.PRE; import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -109,7 +108,7 @@ public class SqlAddData extends SequentialLessonAdapter } else { - ec.addElement(WebGoatI18N.get("NoResultsMatched")); + ec.addElement(getLabelManager().get("NoResultsMatched")); } // see if the number of rows in the table has changed @@ -131,7 +130,7 @@ public class SqlAddData extends SequentialLessonAdapter } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -143,13 +142,13 @@ public class SqlAddData extends SequentialLessonAdapter protected Element makeAccountLine(WebSession s) { ElementContainer ec = new ElementContainer(); - ec.addElement(new P().addElement(WebGoatI18N.get("EnterUserid"))); + ec.addElement(new P().addElement(getLabelManager().get("EnterUserid"))); userid = s.getParser().getRawParameter(USERID, "jsmith"); Input input = new Input(Input.TEXT, USERID, userid.toString()); ec.addElement(input); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); + Element b = ECSFactory.makeButton(getLabelManager().get("Go!")); ec.addElement(b); return ec; @@ -185,11 +184,11 @@ public class SqlAddData extends SequentialLessonAdapter { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("SqlAddDataHint1")); - hints.add(WebGoatI18N.get("SqlAddDataHint2")); - hints.add(WebGoatI18N.get("SqlAddDataHint3")); - hints.add(WebGoatI18N.get("SqlAddDataHint4")); - hints.add(WebGoatI18N.get("SqlAddDataHint5")); + hints.add(getLabelManager().get("SqlAddDataHint1")); + hints.add(getLabelManager().get("SqlAddDataHint2")); + hints.add(getLabelManager().get("SqlAddDataHint3")); + hints.add(getLabelManager().get("SqlAddDataHint4")); + hints.add(getLabelManager().get("SqlAddDataHint5")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/SqlModifyData.java b/src/main/java/org/owasp/webgoat/lessons/SqlModifyData.java index 66e8ebbb0..8e05c9c3e 100644 --- a/src/main/java/org/owasp/webgoat/lessons/SqlModifyData.java +++ b/src/main/java/org/owasp/webgoat/lessons/SqlModifyData.java @@ -19,7 +19,6 @@ import org.apache.ecs.html.PRE; import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -117,7 +116,7 @@ public class SqlModifyData extends SequentialLessonAdapter } else { - ec.addElement(WebGoatI18N.get("NoResultsMatched")); + ec.addElement(getLabelManager().get("NoResultsMatched")); } // see if target data was modified @@ -149,7 +148,7 @@ public class SqlModifyData extends SequentialLessonAdapter } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -161,13 +160,13 @@ public class SqlModifyData extends SequentialLessonAdapter protected Element makeAccountLine(WebSession s) { ElementContainer ec = new ElementContainer(); - ec.addElement(new P().addElement(WebGoatI18N.get("EnterUserid"))); + ec.addElement(new P().addElement(getLabelManager().get("EnterUserid"))); userid = s.getParser().getRawParameter(USERID, "jsmith"); Input input = new Input(Input.TEXT, USERID, userid.toString()); ec.addElement(input); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); + Element b = ECSFactory.makeButton(getLabelManager().get("Go!")); ec.addElement(b); return ec; @@ -203,11 +202,11 @@ public class SqlModifyData extends SequentialLessonAdapter { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("SqlModifyDataHint1")); - hints.add(WebGoatI18N.get("SqlModifyDataHint2")); - hints.add(WebGoatI18N.get("SqlModifyDataHint3")); - hints.add(WebGoatI18N.get("SqlModifyDataHint4")); - hints.add(WebGoatI18N.get("SqlModifyDataHint5")); + hints.add(getLabelManager().get("SqlModifyDataHint1")); + hints.add(getLabelManager().get("SqlModifyDataHint2")); + hints.add(getLabelManager().get("SqlModifyDataHint3")); + hints.add(getLabelManager().get("SqlModifyDataHint4")); + hints.add(getLabelManager().get("SqlModifyDataHint5")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/SqlNumericInjection.java b/src/main/java/org/owasp/webgoat/lessons/SqlNumericInjection.java index 4b5ecd67e..64693cf29 100644 --- a/src/main/java/org/owasp/webgoat/lessons/SqlNumericInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/SqlNumericInjection.java @@ -22,7 +22,6 @@ import org.apache.ecs.html.Select; import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -131,14 +130,14 @@ public class SqlNumericInjection extends SequentialLessonAdapter getLessonTracker(s).setStage(2); StringBuffer msg = new StringBuffer(); - msg.append(WebGoatI18N.get("NumericSqlInjectionSecondStage")); + msg.append(getLabelManager().get("NumericSqlInjectionSecondStage")); s.setMessage(msg.toString()); } } else { - ec.addElement(WebGoatI18N.get("NoResultsMatched")); + ec.addElement(getLabelManager().get("NoResultsMatched")); } } catch (SQLException sqle) @@ -147,7 +146,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -158,7 +157,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter { ElementContainer ec = new ElementContainer(); - ec.addElement(WebGoatI18N.get("NumericSqlInjectionSecondStage2")); + ec.addElement(getLabelManager().get("NumericSqlInjectionSecondStage2")); // if ( s.getParser().getRawParameter( ACCT_NUM, "101" ).equals("restart")) // { // getLessonTracker(s).setStage(1); @@ -202,14 +201,14 @@ public class SqlNumericInjection extends SequentialLessonAdapter } else { - ec.addElement(WebGoatI18N.get("NoResultsMatched")); + ec.addElement(getLabelManager().get("NoResultsMatched")); } } catch (SQLException sqle) { ec.addElement(new P().addElement(sqle.getMessage())); } catch (NumberFormatException npe) { - ec.addElement(new P().addElement(WebGoatI18N.get("ErrorParsingAsNumber") + npe.getMessage())); + ec.addElement(new P().addElement(getLabelManager().get("ErrorParsingAsNumber") + npe.getMessage())); } } catch (Exception e) { @@ -224,7 +223,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter { ElementContainer ec = new ElementContainer(); - ec.addElement(new P().addElement(WebGoatI18N.get("SelectYourStation"))); + ec.addElement(new P().addElement(getLabelManager().get("SelectYourStation"))); Map stations = getStations(s); Select select = new Select(STATION_ID); @@ -237,7 +236,7 @@ public class SqlNumericInjection extends SequentialLessonAdapter ec.addElement(select); ec.addElement(new P()); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); + Element b = ECSFactory.makeButton(getLabelManager().get("Go!")); ec.addElement(b); return ec; @@ -307,10 +306,10 @@ public class SqlNumericInjection extends SequentialLessonAdapter protected List getHints(WebSession s) { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("SqlNumericInjectionHint1")); - hints.add(WebGoatI18N.get("SqlNumericInjectionHint2")); - hints.add(WebGoatI18N.get("SqlNumericInjectionHint3")); - hints.add(WebGoatI18N.get("SqlNumericInjectionHint4")); + hints.add(getLabelManager().get("SqlNumericInjectionHint1")); + hints.add(getLabelManager().get("SqlNumericInjectionHint2")); + hints.add(getLabelManager().get("SqlNumericInjectionHint3")); + hints.add(getLabelManager().get("SqlNumericInjectionHint4")); diff --git a/src/main/java/org/owasp/webgoat/lessons/SqlStringInjection.java b/src/main/java/org/owasp/webgoat/lessons/SqlStringInjection.java index e5b02048a..ea5d60836 100644 --- a/src/main/java/org/owasp/webgoat/lessons/SqlStringInjection.java +++ b/src/main/java/org/owasp/webgoat/lessons/SqlStringInjection.java @@ -18,7 +18,6 @@ import org.apache.ecs.html.PRE; import org.owasp.webgoat.session.DatabaseUtilities; import org.owasp.webgoat.session.ECSFactory; import org.owasp.webgoat.session.WebSession; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -114,14 +113,14 @@ public class SqlStringInjection extends SequentialLessonAdapter StringBuffer msg = new StringBuffer(); - msg.append(WebGoatI18N.get("StringSqlInjectionSecondStage")); + msg.append(getLabelManager().get("StringSqlInjectionSecondStage")); s.setMessage(msg.toString()); } } else { - ec.addElement(WebGoatI18N.get("NoResultsMatched")); + ec.addElement(getLabelManager().get("NoResultsMatched")); } } catch (SQLException sqle) { @@ -130,7 +129,7 @@ public class SqlStringInjection extends SequentialLessonAdapter } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -141,7 +140,7 @@ public class SqlStringInjection extends SequentialLessonAdapter { ElementContainer ec = new ElementContainer(); - ec.addElement(WebGoatI18N.get("StringSqlInjectionSecondStage")); + ec.addElement(getLabelManager().get("StringSqlInjectionSecondStage")); if (s.getParser().getRawParameter(ACCT_NAME, "YOUR_NAME").equals("restart")) { getLessonTracker(s).getLessonProperties().setProperty(STAGE, "1"); @@ -180,7 +179,7 @@ public class SqlStringInjection extends SequentialLessonAdapter } else { - ec.addElement(WebGoatI18N.get("NoResultsMatched")); + ec.addElement(getLabelManager().get("NoResultsMatched")); } } catch (SQLException sqle) { @@ -188,7 +187,7 @@ public class SqlStringInjection extends SequentialLessonAdapter } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -198,13 +197,13 @@ public class SqlStringInjection extends SequentialLessonAdapter protected Element makeAccountLine(WebSession s) { ElementContainer ec = new ElementContainer(); - ec.addElement(new P().addElement(WebGoatI18N.get("EnterLastName"))); + ec.addElement(new P().addElement(getLabelManager().get("EnterLastName"))); accountName = s.getParser().getRawParameter(ACCT_NAME, "Your Name"); Input input = new Input(Input.TEXT, ACCT_NAME, accountName.toString()); ec.addElement(input); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!")); + Element b = ECSFactory.makeButton(getLabelManager().get("Go!")); ec.addElement(b); return ec; @@ -230,10 +229,10 @@ public class SqlStringInjection extends SequentialLessonAdapter { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("SqlStringInjectionHint1")); - hints.add(WebGoatI18N.get("SqlStringInjectionHint2")); - hints.add(WebGoatI18N.get("SqlStringInjectionHint3")); - hints.add(WebGoatI18N.get("SqlStringInjectionHint4")); + hints.add(getLabelManager().get("SqlStringInjectionHint1")); + hints.add(getLabelManager().get("SqlStringInjectionHint2")); + hints.add(getLabelManager().get("SqlStringInjectionHint3")); + hints.add(getLabelManager().get("SqlStringInjectionHint4")); return hints; } diff --git a/src/main/java/org/owasp/webgoat/lessons/StoredXss.java b/src/main/java/org/owasp/webgoat/lessons/StoredXss.java index 2807bc1b9..2d6902200 100644 --- a/src/main/java/org/owasp/webgoat/lessons/StoredXss.java +++ b/src/main/java/org/owasp/webgoat/lessons/StoredXss.java @@ -21,7 +21,6 @@ import org.apache.ecs.html.Table; import org.apache.ecs.html.TextArea; import org.owasp.webgoat.session.*; import org.owasp.webgoat.util.HtmlEncoder; -import org.owasp.webgoat.util.WebGoatI18N; /** * ************************************************************************************************* @@ -110,7 +109,7 @@ public class StoredXss extends LessonAdapter { // that could be trapped here but we will let them try. One error would be something // like "Characters found after end of SQL statement." if (e.getMessage().indexOf("No ResultSet was produced") == -1) { - s.setMessage(WebGoatI18N.get("CouldNotAddMessage")); + s.setMessage(getLabelManager().get("CouldNotAddMessage")); } e.printStackTrace(); } @@ -151,10 +150,10 @@ public class StoredXss extends LessonAdapter { */ protected List getHints(WebSession s) { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("StoredXssHint1")); - hints.add(WebGoatI18N.get("StoredXssHint2")); - hints.add(WebGoatI18N.get("StoredXssHint3")); - hints.add(WebGoatI18N.get("StoredXssHint4")); + hints.add(getLabelManager().get("StoredXssHint1")); + hints.add(getLabelManager().get("StoredXssHint2")); + hints.add(getLabelManager().get("StoredXssHint3")); + hints.add(getLabelManager().get("StoredXssHint4")); return hints; } @@ -201,14 +200,14 @@ public class StoredXss extends LessonAdapter { ResultSet results = statement.executeQuery(); if ((results != null) && results.first()) { - ec.addElement(new H1(WebGoatI18N.get("MessageContentsFor") + ": " + results.getString(TITLE_COL))); + ec.addElement(new H1(getLabelManager().get("MessageContentsFor") + ": " + 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(WebGoatI18N.get("Title") + ":")))); + TR row1 = new TR(new TD(new B(new StringElement(getLabelManager().get("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(WebGoatI18N.get("Message") + ":")))); + TR row2 = new TR(new TD(new B(new StringElement(getLabelManager().get("Message") + ":")))); row2.addElement(new TD(new StringElement(messageData))); t.addElement(row2); @@ -217,7 +216,7 @@ public class StoredXss extends LessonAdapter { // if users use a cross site request forgery or XSS to make another user post a // message, // they can see that the message is attributed to that user - TR row3 = new TR(new TD(new StringElement(WebGoatI18N.get("PostedBy") + ":"))); + TR row3 = new TR(new TD(new StringElement(getLabelManager().get("PostedBy") + ":"))); row3.addElement(new TD(new StringElement(results.getString(USER_COL)))); t.addElement(row3); @@ -232,11 +231,11 @@ public class StoredXss extends LessonAdapter { } else { if (messageNum != 0) { - ec.addElement(new P().addElement(WebGoatI18N.get("CouldNotFindMessage") + messageNum)); + ec.addElement(new P().addElement(getLabelManager().get("CouldNotFindMessage") + messageNum)); } } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -253,14 +252,14 @@ public class StoredXss extends LessonAdapter { 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(WebGoatI18N.get("Title") + ": "))); + row1.addElement(new TD(new StringElement(getLabelManager().get("Title") + ": "))); Input inputTitle = new Input(Input.TEXT, TITLE, ""); row1.addElement(new TD(inputTitle)); TD item1 = new TD(); item1.setVAlign("TOP"); - item1.addElement(new StringElement(WebGoatI18N.get("Message") + ": ")); + item1.addElement(new StringElement(getLabelManager().get("Message") + ": ")); row2.addElement(item1); TD item2 = new TD(); @@ -270,7 +269,7 @@ public class StoredXss extends LessonAdapter { t.addElement(row1); t.addElement(row2); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit")); + Element b = ECSFactory.makeButton(getLabelManager().get("Submit")); ElementContainer ec = new ElementContainer(); ec.addElement(t); ec.addElement(new P().addElement(b)); @@ -312,11 +311,11 @@ public class StoredXss extends LessonAdapter { } } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGeneratingMessageList")); + s.setMessage(getLabelManager().get("ErrorGeneratingMessageList")); } ElementContainer ec = new ElementContainer(); - ec.addElement(new H1(WebGoatI18N.get("MessageList"))); + ec.addElement(new H1(getLabelManager().get("MessageList"))); ec.addElement(t); return (ec); diff --git a/src/main/java/org/owasp/webgoat/lessons/WeakAuthenticationCookie.java b/src/main/java/org/owasp/webgoat/lessons/WeakAuthenticationCookie.java index 9211e1686..f6b786485 100644 --- a/src/main/java/org/owasp/webgoat/lessons/WeakAuthenticationCookie.java +++ b/src/main/java/org/owasp/webgoat/lessons/WeakAuthenticationCookie.java @@ -18,7 +18,6 @@ import org.apache.ecs.html.TH; import org.apache.ecs.html.TR; import org.apache.ecs.html.Table; import org.owasp.webgoat.session.*; -import org.owasp.webgoat.util.WebGoatI18N; /*************************************************************************************************** @@ -104,7 +103,7 @@ public class WeakAuthenticationCookie extends LessonAdapter } else { - s.setMessage(WebGoatI18N.get("InvalidCookie")); + s.setMessage(getLabelManager().get("InvalidCookie")); s.eatCookies(); } } @@ -142,14 +141,14 @@ public class WeakAuthenticationCookie extends LessonAdapter if (loginID != "") { Cookie newCookie = new Cookie(AUTHCOOKIE, loginID); - s.setMessage(WebGoatI18N.get("IdentityRemembered")); + s.setMessage(getLabelManager().get("IdentityRemembered")); s.getResponse().addCookie(newCookie); return (username); } else { - s.setMessage(WebGoatI18N.get("InvalidUsernameAndPassword")); + s.setMessage(getLabelManager().get("InvalidUsernameAndPassword")); } } @@ -169,7 +168,7 @@ public class WeakAuthenticationCookie extends LessonAdapter if (logout) { - s.setMessage(WebGoatI18N.get("PasswordForgotten")); + s.setMessage(getLabelManager().get("PasswordForgotten")); s.eatCookies(); return (makeLogin(s)); @@ -186,7 +185,7 @@ public class WeakAuthenticationCookie extends LessonAdapter if ((user != null) && (user.length() > 0)) { return (makeUser(s, user, "PARAMETERS")); } } catch (Exception e) { - s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName()); + s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName()); e.printStackTrace(); } @@ -251,10 +250,10 @@ public class WeakAuthenticationCookie extends LessonAdapter protected List getHints(WebSession s) { List hints = new ArrayList(); - hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints1")); - hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints2")); - hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints3")); - hints.add(WebGoatI18N.get("WeakAuthenticationCookieHints4")); + hints.add(getLabelManager().get("WeakAuthenticationCookieHints1")); + hints.add(getLabelManager().get("WeakAuthenticationCookieHints2")); + hints.add(getLabelManager().get("WeakAuthenticationCookieHints3")); + hints.add(getLabelManager().get("WeakAuthenticationCookieHints4")); return hints; @@ -290,7 +289,7 @@ public class WeakAuthenticationCookie extends LessonAdapter { ElementContainer ec = new ElementContainer(); - ec.addElement(new H1().addElement(WebGoatI18N.get("SignIn"))); + ec.addElement(new H1().addElement(getLabelManager().get("SignIn"))); Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(0).setWidth("90%").setAlign("center"); if (s.isColor()) @@ -300,12 +299,12 @@ public class WeakAuthenticationCookie extends LessonAdapter TR tr = new TR(); tr.addElement(new TH() - .addElement(WebGoatI18N.get("WeakAuthenticationCookiePleaseSignIn")) + .addElement(getLabelManager().get("WeakAuthenticationCookiePleaseSignIn")) .setColSpan(2).setAlign("left")); t.addElement(tr); tr = new TR(); - tr.addElement(new TD().addElement("*"+WebGoatI18N.get("RequiredFields")).setWidth("30%")); + tr.addElement(new TD().addElement("*"+getLabelManager().get("RequiredFields")).setWidth("30%")); t.addElement(tr); tr = new TR(); @@ -314,8 +313,8 @@ public class WeakAuthenticationCookie extends LessonAdapter 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"))))); + row1.addElement(new TD(new B(new StringElement("*"+getLabelManager().get("UserName"))))); + row2.addElement(new TD(new B(new StringElement("*"+getLabelManager().get("Password"))))); Input input1 = new Input(Input.TEXT, USERNAME, ""); Input input2 = new Input(Input.PASSWORD, PASSWORD, ""); @@ -324,7 +323,7 @@ public class WeakAuthenticationCookie extends LessonAdapter t.addElement(row1); t.addElement(row2); - Element b = ECSFactory.makeButton(WebGoatI18N.get("Login")); + Element b = ECSFactory.makeButton(getLabelManager().get("Login")); t.addElement(new TR(new TD(b))); ec.addElement(t); @@ -347,10 +346,10 @@ public class WeakAuthenticationCookie extends LessonAdapter 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)); - ec.addElement(new P().addElement(ECSFactory.makeLink(WebGoatI18N.get("Logout"), LOGOUT, true))); - ec.addElement(new P().addElement(ECSFactory.makeLink(WebGoatI18N.get("Refresh"), "", ""))); + ec.addElement(new P().addElement(getLabelManager().get("WelcomeUser") + user)); + ec.addElement(new P().addElement(getLabelManager().get("YouHaveBeenAuthenticatedWith") + method)); + ec.addElement(new P().addElement(ECSFactory.makeLink(getLabelManager().get("Logout"), LOGOUT, true))); + ec.addElement(new P().addElement(ECSFactory.makeLink(getLabelManager().get("Refresh"), "", ""))); return (ec); } diff --git a/src/main/java/org/owasp/webgoat/session/Course.java b/src/main/java/org/owasp/webgoat/session/Course.java index 3894cd860..9245db83c 100644 --- a/src/main/java/org/owasp/webgoat/session/Course.java +++ b/src/main/java/org/owasp/webgoat/session/Course.java @@ -1,398 +1,397 @@ -package org.owasp.webgoat.session; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.LinkedList; -import javax.servlet.ServletContext; -import org.owasp.webgoat.HammerHead; -import org.owasp.webgoat.lessons.AbstractLesson; -import org.owasp.webgoat.lessons.Category; -import org.owasp.webgoat.util.WebGoatI18N; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ************************************************************************************************* - * - * - * This file is part of WebGoat, an Open Web Application Security Project - * utility. For details, please see http://www.owasp.org/ - * - * Copyright (c) 2002 - 20014 Bruce Mayhew - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; either version 2 of the License, or (at your option) any later - * version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place - Suite 330, Boston, MA 02111-1307, USA. - * - * Getting Source ============== - * - * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository - * for free software projects. - * - * For details, please see http://webgoat.github.io - * - * @author Bruce Mayhew WebGoat - * @created October 28, 2003 - */ -public class Course { - - final Logger logger = LoggerFactory.getLogger(Course.class); - - private final List lessons = new LinkedList(); - - private final static String PROPERTIES_FILENAME = HammerHead.propertiesPath; - - private WebgoatProperties properties = null; - - private final List files = new LinkedList(); - - private WebgoatContext webgoatContext; - - public Course() { - try { - properties = new WebgoatProperties(PROPERTIES_FILENAME); - } catch (IOException e) { - logger.error("Error loading webgoat properties", e); - } - } - - /** - * Take an absolute file and return the filename. - * - * Ex. /etc/password becomes password - * - * @param s - * @return the file name - */ - private static String getFileName(String s) { - String fileName = new File(s).getName(); - - if (fileName.contains("/")) { - fileName = fileName.substring(fileName.lastIndexOf("/"), fileName.length()); - } - - if (fileName.contains(".")) { - fileName = fileName.substring(0, fileName.indexOf(".")); - } - - return fileName; - } - - /** - * Take a class name and return the equivalent file name - * - * Ex. org.owasp.webgoat becomes org/owasp/webgoat.java - * - * @param className - * @return - */ - private static String getSourceFile(String className) { - StringBuilder sb = new StringBuilder(); - - sb.append(className.replace(".", "/")); - sb.append(".java"); - - return sb.toString(); - } - - /** - * Takes a file name and builds the class file name - * - * @param fileName Description of the Parameter - * @param path Description of the Parameter - * @return Description of the Return Value - */ - private static String getClassFile(String fileName, String path) { - String ext = ".class"; - fileName = fileName.trim(); - - /** - * We do not handle directories. We do not handle files with different - * extensions - */ - if (fileName.endsWith("/") || !fileName.endsWith(ext)) { - return null; - } - - // if the file is in /WEB-INF/classes strip the dir info off - int index = fileName.indexOf("/WEB-INF/classes/"); - if (index != -1) { - fileName = fileName.substring(index + "/WEB-INF/classes/".length(), fileName.length() - ext.length()); - fileName = fileName.replace('/', '.'); - fileName = fileName.replace('\\', '.'); - } else { - // Strip off the leading path info - fileName = fileName.substring(path.length(), fileName.length() - ext.length()); - } - - return fileName; - } - - /** - * Gets the categories attribute of the Course object - * - * @return The categories value - */ - public List getCategories() { - List categories = new ArrayList(); - for (AbstractLesson lesson : lessons) { - if (!categories.contains(lesson.getCategory())) { - categories.add(lesson.getCategory()); - } - } - - Collections.sort(categories); - - return categories; - } - - /** - * Gets the firstLesson attribute of the Course object - * - * @return The firstLesson value - */ - public AbstractLesson getFirstLesson() { - List roles = new ArrayList(); - roles.add(AbstractLesson.USER_ROLE); - // Category 0 is the admin function. We want the first real category - // to be returned. This is noramally the General category and the Http Basics lesson - return ((AbstractLesson) getLessons((Category) getCategories().get(0), roles).get(0)); - } - - /** - * Gets the lesson attribute of the Course object - * - * @param s - * @param lessonId Description of the Parameter - * @param roles - * @return The lesson value - */ - public AbstractLesson getLesson(WebSession s, int lessonId, List roles) { - if (s.isHackedAdmin()) { - roles.add(AbstractLesson.HACKED_ADMIN_ROLE); - } - // System.out.println("getLesson() with roles: " + roles); - Iterator iter = lessons.iterator(); - - while (iter.hasNext()) { - AbstractLesson lesson = iter.next(); - - // System.out.println("getLesson() at role: " + lesson.getRole()); - if (lesson.getScreenId() == lessonId && roles.contains(lesson.getRole())) { - return lesson; - } - } - - return null; - } - - public AbstractLesson getLesson(WebSession s, int lessonId, String role) { - List roles = new ArrayList(); - roles.add(role); - return getLesson(s, lessonId, roles); - } - - public List getLessons(WebSession s, String role) { - List roles = new ArrayList(); - roles.add(role); - return getLessons(s, roles); - } - - /** - * Gets the lessons attribute of the Course object - * - * @param s - * @param roles - * @return The lessons value - */ - public List getLessons(WebSession s, List roles) { - if (s.isHackedAdmin()) { - roles.add(AbstractLesson.HACKED_ADMIN_ROLE); - } - List lessonList = new ArrayList(); - Iterator categoryIter = getCategories().iterator(); - - while (categoryIter.hasNext()) { - lessonList.addAll(getLessons(s, (Category) categoryIter.next(), roles)); - } - return lessonList; - } - - /** - * Gets the lessons attribute of the Course object - * - * @param category Description of the Parameter - * @param role Description of the Parameter - * @return The lessons value - */ - private List getLessons(Category category, List roles) { - List lessonList = new ArrayList(); - - for (AbstractLesson lesson : lessons) { - if (lesson.getCategory().equals(category) && roles.contains(lesson.getRole())) { - lessonList.add(lesson); - } - } - - Collections.sort(lessonList); - // System.out.println(java.util.Arrays.asList(lessonList)); - return lessonList; - } - - public List getLessons(WebSession s, Category category, String role) { - List roles = new ArrayList(); - roles.add(role); - return getLessons(s, category, roles); - } - - public List getLessons(WebSession s, Category category, List roles) { - if (s.isHackedAdmin()) { - roles.add(AbstractLesson.HACKED_ADMIN_ROLE); - } - return getLessons(category, roles); - } - - public AbstractLesson getLesson(int lessonId) { - for (AbstractLesson l : lessons) { - if (l.getScreenId() == lessonId) { - return l; - } - } - return null; - } - - /** - * Load all of the filenames into a temporary cache - * - * @param context - * @param path - */ - private void loadFiles(ServletContext context, String path) { - logger.debug("Loading files into cache, path: " + path); - Set resourcePaths = context.getResourcePaths(path); - if (resourcePaths == null) { - logger.error("Unable to load file cache for courses, this is probably a bug or configuration issue"); - return; - } - Iterator itr = resourcePaths.iterator(); - - while (itr.hasNext()) { - String file = (String) itr.next(); - - if (file.length() != 1 && file.endsWith("/")) { - loadFiles(context, file); - } else { - files.add(file); - } - } - } - - /** - * Instantiate all the lesson objects into a cache - * - * @param path - */ - private void loadLessons(String path) { - for (String file : files) { - String className = getClassFile(file, path); - - if (className != null && !className.endsWith("_i")) { - try { - Class c = Class.forName(className); - Object o = c.newInstance(); - - if (o instanceof AbstractLesson) { - AbstractLesson lesson = (AbstractLesson) o; - lesson.setWebgoatContext(webgoatContext); - - lesson.update(properties); - - if (lesson.getHidden() == false) { - lessons.add(lesson); - } - } - } catch (Exception e) { - logger.error("Error in loadLessons: ", e); - } - } - } - } - - private String getLanguageFromFileName(String first, String absoluteFile) { - int p1 = absoluteFile.indexOf("/", absoluteFile.indexOf(first) + 1); - int p2 = absoluteFile.indexOf("/", p1 + 1); - String langStr = absoluteFile.substring(p1 + 1, p2); - - return langStr; - } - - /** - * For each lesson, set the source file and lesson file - */ - private void loadResources() { - for (AbstractLesson lesson : lessons) { - logger.info("Loading resources for lesson -> " + lesson.getName()); - String className = lesson.getClass().getName(); - String classFile = getSourceFile(className); - logger.info("Lesson classname: " + className); - logger.info("Lesson java file: " + classFile); - - for (String absoluteFile : files) { - String fileName = getFileName(absoluteFile); - //logger.debug("Course: looking at file: " + absoluteFile); - - if (absoluteFile.endsWith(classFile)) { - logger.info("Set source file for " + classFile); - lesson.setSourceFileName(absoluteFile); - } - - if (absoluteFile.startsWith("/lesson_plans") && absoluteFile.endsWith(".html") - && className.endsWith(fileName)) { - logger.info("setting lesson plan file " + absoluteFile + " for lesson " - + lesson.getClass().getName()); - logger.info("fileName: " + fileName + " == className: " + className); - String language = getLanguageFromFileName("/lesson_plans", absoluteFile); - lesson.setLessonPlanFileName(language, absoluteFile); - WebGoatI18N.loadLanguage(language); - } - if (absoluteFile.startsWith("/lesson_solutions") && absoluteFile.endsWith(".html") - && className.endsWith(fileName)) { - logger.info("setting lesson solution file " + absoluteFile + " for lesson " - + lesson.getClass().getName()); - logger.info("fileName: " + fileName + " == className: " + className); - lesson.setLessonSolutionFileName(absoluteFile); - } - } - } - } - - /** - * Description of the Method - * - * @param webgoatContext - * @param path Description of the Parameter - * @param context Description of the Parameter - */ - public void loadCourses(WebgoatContext webgoatContext, ServletContext context, String path) { - logger.info("Loading courses: " + path); - this.webgoatContext = webgoatContext; - loadFiles(context, path); - loadLessons(path); - loadResources(); - } -} +package org.owasp.webgoat.session; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.LinkedList; +import javax.servlet.ServletContext; +import org.owasp.webgoat.HammerHead; +import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Category; +import org.owasp.webgoat.util.WebGoatI18N; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ************************************************************************************************* + * + * + * This file is part of WebGoat, an Open Web Application Security Project + * utility. For details, please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 59 Temple + * Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository + * for free software projects. + * + * For details, please see http://webgoat.github.io + * + * @author Bruce Mayhew WebGoat + * @created October 28, 2003 + */ +public class Course { + + final Logger logger = LoggerFactory.getLogger(Course.class); + + private final List lessons = new LinkedList(); + + private final static String PROPERTIES_FILENAME = HammerHead.propertiesPath; + + private WebgoatProperties properties = null; + + private final List files = new LinkedList(); + + private WebgoatContext webgoatContext; + + public Course() { + try { + properties = new WebgoatProperties(PROPERTIES_FILENAME); + } catch (IOException e) { + logger.error("Error loading webgoat properties", e); + } + } + + /** + * Take an absolute file and return the filename. + * + * Ex. /etc/password becomes password + * + * @param s + * @return the file name + */ + private static String getFileName(String s) { + String fileName = new File(s).getName(); + + if (fileName.contains("/")) { + fileName = fileName.substring(fileName.lastIndexOf("/"), fileName.length()); + } + + if (fileName.contains(".")) { + fileName = fileName.substring(0, fileName.indexOf(".")); + } + + return fileName; + } + + /** + * Take a class name and return the equivalent file name + * + * Ex. org.owasp.webgoat becomes org/owasp/webgoat.java + * + * @param className + * @return + */ + private static String getSourceFile(String className) { + StringBuilder sb = new StringBuilder(); + + sb.append(className.replace(".", "/")); + sb.append(".java"); + + return sb.toString(); + } + + /** + * Takes a file name and builds the class file name + * + * @param fileName Description of the Parameter + * @param path Description of the Parameter + * @return Description of the Return Value + */ + private static String getClassFile(String fileName, String path) { + String ext = ".class"; + fileName = fileName.trim(); + + /** + * We do not handle directories. We do not handle files with different + * extensions + */ + if (fileName.endsWith("/") || !fileName.endsWith(ext)) { + return null; + } + + // if the file is in /WEB-INF/classes strip the dir info off + int index = fileName.indexOf("/WEB-INF/classes/"); + if (index != -1) { + fileName = fileName.substring(index + "/WEB-INF/classes/".length(), fileName.length() - ext.length()); + fileName = fileName.replace('/', '.'); + fileName = fileName.replace('\\', '.'); + } else { + // Strip off the leading path info + fileName = fileName.substring(path.length(), fileName.length() - ext.length()); + } + + return fileName; + } + + /** + * Gets the categories attribute of the Course object + * + * @return The categories value + */ + public List getCategories() { + List categories = new ArrayList(); + for (AbstractLesson lesson : lessons) { + if (!categories.contains(lesson.getCategory())) { + categories.add(lesson.getCategory()); + } + } + + Collections.sort(categories); + + return categories; + } + + /** + * Gets the firstLesson attribute of the Course object + * + * @return The firstLesson value + */ + public AbstractLesson getFirstLesson() { + List roles = new ArrayList(); + roles.add(AbstractLesson.USER_ROLE); + // Category 0 is the admin function. We want the first real category + // to be returned. This is noramally the General category and the Http Basics lesson + return ((AbstractLesson) getLessons((Category) getCategories().get(0), roles).get(0)); + } + + /** + * Gets the lesson attribute of the Course object + * + * @param s + * @param lessonId Description of the Parameter + * @param roles + * @return The lesson value + */ + public AbstractLesson getLesson(WebSession s, int lessonId, List roles) { + if (s.isHackedAdmin()) { + roles.add(AbstractLesson.HACKED_ADMIN_ROLE); + } + // System.out.println("getLesson() with roles: " + roles); + Iterator iter = lessons.iterator(); + + while (iter.hasNext()) { + AbstractLesson lesson = iter.next(); + + // System.out.println("getLesson() at role: " + lesson.getRole()); + if (lesson.getScreenId() == lessonId && roles.contains(lesson.getRole())) { + return lesson; + } + } + + return null; + } + + public AbstractLesson getLesson(WebSession s, int lessonId, String role) { + List roles = new ArrayList(); + roles.add(role); + return getLesson(s, lessonId, roles); + } + + public List getLessons(WebSession s, String role) { + List roles = new ArrayList(); + roles.add(role); + return getLessons(s, roles); + } + + /** + * Gets the lessons attribute of the Course object + * + * @param s + * @param roles + * @return The lessons value + */ + public List getLessons(WebSession s, List roles) { + if (s.isHackedAdmin()) { + roles.add(AbstractLesson.HACKED_ADMIN_ROLE); + } + List lessonList = new ArrayList(); + Iterator categoryIter = getCategories().iterator(); + + while (categoryIter.hasNext()) { + lessonList.addAll(getLessons(s, (Category) categoryIter.next(), roles)); + } + return lessonList; + } + + /** + * Gets the lessons attribute of the Course object + * + * @param category Description of the Parameter + * @param role Description of the Parameter + * @return The lessons value + */ + private List getLessons(Category category, List roles) { + List lessonList = new ArrayList(); + + for (AbstractLesson lesson : lessons) { + if (lesson.getCategory().equals(category) && roles.contains(lesson.getRole())) { + lessonList.add(lesson); + } + } + + Collections.sort(lessonList); + // System.out.println(java.util.Arrays.asList(lessonList)); + return lessonList; + } + + public List getLessons(WebSession s, Category category, String role) { + List roles = new ArrayList(); + roles.add(role); + return getLessons(s, category, roles); + } + + public List getLessons(WebSession s, Category category, List roles) { + if (s.isHackedAdmin()) { + roles.add(AbstractLesson.HACKED_ADMIN_ROLE); + } + return getLessons(category, roles); + } + + public AbstractLesson getLesson(int lessonId) { + for (AbstractLesson l : lessons) { + if (l.getScreenId() == lessonId) { + return l; + } + } + return null; + } + + /** + * Load all of the filenames into a temporary cache + * + * @param context + * @param path + */ + private void loadFiles(ServletContext context, String path) { + logger.debug("Loading files into cache, path: " + path); + Set resourcePaths = context.getResourcePaths(path); + if (resourcePaths == null) { + logger.error("Unable to load file cache for courses, this is probably a bug or configuration issue"); + return; + } + Iterator itr = resourcePaths.iterator(); + + while (itr.hasNext()) { + String file = (String) itr.next(); + + if (file.length() != 1 && file.endsWith("/")) { + loadFiles(context, file); + } else { + files.add(file); + } + } + } + + /** + * Instantiate all the lesson objects into a cache + * + * @param path + */ + private void loadLessons(String path) { + for (String file : files) { + String className = getClassFile(file, path); + + if (className != null && !className.endsWith("_i")) { + try { + Class c = Class.forName(className); + Object o = c.newInstance(); + + if (o instanceof AbstractLesson) { + AbstractLesson lesson = (AbstractLesson) o; + lesson.setWebgoatContext(webgoatContext); + + lesson.update(properties); + + if (lesson.getHidden() == false) { + lessons.add(lesson); + } + } + } catch (Exception e) { + logger.error("Error in loadLessons: ", e); + } + } + } + } + + private String getLanguageFromFileName(String first, String absoluteFile) { + int p1 = absoluteFile.indexOf("/", absoluteFile.indexOf(first) + 1); + int p2 = absoluteFile.indexOf("/", p1 + 1); + String langStr = absoluteFile.substring(p1 + 1, p2); + + return langStr; + } + + /** + * For each lesson, set the source file and lesson file + */ + private void loadResources() { + for (AbstractLesson lesson : lessons) { + logger.info("Loading resources for lesson -> " + lesson.getName()); + String className = lesson.getClass().getName(); + String classFile = getSourceFile(className); + logger.info("Lesson classname: " + className); + logger.info("Lesson java file: " + classFile); + + for (String absoluteFile : files) { + String fileName = getFileName(absoluteFile); + //logger.debug("Course: looking at file: " + absoluteFile); + + if (absoluteFile.endsWith(classFile)) { + logger.info("Set source file for " + classFile); + lesson.setSourceFileName(absoluteFile); + } + + if (absoluteFile.startsWith("/lesson_plans") && absoluteFile.endsWith(".html") + && className.endsWith(fileName)) { + logger.info("setting lesson plan file " + absoluteFile + " for lesson " + + lesson.getClass().getName()); + logger.info("fileName: " + fileName + " == className: " + className); + String language = getLanguageFromFileName("/lesson_plans", absoluteFile); + lesson.setLessonPlanFileName(language, absoluteFile); + } + if (absoluteFile.startsWith("/lesson_solutions") && absoluteFile.endsWith(".html") + && className.endsWith(fileName)) { + logger.info("setting lesson solution file " + absoluteFile + " for lesson " + + lesson.getClass().getName()); + logger.info("fileName: " + fileName + " == className: " + className); + lesson.setLessonSolutionFileName(absoluteFile); + } + } + } + } + + /** + * Description of the Method + * + * @param webgoatContext + * @param path Description of the Parameter + * @param context Description of the Parameter + */ + public void loadCourses(WebgoatContext webgoatContext, ServletContext context, String path) { + logger.info("Loading courses: " + path); + this.webgoatContext = webgoatContext; + loadFiles(context, path); + loadLessons(path); + loadResources(); + } +} diff --git a/src/main/java/org/owasp/webgoat/session/WebSession.java b/src/main/java/org/owasp/webgoat/session/WebSession.java index 266f3f80c..b479a3d7e 100644 --- a/src/main/java/org/owasp/webgoat/session/WebSession.java +++ b/src/main/java/org/owasp/webgoat/session/WebSession.java @@ -1,1044 +1,1047 @@ -package org.owasp.webgoat.session; - -import java.io.IOException; -import java.io.PrintWriter; -import java.security.Principal; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Vector; -import javax.servlet.ServletContext; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.owasp.webgoat.lessons.AbstractLesson; -import org.owasp.webgoat.lessons.Category; -import org.owasp.webgoat.lessons.RandomLessonAdapter; -import org.owasp.webgoat.lessons.SequentialLessonAdapter; -import org.owasp.webgoat.lessons.model.RequestParameter; -import org.owasp.webgoat.util.WebGoatI18N; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ************************************************************************************************* - * - * - * This file is part of WebGoat, an Open Web Application Security Project - * utility. For details, please see http://www.owasp.org/ - * - * Copyright (c) 2002 - 20014 Bruce Mayhew - * - * This program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; either version 2 of the License, or (at your option) any later - * version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * this program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place - Suite 330, Boston, MA 02111-1307, USA. - * - * Getting Source ============== - * - * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository - * for free software projects. - * - * For details, please see http://webgoat.github.io - * - * @author Jeff Williams Aspect - * Security - * @author Bruce Mayhew WebGoat - * - * @created October 28, 2003 - */ -public class WebSession { - - final Logger logger = LoggerFactory.getLogger(WebSession.class); - - /** - * Description of the Field - */ - public final static String ADMIN = "admin"; - - /** - * Tomcat role for a webgoat user - */ - public final static String WEBGOAT_USER = "ROLE_WEBGOAT_USER"; - - /** - * Tomcat role for a webgoat admin - */ - public final static String WEBGOAT_ADMIN = "ROLE_WEBGOAT_ADMIN"; - - /** - * Description of the Field - */ - public final static String CHALLENGE = "Challenge"; - - /** - * Description of the Field - */ - public final static String COLOR = "color"; - - public final static String COURSE = "course"; - - /** - * Description of the Field - */ - public final static int ERROR = 0; - - public static final String STAGE = "stage"; - - /** - * Description of the Field - */ - public final static String JSESSION_ID = "jsessionid"; - - /** - * Description of the Field - */ - public final static String LOGOUT = "Logout"; - - /** - * Description of the Field - */ - public final static String RESTART = "Restart"; - - /** - * Description of the Field - */ - public final static String MENU = "menu"; - - /** - * Description of the Field - */ - public final static String SCREEN = "Screen"; - - /** - * Description of the Field - */ - public final static String SESSION = "websession"; - - public final static String SHOWSOURCE = "ShowSource"; - - public final static String SHOWSOLUTION = "ShowSolution"; - - public final static String SHOWHINTS = "ShowHints"; - - public final static String SHOW = "show"; - - public final static String SHOW_NEXTHINT = "NextHint"; - - public final static String SHOW_PREVIOUSHINT = "PreviousHint"; - - public final static String SHOW_PARAMS = "Params"; - - public final static String SHOW_COOKIES = "Cookies"; - - public final static String SHOW_SOURCE = "Source"; - - public final static String SHOW_SOLUTION = "Solution"; - - public final static String DEBUG = "debug"; - - public final static String LANGUAGE = "language"; - - /** - * Description of the Field - */ - public final static int WELCOME = -1; - - private WebgoatContext webgoatContext; - - private ServletContext context = null; - - private Course course; - - private int currentScreen = WELCOME; - - private int previousScreen = ERROR; - - private int hintNum = -1; - - private boolean isAdmin = false; - - private boolean isHackedAdmin = false; - - private boolean isAuthenticated = false; - - private boolean isColor = false; - - private boolean isDebug = false; - - private boolean hasHackedHackableAdmin = false; - - private StringBuffer message = new StringBuffer(""); - - private ParameterParser myParser; - - private HttpServletRequest request = null; - - private HttpServletResponse response = null; - - private String servletName; - - private HashMap session = new HashMap(); - - private boolean showCookies = false; - - private boolean showParams = false; - - private boolean showRequest = false; - - private boolean showSource = false; - - private boolean showSolution = false; - - private boolean completedHackableAdmin = false; - - private int currentMenu; - - private String currentLanguage = null; - - private List cookiesOnLastRequest; - - private List parmsOnLastRequest; - - /** - * Constructor for the WebSession object - * - * @param webgoatContext - * @param context Description of the Parameter - */ - public WebSession(WebgoatContext webgoatContext, ServletContext context) { - this.webgoatContext = webgoatContext; - // initialize from web.xml - showParams = webgoatContext.isShowParams(); - showCookies = webgoatContext.isShowCookies(); - showSource = webgoatContext.isShowSource(); - showSolution = webgoatContext.isShowSolution(); - showRequest = webgoatContext.isShowRequest(); - currentLanguage = webgoatContext.getDefaultLanguage(); - this.context = context; - - course = new Course(); - course.loadCourses(webgoatContext, context, "/"); - } - - public static synchronized Connection getConnection(WebSession s) throws SQLException { - return DatabaseUtilities.getConnection(s); - } - - public static void returnConnection(WebSession s) { - DatabaseUtilities.returnConnection(s.getUserName()); - } - - /** - * Description of the Method - * - * @param key Description of the Parameter - * @param value Description of the Parameter - */ - public void add(String key, Object value) { - session.put(key, value); - } - - /** - * Description of the Method - */ - public void clearMessage() { - message.setLength(0); - } - - /** - * Description of the Method - */ - public void eatCookies() { - Cookie[] cookies = request.getCookies(); - - for (int loop = 0; loop < cookies.length; loop++) { - if (!cookies[loop].getName().startsWith("JS")) {// skip jsessionid cookie - cookies[loop].setMaxAge(0);// mark for deletion by browser - response.addCookie(cookies[loop]); - } - } - } - - /** - * Description of the Method - * - * @param key Description of the Parameter - * @return Description of the Return Value - */ - public Object get(String key) { - return (session.get(key)); - } - - /** - * Gets the context attribute of the WebSession object - * - * @return The context value - */ - public ServletContext getContext() { - return context; - } - - public List getRoles() { - List roles = new ArrayList(); - - roles.add(AbstractLesson.USER_ROLE); - if (isAdmin()) { - roles.add(AbstractLesson.ADMIN_ROLE); - } - - return roles; - } - - /** - * Sets the admin flag - this routine is ONLY here to allow someone a - * backdoor to setting the user up as an admin. - * - * This is also used by the WebSession to set the admin, but the method - * should be private - * - * @param state - */ - public void setAdmin(boolean state) { - isAdmin = state; - - } - - public String getRole() { - - String role = ""; - if (isAdmin()) { - role = AbstractLesson.ADMIN_ROLE; - } else if (isHackedAdmin()) { - role = AbstractLesson.HACKED_ADMIN_ROLE; - } else if (isChallenge()) { - role = AbstractLesson.CHALLENGE_ROLE; - } else { - role = AbstractLesson.USER_ROLE; - } - - return role; - } - - /** - * Gets the course attribute of the WebSession object - * - * @return The course value - */ - public Course getCourse() { - return course; - } - - public void setCourse(Course course) { - this.course = course; - } - - /** - * Gets the currentScreen attribute of the WebSession object - * - * @return The currentScreen value - */ - public int getCurrentScreen() { - return (currentScreen); - } - - public void setCurrentScreen(int screen) { - currentScreen = screen; - } - - public String getRestartLink() { - return getCurrentLesson().getLink() + "&" + RESTART + "=" + getCurrentScreen(); - } - - public String getCurrentLink() { - String thisLink = "attack"; - Enumeration e = request.getParameterNames(); - boolean isFirstParameter = true; - while (e.hasMoreElements()) { - String name = e.nextElement(); - if (isFirstParameter) { - isFirstParameter = false; - thisLink += "?"; - } else { - thisLink += "&"; - } - thisLink = thisLink + name + "=" + request.getParameter(name); - } - - return thisLink; - } - - public AbstractLesson getCurrentLesson() { - return getCourse().getLesson(this, getCurrentScreen(), getRoles()); - } - - public AbstractLesson getLesson(int id) { - return getCourse().getLesson(this, id, getRoles()); - } - - public List getLessons(Category category) { - return getCourse().getLessons(this, category, getRoles()); - } - - /** - * Gets the hint1 attribute of the WebSession object - * - * @return The hint1 value - */ - private int getHintNum() { - return (hintNum); - } - - public String getHint() { - String hint = null; - int hints = getCurrentLesson().getHintCount(this); - if (getHintNum() > hints) { - hintNum = -1; - } - if (getHintNum() >= 0) // FIXME - { - hint = getCurrentLesson().getHint(this, getHintNum()); - } - - return hint; - } - - public List getParams() { - Vector params = null; - - if (showParams() && getParser() != null) { - params = new Vector(); - - Enumeration e = getParser().getParameterNames(); - - while ((e != null) && e.hasMoreElements()) { - String name = (String) e.nextElement(); - String[] values = getParser().getParameterValues(name); - - for (int loop = 0; (values != null) && (loop < values.length); loop++) { - params.add(new Parameter(name, values[loop])); - // params.add( name + " -> " + values[loop] ); - } - } - - Collections.sort(params); - } - - return params; - } - - public List getCookies() { - List cookies = null; - - if (showCookies()) { - cookies = Arrays.asList(request.getCookies()); - } - - /* - * List cookies = new Vector(); HttpServletRequest request = getRequest(); Cookie[] cookies - * = request.getCookies(); if ( cookies.length == 0 ) { list.addElement( new LI( - * "No Cookies" ) ); } for ( int i = 0; i < cookies.length; i++ ) { Cookie cookie = - * cookies[i]; cookies.add(cookie); //list.addElement( new LI( cookie.getName() + " -> " + - * cookie.getValue() ) ); } - */ - return cookies; - } - - /** - * Gets the cookie attribute of the CookieScreen object - * - * @param s Description of the Parameter - * @return The cookie value - */ - public String getCookie(String cookieName) { - Cookie[] cookies = getRequest().getCookies(); - - for (int i = 0; i < cookies.length; i++) { - if (cookies[i].getName().equalsIgnoreCase(cookieName)) { - return (cookies[i].getValue()); - } - } - - return (null); - } - - public String getSource() { - return "Sorry. No Java Source viewing available."; - // return getCurrentLesson().getSource(this); - } - - public String getSolution() { - return "Sorry. No solution is available."; - // return getCurrentLesson().getSolution(this); - } - - public String getInstructions() { - return getCurrentLesson().getInstructions(this); - } - - /** - * Gets the message attribute of the WebSession object - * - * @return The message value - */ - public String getMessage() { - return (message.toString()); - } - - /** - * Gets the parser attribute of the WebSession object - * - * @return The parser value - */ - public ParameterParser getParser() { - return (myParser); - } - - /** - * Gets the previousScreen attribute of the WebSession object - * - * @return The previousScreen value - */ - public int getPreviousScreen() { - return (previousScreen); - } - - /** - * Gets the request attribute of the WebSession object - * - * @return The request value - */ - public HttpServletRequest getRequest() { - return request; - } - - public void setRequest(HttpServletRequest request) { - this.request = request; - } - - /** - * Gets the response attribute of the WebSession object - * - * @return The response value - */ - public HttpServletResponse getResponse() { - return response; - } - - /** - * Gets the servletName attribute of the WebSession object - * - * @return The servletName value - */ - public String getServletName() { - return (servletName); - } - - /** - * Gets the sourceFile attribute of the WebSession object - * - * @param screen Description of the Parameter - * @return The sourceFile value - */ - public String getWebResource(String fileName) { - // Note: doesn't work for admin path! Maybe with a ../ attack - return (context.getRealPath(fileName)); - } - - /** - * Gets the admin attribute of the WebSession object - * - * @return The admin value - */ - public boolean isAdmin() { - return (isAdmin); - } - - /** - * Gets the hackedAdmin attribute of the WebSession object - * - * @return The hackedAdmin value - */ - public boolean isHackedAdmin() { - return (isHackedAdmin); - } - - /** - * Has the user ever hacked the hackable admin - * - * @return The hackedAdmin value - */ - public boolean completedHackableAdmin() { - return (completedHackableAdmin); - } - - /** - * Gets the authenticated attribute of the WebSession object - * - * @return The authenticated value - */ - public boolean isAuthenticated() { - return (isAuthenticated); - } - - private Map lessonSessions = new Hashtable(); - - public boolean isAuthenticatedInLesson(AbstractLesson lesson) { - boolean authenticated = false; - - LessonSession lessonSession = getLessonSession(lesson); - if (lessonSession != null) { - authenticated = lessonSession.isAuthenticated(); - } - // System.out.println("Authenticated for lesson " + lesson + "? " + authenticated); - - return authenticated; - } - - public boolean isAuthorizedInLesson(int employeeId, String functionId) { - return getCurrentLesson().isAuthorized(this, employeeId, functionId); - } - - public boolean isAuthorizedInLesson(String role, String functionId) { - return getCurrentLesson().isAuthorized(this, role, functionId); - } - - public int getUserIdInLesson() throws ParameterNotFoundException { - return getCurrentLesson().getUserId(this); - } - - public String getUserNameInLesson() throws ParameterNotFoundException { - return getCurrentLesson().getUserName(this); - } - - public void openLessonSession(AbstractLesson lesson) { - System.out.println("Opening new lesson session for lesson " + lesson); - LessonSession lessonSession = new LessonSession(); - lessonSessions.put(lesson, lessonSession); - } - - public void closeLessonSession(AbstractLesson lesson) { - lessonSessions.remove(lesson); - } - - public LessonSession getLessonSession(AbstractLesson lesson) { - return lessonSessions.get(lesson); - } - - /** - * Gets the challenge attribute of the WebSession object - * - * @return The challenge value - */ - public boolean isChallenge() { - if (getCurrentLesson() != null) { - return (Category.CHALLENGE.equals(getCurrentLesson().getCategory())); - } - return false; - } - - /** - * Gets the color attribute of the WebSession object - * - * @return The color value - */ - public boolean isColor() { - return (isColor); - } - - /** - * Gets the screen attribute of the WebSession object - * - * @param value Description of the Parameter - * @return The screen value - */ - public boolean isScreen(int value) { - return (getCurrentScreen() == value); - } - - /** - * Gets the user attribute of the WebSession object - * - * @return The user value - */ - public boolean isUser() { - return (!isAdmin && !isChallenge()); - } - - /** - * Sets the message attribute of the WebSession object - * - * @param text The new message value - */ - public void setMessage(String text) { - message.append("
" + " * " + text); - } - - public void setLineBreak(String text) { - message.append("

" + text); - } - - /** - * Description of the Method - * - * @return Description of the Return Value - */ - public boolean showCookies() { - return (showCookies); - } - - /** - * Description of the Method - * - * @return Description of the Return Value - */ - public boolean showParams() { - return (showParams); - } - - /** - * Description of the Method - * - * @return Description of the Return Value - */ - public boolean showRequest() { - return (showRequest); - } - - /** - * Description of the Method - * - * @return Description of the Return Value - */ - public boolean showSource() { - return (showSource); - } - - public boolean showSolution() { - return (showSolution); - } - - /** - * Gets the userName attribute of the WebSession object - * - * @return The userName value - */ - public String getUserName() { - HttpServletRequest request = getRequest(); - if (request == null) { - throw new RuntimeException("Could not find the ServletRequest in the web session"); - } - Principal principal = request.getUserPrincipal(); - if (principal == null) { - throw new RuntimeException("Could not find the Principal in the Servlet Request"); - } - return principal.getName(); - } - - /** - * Parse parameters from the given request, handle any servlet commands, and - * update this session based on the parameters. - * - * @param request Description of the Parameter - * @param response Description of the Parameter - * @param name Description of the Parameter - */ - public void update(HttpServletRequest request, HttpServletResponse response, String name) throws IOException { - String content = null; - - clearMessage(); - this.request = request; - this.response = response; - this.servletName = name; - - if (myParser == null) { - myParser = new ParameterParser(request); - } else { - myParser.update(request); - } - - if (myParser.getRawParameter(LANGUAGE, null) != null) { - this.currentLanguage = new String(myParser.getRawParameter(LANGUAGE, null)); - WebGoatI18N.setCurrentLanguage(this.currentLanguage); - } - - // System.out.println("Current Screen 1: " + currentScreen ); - // System.out.println("Previous Screen 1: " + previousScreen ); - // FIXME: requires ?Logout=true - // FIXME: doesn't work right -- no reauthentication - // REMOVED - we have explicit logout now via spriing security - /* - if (myParser.getRawParameter(LOGOUT, null) != null) { - System.out.println("Logout " + request.getUserPrincipal()); - eatCookies(); - request.getSession().invalidate(); - currentScreen = WELCOME; - previousScreen = ERROR; - } - */ - - // There are several scenarios where we want the first lesson to be loaded - // 1) Previous screen is Welcome - Start of the course - // 2) After a logout and after the session has been reinitialized - if ((this.getPreviousScreen() == WebSession.WELCOME) || (getRequest().getSession(false) != null - && // getRequest().getSession(false).isNew() && - this.getCurrentScreen() == WebSession.WELCOME && this.getPreviousScreen() == WebSession.ERROR)) { - currentScreen = course.getFirstLesson().getScreenId(); - hintNum = -1; - } - - // System.out.println("Current Screen 2: " + currentScreen ); - // System.out.println("Previous Screen 2: " + previousScreen ); - // update the screen variables - previousScreen = currentScreen; - - try { - // If the request is new there should be no parameters. - // This can occur from a session timeout or a the starting of a new course. - if (!request.getSession().isNew()) { - currentScreen = myParser.getIntParameter(SCREEN, currentScreen); - } else { - if (!myParser.getRawParameter(SCREEN, "NULL").equals("NULL")) { - this.setMessage("Session Timeout - Starting new Session."); - } - } - } catch (Exception e) { - } - - // clear variables when switching screens - if (this.getCurrentScreen() != this.getPreviousScreen()) { - if (webgoatContext.isDebug()) { - setMessage("Changed to a new screen, clearing cookies and hints"); - } - eatCookies(); - hintNum = -1; - } else if (myParser.getRawParameter(STAGE, null) != null) { - AbstractLesson al = getCurrentLesson(); - if (al instanceof SequentialLessonAdapter) { - SequentialLessonAdapter sla = (SequentialLessonAdapter) al; - int stage = myParser.getIntParameter(STAGE, sla.getStage(this)); - if (stage > 0 && stage <= sla.getStageCount()) { - sla.setStage(this, stage); - } - } else if (al instanceof RandomLessonAdapter) { - try { - RandomLessonAdapter rla = (RandomLessonAdapter) al; - int stage = myParser.getIntParameter(STAGE) - 1; - String[] stages = rla.getStages(); - if (stages == null) { - stages = new String[0]; - } - if (stage >= 0 && stage < stages.length) { - rla.setStage(this, stages[stage]); - } - } catch (ParameterNotFoundException pnfe) { - } - } - } // else update global variables for the current screen - else { - // Handle "restart" commands - int lessonId = myParser.getIntParameter(RESTART, -1); - if (lessonId != -1) { - restartLesson(lessonId); - } - // if ( myParser.getBooleanParameter( RESTART, false ) ) - // { - // getCurrentLesson().getLessonTracker( this ).getLessonProperties().setProperty( - // CHALLENGE_STAGE, "1" ); - // } - - // Handle "show" commands - String showCommand = myParser.getStringParameter(SHOW, null); - if (showCommand != null) { - if (showCommand.equalsIgnoreCase(SHOW_PARAMS)) { - showParams = !showParams; - } else if (showCommand.equalsIgnoreCase(SHOW_COOKIES)) { - showCookies = !showCookies; - } else if (showCommand.equalsIgnoreCase(SHOW_SOURCE)) { - content = getSource(); - // showSource = true; - } else if (showCommand.equalsIgnoreCase(SHOW_SOLUTION)) { - content = getSolution(); - // showSource = true; - } else if (showCommand.equalsIgnoreCase(SHOW_NEXTHINT)) { - getNextHint(); - } else if (showCommand.equalsIgnoreCase(SHOW_PREVIOUSHINT)) { - getPreviousHint(); - } - } - - } - - isAdmin = request.isUserInRole(WEBGOAT_ADMIN); - isHackedAdmin = myParser.getBooleanParameter(ADMIN, isAdmin); - if (isHackedAdmin) { - System.out.println("Hacked admin"); - hasHackedHackableAdmin = true; - } - isColor = myParser.getBooleanParameter(COLOR, isColor); - isDebug = myParser.getBooleanParameter(DEBUG, isDebug); - - // System.out.println( "showParams:" + showParams ); - // System.out.println( "showSource:" + showSource ); - // System.out.println( "showSolution:" + showSolution ); - // System.out.println( "showCookies:" + showCookies ); - // System.out.println( "showRequest:" + showRequest ); - if (content != null) { - response.setContentType("text/html"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(content); - out.flush(); - out.close(); - } - } - - public void updateLastAttackRequestInfo(HttpServletRequest request) { - // store cookies - Cookie[] cookies = request.getCookies(); - if (cookies == null) { - this.cookiesOnLastRequest = new ArrayList(); - } else { - this.cookiesOnLastRequest = Arrays.asList(cookies); - } - // store parameters - Map parmMap = request.getParameterMap(); - logger.info("PARM MAP: " + parmMap); - if (parmMap == null) { - this.parmsOnLastRequest = new ArrayList(); - } else { - this.parmsOnLastRequest = new ArrayList(); - for (String name : parmMap.keySet()) { - String[] values = parmMap.get(name); - String delim = ""; - StringBuffer sb = new StringBuffer(); - if (values != null && values.length > 0) { - for (String parm : values) { - sb.append(delim).append(parm); - delim = ","; - } - } - RequestParameter parm = new RequestParameter(name, sb.toString()); - this.parmsOnLastRequest.add(parm); - } - } - } - - public void restartLesson(int lessonId) { - AbstractLesson al = getLesson(lessonId); - System.out.println("Restarting lesson: " + al); - al.getLessonTracker(this).setCompleted(false); - if (al instanceof SequentialLessonAdapter) { - SequentialLessonAdapter sla = (SequentialLessonAdapter) al; - sla.getLessonTracker(this).setStage(1); - } else if (al instanceof RandomLessonAdapter) { - RandomLessonAdapter rla = (RandomLessonAdapter) al; - rla.setStage(this, rla.getStages()[0]); - } - } - - /** - * @param string - */ - public void setHasHackableAdmin(String role) { - hasHackedHackableAdmin = (AbstractLesson.HACKED_ADMIN_ROLE.equals(role) & hasHackedHackableAdmin); - - // if the user got the Admin=true parameter correct AND they accessed an admin screen - if (hasHackedHackableAdmin) { - completedHackableAdmin = true; - } - } - - /** - * @return Returns the isDebug. - */ - public boolean isDebug() { - return isDebug; - } - - /** - * @param header - request header value to return - * @return - */ - public String getHeader(String header) { - return getRequest().getHeader(header); - } - - public String getNextHint() { - String hint = null; - - // FIXME - int maxHints = getCurrentLesson().getHintCount(this); - if (hintNum < maxHints - 1) { - hintNum++; - - // Hints are indexed from 0 - getCurrentLesson().getLessonTracker(this).setMaxHintLevel(getHintNum() + 1); - - hint = (String) getCurrentLesson().getHint(this, getHintNum()); - } - - return hint; - } - - public String getPreviousHint() { - String hint = null; - - if (hintNum > 0) { - hintNum--; - - // Hints are indexed from 0 - getCurrentLesson().getLessonTracker(this).setMaxHintLevel(getHintNum() + 1); - - hint = (String) getCurrentLesson().getHint(this, getHintNum()); - } - - return hint; - } - - public void setCurrentMenu(Integer ranking) { - currentMenu = ranking.intValue(); - } - - public int getCurrentMenu() { - return currentMenu; - } - - public WebgoatContext getWebgoatContext() { - return webgoatContext; - } - - public String getCurrrentLanguage() { - return currentLanguage; - } - - /** - * @return the cookiesOnLastRequest - */ - public List getCookiesOnLastRequest() { - return cookiesOnLastRequest; - } - - /** - * @return the parmsOnLastRequest - */ - public List getParmsOnLastRequest() { - return parmsOnLastRequest; - } - -} +package org.owasp.webgoat.session; + +import java.io.IOException; +import java.io.PrintWriter; +import java.security.Principal; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Vector; +import javax.servlet.ServletContext; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.owasp.webgoat.lessons.AbstractLesson; +import org.owasp.webgoat.lessons.Category; +import org.owasp.webgoat.lessons.RandomLessonAdapter; +import org.owasp.webgoat.lessons.SequentialLessonAdapter; +import org.owasp.webgoat.lessons.model.RequestParameter; +import org.owasp.webgoat.util.BeanProvider; +import org.owasp.webgoat.util.LabelManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ************************************************************************************************* + * + * + * This file is part of WebGoat, an Open Web Application Security Project + * utility. For details, please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 59 Temple + * Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository + * for free software projects. + * + * For details, please see http://webgoat.github.io + * + * @author Jeff Williams Aspect + * Security + * @author Bruce Mayhew WebGoat + * + * @created October 28, 2003 + */ +public class WebSession { + + final Logger logger = LoggerFactory.getLogger(WebSession.class); + + /** + * Description of the Field + */ + public final static String ADMIN = "admin"; + + /** + * Tomcat role for a webgoat user + */ + public final static String WEBGOAT_USER = "ROLE_WEBGOAT_USER"; + + /** + * Tomcat role for a webgoat admin + */ + public final static String WEBGOAT_ADMIN = "ROLE_WEBGOAT_ADMIN"; + + /** + * Description of the Field + */ + public final static String CHALLENGE = "Challenge"; + + /** + * Description of the Field + */ + public final static String COLOR = "color"; + + public final static String COURSE = "course"; + + /** + * Description of the Field + */ + public final static int ERROR = 0; + + public static final String STAGE = "stage"; + + /** + * Description of the Field + */ + public final static String JSESSION_ID = "jsessionid"; + + /** + * Description of the Field + */ + public final static String LOGOUT = "Logout"; + + /** + * Description of the Field + */ + public final static String RESTART = "Restart"; + + /** + * Description of the Field + */ + public final static String MENU = "menu"; + + /** + * Description of the Field + */ + public final static String SCREEN = "Screen"; + + /** + * Description of the Field + */ + public final static String SESSION = "websession"; + + public final static String SHOWSOURCE = "ShowSource"; + + public final static String SHOWSOLUTION = "ShowSolution"; + + public final static String SHOWHINTS = "ShowHints"; + + public final static String SHOW = "show"; + + public final static String SHOW_NEXTHINT = "NextHint"; + + public final static String SHOW_PREVIOUSHINT = "PreviousHint"; + + public final static String SHOW_PARAMS = "Params"; + + public final static String SHOW_COOKIES = "Cookies"; + + public final static String SHOW_SOURCE = "Source"; + + public final static String SHOW_SOLUTION = "Solution"; + + public final static String DEBUG = "debug"; + + public final static String LANGUAGE = "language"; + + /** + * Description of the Field + */ + public final static int WELCOME = -1; + + private WebgoatContext webgoatContext; + + private ServletContext context = null; + + private Course course; + + private int currentScreen = WELCOME; + + private int previousScreen = ERROR; + + private int hintNum = -1; + + private boolean isAdmin = false; + + private boolean isHackedAdmin = false; + + private boolean isAuthenticated = false; + + private boolean isColor = false; + + private boolean isDebug = false; + + private boolean hasHackedHackableAdmin = false; + + private StringBuffer message = new StringBuffer(""); + + private ParameterParser myParser; + + private HttpServletRequest request = null; + + private HttpServletResponse response = null; + + private String servletName; + + private HashMap session = new HashMap(); + + private boolean showCookies = false; + + private boolean showParams = false; + + private boolean showRequest = false; + + private boolean showSource = false; + + private boolean showSolution = false; + + private boolean completedHackableAdmin = false; + + private int currentMenu; + + private String currentLanguage = null; + + private List cookiesOnLastRequest; + + private List parmsOnLastRequest; + + /** + * Constructor for the WebSession object + * + * @param webgoatContext + * @param context Description of the Parameter + */ + public WebSession(WebgoatContext webgoatContext, ServletContext context) { + this.webgoatContext = webgoatContext; + // initialize from web.xml + showParams = webgoatContext.isShowParams(); + showCookies = webgoatContext.isShowCookies(); + showSource = webgoatContext.isShowSource(); + showSolution = webgoatContext.isShowSolution(); + showRequest = webgoatContext.isShowRequest(); + currentLanguage = webgoatContext.getDefaultLanguage(); + this.context = context; + + course = new Course(); + course.loadCourses(webgoatContext, context, "/"); + } + + public static synchronized Connection getConnection(WebSession s) throws SQLException { + return DatabaseUtilities.getConnection(s); + } + + public static void returnConnection(WebSession s) { + DatabaseUtilities.returnConnection(s.getUserName()); + } + + /** + * Description of the Method + * + * @param key Description of the Parameter + * @param value Description of the Parameter + */ + public void add(String key, Object value) { + session.put(key, value); + } + + /** + * Description of the Method + */ + public void clearMessage() { + message.setLength(0); + } + + /** + * Description of the Method + */ + public void eatCookies() { + Cookie[] cookies = request.getCookies(); + + for (int loop = 0; loop < cookies.length; loop++) { + if (!cookies[loop].getName().startsWith("JS")) {// skip jsessionid cookie + cookies[loop].setMaxAge(0);// mark for deletion by browser + response.addCookie(cookies[loop]); + } + } + } + + /** + * Description of the Method + * + * @param key Description of the Parameter + * @return Description of the Return Value + */ + public Object get(String key) { + return (session.get(key)); + } + + /** + * Gets the context attribute of the WebSession object + * + * @return The context value + */ + public ServletContext getContext() { + return context; + } + + public List getRoles() { + List roles = new ArrayList(); + + roles.add(AbstractLesson.USER_ROLE); + if (isAdmin()) { + roles.add(AbstractLesson.ADMIN_ROLE); + } + + return roles; + } + + /** + * Sets the admin flag - this routine is ONLY here to allow someone a + * backdoor to setting the user up as an admin. + * + * This is also used by the WebSession to set the admin, but the method + * should be private + * + * @param state + */ + public void setAdmin(boolean state) { + isAdmin = state; + + } + + public String getRole() { + + String role = ""; + if (isAdmin()) { + role = AbstractLesson.ADMIN_ROLE; + } else if (isHackedAdmin()) { + role = AbstractLesson.HACKED_ADMIN_ROLE; + } else if (isChallenge()) { + role = AbstractLesson.CHALLENGE_ROLE; + } else { + role = AbstractLesson.USER_ROLE; + } + + return role; + } + + /** + * Gets the course attribute of the WebSession object + * + * @return The course value + */ + public Course getCourse() { + return course; + } + + public void setCourse(Course course) { + this.course = course; + } + + /** + * Gets the currentScreen attribute of the WebSession object + * + * @return The currentScreen value + */ + public int getCurrentScreen() { + return (currentScreen); + } + + public void setCurrentScreen(int screen) { + currentScreen = screen; + } + + public String getRestartLink() { + return getCurrentLesson().getLink() + "&" + RESTART + "=" + getCurrentScreen(); + } + + public String getCurrentLink() { + String thisLink = "attack"; + Enumeration e = request.getParameterNames(); + boolean isFirstParameter = true; + while (e.hasMoreElements()) { + String name = e.nextElement(); + if (isFirstParameter) { + isFirstParameter = false; + thisLink += "?"; + } else { + thisLink += "&"; + } + thisLink = thisLink + name + "=" + request.getParameter(name); + } + + return thisLink; + } + + public AbstractLesson getCurrentLesson() { + return getCourse().getLesson(this, getCurrentScreen(), getRoles()); + } + + public AbstractLesson getLesson(int id) { + return getCourse().getLesson(this, id, getRoles()); + } + + public List getLessons(Category category) { + return getCourse().getLessons(this, category, getRoles()); + } + + /** + * Gets the hint1 attribute of the WebSession object + * + * @return The hint1 value + */ + private int getHintNum() { + return (hintNum); + } + + public String getHint() { + String hint = null; + int hints = getCurrentLesson().getHintCount(this); + if (getHintNum() > hints) { + hintNum = -1; + } + if (getHintNum() >= 0) // FIXME + { + hint = getCurrentLesson().getHint(this, getHintNum()); + } + + return hint; + } + + public List getParams() { + Vector params = null; + + if (showParams() && getParser() != null) { + params = new Vector(); + + Enumeration e = getParser().getParameterNames(); + + while ((e != null) && e.hasMoreElements()) { + String name = (String) e.nextElement(); + String[] values = getParser().getParameterValues(name); + + for (int loop = 0; (values != null) && (loop < values.length); loop++) { + params.add(new Parameter(name, values[loop])); + // params.add( name + " -> " + values[loop] ); + } + } + + Collections.sort(params); + } + + return params; + } + + public List getCookies() { + List cookies = null; + + if (showCookies()) { + cookies = Arrays.asList(request.getCookies()); + } + + /* + * List cookies = new Vector(); HttpServletRequest request = getRequest(); Cookie[] cookies + * = request.getCookies(); if ( cookies.length == 0 ) { list.addElement( new LI( + * "No Cookies" ) ); } for ( int i = 0; i < cookies.length; i++ ) { Cookie cookie = + * cookies[i]; cookies.add(cookie); //list.addElement( new LI( cookie.getName() + " -> " + + * cookie.getValue() ) ); } + */ + return cookies; + } + + /** + * Gets the cookie attribute of the CookieScreen object + * + * @param s Description of the Parameter + * @return The cookie value + */ + public String getCookie(String cookieName) { + Cookie[] cookies = getRequest().getCookies(); + + for (int i = 0; i < cookies.length; i++) { + if (cookies[i].getName().equalsIgnoreCase(cookieName)) { + return (cookies[i].getValue()); + } + } + + return (null); + } + + public String getSource() { + return "Sorry. No Java Source viewing available."; + // return getCurrentLesson().getSource(this); + } + + public String getSolution() { + return "Sorry. No solution is available."; + // return getCurrentLesson().getSolution(this); + } + + public String getInstructions() { + return getCurrentLesson().getInstructions(this); + } + + /** + * Gets the message attribute of the WebSession object + * + * @return The message value + */ + public String getMessage() { + return (message.toString()); + } + + /** + * Gets the parser attribute of the WebSession object + * + * @return The parser value + */ + public ParameterParser getParser() { + return (myParser); + } + + /** + * Gets the previousScreen attribute of the WebSession object + * + * @return The previousScreen value + */ + public int getPreviousScreen() { + return (previousScreen); + } + + /** + * Gets the request attribute of the WebSession object + * + * @return The request value + */ + public HttpServletRequest getRequest() { + return request; + } + + public void setRequest(HttpServletRequest request) { + this.request = request; + } + + /** + * Gets the response attribute of the WebSession object + * + * @return The response value + */ + public HttpServletResponse getResponse() { + return response; + } + + /** + * Gets the servletName attribute of the WebSession object + * + * @return The servletName value + */ + public String getServletName() { + return (servletName); + } + + /** + * Gets the sourceFile attribute of the WebSession object + * + * @param screen Description of the Parameter + * @return The sourceFile value + */ + public String getWebResource(String fileName) { + // Note: doesn't work for admin path! Maybe with a ../ attack + return (context.getRealPath(fileName)); + } + + /** + * Gets the admin attribute of the WebSession object + * + * @return The admin value + */ + public boolean isAdmin() { + return (isAdmin); + } + + /** + * Gets the hackedAdmin attribute of the WebSession object + * + * @return The hackedAdmin value + */ + public boolean isHackedAdmin() { + return (isHackedAdmin); + } + + /** + * Has the user ever hacked the hackable admin + * + * @return The hackedAdmin value + */ + public boolean completedHackableAdmin() { + return (completedHackableAdmin); + } + + /** + * Gets the authenticated attribute of the WebSession object + * + * @return The authenticated value + */ + public boolean isAuthenticated() { + return (isAuthenticated); + } + + private Map lessonSessions = new Hashtable(); + + public boolean isAuthenticatedInLesson(AbstractLesson lesson) { + boolean authenticated = false; + + LessonSession lessonSession = getLessonSession(lesson); + if (lessonSession != null) { + authenticated = lessonSession.isAuthenticated(); + } + // System.out.println("Authenticated for lesson " + lesson + "? " + authenticated); + + return authenticated; + } + + public boolean isAuthorizedInLesson(int employeeId, String functionId) { + return getCurrentLesson().isAuthorized(this, employeeId, functionId); + } + + public boolean isAuthorizedInLesson(String role, String functionId) { + return getCurrentLesson().isAuthorized(this, role, functionId); + } + + public int getUserIdInLesson() throws ParameterNotFoundException { + return getCurrentLesson().getUserId(this); + } + + public String getUserNameInLesson() throws ParameterNotFoundException { + return getCurrentLesson().getUserName(this); + } + + public void openLessonSession(AbstractLesson lesson) { + System.out.println("Opening new lesson session for lesson " + lesson); + LessonSession lessonSession = new LessonSession(); + lessonSessions.put(lesson, lessonSession); + } + + public void closeLessonSession(AbstractLesson lesson) { + lessonSessions.remove(lesson); + } + + public LessonSession getLessonSession(AbstractLesson lesson) { + return lessonSessions.get(lesson); + } + + /** + * Gets the challenge attribute of the WebSession object + * + * @return The challenge value + */ + public boolean isChallenge() { + if (getCurrentLesson() != null) { + return (Category.CHALLENGE.equals(getCurrentLesson().getCategory())); + } + return false; + } + + /** + * Gets the color attribute of the WebSession object + * + * @return The color value + */ + public boolean isColor() { + return (isColor); + } + + /** + * Gets the screen attribute of the WebSession object + * + * @param value Description of the Parameter + * @return The screen value + */ + public boolean isScreen(int value) { + return (getCurrentScreen() == value); + } + + /** + * Gets the user attribute of the WebSession object + * + * @return The user value + */ + public boolean isUser() { + return (!isAdmin && !isChallenge()); + } + + /** + * Sets the message attribute of the WebSession object + * + * @param text The new message value + */ + public void setMessage(String text) { + message.append("
" + " * " + text); + } + + public void setLineBreak(String text) { + message.append("

" + text); + } + + /** + * Description of the Method + * + * @return Description of the Return Value + */ + public boolean showCookies() { + return (showCookies); + } + + /** + * Description of the Method + * + * @return Description of the Return Value + */ + public boolean showParams() { + return (showParams); + } + + /** + * Description of the Method + * + * @return Description of the Return Value + */ + public boolean showRequest() { + return (showRequest); + } + + /** + * Description of the Method + * + * @return Description of the Return Value + */ + public boolean showSource() { + return (showSource); + } + + public boolean showSolution() { + return (showSolution); + } + + /** + * Gets the userName attribute of the WebSession object + * + * @return The userName value + */ + public String getUserName() { + HttpServletRequest request = getRequest(); + if (request == null) { + throw new RuntimeException("Could not find the ServletRequest in the web session"); + } + Principal principal = request.getUserPrincipal(); + if (principal == null) { + throw new RuntimeException("Could not find the Principal in the Servlet Request"); + } + return principal.getName(); + } + + /** + * Parse parameters from the given request, handle any servlet commands, and + * update this session based on the parameters. + * + * @param request Description of the Parameter + * @param response Description of the Parameter + * @param name Description of the Parameter + */ + public void update(HttpServletRequest request, HttpServletResponse response, String name) throws IOException { + String content = null; + + clearMessage(); + this.request = request; + this.response = response; + this.servletName = name; + + if (myParser == null) { + myParser = new ParameterParser(request); + } else { + myParser.update(request); + } + + Locale locale = request.getLocale(); + if(locale != null) { + LabelManager labelManager = BeanProvider.getBean("labelManager", LabelManager.class); + labelManager.setLocale(locale); + } + + // System.out.println("Current Screen 1: " + currentScreen ); + // System.out.println("Previous Screen 1: " + previousScreen ); + // FIXME: requires ?Logout=true + // FIXME: doesn't work right -- no reauthentication + // REMOVED - we have explicit logout now via spriing security + /* + if (myParser.getRawParameter(LOGOUT, null) != null) { + System.out.println("Logout " + request.getUserPrincipal()); + eatCookies(); + request.getSession().invalidate(); + currentScreen = WELCOME; + previousScreen = ERROR; + } + */ + + // There are several scenarios where we want the first lesson to be loaded + // 1) Previous screen is Welcome - Start of the course + // 2) After a logout and after the session has been reinitialized + if ((this.getPreviousScreen() == WebSession.WELCOME) || (getRequest().getSession(false) != null + && // getRequest().getSession(false).isNew() && + this.getCurrentScreen() == WebSession.WELCOME && this.getPreviousScreen() == WebSession.ERROR)) { + currentScreen = course.getFirstLesson().getScreenId(); + hintNum = -1; + } + + // System.out.println("Current Screen 2: " + currentScreen ); + // System.out.println("Previous Screen 2: " + previousScreen ); + // update the screen variables + previousScreen = currentScreen; + + try { + // If the request is new there should be no parameters. + // This can occur from a session timeout or a the starting of a new course. + if (!request.getSession().isNew()) { + currentScreen = myParser.getIntParameter(SCREEN, currentScreen); + } else { + if (!myParser.getRawParameter(SCREEN, "NULL").equals("NULL")) { + this.setMessage("Session Timeout - Starting new Session."); + } + } + } catch (Exception e) { + } + + // clear variables when switching screens + if (this.getCurrentScreen() != this.getPreviousScreen()) { + if (webgoatContext.isDebug()) { + setMessage("Changed to a new screen, clearing cookies and hints"); + } + eatCookies(); + hintNum = -1; + } else if (myParser.getRawParameter(STAGE, null) != null) { + AbstractLesson al = getCurrentLesson(); + if (al instanceof SequentialLessonAdapter) { + SequentialLessonAdapter sla = (SequentialLessonAdapter) al; + int stage = myParser.getIntParameter(STAGE, sla.getStage(this)); + if (stage > 0 && stage <= sla.getStageCount()) { + sla.setStage(this, stage); + } + } else if (al instanceof RandomLessonAdapter) { + try { + RandomLessonAdapter rla = (RandomLessonAdapter) al; + int stage = myParser.getIntParameter(STAGE) - 1; + String[] stages = rla.getStages(); + if (stages == null) { + stages = new String[0]; + } + if (stage >= 0 && stage < stages.length) { + rla.setStage(this, stages[stage]); + } + } catch (ParameterNotFoundException pnfe) { + } + } + } // else update global variables for the current screen + else { + // Handle "restart" commands + int lessonId = myParser.getIntParameter(RESTART, -1); + if (lessonId != -1) { + restartLesson(lessonId); + } + // if ( myParser.getBooleanParameter( RESTART, false ) ) + // { + // getCurrentLesson().getLessonTracker( this ).getLessonProperties().setProperty( + // CHALLENGE_STAGE, "1" ); + // } + + // Handle "show" commands + String showCommand = myParser.getStringParameter(SHOW, null); + if (showCommand != null) { + if (showCommand.equalsIgnoreCase(SHOW_PARAMS)) { + showParams = !showParams; + } else if (showCommand.equalsIgnoreCase(SHOW_COOKIES)) { + showCookies = !showCookies; + } else if (showCommand.equalsIgnoreCase(SHOW_SOURCE)) { + content = getSource(); + // showSource = true; + } else if (showCommand.equalsIgnoreCase(SHOW_SOLUTION)) { + content = getSolution(); + // showSource = true; + } else if (showCommand.equalsIgnoreCase(SHOW_NEXTHINT)) { + getNextHint(); + } else if (showCommand.equalsIgnoreCase(SHOW_PREVIOUSHINT)) { + getPreviousHint(); + } + } + + } + + isAdmin = request.isUserInRole(WEBGOAT_ADMIN); + isHackedAdmin = myParser.getBooleanParameter(ADMIN, isAdmin); + if (isHackedAdmin) { + System.out.println("Hacked admin"); + hasHackedHackableAdmin = true; + } + isColor = myParser.getBooleanParameter(COLOR, isColor); + isDebug = myParser.getBooleanParameter(DEBUG, isDebug); + + // System.out.println( "showParams:" + showParams ); + // System.out.println( "showSource:" + showSource ); + // System.out.println( "showSolution:" + showSolution ); + // System.out.println( "showCookies:" + showCookies ); + // System.out.println( "showRequest:" + showRequest ); + if (content != null) { + response.setContentType("text/html"); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.print(content); + out.flush(); + out.close(); + } + } + + public void updateLastAttackRequestInfo(HttpServletRequest request) { + // store cookies + Cookie[] cookies = request.getCookies(); + if (cookies == null) { + this.cookiesOnLastRequest = new ArrayList(); + } else { + this.cookiesOnLastRequest = Arrays.asList(cookies); + } + // store parameters + Map parmMap = request.getParameterMap(); + logger.info("PARM MAP: " + parmMap); + if (parmMap == null) { + this.parmsOnLastRequest = new ArrayList(); + } else { + this.parmsOnLastRequest = new ArrayList(); + for (String name : parmMap.keySet()) { + String[] values = parmMap.get(name); + String delim = ""; + StringBuffer sb = new StringBuffer(); + if (values != null && values.length > 0) { + for (String parm : values) { + sb.append(delim).append(parm); + delim = ","; + } + } + RequestParameter parm = new RequestParameter(name, sb.toString()); + this.parmsOnLastRequest.add(parm); + } + } + } + + public void restartLesson(int lessonId) { + AbstractLesson al = getLesson(lessonId); + System.out.println("Restarting lesson: " + al); + al.getLessonTracker(this).setCompleted(false); + if (al instanceof SequentialLessonAdapter) { + SequentialLessonAdapter sla = (SequentialLessonAdapter) al; + sla.getLessonTracker(this).setStage(1); + } else if (al instanceof RandomLessonAdapter) { + RandomLessonAdapter rla = (RandomLessonAdapter) al; + rla.setStage(this, rla.getStages()[0]); + } + } + + /** + * @param string + */ + public void setHasHackableAdmin(String role) { + hasHackedHackableAdmin = (AbstractLesson.HACKED_ADMIN_ROLE.equals(role) & hasHackedHackableAdmin); + + // if the user got the Admin=true parameter correct AND they accessed an admin screen + if (hasHackedHackableAdmin) { + completedHackableAdmin = true; + } + } + + /** + * @return Returns the isDebug. + */ + public boolean isDebug() { + return isDebug; + } + + /** + * @param header - request header value to return + * @return + */ + public String getHeader(String header) { + return getRequest().getHeader(header); + } + + public String getNextHint() { + String hint = null; + + // FIXME + int maxHints = getCurrentLesson().getHintCount(this); + if (hintNum < maxHints - 1) { + hintNum++; + + // Hints are indexed from 0 + getCurrentLesson().getLessonTracker(this).setMaxHintLevel(getHintNum() + 1); + + hint = (String) getCurrentLesson().getHint(this, getHintNum()); + } + + return hint; + } + + public String getPreviousHint() { + String hint = null; + + if (hintNum > 0) { + hintNum--; + + // Hints are indexed from 0 + getCurrentLesson().getLessonTracker(this).setMaxHintLevel(getHintNum() + 1); + + hint = (String) getCurrentLesson().getHint(this, getHintNum()); + } + + return hint; + } + + public void setCurrentMenu(Integer ranking) { + currentMenu = ranking.intValue(); + } + + public int getCurrentMenu() { + return currentMenu; + } + + public WebgoatContext getWebgoatContext() { + return webgoatContext; + } + + public String getCurrrentLanguage() { + return currentLanguage; + } + + /** + * @return the cookiesOnLastRequest + */ + public List getCookiesOnLastRequest() { + return cookiesOnLastRequest; + } + + /** + * @return the parmsOnLastRequest + */ + public List getParmsOnLastRequest() { + return parmsOnLastRequest; + } + +} diff --git a/src/main/java/org/owasp/webgoat/session/WebgoatContext.java b/src/main/java/org/owasp/webgoat/session/WebgoatContext.java index c0e0ebbea..1d3fb8266 100644 --- a/src/main/java/org/owasp/webgoat/session/WebgoatContext.java +++ b/src/main/java/org/owasp/webgoat/session/WebgoatContext.java @@ -1,231 +1,216 @@ -package org.owasp.webgoat.session; - -import javax.servlet.http.HttpServlet; - -import org.owasp.webgoat.util.WebGoatI18N; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class WebgoatContext { - - final Logger logger = LoggerFactory.getLogger(WebgoatContext.class); - - public final static String DATABASE_CONNECTION_STRING = "DatabaseConnectionString"; - - public final static String DATABASE_DRIVER = "DatabaseDriver"; - - public final static String DATABASE_USER = "DatabaseUser"; - - public final static String DATABASE_PASSWORD = "DatabasePassword"; - - public final static String ENTERPRISE = "Enterprise"; - - public final static String CODING_EXERCISES = "CodingExercises"; - - public final static String SHOWCOOKIES = "ShowCookies"; - - public final static String SHOWPARAMS = "ShowParams"; - - public final static String SHOWREQUEST = "ShowRequest"; - - public final static String SHOWSOURCE = "ShowSource"; - - public final static String SHOWSOLUTION = "ShowSolution"; - - public final static String SHOWHINTS = "ShowHints"; - - public final static String DEFUSEOSCOMMANDS = "DefuseOSCommands"; - - public final static String FEEDBACK_ADDRESS_HTML = "FeedbackAddressHTML"; - - public final static String FEEDBACK_ADDRESS = "email"; - - public final static String DEBUG = "debug"; - - public final static String DEFAULTLANGUAGE = "DefaultLanguage"; - - private String databaseConnectionString; - - private String realConnectionString = null; - - private String databaseDriver; - - private String databaseUser; - - private String databasePassword; - - private boolean showCookies = false; - - private boolean showParams = false; - - private boolean showRequest = false; - - private boolean showSource = false; - - private boolean showSolution = false; - - private boolean defuseOSCommands = false; - - private boolean enterprise = false; - - private boolean codingExercises = false; - - private String feedbackAddress = "webgoat@owasp.org"; - - private String feedbackAddressHTML = "webgoat@owasp.org"; - - private boolean isDebug = false; - - private String servletName; - - private HttpServlet servlet; - - private String defaultLanguage; - - private WebGoatI18N webgoati18n = null; - - public WebgoatContext(HttpServlet servlet) { - this.servlet = servlet; - databaseConnectionString = getParameter(servlet, DATABASE_CONNECTION_STRING); - databaseDriver = getParameter(servlet, DATABASE_DRIVER); - databaseUser = getParameter(servlet, DATABASE_USER); - databasePassword = getParameter(servlet, DATABASE_PASSWORD); - - // initialize from web.xml - showParams = "true".equals(getParameter(servlet, SHOWPARAMS)); - showCookies = "true".equals(getParameter(servlet, SHOWCOOKIES)); - showSource = "true".equals(getParameter(servlet, SHOWSOURCE)); - showSolution = "true".equals(getParameter(servlet, SHOWSOLUTION)); - defuseOSCommands = "true".equals(getParameter(servlet, DEFUSEOSCOMMANDS)); - enterprise = "true".equals(getParameter(servlet, ENTERPRISE)); - codingExercises = "true".equals(getParameter(servlet, CODING_EXERCISES)); - feedbackAddressHTML = getParameter(servlet, FEEDBACK_ADDRESS_HTML) != null ? getParameter(servlet, - FEEDBACK_ADDRESS_HTML) - : feedbackAddressHTML; - feedbackAddress = getParameter(servlet, FEEDBACK_ADDRESS) != null ? getParameter(servlet, FEEDBACK_ADDRESS) - : feedbackAddress; - showRequest = "true".equals(getParameter(servlet, SHOWREQUEST)); - isDebug = "true".equals(getParameter(servlet, DEBUG)); - servletName = servlet.getServletName(); - defaultLanguage = getParameter(servlet, DEFAULTLANGUAGE) != null ? new String(getParameter(servlet, DEFAULTLANGUAGE)) : new String("en"); - - webgoati18n = new WebGoatI18N(this); - - } - - private String getParameter(HttpServlet servlet, String key) { - String value = System.getenv().get(key); - if (value == null) { - value = servlet.getInitParameter(key); - } - return value; - } - - /** - * returns the connection string with the real path to the database - * directory inserted at the word PATH - * - * @return The databaseConnectionString value - */ - public String getDatabaseConnectionString() { - if (realConnectionString == null) { - try { - String path = servlet.getServletContext().getRealPath("/database").replace('\\', '/'); - System.out.println("PATH: " + path); - realConnectionString = databaseConnectionString.replaceAll("PATH", path); - System.out.println("Database Connection String: " + realConnectionString); - } catch (Exception e) { - logger.error("Couldn't open database: check web.xml database parameters", e); - } - } - return realConnectionString; - } - - /** - * Gets the databaseDriver attribute of the WebSession object - * - * @return The databaseDriver value - */ - public String getDatabaseDriver() { - return (databaseDriver); - } - - /** - * Gets the databaseUser attribute of the WebSession object - * - * @return The databaseUser value - */ - public String getDatabaseUser() { - return (databaseUser); - } - - /** - * Gets the databasePassword attribute of the WebSession object - * - * @return The databasePassword value - */ - public String getDatabasePassword() { - return (databasePassword); - } - - public boolean isDefuseOSCommands() { - return defuseOSCommands; - } - - public boolean isEnterprise() { - return enterprise; - } - - public boolean isCodingExercises() { - return codingExercises; - } - - public String getFeedbackAddress() { - return feedbackAddress; - } - - public String getFeedbackAddressHTML() { - return feedbackAddressHTML; - } - - public boolean isDebug() { - return isDebug; - } - - public String getServletName() { - return servletName; - } - - public boolean isShowCookies() { - return showCookies; - } - - public boolean isShowParams() { - return showParams; - } - - public boolean isShowRequest() { - return showRequest; - } - - public boolean isShowSource() { - return showSource; - } - - public boolean isShowSolution() { - return showSolution; - } - - public String getDefaultLanguage() { - return defaultLanguage; - } - - public void setWebgoatiI18N(WebGoatI18N webgoati18n) { - this.webgoati18n = webgoati18n; - } - - public WebGoatI18N getWebgoatI18N() { - return webgoati18n; - } - -} +package org.owasp.webgoat.session; + +import javax.servlet.http.HttpServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class WebgoatContext { + + final Logger logger = LoggerFactory.getLogger(WebgoatContext.class); + + public final static String DATABASE_CONNECTION_STRING = "DatabaseConnectionString"; + + public final static String DATABASE_DRIVER = "DatabaseDriver"; + + public final static String DATABASE_USER = "DatabaseUser"; + + public final static String DATABASE_PASSWORD = "DatabasePassword"; + + public final static String ENTERPRISE = "Enterprise"; + + public final static String CODING_EXERCISES = "CodingExercises"; + + public final static String SHOWCOOKIES = "ShowCookies"; + + public final static String SHOWPARAMS = "ShowParams"; + + public final static String SHOWREQUEST = "ShowRequest"; + + public final static String SHOWSOURCE = "ShowSource"; + + public final static String SHOWSOLUTION = "ShowSolution"; + + public final static String SHOWHINTS = "ShowHints"; + + public final static String DEFUSEOSCOMMANDS = "DefuseOSCommands"; + + public final static String FEEDBACK_ADDRESS_HTML = "FeedbackAddressHTML"; + + public final static String FEEDBACK_ADDRESS = "email"; + + public final static String DEBUG = "debug"; + + public final static String DEFAULTLANGUAGE = "DefaultLanguage"; + + private String databaseConnectionString; + + private String realConnectionString = null; + + private String databaseDriver; + + private String databaseUser; + + private String databasePassword; + + private boolean showCookies = false; + + private boolean showParams = false; + + private boolean showRequest = false; + + private boolean showSource = false; + + private boolean showSolution = false; + + private boolean defuseOSCommands = false; + + private boolean enterprise = false; + + private boolean codingExercises = false; + + private String feedbackAddress = "webgoat@owasp.org"; + + private String feedbackAddressHTML = "webgoat@owasp.org"; + + private boolean isDebug = false; + + private String servletName; + + private HttpServlet servlet; + + private String defaultLanguage; + + public WebgoatContext(HttpServlet servlet) { + this.servlet = servlet; + databaseConnectionString = getParameter(servlet, DATABASE_CONNECTION_STRING); + databaseDriver = getParameter(servlet, DATABASE_DRIVER); + databaseUser = getParameter(servlet, DATABASE_USER); + databasePassword = getParameter(servlet, DATABASE_PASSWORD); + + // initialize from web.xml + showParams = "true".equals(getParameter(servlet, SHOWPARAMS)); + showCookies = "true".equals(getParameter(servlet, SHOWCOOKIES)); + showSource = "true".equals(getParameter(servlet, SHOWSOURCE)); + showSolution = "true".equals(getParameter(servlet, SHOWSOLUTION)); + defuseOSCommands = "true".equals(getParameter(servlet, DEFUSEOSCOMMANDS)); + enterprise = "true".equals(getParameter(servlet, ENTERPRISE)); + codingExercises = "true".equals(getParameter(servlet, CODING_EXERCISES)); + feedbackAddressHTML = getParameter(servlet, FEEDBACK_ADDRESS_HTML) != null ? getParameter(servlet, + FEEDBACK_ADDRESS_HTML) + : feedbackAddressHTML; + feedbackAddress = getParameter(servlet, FEEDBACK_ADDRESS) != null ? getParameter(servlet, FEEDBACK_ADDRESS) + : feedbackAddress; + showRequest = "true".equals(getParameter(servlet, SHOWREQUEST)); + isDebug = "true".equals(getParameter(servlet, DEBUG)); + servletName = servlet.getServletName(); + defaultLanguage = getParameter(servlet, DEFAULTLANGUAGE) != null ? new String(getParameter(servlet, DEFAULTLANGUAGE)) : new String("en"); + } + + private String getParameter(HttpServlet servlet, String key) { + String value = System.getenv().get(key); + if (value == null) { + value = servlet.getInitParameter(key); + } + return value; + } + + /** + * returns the connection string with the real path to the database + * directory inserted at the word PATH + * + * @return The databaseConnectionString value + */ + public String getDatabaseConnectionString() { + if (realConnectionString == null) { + try { + String path = servlet.getServletContext().getRealPath("/database").replace('\\', '/'); + System.out.println("PATH: " + path); + realConnectionString = databaseConnectionString.replaceAll("PATH", path); + System.out.println("Database Connection String: " + realConnectionString); + } catch (Exception e) { + logger.error("Couldn't open database: check web.xml database parameters", e); + } + } + return realConnectionString; + } + + /** + * Gets the databaseDriver attribute of the WebSession object + * + * @return The databaseDriver value + */ + public String getDatabaseDriver() { + return (databaseDriver); + } + + /** + * Gets the databaseUser attribute of the WebSession object + * + * @return The databaseUser value + */ + public String getDatabaseUser() { + return (databaseUser); + } + + /** + * Gets the databasePassword attribute of the WebSession object + * + * @return The databasePassword value + */ + public String getDatabasePassword() { + return (databasePassword); + } + + public boolean isDefuseOSCommands() { + return defuseOSCommands; + } + + public boolean isEnterprise() { + return enterprise; + } + + public boolean isCodingExercises() { + return codingExercises; + } + + public String getFeedbackAddress() { + return feedbackAddress; + } + + public String getFeedbackAddressHTML() { + return feedbackAddressHTML; + } + + public boolean isDebug() { + return isDebug; + } + + public String getServletName() { + return servletName; + } + + public boolean isShowCookies() { + return showCookies; + } + + public boolean isShowParams() { + return showParams; + } + + public boolean isShowRequest() { + return showRequest; + } + + public boolean isShowSource() { + return showSource; + } + + public boolean isShowSolution() { + return showSolution; + } + + public String getDefaultLanguage() { + return defaultLanguage; + } + +} diff --git a/src/main/java/org/owasp/webgoat/util/BeanProvider.java b/src/main/java/org/owasp/webgoat/util/BeanProvider.java new file mode 100644 index 000000000..71e2e1998 --- /dev/null +++ b/src/main/java/org/owasp/webgoat/util/BeanProvider.java @@ -0,0 +1,63 @@ + +package org.owasp.webgoat.util; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + + +/*************************************************************************************************** + * + * + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with this program; if + * not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for + * free software projects. + * + * For details, please see http://webgoat.github.io + */ +@Component +public class BeanProvider implements ApplicationContextAware +{ + private static ApplicationContext ctx; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException + { + ctx = applicationContext; + + } + + /** + * Get access to managed beans from id. + * + * @param beanName + * the id of the searched bean + * @param beanClass + * the type of tye searched bean + * @return + */ + @SuppressWarnings("unchecked") + public static T getBean(final String beanName, final Class beanClass) + { + return (T) ctx.getBean(beanName); + } +} diff --git a/src/main/java/org/owasp/webgoat/util/LabelManager.java b/src/main/java/org/owasp/webgoat/util/LabelManager.java new file mode 100644 index 000000000..b83e0a538 --- /dev/null +++ b/src/main/java/org/owasp/webgoat/util/LabelManager.java @@ -0,0 +1,41 @@ + +package org.owasp.webgoat.util; + +import java.util.Locale; + + +/*************************************************************************************************** + * + * + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with this program; if + * not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for + * free software projects. + * + * For details, please see http://webgoat.github.io + */ +public interface LabelManager +{ + + public void setLocale(Locale locale); + + public String get(String labelKey); + +} diff --git a/src/main/java/org/owasp/webgoat/util/LabelManagerImpl.java b/src/main/java/org/owasp/webgoat/util/LabelManagerImpl.java new file mode 100644 index 000000000..6efd3b8c0 --- /dev/null +++ b/src/main/java/org/owasp/webgoat/util/LabelManagerImpl.java @@ -0,0 +1,61 @@ + +package org.owasp.webgoat.util; + +import java.util.Locale; +import javax.annotation.Resource; +import org.springframework.context.annotation.Scope; +import org.springframework.context.annotation.ScopedProxyMode; +import org.springframework.stereotype.Component; + + +/*************************************************************************************************** + * + * + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with this program; if + * not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for + * free software projects. + * + * For details, please see http://webgoat.github.io + */ +@Component("labelManager") +@Scope(value="session", proxyMode=ScopedProxyMode.INTERFACES) +public class LabelManagerImpl implements LabelManager +{ + @Resource + private LabelProvider labelProvider; + + /** Locale mapped with current session. */ + private Locale locale = new Locale(LabelProvider.DEFAULT_LANGUAGE); + + public void setLocale(Locale locale) + { + if (locale != null) + { + this.locale = locale; + } + } + + public String get(String labelKey) + { + return labelProvider.get(locale, labelKey); + } + +} diff --git a/src/main/java/org/owasp/webgoat/util/LabelProvider.java b/src/main/java/org/owasp/webgoat/util/LabelProvider.java new file mode 100644 index 000000000..ad6ffe4ff --- /dev/null +++ b/src/main/java/org/owasp/webgoat/util/LabelProvider.java @@ -0,0 +1,67 @@ + +package org.owasp.webgoat.util; + +import java.util.HashMap; +import java.util.Locale; +import java.util.ResourceBundle; +import org.springframework.stereotype.Component; + + +/*************************************************************************************************** + * + * + * This file is part of WebGoat, an Open Web Application Security Project utility. For details, + * please see http://www.owasp.org/ + * + * Copyright (c) 2002 - 20014 Bruce Mayhew + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with this program; if + * not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + * + * Getting Source ============== + * + * Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for + * free software projects. + * + * For details, please see http://webgoat.github.io + */ +@Component +public class LabelProvider +{ + public final static String DEFAULT_LANGUAGE = "en"; + + private final HashMap labels = new HashMap(); + private final WebGoatResourceBundleController localeController = new WebGoatResourceBundleController(); + + public String get(Locale locale, String strName) + { + if (!labels.containsKey(locale)) + { + ResourceBundle resBundle = ResourceBundle.getBundle("WebGoatLabels", locale, localeController); + labels.put(locale, resBundle); + } + return labels.get(locale).getString(strName); + } + + private class WebGoatResourceBundleController extends ResourceBundle.Control + { + private final Locale fallbackLocale = new Locale(DEFAULT_LANGUAGE); + + @Override + public Locale getFallbackLocale(String baseName, Locale locale) + { + if (!fallbackLocale.equals(locale)) { return fallbackLocale; } + return Locale.ROOT; + } + } + +} diff --git a/src/main/java/org/owasp/webgoat/util/WebGoatI18N.java b/src/main/java/org/owasp/webgoat/util/WebGoatI18N.java index c7f6b00d0..8285f76fd 100644 --- a/src/main/java/org/owasp/webgoat/util/WebGoatI18N.java +++ b/src/main/java/org/owasp/webgoat/util/WebGoatI18N.java @@ -6,36 +6,61 @@ import java.util.ResourceBundle; import org.owasp.webgoat.session.WebgoatContext; -public class WebGoatI18N { +@Deprecated +public class WebGoatI18N +{ - private static HashMap labels= new HashMap(); - private static String defaultLanguage ; - private static String currentLanguage; + private static HashMap labels = new HashMap(); + private static Locale currentLocale; + private static WebGoatResourceBundleController localeController; - public WebGoatI18N(WebgoatContext context){ - Locale l = new Locale(context.getDefaultLanguage()); - WebGoatI18N.defaultLanguage=context.getDefaultLanguage(); - labels.put(context.getDefaultLanguage(),ResourceBundle.getBundle("WebGoatLabels_english",l)); + public WebGoatI18N(WebgoatContext context) + { + currentLocale = new Locale(context.getDefaultLanguage()); + localeController = new WebGoatResourceBundleController(currentLocale); } - public static void loadLanguage(String language){ - Locale l = new Locale(language); - labels.put(language, ResourceBundle.getBundle("WebGoatLabels_english",l)); + @Deprecated + public static void loadLanguage(String language) + { + // Do nothing } - public static void setCurrentLanguage(String language){ - WebGoatI18N.currentLanguage=language; - } - - public static String get(String strName) { - if(labels.containsKey(WebGoatI18N.currentLanguage)){ - return labels.get(WebGoatI18N.currentLanguage).getString(strName); - } - else { - return labels.get(WebGoatI18N.defaultLanguage).getString(strName); + public static void setCurrentLocale(Locale locale) + { + if (!currentLocale.equals(locale)) + { + if (!labels.containsKey(locale)) + { + ResourceBundle resBundle = ResourceBundle.getBundle("WebGoatLabels", locale, localeController); + labels.put(locale, resBundle); + } + WebGoatI18N.currentLocale = locale; } } + public static String get(String strName) + { + return labels.get(WebGoatI18N.currentLocale).getString(strName); + } + + private static class WebGoatResourceBundleController extends ResourceBundle.Control + { + private Locale fallbackLocale; + + public WebGoatResourceBundleController(Locale l) + { + fallbackLocale = l; + } + @Override + public Locale getFallbackLocale(String baseName, Locale locale) + { + if(! fallbackLocale.equals(locale)) { + return fallbackLocale; + } + return Locale.ROOT; + } + } } diff --git a/src/main/resources/WebGoatLabels_english.properties b/src/main/resources/WebGoatLabels.properties similarity index 100% rename from src/main/resources/WebGoatLabels_english.properties rename to src/main/resources/WebGoatLabels.properties diff --git a/src/main/resources/WebGoatLabels_german.properties b/src/main/resources/WebGoatLabels_de.properties similarity index 100% rename from src/main/resources/WebGoatLabels_german.properties rename to src/main/resources/WebGoatLabels_de.properties diff --git a/src/main/resources/WebGoatLabels_fr.properties b/src/main/resources/WebGoatLabels_fr.properties new file mode 100644 index 000000000..511292d97 --- /dev/null +++ b/src/main/resources/WebGoatLabels_fr.properties @@ -0,0 +1,222 @@ +#General +LessonCompleted=F\u00e9licitations. Vous avez termin\u00e9 cette le\u00e7on avec succ\u00e9s. +RestartLesson=Recommencer cette le\u00e7on +SolutionVideos=Solution vid\u00e9os +ErrorGenerating=Error generating +InvalidData=Donn\u00e9e invalide + +#HttpBasics.java +EnterYourName=Entrez votre nom +Go!=Go! + +#BasicAuthentication.java +BasicAuthHeaderNameIncorrect=Le nom de l'en-t\u00eate d'authentification Basic est incorrect. +BasicAuthHeaderValueIncorrect=La valeur de l'en-t\u00eate d'authentification Basic est incorrecte. +BasicAuthenticationWhatIsNameOfHeader=Quel est le nom de l'en-t\u00eate d'authentification ? +BasicAuthenticationWhatIsDecodedValueOfHeader=Quelle est la valeur d\u00e9cod\u00e9e de l'en-t\u00eate d'authentification ? +Submit=Envoyer +BasicAuthenticationGreenStars1=Fermer votre navigateur et connectez-vous en tant que +BasicAuthenticationGreenStars2= afin de retrouver vos \u00e9toiles vertes. +BasicAuthenticationStage1Completed=F\u00e9licitations, vous avez compris la m\u00e9canique de l'authentification Basic.  - Vous devez maintenant faire en sorte que WebGoat vous r\u00e9authentifie en tant que:     - username: basic     - password: basic. Utilisez le menu Basic Authentication pour d\u00e9marrer \u00e0 la page de connexion. +BasicAuthenticationAlmostThere1=Vous y \u00eates presque ! Vous avez modifi\u00e9 l'en-t\u00eate +BasicAuthenticationAlmostThere2= mais vous \u00eates toujours connect\u00e9 en tant que +BasicAuthenticationAlmostThere3=. Etudiez la requ\u00eate soumise apr\u00e8s la saisie des identifiants 'basic' d'utilisateur. Souvenez-vous de l'ordre des \u00e9v\u00e9nements intervenant durant l'authentification Basic. +BasicAuthenticationReallyClose=Vous touchez au but ! Changer le cookie de session contraint le serveur \u00e0 vous assigner une nouvelle session. Cela ne contraint pas le serveur \u00e0 vous r\u00e9authentifier. Quand vous aurez d\u00e9termin\u00e9 comment forcer le serveur \u00e0 op\u00e9rer une requ\u00eate d'authentification, vous devrez vous authentifier en tant que:

    user name: basic
    password: basic
+BasicAuthenticationUseTheHints=Utiliez les indices ! Un \u00e0 la fois... + +BasicAuthenticationHint1=L'authentification Basic utilise un cookie pour transmettre les donn\u00e9es d'identification. Utilisez un proxy pour intercepter la requ\u00eate. Etudiez les cookies. +BasicAuthenticationHint2=L'authentification Basic utilise l'encodage Base64 pour 'brouiller' the " + "user's login credentials. +BasicAuthenticationHint3=L'authentification Basic utilise 'Authorization' comme nom de cookie pour " + "store the user's credentials. +BasicAuthenticationHint4=Utiliez WebScarab -> Tools -> Transcoder to Base64 decode the value in the Authorization cookie. +BasicAuthenticationHint5=L'authentification Basic utilise un cookie pour transmettre les donn\u00e9es d'identification. Utilisez un proxy pour intercepter la requ\u00eate. Etudiez les cookies. +BasicAuthenticationHint6=Avant que le serveur web ne requiert une identification du client, la validit\u00e9 de la session courante est contr\u00f4l\u00e9e. +BasicAuthenticationHint7=Si la session est invalide, le serveur web utilisera les identifiants d'authentification Basic +BasicAuthenticationHint8=Si la session est invalide et que les identifiants d'authentification Basic sont \u00e9galement invalides, de nouveaux identifiants seront r\u00e9clam\u00e9s au client. +BasicAuthenticationHint9=Interceptez la requ\u00eate et falsifiez le JSESSIONID et l'en-t\u00eate d'Authorization. + + +#WeakAuthenticationCookie.java +InvalidCookie=Cookie invalide +IdentityRemembered=Votre identit\u00e9 a \u00e9t\u00e9 m\u00e9moris\u00e9e +InvalidUsernameAndPassword=Nom d'utilisateur et mot de passe saisis invalides. +UserName=Nom d'utilisateur +Password=Mot de passe +Login=Login +RequiredFields=Champs obligatoires +WeakAuthenticationCookiePleaseSignIn=Veuillez vous connecter \u00e0 votre compte. Contactez l'admin OWASP si vous n'avez pas de compte. +SignIn=Connexion +PasswordForgotten=Au revoir ! Votre mot de passe a \u00e9t\u00e9 oubli\u00e9 +WelcomeUser=Bienvenue, +YouHaveBeenAuthenticatedWith=Vous avez \u00e9t\u00e9 authentifi\u00e9 par +Logout=D\u00e9connexion +Refresh=Rafraichir + +WeakAuthenticationCookieHints1=Le serveur authentifie l'utilisateur au moyen d'un cookie, si vous envoyez le bon cookie. +WeakAuthenticationCookieHints2=La valeur AuthCookie peut-elle \u00eatre d\u00e9duite du nom d'utilisateur et du mot de passe ? +WeakAuthenticationCookieHints3=Ajoutez 'AuthCookie=********;' \u00e0 l'en-t\u00eate Cookie: header en utilisant ZAP. +WeakAuthenticationCookieHints4=Apr\u00e8s s'\u00eatre connect\u00e9 \u00e0 en tant que webgoat, un cookie est ajout\u00e9. 65432ubphcfx
Apr\u00e8s s'\u00eatre connect\u00e9 en tant que aspect, un cookie est ajout\u00e9. 65432udfqtb
Existe-t-il des similarit\u00e9s entre le cookie et les noms de login ? + +#RemoteAdminFlaw.java +RemoteAdminFlawHint1=WebGoat a 2 interfaces d'admin. +RemoteAdminFlawHint2=WebGoat a une interface d'admin qui est contr\u00f4l\u00e9e via un param\u00e8tre d'URL et est 'attaquable' +RemoteAdminFlawHint3=WebGoat a une interface d'admin qui est contr\u00f4l\u00e9e par des contraintes de s\u00e9curit\u00e9 c\u00f4t\u00e9 serveur, et ne devrait pas \u00eatre 'attaquable' +RemoteAdminFlawHint4=Follow the Source! +RemoteAdminFlawHint5=En cas de succ\u00e8s, vous verrez appara\u00eetre de nouveaux sous-menus sous l'entr\u00e9e 'Admin Functions' + + + +#PathBasedAccessControl.java +CurrentDirectory=R\u00e9pertoire courant : +ChooseFileToView=Choisissez le fichier \u00e0 visualiser : +ViewFile=Voir le fichier +AccessDenied=Acc\u00e8s refus\u00e9 +ItAppears1=Vous \u00eates sur la bonne voie. Les commandes pouvant compromettre le syst\u00e8me d'exploitation ont \u00e9t\u00e9 d\u00e9sactiv\u00e9es. Vous \u00eates seulement autoris\u00e9 \u00e0 visualiser un fichier dans ce r\u00e9pertoire. +ItAppears2=Vous \u00eates sur la bonne voie. Les commandes pouvant compromettre le syst\u00e8me d'exploitation ont \u00e9t\u00e9 d\u00e9sactiv\u00e9es. Vous \u00eates seulement autoris\u00e9 \u00e0 visualiser les fichiers dans le r\u00e9pertoire webgoat. +CongratsAccessToFileAllowed=F\u00e9licitations ! Acc\u00e8s au fichier autoris\u00e9 +FileInAllowedDirectory=Le fichier est d\u00e9j\u00e0 dans un r\u00e9pertoire autoris\u00e9 - essayez \u00e0 nouveau ! +AccessToFileDenied1=Acc\u00e8s au fichier/r\u00e9pertoire " +AccessToFileDenied2=" refus\u00e9 +FileTooLarge=Le fichier est trop volumineux +FileBinary=Le fichier est binaire +TheFollowingError=L'erreur suivante est intervenue lors de l'acc\u00e8s au fichier : < +PathBasedAccessControlInstr1=L'utilisateur ' +PathBasedAccessControlInstr2=' a acc\u00e8s \u00e0 tous les fichiers du r\u00e9pertoire lesson_plans/English directory. Essayez de tromper le m\u00e9canisme de contr\u00f4le d'acc\u00e8s et d'acc\u00e9der \u00e0 une ressource ext\u00e9rieure au r\u00e9pertoire list\u00e9. Un ressource int\u00e9ressante \u00e0 obtenir peut \u00eatre un fichier tel que tomcat/conf/tomcat-users.xml. Souvenez-vous que les chemins d'acc\u00e8s seront diff\u00e9rents si vous utilisez les sources WebGoat. +ErrorGenerating=Error generating +ViewingFile=Fichier visualis\u00e9: +File=Fichier: +Dir=R\u00e9pertoire : +IsFile= - isFile() : +Exists= - exists() : +PathBasedAccessControlHint1=La plupart des syst\u00e8mes d'exploitation autorise les caract\u00e8res sp\u00e9ciaux dans un chemin. +PathBasedAccessControlHint2=Utilisez un explorateur de fichiers pour trouver the tomcat\\webapps\\WebGoat\\lesson_plans directory"); +PathBasedAccessControlHint3=Essayez .. dans le chemin +PathBasedAccessControlHint4=Essayez ..\\..\\..\\LICENSE + + +#CommandInjection.java +Command=Commande +CommandInjectionRightTrack1=Vous \u00eates sur la bonne voie. Les commandes pouvant compromettre le syst\u00e8me d'exploitation ont \u00e9t\u00e9 d\u00e9sactiv\u00e9es. Les commandes suivantes sont autoris\u00e9es : netstat -a, dir, ls, ifconfig, and ipconfig. +CommandInjectionRightTrack2=Vous \u00eates sur la bonne voie. Les commandes pouvant compromettre le syst\u00e8me d'exploitation ont \u00e9t\u00e9 d\u00e9sactiv\u00e9es. Cette le\u00e7on est une le\u00e7on sur l'injection de commande, pas sur le contr\u00f4le d'acc\u00e8s. +YouAreCurrentlyViewing=Vous \u00eates en train de visualiser : +SelectFileFromListBelow=S\u00e9lectionnez un fichier depuis la liste ci-dessous +SelectLessonPlanToView=S\u00e9lectionnez le plan de le\u00e7on \u00e0 visualiser : +View=Voir +CommandInjectionHint1=L'application utilise une commande syst\u00e8me pour retourner le contenu d'un fichier. +CommandInjectionHint2=L'esperluette(&) s\u00e9pare les commandes dans le shell de commandes de Windows 2000. Sous Unix, le s\u00e9parateur est g\u00e9n\u00e9ralement un point-virgule(;) +CommandInjectionHint3=Utilisez un proxy pour ins\u00e9rer & netstat -a sous Windows or ;netstat -a sous Unix. +CommandInjectionHint4=Notez que le serveur peut encadrer le fichier soumis par des guillements + + + +#NumericSqlInjection.java +NumericSqlInjectionSecondStage=Pas capable de r\u00e9ussir \u00e0 nouveau ! La le\u00e7on a d\u00e9tect\u00e9 votre attaque r\u00e9ussie et a maintenant bascul\u00e9 en mode d\u00e9fensif. Essayez \u00e0 nouveau d'attaquer une requ\u00eate param\u00e9tr\u00e9e. +NoResultsMatched=Aucun r\u00e9sultat retourn\u00e9. Essayez \u00e0 nouveau. +NumericSqlInjectionSecondStage2=Maintenant que vous avez r\u00e9alis\u00e9 une injection SQL avec succ\u00e8s, essayer le m\u00eame type d'attaque sur une requ\u00eate param\u00e9tr\u00e9e. +ErrorParsingAsNumber=Erreur lors de l'interpr\u00e9tation de station comme valeur num\u00e9rique : +SelectYourStation=S\u00e9lectionnez votre station m\u00e9t\u00e9o locale : +SqlNumericInjectionHint1=L'application r\u00e9cup\u00e8re la valeur sp\u00e9cifi\u00e9e depuis la liste d\u00e9roulante et l'ins\u00e8re \u00e0 la fin d'une commande SQL pr\u00e9-form\u00e9e. +SqlNumericInjectionHint2=Voici le code de la requ\u00eate assembl\u00e9e et ex\u00e9cut\u00e9e par WebGoat :

"SELECT * FROM weather_data WHERE station = " + station +SqlNumericInjectionHint3=Les commandes SQL compos\u00e9es peuvent \u00eatre assembl\u00e9es en associant de multiples conditions au moyen de mots-cl\u00e9 tels que AND et OR. Essayez d'assembler une commande qui sera toujours r\u00e9solue \u00e0 vrai. +SqlNumericInjectionHint4=Essayez d'intercepter la requ\u00eate post avec ZAP, et remplacez la valeur du param\u00e8tre station par [ 101 OR 1 = 1 ]. + + +#StringSqlInjection.java +StringSqlInjectionSecondStage=Maintenant que vous avez r\u00e9alis\u00e9 une injection SQL avec succ\u00e8s, essayer le m\u00eame type d'attaque sur une requ\u00eate param\u00e9tr\u00e9e. Red\u00e9marrez la le\u00e7on si vous souhaitez revenir \u00e0 la requ\u00eate injectable. +EnterLastName=Entrez votre nom : +NoResultsMatched=Aucun r\u00e9sultat correspondant. Essayez encore. +SqlStringInjectionHint1=L'application r\u00e9cup\u00e8re votre saisie et l'ins\u00e8re \u00e0 la fin d'une commande SQL pr\u00e9-form\u00e9e. +SqlStringInjectionHint2=Voici le code de la requ\u00eate assembl\u00e9e et ex\u00e9cut\u00e9e par WebGoat :

"SELECT * FROM user_data WHERE last_name = "accountName" +SqlStringInjectionHint3=Les commandes SQL compos\u00e9es peuvent \u00eatre assembl\u00e9es en associant de multiples conditions au moyen de mots-cl\u00e9 tels que AND et OR. Essayez d'assembler une condition qui sera toujours r\u00e9solue \u00e0 vrai. +SqlStringInjectionHint4=Essayez de saisir [ smith' OR '1' = '1 ]. + + +#LogSpoofing.java +LoginFailedForUserName=Login failed for username +LoginSucceededForUserName=LOGIN SUCCEEDED FOR USERNAME +LogSpoofingHint1=Essayez de tromper l'\u0153il humain en utilisant de nouvelles lignes. +LogSpoofingHint2=Utilisez CR (%0d) et LF (%0a) pour une nouvelle ligne. +LogSpoofingHint3=Essayez : Smith%0d%0aLogin Succeeded for username: admin +LogSpoofingHint4=Essayez : Smith%0d%0aLogin Succeeded for username: admin<script>alert(document.cookie)</script> + +#StoredXss.java +StoredXssHint1=Vous pouvez utiliser des tags HTML dans votre message. +StoredXssHint1=Dissimulez un tag SCRIPT dns le message afin d'attaquer quiconque le lira. +StoredXssHint1=Entrez : <script language=\"javascript\" type=\"text/javascript\">alert(\"Ha Ha Ha\");</script> dans le champ message. +StoredXssHint1=Entrez : <script>alert(document.cookie);</script> dans le champ message. +MessageContentsFor=Contenu du message pour +Title=Titre +PostedBy=Post\u00e9 par +CouldNotFindMessage=Impossible de trouver ce message +Message=Message +MessageList=Liste de Messages +CouldNotAddMessage=Impossible d'ajouter un message \u00e0 la base de donn\u00e9es +ErroGeneratingMessageList=Erreur lors de la r\u00e9cup\u00e9ration de la liste de messages. + +#ReflectedXSS.java +ReflectedXSSWhoops1=Whoops! Vous avez saisi +ReflectedXSSWhoops2= au lieu de votre code de trois digits. Veuillez essayez \u00e0 nouveau. +ShoppingCart=Panier +ShoppingCartItems=Articles du panier -- To Buy Now +Price=Prix +Quantity=Quantit\u00e9 +Total=Total +TotalChargedCreditCard=Le montant pr\u00e9lev\u00e9 sur votre carte de cr\u00e9dit +UpdateCart=UpdateCart +EnterCreditCard=Entrez votre num\u00e9ro de carte de cr\u00e9dit +Enter3DigitCode=Entrez votre code d'acc\u00e8s de trois digits +Purchase=Acheter +ReflectedXSSHint1=Un script simple est <SCRIPT>alert('bang!');</SCRIPT>. +ReflectedXSSHint2=Pouvez-vous r\u00e9v\u00e9ler le cookie JSESSIONID au moyen du script ? +ReflectedXSSHint3=Vous pouvez utiliser <SCRIPT>alert(document.cookie);</SCRIPT> pour acc\u00e9der au session id du cookie +ReflectedXSSHint4=Pouvez-vous acc\u00e9der au champ carte de cr\u00e9dit du formulaire depuis le script ? +ReflectedXSSHint5=Essayez une commande de cross site trace (XST) :
<script type=\"text/javascript\">if ( navigator.appName.indexOf(\"Microsoft\") !=-1){var xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");xmlHttp.open(\"TRACE\", \"./\", false); xmlHttp.send();str1=xmlHttp.responseText; while (str1.indexOf(\"\\n\") > -1) str1 = str1.replace(\"\\n\",\"<br>\"); document.write(str1);}</script>"); + +#HtmlClues.java +HtmlCluesBINGO=BINGO -- admin authentifi\u00e9 +HtmlCluesHint1=Vous pouvez visualiser les sources HTML en s\u00e9lectionnant 'Afficher le code source' depuis les menus du navigateur. +HtmlCluesHint2=De nombreux indices sont pr\u00e9sents dans le code HTML +HtmlCluesHint3=Recherchez le mot HIDDEN, \u00e9tudiez les URL, recherchez les commentaires. + +#JavaScriptValidation.java +3LowerCase=Champ1 : exactement trois caract\u00e8res miniscules +Exactly3Digits=Champ2 : exactement trois digits +LettersNumbersSpaceOnly=Champ3 : lettres, nombres et espace seulement +EnumerationOfNumbers=Champ4 : \u00e9numeration de nombres +SimpleZipCode=Champ5 : code postal simple +ZIPDashFour=Champ6 : zip with optional dash four +USPhoneNumber=Champ7 : num\u00e9ro de t\u00e9l\u00e9phone US avec ou sans tiret(s) + +ServerSideValidationViolation=Violation de la validation c\u00f4t\u00e9 serveur : You succeeded for +JavaScriptValidationHint1=La validation s'op\u00e8re dans votre navigateur. +JavaScriptValidationHint2=Essayez de modifier les valeurs au moyen d'un proxy apr\u00e8s soumission depuis le navigateur +JavaScriptValidationHint3=Une autre approche est de supprimer le JavaScript avant de visualiser la page. + +#HiddenFieldTampering.java +TotalPriceIs=Votre montant total est de +ThisAmountCharged=Ce montant sera d\u00e9bit\u00e9 sur votre carte de cr\u00e9dit imm\u00e9diatement. + +HiddenFieldTamperingHint1=Cette application utilise des champs cach\u00e9s pour transmettre des informations de tarification au serveur. +HiddenFieldTamperingHint2=Utilisez un programme pour intercepter et modifier la valeur du champ cach\u00e9. +HiddenFieldTamperingHint3=Utilisez ZAP pour modifier le prix de la TV de " +HiddenFieldTamperingHint32= \u00e0 + +# Modify data with SQL Injection +EnterUserid=Entrez votre userid : +SqlModifyDataHint1=Vous pouvez utiliser l'injection SQL pour ex\u00e9cuter plus d'une instruction SQL. +SqlModifyDataHint2=Utilisez le point-virgule (;) pour s\u00e9parer les instructions SQL. +SqlModifyDataHint3=Modifiez les donn\u00e9es en utilisant une instruction SQL UPDATE. +SqlModifyDataHint4=Pour des d\u00e9tails et des exemples d'utilisation d'instructions SQL UPDATE, consultez http://www.w3schools.com/SQl/sql_update.asp +SqlModifyDataHint5=SOLUTION :
foo'; UPDATE salaries SET salary=9999999 WHERE userid='jsmith + +# Modify data with SQL Injection +SqlAddDataHint1=Vous pouvez utiliser l'injection SQL pour ex\u00e9cuter plus d'une instruction SQL. +SqlAddDataHint2=Utilisez le point-virgule (;) pour s\u00e9parer les instructions SQL. Vous aurez \u00e9galement besoin de commenter certains caract\u00e8res pr\u00e9sents apr\u00e8s l'injection avec un double tiret (--). +SqlAddDataHint3=Modifiez les donn\u00e9es en utilisant une instruction SQL INSERT. +SqlAddDataHint4=Pour des d\u00e9tails et des exemples d'utilisation d'instructions SQL INSERT, consultez http://www.w3schools.com/SQl/sql_insert.asp +SqlAddDataHint5=SOLUTION :
bar'; INSERT INTO salaries VALUES ('cwillis', 999999); -- + +# Bypass Html Field Restrictions +BypassHtmlFieldRestrictionsHint1=Vous devez r\u00e9activer le champ de formulaire d\u00e9sactiv\u00e9 ou ajouter manuellement le param\u00e8tre correspondant \u00e0 votre requ\u00eate. +BypassHtmlFieldRestrictionsHint2=Vous pouvez utiliser ZAP pour intercepter et modifier les requ\u00eates. +BypassHtmlFieldRestrictionsHint3=Plut\u00f4t que d'utiliser ZAP, vous pouvez utiliser Web Developer et/ou l'extension Firefox Hackbar pour mener \u00e0 bien cette le\u00e7on. + diff --git a/src/main/resources/WebGoatLabels_russian.properties b/src/main/resources/WebGoatLabels_ru.properties similarity index 100% rename from src/main/resources/WebGoatLabels_russian.properties rename to src/main/resources/WebGoatLabels_ru.properties diff --git a/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml index 943637baa..3e60f1024 100644 --- a/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml +++ b/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -1,59 +1,59 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml index 4612dd975..f0d38c3ce 100644 --- a/src/main/webapp/WEB-INF/web.xml +++ b/src/main/webapp/WEB-INF/web.xml @@ -1,288 +1,294 @@ - - - - WebGoat - - This web application is designed to demonstrate web - application security flaws for the purpose of educating - developers and security professionals about web - application security problems. Please contact Bruce Mayhew - (webgoat@owasp.org) if you have any questions. - - - - email - webgoat@owasp.org - - The EMAIL address of the administrator to whom questions - and comments about this application should be addressed. - - - - emaillist - owasp-webgoat@lists.owasp.org - - The EMAIL address of the webgoat email list - - - - - contextConfigLocation - - /WEB-INF/mvc-dispatcher-servlet.xml, - /WEB-INF/spring-security.xml - - - - - AxisServlet - Apache-Axis Servlet - - org.apache.axis.transport.http.AxisServlet - - - - AdminServlet - Axis Admin Servlet - - org.apache.axis.transport.http.AdminServlet - - 100 - - - SOAPMonitorService - SOAPMonitorService - - org.apache.axis.monitor.SOAPMonitorService - - - SOAPMonitorPort - 5001 - - 100 - - - WebGoat - - This servlet plays the "controller" role in the MVC architecture - used in this application. - - The initialization parameter namess for this servlet are the - "servlet path" that will be received by this servlet (after the - filename extension is removed). The corresponding value is the - name of the action class that will be used to process this request. - - org.owasp.webgoat.HammerHead - - email - WebGoat@owasp.org - The EMAIL address of the administrator to whom questions - and comments about this application should be addressed. - - - - debug - false - - - CookieDebug - true - - - DefuseOSCommands - false - - - Enterprise - true - - - CodingExercises - true - - - - - - FeedbackAddress - - <A HREF=mailto:webgoat@owasp.org>webgoat@owasp.org</A> - - - - DatabaseDriver - - org.hsqldb.jdbcDriver - - - - DatabaseConnectionString - - jdbc:hsqldb:mem:${USER} - - - DefaultLanguage - en - - - 5 - - - LessonSource - - This servlet returns the Java source of the current lesson. - - org.owasp.webgoat.LessonSource - - - Catcher - - This servlet catches any posts and marks the appropriate lesson property. - - org.owasp.webgoat.Catcher - - - conf - /lessons/ConfManagement/config.jsp - - - - mvc-dispatcher - org.springframework.web.servlet.DispatcherServlet - 1 - - - mvc-dispatcher - *.mvc - - - Spring context init - org.springframework.web.context.ContextLoaderListener - - - WebGoat application init - org.owasp.webgoat.application.WebGoatServletListener - - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - springSecurityFilterChain - /* - - - - - AxisServlet - /servlet/AxisServlet - - - AxisServlet - *.jws - - - AxisServlet - /services/* - - - SOAPMonitorService - /SOAPMonitor - - - - AdminServlet - /servlet/AdminServlet - - - WebGoat - /attack - - - LessonSource - /source - - - Catcher - /catcher - - - conf - /conf - - - - - 2880 - - - wmv - video/x-ms-wmv - - - index.jsp - - + + + + WebGoat + + This web application is designed to demonstrate web + application security flaws for the purpose of educating + developers and security professionals about web + application security problems. Please contact Bruce Mayhew + (webgoat@owasp.org) if you have any questions. + + + + email + webgoat@owasp.org + + The EMAIL address of the administrator to whom questions + and comments about this application should be addressed. + + + + emaillist + owasp-webgoat@lists.owasp.org + + The EMAIL address of the webgoat email list + + + + + contextConfigLocation + + /WEB-INF/mvc-dispatcher-servlet.xml, + /WEB-INF/spring-security.xml + + + + + AxisServlet + Apache-Axis Servlet + + org.apache.axis.transport.http.AxisServlet + + + + AdminServlet + Axis Admin Servlet + + org.apache.axis.transport.http.AdminServlet + + 100 + + + SOAPMonitorService + SOAPMonitorService + + org.apache.axis.monitor.SOAPMonitorService + + + SOAPMonitorPort + 5001 + + 100 + + + WebGoat + + This servlet plays the "controller" role in the MVC architecture + used in this application. + + The initialization parameter namess for this servlet are the + "servlet path" that will be received by this servlet (after the + filename extension is removed). The corresponding value is the + name of the action class that will be used to process this request. + + org.owasp.webgoat.HammerHead + + email + WebGoat@owasp.org + The EMAIL address of the administrator to whom questions + and comments about this application should be addressed. + + + + debug + false + + + CookieDebug + true + + + DefuseOSCommands + false + + + Enterprise + true + + + CodingExercises + true + + + + + + FeedbackAddress + + <A HREF=mailto:webgoat@owasp.org>webgoat@owasp.org</A> + + + + DatabaseDriver + + org.hsqldb.jdbcDriver + + + + DatabaseConnectionString + + jdbc:hsqldb:mem:${USER} + + + + 5 + + + LessonSource + + This servlet returns the Java source of the current lesson. + + org.owasp.webgoat.LessonSource + + + Catcher + + This servlet catches any posts and marks the appropriate lesson property. + + org.owasp.webgoat.Catcher + + + conf + /lessons/ConfManagement/config.jsp + + + + mvc-dispatcher + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc-dispatcher + *.mvc + + + Spring context init + org.springframework.web.context.ContextLoaderListener + + + Spring context init + org.springframework.web.context.request.RequestContextListener + + + WebGoat application init + org.owasp.webgoat.application.WebGoatServletListener + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + + + AxisServlet + /servlet/AxisServlet + + + AxisServlet + *.jws + + + AxisServlet + /services/* + + + SOAPMonitorService + /SOAPMonitor + + + + AdminServlet + /servlet/AdminServlet + + + WebGoat + /attack + + + LessonSource + /source + + + Catcher + /catcher + + + conf + /conf + + + + + 2880 + + + wmv + video/x-ms-wmv + + + index.jsp + + diff --git a/src/main/webapp/main.jsp b/src/main/webapp/main.jsp index 04dba86ca..7e704027d 100644 --- a/src/main/webapp/main.jsp +++ b/src/main/webapp/main.jsp @@ -1,294 +1,295 @@ -<%@ page contentType="text/html; charset=ISO-8859-1" language="java" - import="org.owasp.webgoat.session.*, org.owasp.webgoat.lessons.Category, org.owasp.webgoat.lessons.AbstractLesson, org.owasp.webgoat.util.*, java.util.*" - errorPage="" %> -<% - WebSession webSession = ((WebSession) session.getAttribute(WebSession.SESSION)); - Course course = webSession.getCourse(); - AbstractLesson currentLesson = webSession.getCurrentLesson(); -%> - - -<%@page import="org.owasp.webgoat.lessons.RandomLessonAdapter"%> - - - - <%=currentLesson.getTitle()%> - - - - - - - - - - - <% - final String menuPrefix = WebSession.MENU; - final String submenuPrefix = "submenu"; - final String mbutPrefix = "mbut"; - String printHint = ""; - String printParameters = ""; - String printCookies = ""; - String lessonComplete = ""; - - List categories = course.getCategories(); - - StringBuffer buildList = new StringBuffer(); - - Iterator iter1 = categories.iterator(); - while (iter1.hasNext()) { - Category category = (Category) iter1.next(); - - buildList.append("'"); - buildList.append(menuPrefix); - buildList.append(category.getRanking()); - buildList.append("','"); - buildList.append(submenuPrefix); - buildList.append(category.getRanking()); - buildList.append("','"); - buildList.append(mbutPrefix); - buildList.append(category.getRanking()); - buildList.append("'"); - - if (iter1.hasNext()) { - buildList.append(","); - } - }%> - - -
- <% - int topCord = 140; - int zIndex = 105; - - Iterator iter2 = categories.iterator(); - while (iter2.hasNext()) { - Category category = (Category) iter2.next(); - %> - - <% - topCord = topCord + 30; - zIndex = zIndex + 1; - } - - int topSubMenu = 72; - - Iterator iter3 = categories.iterator(); - while (iter3.hasNext()) { - Category category = (Category) iter3.next(); - List lessons = webSession.getLessons(category); - Iterator iter4 = lessons.iterator(); - %> - <% - }%> -
-
-
- <% if (currentLesson.getAvailableLanguages().size() != 0) { - %> -
- Choose another language:
- <% - } else { - %> - Internationalization is not available for this lesson - <% - } - %> -
-
- LogOut Help -
-
<%=currentLesson.getTitle()%>
-
- <% - if (webSession.isAuthorizedInLesson(webSession.getRole(), WebSession.SHOWHINTS)) { - %> - - Previous Hint - - - Hints - - - Next Hint - - <%}%> - - Show Params - - - Show Cookies - - - Lesson Plans - - <% - if (webSession.isAuthorizedInLesson(webSession.getRole(), WebSession.SHOWSOURCE)) { - %> - - Show Java - - - Show Solution - - <%}%> - -
-
- -
- <% - if (currentLesson != null) { - %> - - <% - } - %> -
-
- <% - if (webSession.getHint() != null) { - printHint = "
" + webSession.getHint() + "

"; - out.println(printHint); - } - - if (webSession.getParams() != null) { - Iterator i = webSession.getParams().iterator(); - while (i.hasNext()) { - Parameter p = (Parameter) i.next(); - printParameters = "
" + p.getName() + "=" + p.getValue() + "

"; - out.println(printParameters); - } - } - - if (webSession.getCookies() != null) { - Iterator i = webSession.getCookies().iterator(); - while (i.hasNext()) { - Cookie c = (Cookie) i.next(); - printCookies = "
" + c.getName() + " \"\" " + c.getValue() + "

"; - out.println(printCookies); - } - }%> - -
- <% - AbstractLesson lesson = webSession.getCurrentLesson(); - if (lesson instanceof RandomLessonAdapter) { - RandomLessonAdapter rla = (RandomLessonAdapter) lesson; - %> -
Stage <%= rla.getLessonTracker(webSession).getStageNumber(rla.getStage(webSession)) + 1%>
- <% - } - %> - <%=webSession.getInstructions()%>
-
<%=webSession.getMessage()%>
- - <% - if (currentLesson.getTemplatePage(webSession) != null) { - //System.out.println("Main.jsp - current lesson: " + currentLesson.getName() ); - //System.out.println(" - template Page: " + currentLesson.getTemplatePage(webSession)); -%> - - <% - } else { - %> -
<%=currentLesson.getContent()%>
- <% - } - %> -
- <% out.println(currentLesson.getCredits());%> -
-
-
- - -
- - +<%@ page contentType="text/html; charset=ISO-8859-1" language="java" + import="org.owasp.webgoat.session.*, org.owasp.webgoat.lessons.Category, org.owasp.webgoat.lessons.AbstractLesson, org.owasp.webgoat.util.*, java.util.*" + errorPage="" %> +<% + WebSession webSession = ((WebSession) session.getAttribute(WebSession.SESSION)); + Course course = webSession.getCourse(); + AbstractLesson currentLesson = webSession.getCurrentLesson(); + LabelManager labelManager = BeanProvider.getBean("labelManager", LabelManager.class); +%> + + +<%@page import="org.owasp.webgoat.lessons.RandomLessonAdapter"%> + + + + <%=currentLesson.getTitle()%> + + + + + + + + + + + <% + final String menuPrefix = WebSession.MENU; + final String submenuPrefix = "submenu"; + final String mbutPrefix = "mbut"; + String printHint = ""; + String printParameters = ""; + String printCookies = ""; + String lessonComplete = ""; + + List categories = course.getCategories(); + + StringBuffer buildList = new StringBuffer(); + + Iterator iter1 = categories.iterator(); + while (iter1.hasNext()) { + Category category = (Category) iter1.next(); + + buildList.append("'"); + buildList.append(menuPrefix); + buildList.append(category.getRanking()); + buildList.append("','"); + buildList.append(submenuPrefix); + buildList.append(category.getRanking()); + buildList.append("','"); + buildList.append(mbutPrefix); + buildList.append(category.getRanking()); + buildList.append("'"); + + if (iter1.hasNext()) { + buildList.append(","); + } + }%> + + +
+ <% + int topCord = 140; + int zIndex = 105; + + Iterator iter2 = categories.iterator(); + while (iter2.hasNext()) { + Category category = (Category) iter2.next(); + %> + + <% + topCord = topCord + 30; + zIndex = zIndex + 1; + } + + int topSubMenu = 72; + + Iterator iter3 = categories.iterator(); + while (iter3.hasNext()) { + Category category = (Category) iter3.next(); + List lessons = webSession.getLessons(category); + Iterator iter4 = lessons.iterator(); + %> + <% + }%> +
+
+
+ <% if (currentLesson.getAvailableLanguages().size() != 0) { + %> +
+ Choose another language:
+ <% + } else { + %> + Internationalization is not available for this lesson + <% + } + %> +
+
+ LogOut Help +
+
<%=currentLesson.getTitle()%>
+
+ <% + if (webSession.isAuthorizedInLesson(webSession.getRole(), WebSession.SHOWHINTS)) { + %> + + Previous Hint + + + Hints + + + Next Hint + + <%}%> + + Show Params + + + Show Cookies + + + Lesson Plans + + <% + if (webSession.isAuthorizedInLesson(webSession.getRole(), WebSession.SHOWSOURCE)) { + %> + + Show Java + + + Show Solution + + <%}%> + +
+
+ +
+ <% + if (currentLesson != null) { + %> + + <% + } + %> +
+
+ <% + if (webSession.getHint() != null) { + printHint = "
" + webSession.getHint() + "

"; + out.println(printHint); + } + + if (webSession.getParams() != null) { + Iterator i = webSession.getParams().iterator(); + while (i.hasNext()) { + Parameter p = (Parameter) i.next(); + printParameters = "
" + p.getName() + "=" + p.getValue() + "

"; + out.println(printParameters); + } + } + + if (webSession.getCookies() != null) { + Iterator i = webSession.getCookies().iterator(); + while (i.hasNext()) { + Cookie c = (Cookie) i.next(); + printCookies = "
" + c.getName() + " \"\" " + c.getValue() + "

"; + out.println(printCookies); + } + }%> + +
+ <% + AbstractLesson lesson = webSession.getCurrentLesson(); + if (lesson instanceof RandomLessonAdapter) { + RandomLessonAdapter rla = (RandomLessonAdapter) lesson; + %> +
Stage <%= rla.getLessonTracker(webSession).getStageNumber(rla.getStage(webSession)) + 1%>
+ <% + } + %> + <%=webSession.getInstructions()%>
+
<%=webSession.getMessage()%>
+ + <% + if (currentLesson.getTemplatePage(webSession) != null) { + //System.out.println("Main.jsp - current lesson: " + currentLesson.getName() ); + //System.out.println(" - template Page: " + currentLesson.getTemplatePage(webSession)); +%> + + <% + } else { + %> +
<%=currentLesson.getContent()%>
+ <% + } + %> +
+ <% out.println(currentLesson.getCredits());%> +
+
+
+ + +
+ +