Safe Coding Practices
by Gwyn Fisher

Example 1

(a)
void LoadTypeFromStream(unsigned char* stream, SOMETYPE* typtr)
{
  int len;
  // Get the size of our type's serialized form
  memcpy(&len, stream, sizeof(int));
  // De-serialize the type
  memcpy(typtr, stream + sizeof(int), len);
}

(b)

void foo(unsigned char* stream)
{
  SOMETYPE ty;
  LoadTypeFromStream(stream, &ty);
}

(c)
void LoadTypeFromStream(unsigned char* stream, SOMETYPE* typtr)
{
    int len;
    // Get the size of our type's serialized form
    memcpy(&len, stream, sizeof(int));
    // GUARD
    if( len < 0 || len > sizeof(SOMETYPE) )
        throw TaintedDataException();
    // De-serialize the type
    memcpy(typtr, stream + sizeof(int), len);
}


Example 2

public void validateUser(String user, String pwd, Connection db)
    throws InvalidUserException
{
    Statement stmt = null;
    ResultSet rs = null;
    try
    {
        // Create the statement
        stmt = db.createStatement();
        String sql = "select id from users where user='" + user +
                     "' and pwd='" + pwd + "'";
        // Execute it, process the result
        rs = stmt.executeQuery(sql);
        if( rs == null || rs.next() == null )
            throw new InvalidUserException(user);
    }
    catch( SQLException e )
    {
        throw new InvalidUserException(user);
    }
    finally
    {
      try { if( rs != null ) rs.close(); } catch( Exception e ) { }
      try { if( stmt != null ) stmt.close(); } catch( Exception e ) { }
    }
}


Example 3

public void validateUser(String user, String pwd, Connection db)
    throws InvalidUserException
{
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try
    {
        // Prepare the statement, rather than concatenating it
        String sql = "select id from users where user=? and pwd=?");
        stmt = db.prepareStatement(sql);

        // Substitute our incoming parameters into the query
        stmt.setString(1, user);
        stmt.setString(2, pwd);

        // Execute the query and process the results as before
        rs = stmt.executeQuery();
        if( rs == null || rs.next() == null )
            throw new InvalidUserException();
    }
    catch( SQLException e )
    {
        throw new InvalidUserException();
    }
    finally
    {
      try { if( rs != null ) rs.close(); } catch( Exception e ) { }
      try { if( stmt != null ) stmt.close(); } catch( Exception e ) { }
    }
}




2


