Bugs Patterns

The complete list of descriptions given when FindBugs identify potential weaknesses.

?????????????????????????????????????????????????????????????????????????????

  • CSRF ????
  • ????????????? (???????????)
  • ????????

?????????? java.util.Random ???? java.security.SecureRandom ?????????????????????

??????:

String generateSecretToken() {
    Random r = new Random();
    return Long.toHexString(r.nextLong());
}

???:

import org.apache.commons.codec.binary.Hex;

String generateSecretToken() {
    SecureRandom secRandom = new SecureRandom();

    byte[] result = new byte[32];
    secRandom.nextBytes(result);
    return Hex.encodeHexString(result);
}


????
Cracking Random Number Generators - Part 1 (http://jazzy.id.au)
CERT: MSC02-J. Generate strong random numbers
CWE-330: Use of Insufficiently Random Values
Predicting Struts CSRF Token (Example of real-life vulnerability and exploitation)

???????????????? GET ? POST ?????????????????????????????????????? ????????????? API ?????????????????????????????????????

  • SQL ???? (SQL ????????????????)
  • ???????? (????????????????)
  • ????????????????????????
  • HTML?????????? XSS?
  • ??...

????
CWE-20: Improper Input Validation

HTTP ???? Content-Type ??????????????????????????????????????????????????????


????
CWE-807: Untrusted Inputs in a Security Decision

Host ?????????????????????????????????????????????????????????? ServletRequest.getServerName() ? HttpServletRequest.getHeader("Host") ?? ???? Host ?????????????????????

GET /testpage HTTP/1.1
Host: www.example.com
[...]

?????????????????????????????????????????????????????????????????? ?????????????????????????????????????????? ?????????????????????????????????????????????


????
CWE-807: Untrusted Inputs in a Security Decision

???? HttpServletRequest.getRequestedSessionId() ?????? JSESSIONID ??????????? ????????????????????????????????????????????

???????????????????????? (??? JSESSIONID=jp6q31lq2myn)??????????????????????????????? ??? HTTP ?????????????????????????

GET /somePage HTTP/1.1
Host: yourwebsite.com
User-Agent: Mozilla/5.0
Cookie: JSESSIONID=Any value of the user's choice!!??'''">

?????JSESSIONID ?????????????? ID ?????????????????????????????????????????????????????????????????? ????????? ID ??????????????????????????????????????????? ID ?????????ID ????????????????????????????????????????????????????


????
OWASP: Session Management Cheat Sheet
CWE-20: Improper Input Validation

?????????GET ????????????????????????????????????????????

URL ?????? /app/servlet.htm?a=1&b=2 ?????????????????? a=1&b=2 ??????

HttpServletRequest.getParameter() ????????????????????????????????? HttpServletRequest.getQueryString() ?????????????????????? ??????? API ????????????????????????????????????????????????


????
CWE-20: Improper Input Validation

???????????????????????????????????????????? ????????????????????????????????????????????????????? ??????????????????????????????????????????????????????


????
CWE-807: Untrusted Inputs in a Security Decision

??:

  • ?????????????????????????????????????????????????
  • ???????? (https) ????????????????????"Referer" ????????

????:

  • ???????????????????????????????????
  • CSRF ??????????????????????????(?????????????)


????
CWE-807: Untrusted Inputs in a Security Decision

???? "User-Agent" ?????????????????????????????????????????? (????? UA ????) ?????????????????????


????
CWE-807: Untrusted Inputs in a Security Decision

???????????????????????????????????????????????????????????????????????????????????????????????????????? HttpSession (HttpServletRequest.getSession()) ??????????

????????????????????????????????????????????????????????


????
CWE-315: Cleartext Storage of Sensitive Information in a Cookie

????????????????????????????????????????????????? ???????????????????????? API ??????????????????????????????????????????

?????????????????????????????????????????????????????????????????????????????????????????


????
WASC: Path Traversal
OWASP: Path Traversal
CAPEC-126: Path Traversal
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

????????????????????????????????????????????????? ???????????????????????? API ??????????????????????????????????????????

?????????????????????????????????????????????????????????????????????????????????????????


????
WASC-33: Path Traversal
OWASP: Path Traversal
CAPEC-126: Path Traversal
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

??????? API ????????????????????????????????????????????? API ???????????????????????????????


????
OWASP: Command Injection
OWASP: Top 10 2013-A1-Injection
CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')

????? FilenameUtils ?????? NULL ??? (0x00) ???????????

Null ??????????????????????? OS ?????????????????? Null ????????????????????????? OS ???????????? Java ??? Null ????????????????????????????? Null ???????????? ?? OS ??????????????????????? (??????? ".log" ????) ??????????????????????????????????????????????????????

??????????2 ?????????????:

Null ???????????????????????????? Java ????????????????????????????????????


????
WASC-28: Null Byte Injection
CWE-158: Improper Neutralization of Null Byte or NUL Character

?? TrustManager ????????????????????????????????????????????????? ??????????????????????????????????????????????

(????truststore ?????) ??????????? TrustManager ????????????? ??????????????????: [1] [2]


????
WASC-04: Insufficient Transport Layer Protection
CWE-295: Improper Certificate Validation

????????SOAP Web ???? (JSR224) ??????

?? Web ????????????????????????:

  • ?????????????????????????
  • ?????????????????????????????
  • ????????????????????????
  • ???????? SSL ???????????????


????
OWASP: Web Service Security Cheat Sheet
CWE-20: Improper Input Validation

??????? REST Web ???? (JSR311) ??????

?? Web ????????????????????????:

  • ?????????????????????????
  • ?????????????????????????????
  • ????????????????????????
  • ???????? SSL ???????????????
  • ?????????????????? (??? POST ????) ???CSRF ???????????????????? [1]


????
OWASP: REST Assessment Cheat Sheet
OWASP: REST Security Cheat Sheet
OWASP: Web Service Security Cheat Sheet
1. OWASP: Cross-Site Request Forgery
OWASP: CSRF Prevention Cheat Sheet
CWE-20: Improper Input Validation

Tapestry ?????????????????????????????Tapestry ??????????????? Java ???????? Tapestry ??????????? (.tml ????) ?????????? ?????????????GET/POST ???????????? Java ????????????????????? ?????????????????
???????:


    [...]
    protected String input;
    [...]

???????????????????:


    [...]
    @org.apache.tapestry5.annotations.Parameter
    protected String parameter1;

    @org.apache.tapestry5.annotations.Component(id = "password")
    private PasswordField passwordField;
    [...]

???????? [/resources/package/PageName].tml ???????????

???????????? Tapestry ??????????????????????????????????????????????????????????????????????


????
Apache Tapestry Home Page
CWE-20: Improper Input Validation

???????Wicket ? WebPage ?????? ???????????????? PageParameters ???????????????????? ???????? ??? [/package/WebPageName].html ???????????

???????????? Wicket ??????????????????????????????????????????????????????????????????????


????
Apache Wicket Home Page

?????????????????????????????????????

NIST ??SHA-1? SHA-224*? SHA-256? SHA-384? SHA-512? SHA-512/224? ??? SHA-512/256 ????????????

* SHA-224 ??????? SUN ?????????????????

????????????????????????????????????????????????????????????????????????????????


????
NIST Approved Hashing Algorithms
CWE-327: Use of a Broken or Risky Cryptographic Algorithm

????????????????????????????????????

NIST ??SHA-1? SHA-224*? SHA-256? SHA-384? SHA-512? SHA-512/224? ??? SHA-512/256 ????????????

* SHA-224 ??????? SUN ?????????????????

??????:

MyProprietaryMessageDigest extends MessageDigest {
    @Override
    protected byte[] engineDigest() {
        [...]
        // ???????????????
        return [...];
    }
}

????????????????????????????????????????????????????????????????????????????????

???:

MessageDigest sha256Digest = MessageDigest.getInstance("SHA256");
sha256Digest.update(password.getBytes());


????
NIST Approved Hashing Algorithms
CWE-327: Use of a Broken or Risky Cryptographic Algorithm

?????????? API ????????????????????????????????????????????????????????????

???:

  • "../../../config/overide_file"
  • "shell.jsp\u0000expected.gif"

????????????????????? API ??????????????? ?????????????????????????????????????? ????????????????????????????????? (????/ \)??????????????????????????????????????????????????????????????


????
Securiteam: File upload security recommendations
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
WASC-33: Path Traversal
OWASP: Path Traversal
CAPEC-126: Path Traversal
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')

???? (regexs) ???????????? (DoS) ?????????? (ReDoS ??????)? ???????????????????????????????????????????????????????????

???? ?????????: ^(a+)+$? ?? "aaaaaaaaaaaaaaaaX" ?????????? 665535 ??????????????????? [1] OWASP ?????????????

????????????????????????????????????????? ??????(???????????)????????????????? + (??? *) ????????? + (??? *) ???????????????????????????? 2 ?????????? ??????????? + ???? 'a' ???????? ??????????????????????????????????????? ????^a+$ ?????????????????????????????????????????? (a ?????????) ? ??????????????????????????????????ReDoS ??????????


????
Sebastian Kubeck's Weblog: Detecting and Preventing ReDoS Vulnerabilities
[1] OWASP: Regular expression Denial of Service
CWE-400: Uncontrolled Resource Consumption ('Resource Exhaustion')

??

???????????????? XML ??????XML ????? XML ?????????????????XML ???????? (XXE) ????????????????

??? 1: ?????????????? (XXE: XML eXternal Entity)

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
   <!ENTITY xxe SYSTEM "file:///etc/passwd" > ]>
