Secure Code Review
-Sunil
PART - I
Is Code Review Easy?
Asset
Definition: “an item of property owned by a
person or company, regarded as having
value and available to meet debts,
commitments, or legacies”
Tom & Jerry
Threat
Vulnerability
Security Engineers
A Suggestion!
Before starting Threat Modeling warn
development team that “ Do Not Hide
Sensitive information from Doctors, Lawyers
and SECURITY ENGINEERS”
But you can from GF/Wife
Where does code review fit?
• Get Security RequirementsRequirements
• Perform Threat ModelDesign
• Static code Analysis
• Manual Code Review
Coding
• Penetration TestingTesting
• Server Configuration Review
• Network Configuration Review
Deployment
Cost of Bug Fixing
Code Review in One Slide
Why Code Review?
• It is too expensive or time consuming but it is the
fastest way to find many security problems.
• Tools are more like spell-checkers or grammar-
checkers. While important, they don't understand the
context, and miss many important security issues.
• Use security code review to find a problem, and
penetration testing to prove that it is exploitable
WHY DOES CODE HAVE VULNERABILITIES?
• Not taught about secure practices in
school/college
• Increase in new technologies and
protocols at a shocking rate
• Businesses are not spending the
appropriate amount of time on security
• Copy & Paste
Push Backs for the Code Review
“We never get hacked (that I know of), we
don’t need security”
“We have a firewall that protects our
applications”
"We trust our employees not to attack our
applications"
"...we know, there are known knowns; there are things we
know we know. We also know there are known unknowns;
that is to say we know there are some things we do not
know. But there are also unknown unknowns -- the ones we
don't know we don't know."
- Donald Rumsfeld
Best Quote
Things to Keep in Mind
Code
Context
Audience
Importance
Priority
THREAT MODELING
Step -1
17
Threat Modeling
● Structured approach to Analyze the security of the application
● Allows to understand the entry points to the application and their
associated threats.
● Not an approach to review code.
● Threat Modeling will be done in design phase of SDLC.
● Threat modeling will ensure the security builtin from the very beginning
of the application development.
Different Ways to perform Threat Modeling
• Attack Centric
• Software Centric
• Asset Centric
• Worst Case Analysis
• Negation Analysis
• Defensive
• Offensive
• Threat Traceability Matrix
My Presentation in Slide Share
CODE REVIEW
21
Free static analysis tools
Commercial static analysis tools
Disadvantages of Static Code Analyzers
• Business Logic Flaws remain untouched
• Limited scope
• Custom validations
• Design flaws
• Application specific recommendations
Code Review Flow Chart
Code Submitted for
MCR
Has
context
of code
been
defined?
Perform Code
Review
Record Findings
and
Recommendatio
ns
Schedule a meeting
Policies Standards Guidelines
YES
NO
Submit the Final
Report
Manual Code Review
• Identification of Entry points(Will be done as part of Threat Model)
• Identification of the trust boundaries in the code. (same)
• Identification of data paths and storage classes(like DBs).(same)
• Identification of authorization components.(same)
• Identification of authentication components.(same)
• Review of input validation and encoding methods.
• Review of logging components.
• Review of Cryptography risks
• Identify Use cases for the application(Threat model)
Checklist Should Include Attacks on…
• Data/Input Validation
• Authentication
• Authorization
• Cookie/Session Management
• Error Handling/Information leakage
• Logging/Auditing
• Cryptography
• Secure Code Environment
Checklist Should Include Attacks on…
• Data/Input Validation(Some Vulnerabilities)
• Authentication
• Authorization
• Cookie/Session Management
• Error Handling/Information leakage
• Logging/Auditing
• Cryptography
• Secure Code Environment
Input Validation Vulnerabilities
These are the Input Validation vulnerabilities that I am going to cover
in this session:
• Command Injection
• Log Forging
• SQL Injection
Remaining vulnerabilities in next session.
Entry points to the Code
Browser input
Cookies
Property files
External processes
Data feeds
Service responses
Flat files
Command line parameters
Environment variables
BAD CODE
try
{
String clg=request.getparameter(“clgname”);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';");
tableNames="login information trans";
process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename);
message="BackUp done Successfully.....";
}
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.warn(“Failed while taking backup for”+clg);
}
Command Injection
try
{
String clg=request.getparameter(“clgname”);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';");
tableNames="login information trans";
process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename);
message="BackUp done Successfully.....";
}
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.warn(“Failed while taking backup for”+clg);
}
Command Injection
try
{
String clg=request.getparameter(“clgname”);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';");
tableNames="login information trans";
process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename.sql & rm –rf /);
message="BackUp done Successfully.....";
}
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.warn(“Failed while taking backup for”+clg);
}
Improper Error Handling & Log forging
try
{
String clg=request.getparameter(“clgname”);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';");
tableNames="login information trans";
process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename+".sql");
message="BackUp done Successfully.....";
}
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.warn(“Failed while taking backup for”+clg);
}
Log forging
If input for clg is “random college %0d%0a%0a INFO: Backup successful for Random college”
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.error(“Failed while taking backup for”+clg);
}
Output:
ERROR: Failed while taking backup for random college
INFO: Backup successful for Random college
INFORMATION LEAKAGE
Hard Coded Credentials
try
{
String clg=request.getparameter(“clgname”);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';");
tableNames="login information trans";
process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename+".sql");
message="BackUp done Successfully.....";
}
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.warn(“Failed while taking backup for”+clg);
}
Source Code Analyzer didn’t find the second one….
try
{
String clg=request.getparameter(“clgname”);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';");
tableNames="login information trans";
process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename+".sql");
message="BackUp done Successfully.....";
}
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.warn(“Failed while taking backup for”+clg);
}
Example 1
void handle_cc_info(HttpServletRequest request) {
cc_num=request.getParameter(“cc_num”);
cvv=request.getParameter(“cvv”);
if (!is_valid_cvv(cc_num,cvv) {
log.info(cvv+” is not a valid for cc number ”+cc_num));
throw new AuthroizationException();
}
log.info(cvv+” is valid for cc number ”+cc_num));
...
}
Example 1
void handle_cc_info(HttpServletRequest request) {
cc_num=request.getParameter(“cc_num”);
cvv=request.getParameter(“cvv”);
if (!is_valid_cvv(cc_num,cvv) {
log.info(cvv+” is not a valid for cc number ”+cc_num));
throw new AuthroizationException();
}
log.info(cvv+” is valid for cc number ”+cc_num));
...
}
Example 2
<form name="f1" action="usercheck.jsp" method=“GET">
<B>User Name: </B><input type="text" name="username"/>
<B>Password: </B><input type="password" name="password"/>
<input type="submit" value="Log in" onClick="display()"/>
</form>
Example 2
<form name="f1" action="usercheck.jsp" method=“GET">
<B>User Name: </B><input type="text" name="username"/>
<B>Password: </B><input type="password" name="password"/>
<input type="submit" value="Log in" onClick="display()"/>
</form>
What if I use HTTPS?
It will logged in application logs and intermediate proxy logs
SQL Injection
try
{
String clg=request.getparameter(“clgname”);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';");
tableNames="login information trans";
process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename);
message="BackUp done Successfully.....";
}
catch(Exception e)
{
out.println("Exception while taking backup“+e+”while taking back up for”+clg);
log.warn(“Failed while taking backup for”+clg);
}
SQL Injection
If input for clg is “random college’; DROP TABLE college;--”
The query becomes:
SELECT college FROM logins where clgname='random college’; DROP
TABLE college;--”
Preventions for SQL Injection
Stored Procedures
Hibernates
Input validation
Prepared Statements
Improper use of Prepared Statements
String sql = "SELECT bal,name From information WHERE accno =
“+request.getParameter("accno");
pstmt=con.prepareStatement(sql);
rs=pstmt.executeQuery();
String sql = "SELECT bal,name From information WHERE accno = ?";
pstmt=con.prepareStatement(sql);
pstmt.setString(1, request.getParameter("accno"));
rs=pstmt.executeQuery();
Stored Procedures- Oracle PL/SQL
PROCEDURE SafeGetBalanceQuery( UserID varchar, Dept
varchar)
AS BEGIN
SELECT balance FROM accounts_table WHERE user_ID = UserID
AND department = Dept;
END;
Stored Procedures- Oracle PL/SQL
PROCEDURE SafeGetBalanceQuery( UserID varchar, Dept
varchar)
AS BEGIN
SELECT balance FROM accounts_table WHERE user_ID = UserID
AND department = Dept;
END;
Stored Procedures- Oracle PL/SQL- FIX
PROCEDURE AnotherSafeGetBalanceQuery( UserID varchar, Dept varchar)
AS
stmt VARCHAR(400); result NUMBER;
BEGIN stmt := 'SELECT balance FROM accounts_table WHERE user_ID = :1
AND department = :2';
EXECUTE IMMEDIATE stmt INTO result USING UserID, Dept;
RETURN result;
END;
Stored Procedure – SQL Server
PROCEDURE SafeGetBalanceQuery( @UserID varchar(20), @Dept varchar(10))
AS BEGIN
SELECT balance FROM accounts_table WHERE user_ID = @UserID AND department = @Dept
END
Example code
PROCEDURE SafeGetBalanceQuery( @UserID varchar(20), @Dept varchar(10))
AS BEGIN
SELECT @sql=‘ SELECT balance FROM accounts_table WHERE user_ID = @UserID
AND department = @Dept ‘
EXEC(@sql)
END
What if Input has:
1' OR '1'='1';EXEC master.dbo.xp_cmdshell 'dir'--'
Result:
PROCEDURE SafeGetBalanceQuery( @UserID varchar(20), @Dept varchar(10))
AS BEGIN
SELECT @sql=‘ SELECT balance FROM accounts_table WHERE user_ID = @UserID
AND department = 1' OR '1'='1';
EXEC master.dbo.xp_cmdshell 'dir'--'
EXEC(@sql)
END
Stored Procedure – SQL Server- FIX
PROCEDURE SafeGetBalanceQuery(@UserID varchar(20), @Dept varchar(10))
AS BEGIN
DECLARE @sql VARCHAR(200)
SELECT @sql = 'SELECT balance FROM accounts_table WHERE ' + 'user_ID = @UID AND department = @DPT'
EXEC sp_executesql @sql, '@UID VARCHAR(20),
@DPT VARCHAR(10)', @UID=@UserID,
@DPT=@Dept
END
Hibernates
Java
Application
POJO ORM Database
Hibernates
String tname = (String) req.getParameter("table");
String employeename = request.getParameter("name");
Session session = sessionFactory.getCurrentSession();
try{
session.beginTransaction();
SQLQuery query = session.createSQLQuery("SELECT * FROM " + tname +
"WHERE stuff=”+ employeename);
session.getTransaction().commit();
}
catch (Exception e) {}
session.close();
Vulnerable code
String tname = (String) req.getParameter("table");
String employeename = request.getParameter("name");
Session session = sessionFactory.getCurrentSession();
try{
session.beginTransaction();
SQLQuery query = session.createSQLQuery("SELECT * FROM " + tname +
"WHERE stuff=”+ employeename); // no input validation for tname & employeename
session.getTransaction().commit();
}
catch (Exception e) {} //no rollback
session.close();
Fixed Code
String tname = (String) req.getParameter("table");
….do input validation for tablename here……….
String employeename = request.getParameter("name");
Session session = sessionFactory.getCurrentSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
SQLQuery query = session.createSQLQuery("SELECT * FROM " + tname + "WHERE stuff=?”);
query.setParameter(0, parameter1);
tx.commit();
}
catch (Exception e)
{
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
Common methods which are used creating SQL queries in
Hibernates are as follows :
• Session.createSQLQuery(String queryString)
• Session.createQuery(String queryString)
• Session.createFilter(Object collection, String queryString)
• Session.find(String queryString)
• Query.executeUpdate()
• Query.getQueryString()
Query.executeUpdate()
String hql = "UPDATE Student set grade =”+request.getparameter(grade)+"WHERE id =”
+request.getparamter(rollno);
Query query = session.createQuery(hql);
query.executeUpdate();
String hql = "UPDATE Employee set salary = :grade " + "WHERE id = :rollno";
Query query = session.createQuery(hql);
query.setParameter("salary", request.getparameter(grade));
query.setParameter("empid", request.getparamter(rollno));
query.executeUpdate();
session.beginTransaction();
Query q1 = session.createQuery(taintSQL); //pretend taintSQL came from unchecked input
sql = q1.getQueryString(); //get taint
SQLsession.getTransaction.commit();
session.beginTransaction();
Query q2 = new QueryImpl(sql, session, parameterMetadata); //reuse taint SQL w/o validation
session.getTransaction.commit(); //evil prevailssession.close();
OWASP Example for Query.getQueryString():
SQL Injections Checklist
• Check for input validation
• Check for parameterized prepared
statements
• Check for ORDERBY clause
• Check for GROUPBY clause
• Check for parameters that we cannot
parametrize
Conclusion
NEXT PART
Credits
https://www.owasp.org/images/2/2e/OWASP_Code_Review_Guide-V1_1.pdf
https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet
https://www.owasp.org/index.php/Hibernate-Guidelines
https://www.owasp.org/index.php/Hibernate
https://thenounproject.com/
http://arthurminduca.com/2014/03/07/quality-assurance-in-software-development-when-should-you-start-the-testing-process/
http://www.curbsideclassic.com
https://animationreview.files.wordpress.com/
https://theparalegalsociety.wordpress.com/2012/07/27/increase-your-productivity-the-desk-dragon-method/
https://pixabay.com/en/check-correct-mark-right-choice-40319/
http://gallery4share.com/w/wrong-symbol.html
Social Media
@anvsunil https://in.linkedin.com/in/anvsunil
THANK YOU

Null meet Code Review

  • 1.
  • 2.
  • 3.
    Asset Definition: “an itemof property owned by a person or company, regarded as having value and available to meet debts, commitments, or legacies”
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
    A Suggestion! Before startingThreat Modeling warn development team that “ Do Not Hide Sensitive information from Doctors, Lawyers and SECURITY ENGINEERS” But you can from GF/Wife
  • 9.
    Where does codereview fit? • Get Security RequirementsRequirements • Perform Threat ModelDesign • Static code Analysis • Manual Code Review Coding • Penetration TestingTesting • Server Configuration Review • Network Configuration Review Deployment
  • 10.
  • 11.
    Code Review inOne Slide
  • 12.
    Why Code Review? •It is too expensive or time consuming but it is the fastest way to find many security problems. • Tools are more like spell-checkers or grammar- checkers. While important, they don't understand the context, and miss many important security issues. • Use security code review to find a problem, and penetration testing to prove that it is exploitable
  • 13.
    WHY DOES CODEHAVE VULNERABILITIES? • Not taught about secure practices in school/college • Increase in new technologies and protocols at a shocking rate • Businesses are not spending the appropriate amount of time on security • Copy & Paste
  • 14.
    Push Backs forthe Code Review “We never get hacked (that I know of), we don’t need security” “We have a firewall that protects our applications” "We trust our employees not to attack our applications"
  • 15.
    "...we know, thereare known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns -- the ones we don't know we don't know." - Donald Rumsfeld Best Quote
  • 16.
    Things to Keepin Mind Code Context Audience Importance Priority
  • 17.
  • 18.
    Threat Modeling ● Structuredapproach to Analyze the security of the application ● Allows to understand the entry points to the application and their associated threats. ● Not an approach to review code. ● Threat Modeling will be done in design phase of SDLC. ● Threat modeling will ensure the security builtin from the very beginning of the application development.
  • 19.
    Different Ways toperform Threat Modeling • Attack Centric • Software Centric • Asset Centric • Worst Case Analysis • Negation Analysis • Defensive • Offensive • Threat Traceability Matrix
  • 20.
    My Presentation inSlide Share
  • 21.
  • 22.
  • 23.
  • 24.
    Disadvantages of StaticCode Analyzers • Business Logic Flaws remain untouched • Limited scope • Custom validations • Design flaws • Application specific recommendations
  • 25.
    Code Review FlowChart Code Submitted for MCR Has context of code been defined? Perform Code Review Record Findings and Recommendatio ns Schedule a meeting Policies Standards Guidelines YES NO Submit the Final Report
  • 26.
    Manual Code Review •Identification of Entry points(Will be done as part of Threat Model) • Identification of the trust boundaries in the code. (same) • Identification of data paths and storage classes(like DBs).(same) • Identification of authorization components.(same) • Identification of authentication components.(same) • Review of input validation and encoding methods. • Review of logging components. • Review of Cryptography risks • Identify Use cases for the application(Threat model)
  • 27.
    Checklist Should IncludeAttacks on… • Data/Input Validation • Authentication • Authorization • Cookie/Session Management • Error Handling/Information leakage • Logging/Auditing • Cryptography • Secure Code Environment
  • 28.
    Checklist Should IncludeAttacks on… • Data/Input Validation(Some Vulnerabilities) • Authentication • Authorization • Cookie/Session Management • Error Handling/Information leakage • Logging/Auditing • Cryptography • Secure Code Environment
  • 29.
    Input Validation Vulnerabilities Theseare the Input Validation vulnerabilities that I am going to cover in this session: • Command Injection • Log Forging • SQL Injection Remaining vulnerabilities in next session.
  • 30.
    Entry points tothe Code Browser input Cookies Property files External processes Data feeds Service responses Flat files Command line parameters Environment variables
  • 31.
    BAD CODE try { String clg=request.getparameter(“clgname”); Class.forName("com.mysql.jdbc.Driver"); Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';"); tableNames="login information trans"; process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename); message="BackUp done Successfully....."; } catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.warn(“Failed while taking backup for”+clg); }
  • 33.
    Command Injection try { String clg=request.getparameter(“clgname”); Class.forName("com.mysql.jdbc.Driver"); Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';"); tableNames="login information trans"; process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename); message="BackUp done Successfully....."; } catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.warn(“Failed while taking backup for”+clg); }
  • 34.
    Command Injection try { String clg=request.getparameter(“clgname”); Class.forName("com.mysql.jdbc.Driver"); Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';"); tableNames="login information trans"; process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename.sql & rm –rf /); message="BackUp done Successfully....."; } catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.warn(“Failed while taking backup for”+clg); }
  • 35.
    Improper Error Handling& Log forging try { String clg=request.getparameter(“clgname”); Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';"); tableNames="login information trans"; process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename+".sql"); message="BackUp done Successfully....."; } catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.warn(“Failed while taking backup for”+clg); }
  • 36.
    Log forging If inputfor clg is “random college %0d%0a%0a INFO: Backup successful for Random college” catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.error(“Failed while taking backup for”+clg); } Output: ERROR: Failed while taking backup for random college INFO: Backup successful for Random college
  • 37.
  • 38.
    Hard Coded Credentials try { Stringclg=request.getparameter(“clgname”); Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';"); tableNames="login information trans"; process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename+".sql"); message="BackUp done Successfully....."; } catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.warn(“Failed while taking backup for”+clg); }
  • 39.
    Source Code Analyzerdidn’t find the second one…. try { String clg=request.getparameter(“clgname”); Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';"); tableNames="login information trans"; process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename+".sql"); message="BackUp done Successfully....."; } catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.warn(“Failed while taking backup for”+clg); }
  • 40.
    Example 1 void handle_cc_info(HttpServletRequestrequest) { cc_num=request.getParameter(“cc_num”); cvv=request.getParameter(“cvv”); if (!is_valid_cvv(cc_num,cvv) { log.info(cvv+” is not a valid for cc number ”+cc_num)); throw new AuthroizationException(); } log.info(cvv+” is valid for cc number ”+cc_num)); ... }
  • 41.
    Example 1 void handle_cc_info(HttpServletRequestrequest) { cc_num=request.getParameter(“cc_num”); cvv=request.getParameter(“cvv”); if (!is_valid_cvv(cc_num,cvv) { log.info(cvv+” is not a valid for cc number ”+cc_num)); throw new AuthroizationException(); } log.info(cvv+” is valid for cc number ”+cc_num)); ... }
  • 42.
    Example 2 <form name="f1"action="usercheck.jsp" method=“GET"> <B>User Name: </B><input type="text" name="username"/> <B>Password: </B><input type="password" name="password"/> <input type="submit" value="Log in" onClick="display()"/> </form>
  • 43.
    Example 2 <form name="f1"action="usercheck.jsp" method=“GET"> <B>User Name: </B><input type="text" name="username"/> <B>Password: </B><input type="password" name="password"/> <input type="submit" value="Log in" onClick="display()"/> </form> What if I use HTTPS? It will logged in application logs and intermediate proxy logs
  • 44.
    SQL Injection try { String clg=request.getparameter(“clgname”); Class.forName("com.mysql.jdbc.Driver"); Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","alamuri"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("SELECT tablename FROM logins where clgname='"+clg+"';"); tableNames="login information trans"; process = runtime.exec("cmd /c mysqldump -u root -h localhost --password=alamuri bank> C:backup"+filename); message="BackUp done Successfully....."; } catch(Exception e) { out.println("Exception while taking backup“+e+”while taking back up for”+clg); log.warn(“Failed while taking backup for”+clg); }
  • 45.
    SQL Injection If inputfor clg is “random college’; DROP TABLE college;--” The query becomes: SELECT college FROM logins where clgname='random college’; DROP TABLE college;--”
  • 46.
    Preventions for SQLInjection Stored Procedures Hibernates Input validation Prepared Statements
  • 47.
    Improper use ofPrepared Statements String sql = "SELECT bal,name From information WHERE accno = “+request.getParameter("accno"); pstmt=con.prepareStatement(sql); rs=pstmt.executeQuery(); String sql = "SELECT bal,name From information WHERE accno = ?"; pstmt=con.prepareStatement(sql); pstmt.setString(1, request.getParameter("accno")); rs=pstmt.executeQuery();
  • 48.
    Stored Procedures- OraclePL/SQL PROCEDURE SafeGetBalanceQuery( UserID varchar, Dept varchar) AS BEGIN SELECT balance FROM accounts_table WHERE user_ID = UserID AND department = Dept; END;
  • 49.
    Stored Procedures- OraclePL/SQL PROCEDURE SafeGetBalanceQuery( UserID varchar, Dept varchar) AS BEGIN SELECT balance FROM accounts_table WHERE user_ID = UserID AND department = Dept; END;
  • 50.
    Stored Procedures- OraclePL/SQL- FIX PROCEDURE AnotherSafeGetBalanceQuery( UserID varchar, Dept varchar) AS stmt VARCHAR(400); result NUMBER; BEGIN stmt := 'SELECT balance FROM accounts_table WHERE user_ID = :1 AND department = :2'; EXECUTE IMMEDIATE stmt INTO result USING UserID, Dept; RETURN result; END;
  • 51.
    Stored Procedure –SQL Server PROCEDURE SafeGetBalanceQuery( @UserID varchar(20), @Dept varchar(10)) AS BEGIN SELECT balance FROM accounts_table WHERE user_ID = @UserID AND department = @Dept END
  • 52.
    Example code PROCEDURE SafeGetBalanceQuery(@UserID varchar(20), @Dept varchar(10)) AS BEGIN SELECT @sql=‘ SELECT balance FROM accounts_table WHERE user_ID = @UserID AND department = @Dept ‘ EXEC(@sql) END
  • 53.
    What if Inputhas: 1' OR '1'='1';EXEC master.dbo.xp_cmdshell 'dir'--' Result: PROCEDURE SafeGetBalanceQuery( @UserID varchar(20), @Dept varchar(10)) AS BEGIN SELECT @sql=‘ SELECT balance FROM accounts_table WHERE user_ID = @UserID AND department = 1' OR '1'='1'; EXEC master.dbo.xp_cmdshell 'dir'--' EXEC(@sql) END
  • 54.
    Stored Procedure –SQL Server- FIX PROCEDURE SafeGetBalanceQuery(@UserID varchar(20), @Dept varchar(10)) AS BEGIN DECLARE @sql VARCHAR(200) SELECT @sql = 'SELECT balance FROM accounts_table WHERE ' + 'user_ID = @UID AND department = @DPT' EXEC sp_executesql @sql, '@UID VARCHAR(20), @DPT VARCHAR(10)', @UID=@UserID, @DPT=@Dept END
  • 55.
  • 56.
    Hibernates String tname =(String) req.getParameter("table"); String employeename = request.getParameter("name"); Session session = sessionFactory.getCurrentSession(); try{ session.beginTransaction(); SQLQuery query = session.createSQLQuery("SELECT * FROM " + tname + "WHERE stuff=”+ employeename); session.getTransaction().commit(); } catch (Exception e) {} session.close();
  • 57.
    Vulnerable code String tname= (String) req.getParameter("table"); String employeename = request.getParameter("name"); Session session = sessionFactory.getCurrentSession(); try{ session.beginTransaction(); SQLQuery query = session.createSQLQuery("SELECT * FROM " + tname + "WHERE stuff=”+ employeename); // no input validation for tname & employeename session.getTransaction().commit(); } catch (Exception e) {} //no rollback session.close();
  • 58.
    Fixed Code String tname= (String) req.getParameter("table"); ….do input validation for tablename here………. String employeename = request.getParameter("name"); Session session = sessionFactory.getCurrentSession(); Transaction tx=null; try{ tx=session.beginTransaction(); SQLQuery query = session.createSQLQuery("SELECT * FROM " + tname + "WHERE stuff=?”); query.setParameter(0, parameter1); tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { sess.close(); }
  • 59.
    Common methods whichare used creating SQL queries in Hibernates are as follows : • Session.createSQLQuery(String queryString) • Session.createQuery(String queryString) • Session.createFilter(Object collection, String queryString) • Session.find(String queryString) • Query.executeUpdate() • Query.getQueryString()
  • 60.
    Query.executeUpdate() String hql ="UPDATE Student set grade =”+request.getparameter(grade)+"WHERE id =” +request.getparamter(rollno); Query query = session.createQuery(hql); query.executeUpdate(); String hql = "UPDATE Employee set salary = :grade " + "WHERE id = :rollno"; Query query = session.createQuery(hql); query.setParameter("salary", request.getparameter(grade)); query.setParameter("empid", request.getparamter(rollno)); query.executeUpdate();
  • 61.
    session.beginTransaction(); Query q1 =session.createQuery(taintSQL); //pretend taintSQL came from unchecked input sql = q1.getQueryString(); //get taint SQLsession.getTransaction.commit(); session.beginTransaction(); Query q2 = new QueryImpl(sql, session, parameterMetadata); //reuse taint SQL w/o validation session.getTransaction.commit(); //evil prevailssession.close(); OWASP Example for Query.getQueryString():
  • 62.
    SQL Injections Checklist •Check for input validation • Check for parameterized prepared statements • Check for ORDERBY clause • Check for GROUPBY clause • Check for parameters that we cannot parametrize
  • 63.
  • 64.
  • 65.
  • 66.

Editor's Notes

  • #2 I tried my best to copy that In this part I am mainly focusing on the procedure to follow for code reviews not the complete code review itself. I am not gonna explain about each vulnerability
  • #3 Hell no… Who says that? Lets forget about security for a moment Lets assume that there is a functionality break and a support engineer is debugging the code. Then he feels like…”Abey kisne lika ye code?” ;)
  • #4 An asset requires: limited accessibility and generates value• Assets can be intangible Tell me general assets that you feel like assets in real life. There are three important terms in Security associated with assests How many of you are fans of Tom and Jerry?
  • #5 Lets take an external attacker and security engineer situation here Jerry-> Application/Developer Tom Attacker
  • #7 Application vulnerable to Cheese
  • #8 As a security engineer you need to identify What do you want to protect? Who do you want to protect it from? How likely is it that you will need to protect it? How bad are the consequences if you fail? How much trouble are you willing to go through in order to try to prevent those?
  • #10 You guys know about SDLC right? SSDLC Do we need to all of this? Arguments about which technique is the best are like arguing whether a hammer or saw is more valuable when building a house. Or is it about Tammana or Anjelina No matter what ever stage you take there is security associate with it… These is my day to day job expect for Network Configuration Review
  • #11 Why do you need to do code review or threat modeling? Because you guys might have studied in “Software Project Management” course about
  • #12 https://theparalegalsociety.wordpress.com/2012/07/27/increase-your-productivity-the-desk-dragon-method/ Like I said code review is “not easy”
  • #13 1st point: Despite the many claims that code review is too expensive or time consuming, there is no question that it is the fastest and most accurate way to find and diagnose many security problems. Because the code doesn't lie. Actually, the code is your only advantage over the hackers. Don't give up this advantage and rely only on external penetration testing. Use the code. For example second order sql injections… How do you identify with blind sql injection/xss there? 3rd point: One common pattern is to use security code review to find a problem, and penetration testing to prove that it is exploitable. Another pattern is finding a potential issue with penetration testing, and then verifying the issue by finding and examining the code. I strongly believe that the "combined" approach is the best choice for most applications. Before doing the code review think about assests
  • #14 1. Software developers are not taught about these weaknesses in school and most do not receive any training on the job about these problems. 2. Increasing connectivity lead to new technologies and protocols at a shocking rate. Our ability to invent technology has seriously outstripped our ability to secure it. Many of the technologies in use today simply have not received any security scrutiny. (IOT). Probably they might know how to code securely in one technology 3. There are many reasons why businesses are not spending the appropriate amount of time on security. Because software is essentially a black-box, it is extremely difficult to tell the difference between good code and insecure code. Without this visibility, buyers won’t pay more for secure code, and vendors would be foolish to spend extra effort to produce secure code. 4. If you ask me how many lines of code you wrote I might say… http://www.dailygood.org/story/164/12-things-you-were-not-taught-in-school-about-creative-thinking/
  • #15 Here are some of the (unjustified) excuses that we hear for not putting more effort into security Really Seriously Dumb If you ask a business person about their security priority. They will say “See… our priority in this order design, code, quality, usability and then…. security will come at………. 500 in a list 500”
  • #17 The reviewer(s) need to be familiar with: 1. Code: The language(s) used, the features and issues of that language from a security perspective. The issues one needs to look out for and best practices from a security and performance perspective. 2. Context: The working of the application being reviewed. All security is in context of what we are trying to secure. What type of data is being manipulated or processed and what would the damage to the company be if this data was compromised. 3. Audience: The intended users of the application, is it externally facing or internal to “trusted” users. Does this application talk to other entities (machines/services)? Do humans use this application? 4. Importance: The availability of the application is also important. Shall the enterprise be affected(bank sites) in any great way if the application is “bounced” or shut down for a significant or insignificant amount of time? 5. The information should be assembled into a threat model that can be used to prioritize the review. Frequently, this information can be obtained by studying design documents, business requirements, functional specifications, test results, and the like.
  • #19 You may ask me a question, Why do we need Threat modeling? Threat modeling is a structured approach which is used to analyze the security of the application If you need to perform SCA on a project and you do not have enough time. Through the results of the threat modeling instead of reviewing all source code with with equal focus, you can prioritize the components whose threat modeling has ranked with high risk threats. Which will save lot of time. There something called SSDLC, So the inclusion of Threat modeling in SDLC will ensure the security builtin from the very beginning of the application development. Microsoft The inclusion of threat modeling in the SDLC can help to ensure that applications are being developed with security built-in from the very beginning. This, combined with the documentation produced as part of the threat modeling process, can give the reviewer a greater understanding of the system. This allows the reviewer to see where the entry points to the application are and the associated threats with each entry point.
  • #22 After identifying the important usecases from threat model Code reviews are of Two types: Manual Code review and Automated code review
  • #25 Explain about how fortify works 1. Business Logic Flaws remain untouched – The flaws that are related to application’s logic, transactions, and specific sensitive data remain untouched by the scanners. The security controls that needs to be implemented in the application specific its features and design are often not pointed by the scanners. This stands as a biggest limitation of the static code analyzers. Ex: Bank balance 2. Limited scope – Static code analyzers are often designed for specific frameworks or certain set of vulnerable patterns, they fail to address the issues not covered in their search pattern repository. So the scanners often fail in catching up the vulnerabilities of the new versions of the framework that keeps coming up. 3. Custom validations - Most of the static analyzers tool miss out the custom validations added in the application while identifying the flaws. These could include blacklist or whitelist validation present in the application before the input sources. It could also mean the customization added by the developers to the existing design frameworks and inbuilt framework based API, the scanners that go by pattern based search usually miss out in understanding such intricate details of the code. 4. Design flaws – Design flaws are lessen known issues and static code analyzers often focus more on the code than the design. Mainly if the application design is custom built it becomes challenging for the scanners to trace the code flow. Ex: CAPTCHA protection etc.. 5. Application specific recommendations – Scanners usually provide a generic solution and do not point out application specific code changes. If the solutions are customized as per the design and the feasibility of the application it will be clearer to the developers and require less code change. Ex: CSRF fix for Ruby on Rails
  • #27 Before doing code review you need to have following information
  • #31 In order to find input validation vulnerabilities you need to have entry points to the code I am going to show some sample code that I wrote for a project while I am doing my b.tech I will give 5 secs tell me how many vulnerabilities you find.
  • #33 After looking at the code.. What did you guys understand? - that I don’t know how to code Sorry guys I did my m.tech from iit roorkee and coding from IIN they don’t know net in internet stands for network
  • #34 Path Manipulation
  • #35 Path Manipulation
  • #36 XSS could also be possible
  • #37 XSS could also be possible
  • #45 For the matter of fact why any injections vulnerabilities will happen?
  • #46 For the matter of fact why any injections vulnerabilities will happen?
  • #50 Oracle - PL/SQL
  • #51 https://www.owasp.org/index.php/Query_Parameterization_Cheat_Sheet https://mycrowd.com/requesting-tasks-tips-power-freelancers/ Now let us see example for Stored Procedures for SQL servers
  • #53 These is what I meant when I talked about the technology or language that you are using
  • #55 Technologies did not stop here. There are like sqlite for mobiles and there are nosql servers like mangodb
  • #56 Hibernates removed the burden over the developers to learn SQL Plain old java object
  • #58 Ask about why input validation and not parameterization
  • #60 Session.createFilter(Object collection, String queryString) – this will create a query with filter string.
  • #64 DFDs can be used in next release. If there are small modifications then those can be easily added and analysed.