Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
class Login {
  public Connection getConnection() throws SQLException {
    DriverManager.registerDriver(new
            com.microsoft.sqlserver.jdbc.sqlserver.SQLServerDriver());
    String dbConnection = 
      PropertyManager.getProperty("db.connection");
    // can hold some value like
    // "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>"
    return DriverManager.getConnection(dbConnection);
  }

  String hashPassword(char[] password) {
    // create hash of password
  }

  public void doPrivilegedAction(String username, char[] password)
  throws SQLException {
    Connection connection = getConnection();
    if (connection == null) {
      // handle error
    }
    try {
      String pwd = hashPassword(password);

      String sqlString = "SELECT * FROM db_user WHERE username = '" 
                         + username +
                         "' AND password = '" + pwd + "'";
      Statement stmt = connection.createStatement();
      ResultSet rs = stmt.executeQuery(sqlString);

      if (!rs.next()) {
        throw new SecurityException(
          "User name or password incorrect"
        );
      }

      // Authenticated; proceed
    } finally {
      try {
        connection.close();
      } catch (SQLException x) {
        // forward to handler
      }
    }
  }
}

...

Code Block
bgColor#ccccff
  public void doPrivilegedAction(
    String username, char[] password
  ) throws SQLException {
    Connection connection = getConnection();
    if (connection == null) {
      // handleHandle error
    }
    try {
      String pwd = hashPassword(password);

      // Ensure that the length of user name is legitimate
      if ((username.length() > 8) {
        // Handle error
      }

      String sqlString = 
        "select * from db_user where username=? and password=?";
      PreparedStatement stmt = connection.prepareStatement(sqlString);
      stmt.setString(1, username);
      stmt.setString(2, pwd);
      ResultSet rs = stmt.executeQuery();
      if (!rs.next()) {
        throw new SecurityException("User name or password incorrect");
      }

      // Authenticated, proceed
    } finally {
      try {
        connection.close();
      } catch (SQLException x) {
        // forward to handler
      }
    }
  }

...

Code Block
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="item">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="description" type="xs:string"/>
      <xs:element name="price" type="xs:decimal"/>
      <xs:element name="quantity" type="xs:integer"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema>

The schema is available as the file schema.xsd. This compliant code example solution employs this schema to prevent XML injection from succeeding. The schema is avaialble as the file schema.xsd. It also relies on the CustomResolver class to prevent XXE attacks. This class, as well as XXE attacks, are described in the subsequent code examples.

...

This noncompliant code example attempts to parse the file evil.xml, reports report any errors, and exitsexit. However, a SAX or a DOM (Document Object Model) parser will attempt to access the URL specified by the SYSTEM attribute, which means it will attempt to read the contents of the local /dev/tty file. On POSIX systems, reading this file causes the program to block until input data is supplied to the machine's console. Consequently, an attacker can use this malicious XML file to cause the program to hang.

Code Block
bgColor#FFcccc
class XXE {
  private static void receiveXMLStream(InputStream inStream,
                                       DefaultHandler defaultHandler)
      throws ParserConfigurationException, SAXException, IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.parse(inStream, defaultHandler);
  }

  public static void main(String[] args)
      throws ParserConfigurationException, SAXException, IOException {
    receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler());
  }
}

Unfortunately, this This program is subject to a remote XXE attack if the evil.xml file contains the following:

...

This compliant solution defines a CustomResolver class that implements the interface org.xml.sax.EntityResolver. This enables a SAX application to implement customized customize handling of external entities. The setEntityResolver() method registers the instance with the corresponding SAX driver. The customized handler uses a simple whitelist for external entities. The resolveEntity() method returns an empty InputSource when an input fails to resolve to any of the specified, safe entity source paths. Consequently, when parsing malicious input, the empty InputSource returned by the custom resolver causes a java.net.MalformedURLException to be thrown. Note that you must create an XMLReader object on which to set the custom entity resolver.

...

CERT C Secure Coding Standard

STR02-C. Sanitize data passed to complex subsystems

CERT C++ Secure Coding Standard

STR02-CPP. Sanitize data passed to complex subsystems

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="56ebc46cee5cee0f-ad5d905b-43024429-a9bab607-9f826b4eb5f6609a2f68d4cb"><ac:plain-text-body><![CDATA[

[ISO/IEC TR 24772:2010

http://www.aitcnet.org/isai/]

Injection [RST]

]]></ac:plain-text-body></ac:structured-macro>

MITRE CWE

CWE-116. Improper Encoding or Escaping of Output

...

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="45b202d03d78fd90-cf8cebb7-4fdf4b97-a893b3fa-16c8d9dc451bedb98e151a2e"><ac:plain-text-body><![CDATA[

[[OWASP 2005

AA. Bibliography#OWASP 05]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="4750b05237d6e974-cbd9fc15-4fca45ef-b29aa27e-46f9eaa82ba52e81e171a309"><ac:plain-text-body><![CDATA[

[[OWASP 2007

AA. Bibliography#OWASP 07]]

 

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="882805709ff57f5a-bfe52096-43d14c63-8d9cb92c-94fd55fca36cfff06f0f018c"><ac:plain-text-body><![CDATA[

[[OWASP 2008

AA. Bibliography#OWASP 08]]

[Testing for XML Injection (OWASP-DV-008)

https://www.owasp.org/index.php/Testing_for_XML_Injection_%28OWASP-DV-008%29]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="3693fa5c1bbc66c0-495e881c-4e2140d5-91cda8e0-503bfa955555a3a7037cfcc4"><ac:plain-text-body><![CDATA[

[[W3C 2008

AA. Bibliography#W3C 08]]

4.4.3, Included If Validating

]]></ac:plain-text-body></ac:structured-macro>

...