<foo>&xxe;</foo>

??? 2: ?????? (XEE: Xml Entity Expansion)

<?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ELEMENT lolz (#PCDATA)>
 <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
[...]
 <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<lolz>&lol9;</lolz>

???

XML??????????????????????????????????????????

??????:

SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

parser.parse(inputStream, customHandler);

"Secure processing" ???????????:

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
SAXParser parser = spf.newSAXParser();

parser.parse(inputStream, customHandler);

DTD ?????????:

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser parser = spf.newSAXParser();

parser.parse(inputStream, customHandler);


????
CWE-611: Improper Restriction of XML External Entity Reference ('XXE')
CERT: IDS10-J. Prevent XML external entity attacks
OWASP.org: XML External Entity (XXE) Processing
WS-Attacks.org: XML Entity Expansion
WS-Attacks.org: XML External Entity DOS
WS-Attacks.org: XML Entity Reference Attack
Xerces complete features list

??

???????????????? XML ??????XML ????? XML ?????????????????XML ???????? (XXE) ????????????????

??? 1: ?????????????? (XXE: XML eXternal Entity)

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
   <!ENTITY xxe SYSTEM "file:///etc/passwd" > ]>
<foo>&xxe;</foo>

??? 2: ?????? (XEE: Xml Entity Expansion)

