Java Examples for org.owasp.esapi.ESAPI

The following java examples will help you to understand the usage of org.owasp.esapi.ESAPI. These source code samples are taken from different open source projects.

Example 1
Project: find-sec-bugs-master  File: XssServlet3.java View source code
public void writeWithEncoders(PrintWriter pw, String input1) {
    pw.write(input1);
    String encoded = ESAPI.encoder().encodeForHTML(input1);
    pw.write(encoded.toLowerCase() + SAFE_VALUE);
    pw.write(StringEscapeUtils.escapeHtml(input1));
    pw.write(ESAPI.encoder().decodeForHTML(encoded) + SAFE_VALUE);
    pw.write(myEncode(input1));
    pw.write(myDecode(encoded));
    pw.write(input1.replaceAll("[\"'<>&]", ""));
}
Example 2
Project: railo-master  File: ESAPIEncode.java View source code
public static String encode(String item, short encFor) throws PageException {
    PrintStream out = System.out;
    try {
        System.setOut(new PrintStream(DevNullOutputStream.DEV_NULL_OUTPUT_STREAM));
        Encoder encoder = ESAPI.encoder();
        switch(encFor) {
            //case ENC_CSS:return encoder.encodeForBase64(item);
            case ENC_CSS:
                return encoder.encodeForCSS(item);
            case ENC_DN:
                return encoder.encodeForDN(item);
            case ENC_HTML:
                return encoder.encodeForHTML(item);
            case ENC_HTML_ATTR:
                return encoder.encodeForHTMLAttribute(item);
            case ENC_JAVA_SCRIPT:
                return encoder.encodeForJavaScript(item);
            case ENC_LDAP:
                return encoder.encodeForLDAP(item);
            //case ENC_CSS:return encoder.encodeForSQL(arg0, arg1)CSS(item);
            case ENC_URL:
                return encoder.encodeForURL(item);
            case ENC_VB_SCRIPT:
                return encoder.encodeForVBScript(item);
            case ENC_XML:
                return encoder.encodeForXML(item);
            case ENC_XML_ATTR:
                return encoder.encodeForXMLAttribute(item);
            case ENC_XPATH:
                return encoder.encodeForXPath(item);
        }
        throw new ApplicationException("invalid target encoding defintion");
    } catch (EncodingException ee) {
        throw Caster.toPageException(ee);
    } finally {
        System.setOut(out);
    }
}
Example 3
Project: chukwa-master  File: XssFilter.java View source code
/**
     * Strips any potential XSS threats out of the value
     * @param value is a string
     * @return filtered string
     */