<?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ELEMENT lolz (#PCDATA)>
 <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
[...]
 <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<lolz>&lol9;</lolz>

???

XML??????????????????????????????????????????

??????:

XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(customHandler);
reader.parse(new InputSource(inputStream));

"Secure processing" ???????????:

XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
reader.setContentHandler(customHandler);

reader.parse(new InputSource(inputStream));

DTD ?????????:

XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setContentHandler(customHandler);

reader.parse(new InputSource(inputStream));


????
CWE-611: Improper Restriction of XML External Entity Reference ('XXE')
CERT: IDS10-J. Prevent XML external entity attacks
OWASP.org: XML External Entity (XXE) Processing
WS-Attacks.org: XML Entity Expansion
WS-Attacks.org: XML External Entity DOS
WS-Attacks.org: XML Entity Reference Attack
Xerces complete features list

??

???????????????? XML ??????XML ????? XML ?????????????????XML ???????? (XXE) ????????????????

??? 1: ?????????????? (XXE: XML eXternal Entity)

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
   <!ENTITY xxe SYSTEM "file:///etc/passwd" > ]>
<foo>&xxe;</foo>

??? 2: ?????? (XEE: Xml Entity Expansion)

<?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ELEMENT lolz (#PCDATA)>
 <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
[...]
 <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;">
]>
<lolz>&lol9;</lolz>

???

XML??????????????????????????????????????????

??????:

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();

Document doc = db.parse(input);

"Secure processing" ???????????:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse(input);

DTD ?????????:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc = db.parse(input);


????
CWE-611: Improper Restriction of XML External Entity Reference ('XXE')
CERT: IDS10-J. Prevent XML external entity attacks
OWASP.org: XML External Entity (XXE) Processing
WS-Attacks.org: XML Entity Expansion
WS-Attacks.org: XML External Entity DOS
WS-Attacks.org: XML Entity Reference Attack
Xerces2 complete features list

XPath ??????????????SQL ???????????????XPath ????????????????????????????????????????????????? ???????????????????????????????XML?????????????????????


????
WASC-39: XPath Injection
OWASP: Top 10 2013-A1-Injection
CWE-643: Improper Neutralization of Data within XPath Expressions ('XPath Injection')
CERT: IDS09-J. Prevent XPath Injection (archive)
Black Hat Europe 2012: Hacking XPath 2.0
Balisage: XQuery Injection

?????? Struts 1 ????????

???????????????????????????Form ??????? HTTP ?????????????????????????? ???????????????????????????????????????????????????

Struts 2 ??????????????????? Java ?????? (POJO) ???????????????/??????/?????????????????

??????????????? (????????) ????????????????? HTTP ?????????????????????????????? ???????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????????

???????Spring ??????????RequestMapping ?????????????????????????????? ????????????????????????????????????????????????????????????

????????????????????????????????????????????????????????

???????????:

SqlUtil.execQuery("select * from UserEntity t where id = " + parameterInput);


?????????????????:
????????????????????????

??????????????????:

<<??????>>|<<????>>|<<????>>|<<????????????>>=<<????????????????????????>>|<<?????????>>
???:
INVOKEVIRTUAL|testcode/sqli/MySqlWrapper|executeQuery|(Ljava/lang/String;)Ljava/sql/ResultSet;=0|CUSTOM_INJECTION
[...]

??????????????????????????????
-Dfindsecbugs.injection.sources=${basedir}/rules/InjectionSources.properties


????
WASC-19: SQL Injection
OWASP: Top 10 2013-A1-Injection
OWASP: SQL Injection Prevention Cheat Sheet
OWASP: Query Parameterization Cheat Sheet
CAPEC-66: SQL Injection
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')

SQL ???????????????????????????? ??????????????????????SQL ??????????????????????????????????? ??????????????????? Hibernate Criteria ????????

??????:

Session session = sessionFactory.openSession();
Query q = session.createQuery("select t from UserEntity t where id = " + input);
q.execute();

???:

Session session = sessionFactory.openSession();
Query q = session.createQuery("select t from UserEntity t where id = :userId");
q.setString("userId",input);
q.execute();

?????????? (Hibernate Criteria ????):

Session session = sessionFactory.openSession();
Query q = session.createCriteria(UserEntity.class)
    .add( Restrictions.like("id", input) )
    .list();
q.execute();


???? (Hibernate)
Hibernate Documentation: Query Criteria
Hibernate Javadoc: Query Object
HQL for pentesters: ????????????????????????????
???? (SQL ????????)
WASC-19: SQL Injection
CAPEC-66: SQL Injection
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
OWASP: Top 10 2013-A1-Injection
OWASP: SQL Injection Prevention Cheat Sheet
OWASP: Query Parameterization Cheat Sheet

SQL ???????????????????????????? ??????????????????????SQL ???????????????????????????????????

??????:

PersistenceManager pm = getPM();

Query q = pm.newQuery("select * from Users where name = " + input);
q.execute();

???:

PersistenceManager pm = getPM();

Query q = pm.newQuery("select * from Users where name = nameParam");
q.declareParameters("String nameParam");
q.execute(input);


???? (JDO)
JDO: Object Retrieval
???? (SQL ????????)
WASC-19: SQL Injection
CAPEC-66: SQL Injection
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
OWASP: Top 10 2013-A1-Injection
OWASP: SQL Injection Prevention Cheat Sheet
OWASP: Query Parameterization Cheat Sheet

SQL ???????????????????????????? ??????????????????????SQL ???????????????????????????????????

??????:

EntityManager pm = getEM();

TypedQuery q = em.createQuery(
    String.format("select * from Users where name = %s", username),
    UserEntity.class);

UserEntity res = q.getSingleResult();

???:

TypedQuery q = em.createQuery(
    "select * from Users where name = usernameParam",UserEntity.class)
    .setParameter("usernameParam", username);

UserEntity res = q.getSingleResult();


???? (JPA)
The Java EE 6 Tutorial: Creating Queries Using the Java Persistence Query Language
???? (SQL ????????)
WASC-19: SQL Injection
CAPEC-66: SQL Injection
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
OWASP: Top 10 2013-A1-Injection
OWASP: SQL Injection Prevention Cheat Sheet
OWASP: Query Parameterization Cheat Sheet

SQL ???????????????????????????? ??????????????????????SQL ???????????????????????????????????

??????:

JdbcTemplate jdbc = new JdbcTemplate();
int count = jdbc.queryForObject("select count(*) from Users where name = '"+paramName+"'", Integer.class);

???:

JdbcTemplate jdbc = new JdbcTemplate();
int count = jdbc.queryForObject("select count(*) from Users where name = ?", Integer.class, paramName);


???? (Spring JDBC)
Spring Official Documentation: Data access with JDBC
???? (SQL ????????)
WASC-19: SQL Injection
CAPEC-66: SQL Injection
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
OWASP: Top 10 2013-A1-Injection
OWASP: SQL Injection Prevention Cheat Sheet
OWASP: Query Parameterization Cheat Sheet

SQL ???????????????????????????? ??????????????????????SQL ???????????????????????????????????

??????:

Connection conn = [...];
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("update COFFEES set SALES = "+nbSales+" where COF_NAME = '"+coffeeName+"'");

???:

Connection conn = [...];
conn.prepareStatement("update COFFEES set SALES = ? where COF_NAME = ?");
updateSales.setInt(1, nbSales);
updateSales.setString(2, coffeeName);


???? (JDBC)
Oracle Documentation: The Java Tutorials > Prepared Statements
???? (SQL ????????)
WASC-19: SQL Injection
CAPEC-66: SQL Injection
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
OWASP: Top 10 2013-A1-Injection
OWASP: SQL Injection Prevention Cheat Sheet
OWASP: Query Parameterization Cheat Sheet

SQL ?????LDAP ?????????????????????????????? ??????LDAP ???SQL ??????????????????????????????? ?????LDAP ???????????????????LDAP ????????????????????????????????????

?????????:

NamingEnumeration answers = context.search("dc=People,dc=example,dc=com",
        "(uid=" + username + ")", ctrls);