public String filter(String value) {
    if (value == null)
        return null;
    // Use the ESAPI library to avoid encoded attacks.
    value = ESAPI.encoder().canonicalize(value);
    // Avoid null characters
    value = value.replaceAll("\0", "");
    // Clean out HTML
    value = Jsoup.clean(value, Whitelist.none());
    return value;
}
Example 4
Project: Java-Web-Security-master  File: XPathEscapingServlet.java View source code
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    LOGGER.info("Received {} and {} as parameter", name, password);
    String safeName = ESAPI.encoder().encodeForXPath(name);
    String safePassword = ESAPI.encoder().encodeForXPath(password);
    LOGGER.info("Using safe name {} and {}", safeName, safePassword);
    StringBuilder xpathExpression = new StringBuilder();
    xpathExpression.append("/customers/customer[name='");
    xpathExpression.append(safeName);
    xpathExpression.append("' and @password='");
    xpathExpression.append(safePassword);
    xpathExpression.append("']/orderLimit");
    printOrderLimit(xpathExpression.toString(), name, response);
}
Example 5
Project: Lucee-master  File: ESAPIEncode.java View source code
public static String encode(String item, short encFor, boolean canonicalize) throws PageException {
    if (StringUtil.isEmpty(item))
        return item;
    PrintStream out = System.out;
    try {
        System.setOut(new PrintStream(DevNullOutputStream.DEV_NULL_OUTPUT_STREAM));
        Encoder encoder = ESAPI.encoder();
        if (canonicalize)
            item = encoder.canonicalize(item, false);
        switch(encFor) {
            case ENC_CSS:
                return encoder.encodeForCSS(item);
            case ENC_DN:
                return encoder.encodeForDN(item);
            case ENC_HTML:
                return encoder.encodeForHTML(item);
            case ENC_HTML_ATTR:
                return encoder.encodeForHTMLAttribute(item);
            case ENC_JAVA_SCRIPT:
                return encoder.encodeForJavaScript(item);
            case ENC_LDAP:
                return encoder.encodeForLDAP(item);
            case ENC_URL:
                return encoder.encodeForURL(item);
            case ENC_VB_SCRIPT:
                return encoder.encodeForVBScript(item);
            case ENC_XML:
                return encoder.encodeForXML(item);
            case ENC_XML_ATTR:
                return encoder.encodeForXMLAttribute(item);
            case ENC_XPATH:
                return encoder.encodeForXPath(item);
        }
        throw new ApplicationException("invalid target encoding defintion");
    } catch (EncodingException ee) {
        throw Caster.toPageException(ee);
    } finally {
        System.setOut(out);
    }
}
Example 6
Project: simba-os-master  File: DTOValidator.java View source code
private static void encodeFieldForHTML(AbstractIdentifiableDTO dto, String methodName) {
    try {
        String value = (String) dto.getClass().getMethod("get" + methodName).invoke(dto);
        if (value != null && !StringUtils.isBlank(value)) {
            String cleanedValue = ESAPI.encoder().encodeForHTML(value);
            dto.getClass().getMethod("set" + methodName, new Class[] { String.class }).invoke(dto, cleanedValue);
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to access get/set " + methodName + " on " + dto.getClass().getName(), e);
    }
}
Example 7
Project: sling-master  File: XSSAPIImpl.java View source code
/**
     * @see org.apache.sling.xss.XSSAPI#getValidLong(String, long)
     */
@Override
public Long getValidLong(String source, long defaultValue) {
    if (source != null && source.length() > 0) {
        try {
            LongValidationRule ivr = new LongValidationRule("number", ESAPI.encoder(), -9000000000000000000L, 9000000000000000000L);
            ivr.setAllowNull(false);
            return ivr.getValid("XSS", source);
        } catch (Exception e) {
        }
    }
    // fall through to default if empty, null, or validation failure
    return defaultValue;
}
Example 8
Project: webpasswordsafe-master  File: EsapiEncryptor.java View source code
/* (non-Javadoc)
     * @see net.webpasswordsafe.server.plugin.encryption.Encryptor#decrypt(java.lang.String)
     */
@Override
public String decrypt(String cryptedText) {
    String clearText = null;
    try {
        CipherText cipherText = CipherText.fromPortableSerializedBytes(Base64.decode(cryptedText));
        clearText = ESAPI.encryptor().decrypt(cipherText).toString();
    } catch (EncryptionException e) {
        LOG.error("EsapiEncryptor.decrypt: " + e.getMessage(), e);
    }
    return clearText;
}
Example 9
Project: ApacheChemistryInAction-master  File: HTMLHelper.java View source code
public static String format(Object value) {
    if (value == null) {
        return "";
    }
    if (value instanceof Calendar) {
        Date date = ((Calendar) value).getTime();
        long delta = System.currentTimeMillis() - date.getTime();
        if (delta >= 0) {
            if (delta < (60 * 1000)) {
                return "just now";
            }
            if (delta < (2 * 60 * 1000)) {
                return "a minute ago";
            }
            if (delta < (10 * 60 * 1000)) {
                return ((int) Math.floor((double) delta / (60 * 1000))) + " minutes ago";
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z");
        return sdf.format(date);
    } else if (value instanceof Number) {
        return NumberFormat.getInstance().format(value);
    }
    return ESAPI.encoder().encodeForHTML(value.toString());
}
Example 10
Project: appverse-web-master  File: SecurityHelper.java View source code
public static String createXSRFToken(final HttpServletRequest request) throws IOException {
    // getSession(false) as this method never creates a new session
    HttpSession session = request.getSession(false);
    String xsrfSessionToken = (String) session.getAttribute(XSRF_TOKEN_NAME);
    if (xsrfSessionToken == null) {
        long value = System.currentTimeMillis() + ESAPI.randomizer().getRandomLong();
        char ids[] = session.getId().toCharArray();
        for (int i = 0; i < ids.length; i++) {
            value += ids[i] * (i + 1);
        }
        xsrfSessionToken = Long.toString(value);
        session.setAttribute(XSRF_TOKEN_NAME, xsrfSessionToken);
    }
    return xsrfSessionToken;
}
Example 11
Project: coprhd-controller-master  File: SecurityUtils.java View source code
/**
     * Removes any potential XSS threats from the value.
     * Depends on the WASP ESAPI (owasp.org) and jsoup libraries (jsoup.org).
     * 
     * @param value data to be cleaned
     * @return cleaned data
     */
public static String stripXSS(String value) {
    if (value == null) {
        return null;
    }
    // firstly, ESAPI canonicalize input, then Jsoup cleans all html tags, which includes <script> tags.
    value = ESAPI.encoder().canonicalize(value, false, false);
    value = value.replaceAll("\0", "");
    value = Jsoup.clean(value, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
    return value;
}
Example 12
Project: SecurityShepherd-master  File: Getter.java View source code
/**
	 * Returns HTML menu for challenges. Challenges are only referenced by their id, 
	 * The user will have to go through another servlet to get the module's View address
	 * @param ApplicationRoot The current running context of the application
	 * @return HTML menu for challenges	
	 */
public static String getChallenges(String ApplicationRoot, String userId, Locale lang) {
    log.debug("*** Getter.getChallenges ***");
    String output = new String();
    //Getting Translated Level Names
    ResourceBundle bundle = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", lang);
    //Encoder to prevent XSS
    Encoder encoder = ESAPI.encoder();
    Connection conn = Database.getCoreConnection(ApplicationRoot);
    try {
        CallableStatement callstmt = conn.prepareCall("call moduleAllInfo(?, ?)");
        callstmt.setString(1, "challenge");
        callstmt.setString(2, userId);
        log.debug("Gathering moduleAllInfo ResultSet");
        ResultSet challenges = callstmt.executeQuery();
        log.debug("Opening Result Set from moduleAllInfo");
        String challengeCategory = new String();
        // Identifies the first row, ie the start of the list. This is slightly different output to every other row
        int rowNumber = 0;
        while (challenges.next()) {
            if (!challengeCategory.equalsIgnoreCase(challenges.getString(2))) {
                challengeCategory = challenges.getString(2);
                //output prepared for Every row after row 1
                if (rowNumber > 0)
                    output += "</ul></li><li><a href='javascript:;' class='challengeHeader' >" + encoder.encodeForHTML(bundle.getString("category." + challengeCategory)) + "</a><ul class='challengeList' style='display: none;'>";
                else
                    //output prepared for First row in entire challenge
                    output += "<li><a href='javascript:;' class='challengeHeader'>" + encoder.encodeForHTML(bundle.getString("category." + challengeCategory)) + "</a><ul class='challengeList' style='display: none;'>";
            //log.debug("Compiling Challenge Category - " + challengeCategory);
            }
            //Starts next LI element
            output += "<li>";
            if (challenges.getString(4) != null) {
                //Completed marker
                output += "<img src='css/images/completed.png'/>";
            } else {
                //Incomplete marker
                output += "<img src='css/images/uncompleted.png'/>";
            }
            //Final out put compilation
            output += "<a class='lesson' id='" + encoder.encodeForHTMLAttribute(challenges.getString(3)) + "' href='javascript:;'>" + encoder.encodeForHTML(bundle.getString(challenges.getString(1))) + "</a>";
            output += "</li>";
            rowNumber++;
        }
        //Check if output is empty
        if (output.isEmpty()) {
            output = "<li><a href='javascript:;'>No challenges found</a></li>";
        } else {
            log.debug("Appending End tags");
            output += "</ul></li>";
        }
    } catch (Exception e) {
        log.error("Challenge Retrieval: " + e.toString());
    }
    Database.closeConnection(conn);
    log.debug("*** END getChallenges() ***");
    return output;
}
Example 13
Project: XssSanitizer-master  File: XssSanitizerUtil.java View source code
/**
	 * This method takes a string and strips out any potential script injections.
	 *
	 * @param value
	 * @return String - the new "sanitized" string.
	 */
public static String stripXSS(String value) {
    try {
        if (value != null) {
            // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
            // avoid encoded attacks.
            value = ESAPI.encoder().canonicalize(value);
            // Avoid null characters
            value = value.replaceAll("\0", "");
            // test against known XSS input patterns
            for (Pattern xssInputPattern : XSS_INPUT_PATTERNS) {
                value = xssInputPattern.matcher(value).replaceAll("");
            }
        }
    } catch (Exception ex) {
        System.out.println("Could not strip XSS from value = " + value + " | ex = " + ex.getMessage());
    }
    return value;
}
Example 14
Project: threadfixRack-master  File: ApplicationServiceImpl.java View source code
public Application encryptCredentials(Application application) {
    try {
        if (application != null && application.getPassword() != null && application.getPassword() != null) {
            application.setEncryptedPassword(ESAPI.encryptor().encrypt(application.getPassword()));
            application.setEncryptedUserName(ESAPI.encryptor().encrypt(application.getUserName()));
        }
    } catch (EncryptionException e) {
        log.warn("Encountered an ESAPI encryption exception. Check your ESAPI configuration.", e);
    }
    return application;
}
Example 15
Project: easyrec-code-master  File: ProfileRenderer.java View source code
/**
     * This function appends HTML text based on the given nodeList to the given StringBuilder
     * The function will build the HTML recursively until the whole tree is converted to HTML.
     *
     * @param nodeList    the nodeList which you want to convert to HTML
     * @param profileHTML the StringBuilder which is used to write the HTML
     */
private void convertNodeListToHTML(NodeList nodeList, StringBuilder profileHTML) {
    if (nodeList == null) {
        profileHTML.append("<p>could not parse the XML profile of this item. </p>");
        return;
    }
    int elementCounter = countElements(nodeList);
    if (elementCounter == 0)
        return;
    profileHTML.append("<dl>");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node item = nodeList.item(i);
        if (item.getNodeType() == Node.ELEMENT_NODE) {
            profileHTML.append("<dt class=\"profileView\">" + ESAPI.encoder().encodeForHTML(item.getNodeName()) + ":</dt>");
            profileHTML.append("<dd class=\"profileView\">");
            convertNodeListToHTML(item.getChildNodes(), profileHTML);
            String textNodeValue = ESAPI.encoder().encodeForHTML(item.getFirstChild().getNodeValue());
            if (textNodeValue != null)
                profileHTML.append(textNodeValue);
            profileHTML.append("</dd>");
        }
    }
    profileHTML.append("</dl>");
}
Example 16
Project: OpenClinica-master  File: StudySubjectDAO.java View source code
public EntityBean findAnotherBySameLabel(String label, int studyId, int studySubjectId) {
    StudySubjectBean eb = new StudySubjectBean();
    this.setTypesExpected();
    HashMap variables = new HashMap();
    variables.put(new Integer(1), ESAPI.encoder().encodeForHTML(label));
    variables.put(new Integer(2), new Integer(studyId));
    variables.put(new Integer(3), new Integer(studySubjectId));
    String sql = digester.getQuery("findAnotherBySameLabel");
    ArrayList alist = this.select(sql, variables);
    Iterator it = alist.iterator();
    if (it.hasNext()) {
        eb = (StudySubjectBean) this.getEntityFromHashMap((HashMap) it.next());
    }
    return eb;
}
Example 17
Project: JavaSecurity-master  File: EscapedQuery.java View source code
public List<Customer> query(String name) {
    String safeName = ESAPI.encoder().encodeForSQL(new OracleCodec(), name);
    String query = "SELECT * FROM customer WHERE name = '" + safeName + "' ORDER BY id";
    List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
    return CustomerRowMapper.mapRows(rows);
}
Example 18
Project: patientview-master  File: XssUtils.java View source code
public static String encodeForHTML(String strSrc, String[] strReplace) {
    strSrc = ESAPI.encoder().encodeForHTML(strSrc);
    for (String replace : strReplace) {
        strSrc = strSrc.replace(replace, "<br/>");
    }
    return strSrc;
}
Example 19
Project: albert-master  File: SecurityUtil.java View source code
public static final String escapeMySQL(String source) {
    return ESAPI.encoder().encodeForSQL(MYSQL_CODEC, source);
}