????
WASC-29: LDAP Injection
OWASP: Top 10 2013-A1-Injection
CWE-90: Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection')
LDAP Injection Guide: Learn How to Detect LDAP Injections and Improve LDAP Security

??????????????????????????????????? ???????????????????????????????????????????????????

??????????????????????????????????????? (???????)?

?????????:

public void runCustomTrigger(String script) {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");

    engine.eval(script); //??????????????
}

???:

"Cloudbees Rhino Sandbox" ?????????????JavaScript ???????????????

public void runCustomTrigger(String script) {
    SandboxContextFactory contextFactory = new SandboxContextFactory();
    Context context = contextFactory.makeContext();
    contextFactory.enterContext(context);
    try {
        ScriptableObject prototype = context.initStandardObjects();
        prototype.setParentScope(null);
        Scriptable scope = context.newObject(prototype);
        scope.setPrototype(prototype);

        context.evaluateString(scope,script, null, -1, null);
    } finally {
        context.exit();
    }
}


????
Cloudbees Rhino Sandbox: Rhino ??????????????????????? (??????????????????)
CodeUtopia.net: Sandboxing Rhino in Java
Remote Code Execution .. by design: ??????????????????????????????????????????????????????
CWE-94: Improper Control of Generation of Code ('Code Injection')
CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')

Spring ????????????????? ????????????????????????????????????????????????????????

?????????:

public void parseExpressionInterface(Person personObj,String property) {

        ExpressionParser parser = new SpelExpressionParser();

        //???????????????????..
        Expression exp = parser.parseExpression(property+" == 'Albert'");

        StandardEvaluationContext testContext = new StandardEvaluationContext(personObj);
        boolean result = exp.getValue(testContext, Boolean.class);
[...]


????
CWE-95: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection')
CWE-94: Improper Control of Generation of Code ('Code Injection')
Spring Expression Language (SpEL) - Official Documentation
Minded Security: Expression Language Injection
Remote Code Execution .. by design: ??????????????????????????????????????????????????????

???????????????????????????????????????????????????????????????????? ?????????????????????????????????????? Integer.toHexString() ?????????

MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] resultBytes = md.digest(password.getBytes("UTF-8"));

StringBuilder stringBuilder = new StringBuilder();
for(byte b :resultBytes) {
    stringBuilder.append( Integer.toHexString( b & 0xFF ) );
}

return stringBuilder.toString();

??????????????????????????????????? ??????????????????? "0x0679" ? "0x6709" ????? "679" ???????????

??????????????? toHexString() ???? String.format() ??????????:

stringBuilder.append( String.format( "%02X", b ) );


????
CWE-704: Incorrect Type Conversion or Cast

Hazelcast ??????????????? (???? DES ??? blowfish) ?????????????????

?????????????????????????????????????????????????


????
WASC-04: Insufficient Transport Layer Protection
Hazelcast Documentation: Encryption (see second part)
CWE-326: Inadequate Encryption Strength

NullCipher ????????????????????????????????????????????????????????? Cipher ???????????????? ??????????????????? NullCipher ????????????

??????:

Cipher doNothingCihper = new NullCipher();
[...]
//????????????????????
byte[] cipherText = c.doFinal(plainText);

???:
NullCipher ??????????????????????????????????????


????
CWE-327: Use of a Broken or Risky Cryptographic Algorithm

????????????????????????????????????????????????????????????????????????

??????:
???????? (????):

Socket soc = new Socket("www.google.com",80);

???:
SSL ???? (?????):

Socket soc = SSLSocketFactory.getDefault().createSocket("www.google.com", 443);

SSL ??????????????????? SSLSocketFactory ????????????????????????????????????????????????????????????? ????????????????OWASP Transport Layer Protection Cheat Sheet ?????????


????
OWASP: Top 10 2010-A9-Insufficient Transport Layer Protection
OWASP: Top 10 2013-A6-Sensitive Data Exposure
OWASP: Transport Layer Protection Cheat Sheet
WASC-04: Insufficient Transport Layer Protection
CWE-319: Cleartext Transmission of Sensitive Information

DES ??? DESede (3DES) ?????????????????????????????????? ???NIST ? DES/3DES ????? AES ??????????????????

????????:

Cipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);

?????:

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);


????
NIST Withdraws Outdated Data Encryption Standard
CWE-326: Inadequate Encryption Strength

??????????RSA ????????????????????????????? (OAEP) ????????????????????????????

??????:

Cipher.getInstance("RSA/NONE/NoPadding")

???:
????????????????:

Cipher.getInstance("RSA/ECB/OAEPWithMD5AndMGF1Padding")


????
CWE-780: Use of RSA Algorithm without OAEP
Root Labs: Why RSA encryption padding is critical

???????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????? (??????????????????????????????????)

??????:

private String SECRET_PASSWORD = "letMeIn!";

Properties props = new Properties();
props.put(Context.SECURITY_CREDENTIALS, "p@ssw0rd");


????
CWE-259: Use of Hard-coded Password

??????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????? (??????????????????????????????????????????)

??????:

byte[] key = {1, 2, 3, 4, 5, 6, 7, 8};
SecretKeySpec spec = new SecretKeySpec(key, "AES");
Cipher aes = Cipher.getInstance("AES");
aes.init(Cipher.ENCRYPT_MODE, spec);
return aesCipher.doFinal(secretData);


????
CWE-321: Use of Hard-coded Cryptographic Key

????????????????????????????????????????????????????

???? validate ???????????????????

public class RegistrationForm extends ValidatorForm {

    private String name;
    private String email;

    [...]

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        //HttpRequest ??????????????????????????????????
    }
}


????
CWE-20: Improper Input Validation
CWE-106: Struts: Plug-in Framework not in Use

XSSRequestWrapper ????? HttpServletRequestWrapper ????????????????????????? [1] [2]

??????????????????????????:

  • ???????????????????????????????????????????
  • ?????????????? (???????)
  • ???????????????????? (????????/????????????????)

????:

<scrivbscript:pt>alert(1)</scrivbscript:pt>

?????? "<script>alert(1)</script>" ???????? "vbscript:" ?????"<script>.*</script>" ????????????

???????????OWASP XSS Prevention Cheat Sheet ?????? XSS ??????????????? (???????jsp?...) ?????????????????????????????


????
WASC-8: Cross Site Scripting
OWASP: XSS Prevention Cheat Sheet
OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)
CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

Blowfish ????32 ????? 448 ??????????????????????????????????????????????????? Blowfish ????????????????????????? 128 ???????????????????????

????????????????AES ??????????????????????

??????:

KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
keyGen.init(64);

???:

KeyGenerator keyGen = KeyGenerator.getInstance("Blowfish");
keyGen.init(128);


????
Blowfish (cipher)
CWE-326: Inadequate Encryption Strength

RSA ???????????????? 1024 ?????????????????????????????????? 2048 ??????????????? [1]

??????:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);

???:
KeyPairGenerator ??????????????? 2048 ??????????????

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);


????
[1] RSA Laboratories: 3.1.5 How large a key should be used in the RSA cryptosystem?
Wikipedia: Asymmetric algorithm key lengths
CWE-326: Inadequate Encryption Strength
Keylength.com (BlueKrypt): Aggregate key length recommendations.

?????????????????????????????????????? URL ?????????????????????????????????? ???????????????????????????????????????

????
1. ?????????????? URL ????: http://website.com/login?redirect=http://evil.vvebsite.com/fake/login
2. ????????? Web ?????????????????????????????? (http://evil.vvebsite.com/fake/login)
3. ???????????????
4. ???????????????????????????? Web ?????????????

???????????????????????? URL ???????????????????? ??????????????????????????

??????:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    [...]
    resp.sendRedirect(req.getParameter("redirectUrl"));
    [...]
}

???/??:

  • ????????????????????
  • ???????????????????? (???) ????????????
  • ????????????
  • URL ???????? (??????)
  • URL ???????????????????????


????
WASC-38: URL Redirector Abuse
OWASP: Top 10 2013-A10: Unvalidated Redirects and Forwards
OWASP: Unvalidated Redirects and Forwards Cheat Sheet
CWE-601: URL Redirection to Untrusted Site ('Open Redirect')

???? XSS ????????????????????????????? JavaScript ?????????????????????? (?????????????)

??????:

<%
String taintedInput = (String) request.getAttribute("input");
%>
[...]
<%= taintedInput %>

???:

<%
String taintedInput = (String) request.getAttribute("input");
%>
[...]
<%= Encode.forHtml(taintedInput) %>
    

XSS ???????????????????????????????????????? ????? 4 ??????????????: HTML?JavaScript?CSS (????)???? URL? ?????????????????? OWASP XSS Prevention Cheat Sheet ?????? XSS ??????????????


????
WASC-8: Cross Site Scripting
OWASP: XSS Prevention Cheat Sheet
OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)
CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
OWASP Java Encoder

???? XSS ????????????????????????????? JavaScript ?????????????????????? (?????????????)

??????:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String input1 = req.getParameter("input1");
    [...]
    resp.getWriter().write(input1);
}

???:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String input1 = req.getParameter("input1");
    [...]
    resp.getWriter().write(Encode.forHtml(input1));
}

XSS ???????????????????????????????????????? ????? 4 ??????????????: HTML?JavaScript?CSS (????)???? URL? ?????????????????? OWASP XSS Prevention Cheat Sheet ?????? XSS ??????????????

?????????? XSS ????????????????FindBugs ???????XSS: ????????????????????????????????XSS: ???????????????????????????????????????????????????????????????


????
WASC-8: Cross Site Scripting
OWASP: XSS Prevention Cheat Sheet
OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)
CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
OWASP Java Encoder

XMLDecoder ???????????????????????????????? ??????????????????????????????????????? XMLDecoder ???????????????????????????????? ???????????????????????????????????????????????????

????? XML ??:

<?xml version="1.0" encoding="UTF-8" ?>
<java version="1.4.0" class="java.beans.XMLDecoder">
  <object class="java.io.PrintWriter">
    <string>/tmp/Hacked.txt</string>
    <void method="println">
      <string>Hello World!</string>
    </void>
    <void method="close"/>
  </object>
</java>

??? XML ????????"Hello World!" ??????????????????????

??????:

XMLDecoder d = new XMLDecoder(in);
try {
    Object result = d.readObject();
}
[...]

???:
?????????????????????????? XMLDecoder ????????????????


????
Dinis Cruz Blog: Using XMLDecoder to execute server-side Java Code on an Restlet application
RedHat blog : Java deserialization flaws: Part 2, XML deserialization
CWE-20: Improper Input Validation

???????????????????????????????????

??????:

private static byte[] IV = new byte[16] {(byte)0,(byte)1,(byte)2,[...]};

public void encrypt(String message) throws Exception {

    IvParameterSpec ivSpec = new IvParameterSpec(IV);
[...]

???:

public void encrypt(String message) throws Exception {

    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);

    IvParameterSpec ivSpec = new IvParameterSpec(iv);
[...]


????
Wikipedia: Initialization vector
CWE-329: Not Using a Random IV with CBC Mode
Encryption - CBC Mode IV: Secret or Not?

???????????????????????????????????? Electronic Codebook (ECB) ????????????????? ?????ECB ??????????????????????? ????????????????????????????????????????????????? ??????????????????

??????????Galois/Counter Mode (GCM) ????????????????????

?????????:

Cipher c = Cipher.getInstance("AES/ECB/NoPadding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);

???:

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);


????
Wikipedia: Authenticated encryption
NIST: Authenticated Encryption Modes
Wikipedia: Block cipher modes of operation
NIST: Recommendation for Block Cipher Modes of Operation

???????? (PKCS5Padding ???? CBC) ?????????????????????? ???????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????

?????????:

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);

???:

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);


????
Padding Oracles for the masses (by Matias Soler)
Wikipedia: Authenticated encryption
NIST: Authenticated Encryption Modes
CAPEC: Padding Oracle Crypto Attack
CWE-696: Incorrect Behavior Order

??????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????

????????????????????????????????? (HMAC) ??????????????? ?????? HMAC ??????????????????????? [1]? ????????? HMAC ?????????????????????????????????????????????????????????????

?????????:
CBC ???? AES

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);

ECB ???????? DES
Cipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);

???:

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, k, iv);
byte[] cipherText = c.doFinal(plainText);

???????????GCM ?????????????????????????????? HMAC ???????


????
Wikipedia: Authenticated encryption
NIST: Authenticated Encryption Modes
Moxie Marlinspike's blog: The Cryptographic Doom Principle
CWE-353: Missing Support for Integrity Check

ESAPI ????????????????????????????????? ?????????????????????????????????????????????

1. ????????????

??????ESAPI ?????? 2.1.0 ??????????????? 2.0.1 ????MAC ???????????? (CVE-2013-5679)?

Maven ????????????? versions ???????????????????????? ESAPI ???????????????????????

$ mvn versions:display-dependency-updates

??:
[...]
[INFO] The following dependencies in Dependencies have newer versions:
[INFO]   org.slf4j:slf4j-api ................................... 1.6.4 -> 1.7.7
[INFO]   org.owasp.esapi:esapi ................................. 2.0.1 -> 2.1.0
[...]
    

?????????????????

<dependency>
    <groupId>org.owasp.esapi</groupId>
    <artifactId>esapi</artifactId>
    <version>2.1.0</version>
</dependency>

Ant ????????????? jar ? esapi-2.1.0.jar ???????????

2. ??:

?????????????? 2.1.0 ??????????????????????????? (CVE-2013-5960)?????????????????????

???????????????????ESAPI ????????????????????:
???????:
Encryptor.CipherText.useMAC=false

Encryptor.EncryptionAlgorithm=AES
Encryptor.CipherTransformation=AES/CBC/PKCS5Padding

Encryptor.cipher_modes.additional_allowed=CBC

?????:
#???????????
Encryptor.CipherText.useMAC=true

#???????????????????????
Encryptor.EncryptionAlgorithm=AES
Encryptor.CipherTransformation=AES/GCM/NoPadding

#???????????????? CBC ???????????????
Encryptor.cipher_modes.additional_allowed=


????
ESAPI Security bulletin 1 (CVE-2013-5679)
Vulnerability Summary for CVE-2013-5679
Synactiv: Bypassing HMAC validation in OWASP ESAPI symmetric encryption
CWE-310: Cryptographic Issues
ESAPI-dev mailing list: Status of CVE-2013-5960

?????????????????? (SD ??????????????) ???????????????????????????????????????? ??? SD ????????????? READ_EXTERNAL_STORAGE ????????????????????????????? ??????????????????????????????????????????????

?????????:

file file = new File(getExternalFilesDir(TARGET_TYPE), filename);
fos = new FileOutputStream(file);
fos.write(confidentialData.getBytes());
fos.flush();

????????:

fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(string.getBytes());


????
Android Official Doc: Security Tips
CERT: DRD00-J: Do not store sensitive information on external storage [...]
Android Official Doc: Using the External Storage
OWASP Mobile Top 10 2014-M2: Insecure Data Storage
CWE-312: Cleartext Storage of Sensitive Information

??????????????????????????????????????????????? ??????????????????????????

?????????:

Intent i = new Intent();
i.setAction("com.insecure.action.UserConnected");
i.putExtra("username", user);
i.putExtra("email", email);
i.putExtra("session", newSessionId);

this.sendBroadcast(v1);


??? (????):

Intent i = new Intent();
i.setAction("com.secure.action.UserConnected");

sendBroadcast(v1);


?? (?????)[1] ??: StackOverflow:

<manifest ...>

    <!-- Permission declaration -->
    <permission android:name="my.app.PERMISSION" />

    <receiver
        android:name="my.app.BroadcastReceiver"
        android:permission="com.secure.PERMISSION"> <!-- Permission enforcement -->
        <intent-filter>
            <action android:name="com.secure.action.UserConnected" />
        </intent-filter>
    </receiver>

    ...
</manifest>

?? (?????)[1] ??: StackOverflow:

<manifest>
    <!-- We declare we own the permission to send broadcast to the above receiver -->
    <uses-permission android:name="my.app.PERMISSION" />
</manifest>


????
CERT: DRD03-J. Do not broadcast sensitive information using an implicit intent
Android Official Doc: BroadcastReceiver (Security)
Android Official Doc: Receiver configuration (see android:permission)
[1] StackOverflow: How to set permissions in broadcast sender and receiver in android
CWE-925: Improper Verification of Intent by Broadcast Receiver
CWE-927: Use of Implicit Intent for Sensitive Communication

?????????????????????????? MODE_WORLD_READABLE ????????? ??????????????????????????????????????????

?????????:

fos = openFileOutput(filename, MODE_WORLD_READABLE);
fos.write(userInfo.getBytes());


??? (MODE_PRIVATE ????):

fos = openFileOutput(filename, MODE_PRIVATE);

??? (???? SQLite ??????????):
???? SQLite ?????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????


????
CERT: DRD11-J. Ensure that sensitive data is kept secure
Android Official Doc: Security Tips
Android Official Doc: Context.MODE_PRIVATE
vogella.com: Android SQLite database and content provider - Tutorial
OWASP Mobile Top 10 2014-M2: Insecure Data Storage
CWE-312: Cleartext Storage of Sensitive Information

????????????????????????????????????

?????????:

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);
    }
});

???????:
??????????????????????????????

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
        callback.invoke(origin, true, false);

        //???????????
    }
});


????
CERT: DRD15-J. Consider privacy concerns when using Geolocation API
Wikipedia: W3C Geolocation API
W3C: Geolocation Specification

WebView ???? JavaScript ????????????? XSS ???????????????????? ??????? XSS ???? XSS ? DOM ??? XSS ??????????????????????????

WebView myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

?????????:
JavaScript ???????????????????????????????????? XSS ????????????????????????? DOM ??? XSS ????????????? XSS ????????????????

function updateDescription(newDescription) {
    $("#userDescription").html("

"+newDescription+"

"); }


????
Issue: Using setJavaScriptEnabled can introduce XSS vulnerabilities
Android Official Doc: WebView
WASC-8: Cross Site Scripting
OWASP: XSS Prevention Cheat Sheet
OWASP: Top 10 2013-A3: Cross-Site Scripting (XSS)
CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')

JavaScript ???????????? WebView ???? API ????????????? XSS ? WebView ???????????????????? JavaScript ??????????????????????

?????????:

WebView myWebView = (WebView) findViewById(R.id.webView);

myWebView.addJavascriptInterface(new FileWriteUtil(this), "fileWriteUtil");

WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

[...]
class FileWriteUtil {
    Context mContext;

    FileOpenUtil(Context c) {
        mContext = c;
    }

    public void writeToFile(String data, String filename, String tag) {
        [...]
    }
}
    


????
Android Official Doc: WebView.addJavascriptInterface()
CWE-749: Exposed Dangerous Method or Function