SlideShare a Scribd company logo
1 of 67
Hacker Proofing Web A!lications wi"


        "e new Java EE 6

       Abhay Bhargav and Dr. B.V.Kumar
Abhay Bhargav




• Abhay Bhargav - CTO, we45 Solutions India Pvt Ltd.
• Web App Sec Jack Sparrow
• Wakes up every morning with a Web App Exploit
• CISSP, CISA, GWAPT, CPA
# B.V Kumar
            .
• CEO of Altius Inc.
• Protector of Java
• Eats, drinks and breathes public static void main
  (String[]args)
• Writes books when he is bored....
• He turns geeks into uber-geeks!
Secure Java: For Web A!lication Development
It ha!ened one evening....

 •   7:30 PM in one of the many pubs in Bangalore
 •   we challenged each other...
 •   I build a web app....
 •   And I break it......
 •   And so we began a game of Web App
     “Capture the Flag!”
 •   Here we are to talk about what we did
$e PROLOGUE


•   Notice that the world has moved to web apps for
    everything!!
•   Credit Card Info, SSNs, Personal Info are available in
    cyberspace.
•   Web Apps are THE MOST targeted elements in the world
    today
•   70% of Web Apps are vulnerable to attacks by hackers
•   Easy pickings for a hacker looking to retire early.
and its %&ing wors'.....



• web 2.0 and RIA presents a greater attack surface
• Developers are largely unaware.....
• Management doesn’t understand Application Security
• Attack vectors widespread with the use of Social
  networks and URL shortnening: bit.ly/IHACKYOU
Why ( it se)*s?



•   Financial Backlash

•   Loss of Reputation

•   Compliance, Regulations and
    Contracts

•   Hackers and their backers
Compliance Requirements


•   PCI-DSS: Stringent Web
    Application Security
    Requirements

•   HIPAA: Web Application
    Security driven through
    Risk Assessment

•   GLBA: Web Apps
    handling Financial
    Services Information

•   SOX: Internal Control
    Requirements
Case Stu+es
<sc)pt> = ZOMBIE




• Case Study 1 - Online Education Services Provider
• Example of Cross Site Scripting attack against
  “Prudent Educational Services”
XSS - Cross Site Sc)pting A&ack



   interprets
 input as html


                                          </sc ript>
                                ted()                  Attacker
                     ipt> injec
                 <scr                                           •Session Hijacking
                                                                •Browser Hooking
                                                                •User Account Access
                                                                •Denial-of-Service
Your Web App                                                    •Malicious Redirection
                   Bro
                      wse
                          r ex
                              ecu
                                    tes
                                          <sc
                                             ript
                                                 >     Legit User
Prudent Educational Services


•   Educational Services Company - Users access Online
    Learning Modules
•   Thousands of users access app every day
•   XSS found in their user forums
•   Browser Hooking - Browser Command and Control
    Access
•   50 Zombies at the end of the day!
$e a&ack


   XSS Found in the                                         Our team fires up BeEF
“Forum” Functionality of                                   to hook and control user
    the Application                                            browsers through
                                                              executed JavaScript




                                                       d
                                                 o oke
                                           r is h team
                                      rowse d our wser
                                r ’s b EF an ’s bro
                             Use g Be user
                              usin trols
                                con




 Legit User
y*r db = my db




• Case Study 2 - E-Commerce App
• SQL Injection Attack against “OurProfit Pvt. Ltd.”
SQL INJECTION



               someValue’
                            OR ‘1’=’1




Your Web App
                                        Attacker


   DB
OurProfit - SQL Injection A&ack



• E-Commerce site with several thousand users
  accessing daily
• SQL Injection found on one of their catalog pages
• Enumeration of Database users and passwords -
  They were running as root
• Server pwnage!!!
Demo:
au"enticated = ANY




• Case Study 3 - Online Transportation Services
• Authentication and Authorization Bypass against
  “Super Hound Transport Co”
Access control fail!


• Super Hound Transport Co, one of the largest
  transport companies in India
• 3 million bookings a month for buses and other
  transport options.
• Users need to submit their license numbers, passport
  numbers as id proof when they book
• We found Authentication and Authorization Flaws
Demo:
formula for secure web a!s




SSDLC              AAA           crypto


                      Secure          Security
        Logging                        Testing
                      Coding



             Secure Web Application
S+SDLC

•   The unifying step in Secure
    Application Development

•   Security as a priority from
    application inception

•   Risk Assessment + SDLC =
    SSDLC
AAA - Au"entication
•   Authentication Implementation:

    •   Passwords - Strength,
        Complexity, History and
        Expiration

    •   Password Reset Questions -
        Complexity never hurt

    •   Validate Authentication
        Parameters

•   Request Authentication to prevent
    CSRF
AAA - Au"o)zation

• Least Privilege - Role Based Access Control
 • Use the Matrix!
• Server Driven Centralized Authorization Routines
• Resource and Function driven Authorization
• Protect static content through Authorization
AAA - Sessions
•   Don’t override existing session token implementation
•   Validate Session IDs - especially if URL Rewriting
•   Session Idle Time out - Lower for High-Risk Sites
•   Re-Authentication and Regeneration for privileged
    functions - e.g. Transfer of High-Value Transactions
•   Invalidate existing Sessions during a login - Session
    Fixation
Java + AAA

• Services of JAAS handles Authentication and
  Authorization
• Java EE 6 has several new features for Authentication
  and Authorization
• Eases the pains of AAA of Web Apps
What’s new? - Au"entication




•authenticate()
•login()
•logout()
authenticate()
public class AuthenticatingServlet extends HttpServlet {
   resp.setContentType(”text/html″);
   PrintWriter pw = response.getWriter();
   protected void processRequest(HttpServletRequest req,
        HttpServletResponse resp) throws ServletException,
        IOException {
    try {
          //Initiate the BASIC authentication dialog
          req.authenticate(resp);
          out.println(”Authentication Successful”);
    } finally {
         pw.close();
    }
login() & logout()
......
protected void processRequest(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException {
   resp.setContentType(”text/html″);
   PrintWriter pw = response.getWriter();
   try {
         String userName = req.getParameter(”UserName”);
         String passWord = req.getParameter(”Password”);
         try {
             req.login(userName , passWord);
         } catch(ServletException ex) {
             pw.println(”Login Failed” + ex.getMessage());
             return;
         }
         } catch (Exception e) {
                 throw new ServletException(e);
         } finally {
             req.logout();
             out.close();
         }
Java + Au"o)zation




•getRemoteUser()
•isUserInRole(rolename)
•getUserPrincipal()
getRemoteUser()
String userName= request.getParameter(”UserName”);
String passWord= request.getParameter(”Password”);
try {
 request.login(userName, passWord);
}    catch(ServletException ex) {
     pw.println(”Login Failed” + ex.getMessage());
     return;
}
pw.println(”The authenticated user is in Role: ” + req.isUserInRole(”cop”));
pw.println(”The authenticated remote username: ” + req.getRemoteUser());
pw.println(”The authenticated Principal name: ” + req.getUserPrincipal());
pw.println(”The authentication type: ” + req.getAuthType());
} catch (Exception e) {
    throw new ServletException(e);
}    finally {
    req.logout();
    pw.close();
 }
}
isUserInRole()
 String userName= request.getParameter(”UserName”);
 String passWord= request.getParameter(”Password”);
 try {
     request.login(userName, passWord);
 }   catch(ServletException ex) {
     pw.println(”Login Failed” + ex.getMessage());
     return;
 }
if (req.isUserInRole(“cop”)){
        //Do Something
} else {
     //Do Something else.....
}
.....
pw.println(”The authenticated user is in Role: ” + req.isUserInRole(”cop”));
pw.println(”The authenticated remote username: ” + req.getRemoteUser());
pw.println(”The authenticated Principal name: ” + req.getUserPrincipal());
pw.println(”The authentication type: ” + req.getAuthType());
getUserPrincipal()
try {
 request.login(myUsername, myPassword);
}   catch(ServletException ex) {
 pw.println(”Login Failed” + ex.getMessage());
 return;
}
pw.println(”The authenticated user Role is: ” + req.isUserInRole(”cop”));
pw.println(”The authenticated remote username: ” + req.getRemoteUser());
pw.println(”The authenticated Principal name: ” + req.getUserPrincipal());
pw.println(”The authentication type: ” + req.getAuthType());
} catch (Exception e) {
 throw new ServletException(e);
}   finally {
 req.logout();
 pw.close();
}
......
Secu)ty Annotations in Web A!s


• Servlet 3.0 Specification provisions Security
  Annotations
• Equivalent to those defined in the deployment
  descriptor (web.xml)
• Easier to define roles, access control to HTTP
  methods, protection to Transport layer
• @ServletSecurity annotation
@ServletSecurity

•   Allows definition of security constraints as its fields
•   @HTTPConstraint to specify roles to methods to
    ensure transport layer security
•   @HTTPMethodConstraint applied to HTTP methods

•   @DeclareRoles allows security role definition

•   @RoleAllowed facilitates authorized role definition
Servlet Annotation
// Package Declaration
// import declarations
// Declaring Roles
@DeclareRoles("customer","guest")

// Declaring ServletSecurity Annotation
@ServletSecurity(@HttpConstraint(rolesAllowed={"customer"}))
public class ControlServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
  PrintWriter pw = resp.getWriter();
  pw.println("Control Servlet Action");
    ...
    // do something
    ...
  }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
  resp.setContentType("text/html");
  PrintWriter pw = resp.getWriter();
    ...
    // do something
    ...
    pw.close();
  }
}
CSRF - Cross Site Request Forgery
             Attack
      www.bank.com/accounts/transfer.jsp?trTo=005301000201&amt=$2000.00
CSRF - Cross Site Request Forgery
      Using Request Tokens
      www.bank.com/accounts/transfer.jsp?trTo=005301000201&amt=$2000.00
Data protection




•   Encryption-Decryption

•   Hashing
Crypto
• No Home Grown Crypto!
• Strong Algorithms for Encryption - AES, 3DES
  (128bit and above, RSA (1024bit and above)
• One key per task
• DEKS and KEKs for additional security over
  cryptographic materials
More Crypto
•   Central, Application driven key management
•   Key Storage
    •   No keys in Source Code
    •   Non-Export mode for Private keys
    •   Log any key changes
    •   Password based keys must have strong password rules
Even More Crypto




• Transport keys across encrypted channels
• Change keys periodically (annually) or upon
  compromise
• Padding makes for easier crypto!
Java+Crypto



• Currently JCA + JCE are still popular libraries for
  Cryptography requirements
• Java EE 6 has several new features for
  Cryptography / Encryption / Cypher requirements
• Eases the Web App Crypto Security
Crypto Features


• JCA + JCE provides comprehensive API with support
  for a wide range of cryptographic services including
  digital signatures, message digests, ciphers (symmetric,
  asymmetric, stream & block), message authentication
  codes, key generators and key factories
• These libraries also provide support for a wide range
  of standard algorithms such as RSA, DSA, AES, Triple
  DES, SHA, PKCS#5, RC2, and RC4.
• PKCS#11 cryptographic token support
New Crypto Features in Java EE 6


•   Elliptic Curve Cryptography (ECC) in SunPKCS11

•   Elliptic Curve CipherSuites in SunJSSE
•   Access Network Security Services (NSS) using SunPKCS11

•   Cipher Text Stealing (CTS) mode added to SunJCE block ciphers
•   Removed the 2048 RSA keysize limit from local_policy.jar
•   Access to native PKI and cryptographic services on Microsoft
    Windows
Ha.ing




• Hashing is a One way street!
• Strong Hash Algorithms - SHA-1 and upwards
• Salt adds the right flavor to the hash - Entropy
Logging


•   Logging -- no longer an after thought
•   We believe that it is a part of Security requirements!
•   Logging at the application level is oft-ignored
•   What should be logged?
    •   Password Lockouts, Changes and Resets
    •   Privileged Functions or Transactions
    •   Admin Access to Critical Information Assets
    •   Creation/Deletion of (Admin) Users & User Privileges
Logging+Java


•   java.util.logging APIs facilitate the much needed
    software servicing / maintenance / security through log reports
•   APIs help in capturing information on security failures, along with
    other important information such as configuration errors,
    performance bottlenecks and bugs
•   Log reports can be appropriately formatted to suite the
    requirements
•   APIs are capable of interacting with the logging services that are
    existing on the host
Secure Co+ng




• Input Validation
• Output Encoding
• Secure Database Queries
• Error Handling
Input Validation


•   Remedy for several evils
•   Identify and Characterize all input
•   Regular Expressions
•   Server side
•   Whitelist is the Right List
•   Canonicalization
•   Validate early
Input Validation fail!

protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
  throws ServletException, IOException
 {
                        response.setContentType("text/
html;charset=UTF-8");
//Create or get the session object from the HTTPSession object
HttpSession session = request.getSession();
Employee user =
(Employee)session.getAttribute("currentEmployee");
PrintWriter out = response.getWriter();
String familyName = request.getParameter("familyName");
String givenName = request.getParameter("givenName");
String status =   request.getParameter("status");
String pos = request.getParameter("positionGroup");
String email=request.getParameter("email");
String username = request.getParameter("user");
continued...
if (!dob.equals(null) && !dob.equals("")) {
 String revDob = dob.substring(6, dob.length()) + '-' +
 dob.substring(0, 2)+'-' + dob.substring(3, 5);
 sqlBirthDate = java.sql.Date.valueOf(revDob);
 newEmp.setBirthDate(sqlBirthDate);
}
if(!email.equals(null) && !email.equals("")) {
    newEmp.setEmail(email);
}
//More Insecure Code continues
response.sendRedirect("webapp_user/updateUser.jsp?
message=true&familyName=" + familyName +"&givenName=" +
givenName + "&username=" + username + "&email=" +
email + "&dob=" + dob + "&empId=" + empId + "&status="
+ newEmp.getActive());
Java + Input Validation



•java.util.regex
•java.text.Normalizer
•javax.servlet.http.HttpServlet
 RequestWrapper
•javax.servlet.Filter
Input Validation
public class ValidateRequest extends HttpServletRequestWrapper {
public ValidateRequest(HttpServletRequest req) {
    super(req);
}
public String getParameter(String name) {
 HttpServletRequest req = (HttpServletRequest) super.getRequest();
                  return validate( name, req.getParameter( name ) );
}
 private Pattern pattern = Pattern.compile("^[a-zA-Z0-9]{0,20}$");
 private String validate( String name, String input ) throws
ValidationException {
 // canonicalize before validating
    String canonical = canonicalize( input );
// input matches whitelist character set
if ( !pattern.matcher(canonical).matches() ) {
 throw new ValidationException( "Improper format in " + name + "
         field";
}
 return canonical;
Input Validation

.....
private String canonicalize( String input ) {
    String canonical = java.text.Normalizer.normalize(input,
    Normalizer.Form.NFD);
    return canonical;
}
......
public class ValidationFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse
    resp, FilterChain chain) {
    chain.doFilter(new
    ValidationRequest((HttpServletRequest)req),resp);
    }
}
Output Enco+ng



• Identify all output - User, Web Services, Sockets,
  Command Line, etc
• Defangs Injection attacks
• Sanitization of malicious characters in output to
  render injection attacks unsuccessful
Java + Output Enco+ng



•java.net.URLEncoder
•org.apache.commons.lang.String
 EscapeUtils
•org.apache struts.util.Response
           .
 Utils
Output Enco+ng - Flawed
Output Enco+ng - WIN!
Secure Database Access



• Database Access
 • Prepared Statement
 • Error Handling
• Custom Error Handling
 • Default Pages = TMI (Too much Information)
Secu)ty Testing Web A!s



• Testing for Security   - As important as testing for
  functionality
• Security Testing - The two Approaches
 • Black-boxing - Vulnerability Assessments and
    Penetration Tests
  • White-boxing - Code Reviews and Walkthroughs
References


•   Secure Java: For Web
    Application Development -
    Abhay Bhargav and B.V.Kumar

•   OWASP Java Project

•   NIST SP 800-57

•   JavaDocs

•   citadelnotes.blogspot.com

•   and more.....
Presentation will be available @




 www.secure-java.com
Contacts
• Abhay Bhargav
 • Email: abhay@we45.com
 • URL: www.we45.com
 • Blog: citadelnotes.blogspot.com
 • Linkedin: http://in.linkedin.com/in/abhaybhargav
 • Twitter: @abhaybhargav
Contacts

• Dr. B.V.Kumar
 • Email: kumar@altius-inc.com
 • URL: www.altius-inc.com
 • LinkedIn: http://in.linkedin.com/in/kumarbv
 • Twitter: @kumarbv
$ank y*!!




Don’t Applaud, Just Throw Money!!

More Related Content

Recently uploaded

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 

Recently uploaded (20)

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Hacker Proofing Web Apps with the New Java EE 6

  • 1. Hacker Proofing Web A!lications wi" "e new Java EE 6 Abhay Bhargav and Dr. B.V.Kumar
  • 2. Abhay Bhargav • Abhay Bhargav - CTO, we45 Solutions India Pvt Ltd. • Web App Sec Jack Sparrow • Wakes up every morning with a Web App Exploit • CISSP, CISA, GWAPT, CPA
  • 3. # B.V Kumar . • CEO of Altius Inc. • Protector of Java • Eats, drinks and breathes public static void main (String[]args) • Writes books when he is bored.... • He turns geeks into uber-geeks!
  • 4. Secure Java: For Web A!lication Development
  • 5. It ha!ened one evening.... • 7:30 PM in one of the many pubs in Bangalore • we challenged each other... • I build a web app.... • And I break it...... • And so we began a game of Web App “Capture the Flag!” • Here we are to talk about what we did
  • 6. $e PROLOGUE • Notice that the world has moved to web apps for everything!! • Credit Card Info, SSNs, Personal Info are available in cyberspace. • Web Apps are THE MOST targeted elements in the world today • 70% of Web Apps are vulnerable to attacks by hackers • Easy pickings for a hacker looking to retire early.
  • 7. and its %&ing wors'..... • web 2.0 and RIA presents a greater attack surface • Developers are largely unaware..... • Management doesn’t understand Application Security • Attack vectors widespread with the use of Social networks and URL shortnening: bit.ly/IHACKYOU
  • 8. Why ( it se)*s? • Financial Backlash • Loss of Reputation • Compliance, Regulations and Contracts • Hackers and their backers
  • 9. Compliance Requirements • PCI-DSS: Stringent Web Application Security Requirements • HIPAA: Web Application Security driven through Risk Assessment • GLBA: Web Apps handling Financial Services Information • SOX: Internal Control Requirements
  • 11. <sc)pt> = ZOMBIE • Case Study 1 - Online Education Services Provider • Example of Cross Site Scripting attack against “Prudent Educational Services”
  • 12. XSS - Cross Site Sc)pting A&ack interprets input as html </sc ript> ted() Attacker ipt> injec <scr •Session Hijacking •Browser Hooking •User Account Access •Denial-of-Service Your Web App •Malicious Redirection Bro wse r ex ecu tes <sc ript > Legit User
  • 13. Prudent Educational Services • Educational Services Company - Users access Online Learning Modules • Thousands of users access app every day • XSS found in their user forums • Browser Hooking - Browser Command and Control Access • 50 Zombies at the end of the day!
  • 14. $e a&ack XSS Found in the Our team fires up BeEF “Forum” Functionality of to hook and control user the Application browsers through executed JavaScript d o oke r is h team rowse d our wser r ’s b EF an ’s bro Use g Be user usin trols con Legit User
  • 15. y*r db = my db • Case Study 2 - E-Commerce App • SQL Injection Attack against “OurProfit Pvt. Ltd.”
  • 16. SQL INJECTION someValue’ OR ‘1’=’1 Your Web App Attacker DB
  • 17. OurProfit - SQL Injection A&ack • E-Commerce site with several thousand users accessing daily • SQL Injection found on one of their catalog pages • Enumeration of Database users and passwords - They were running as root • Server pwnage!!!
  • 18. Demo:
  • 19. au"enticated = ANY • Case Study 3 - Online Transportation Services • Authentication and Authorization Bypass against “Super Hound Transport Co”
  • 20. Access control fail! • Super Hound Transport Co, one of the largest transport companies in India • 3 million bookings a month for buses and other transport options. • Users need to submit their license numbers, passport numbers as id proof when they book • We found Authentication and Authorization Flaws
  • 21. Demo:
  • 22. formula for secure web a!s SSDLC AAA crypto Secure Security Logging Testing Coding Secure Web Application
  • 23. S+SDLC • The unifying step in Secure Application Development • Security as a priority from application inception • Risk Assessment + SDLC = SSDLC
  • 24. AAA - Au"entication • Authentication Implementation: • Passwords - Strength, Complexity, History and Expiration • Password Reset Questions - Complexity never hurt • Validate Authentication Parameters • Request Authentication to prevent CSRF
  • 25. AAA - Au"o)zation • Least Privilege - Role Based Access Control • Use the Matrix! • Server Driven Centralized Authorization Routines • Resource and Function driven Authorization • Protect static content through Authorization
  • 26. AAA - Sessions • Don’t override existing session token implementation • Validate Session IDs - especially if URL Rewriting • Session Idle Time out - Lower for High-Risk Sites • Re-Authentication and Regeneration for privileged functions - e.g. Transfer of High-Value Transactions • Invalidate existing Sessions during a login - Session Fixation
  • 27. Java + AAA • Services of JAAS handles Authentication and Authorization • Java EE 6 has several new features for Authentication and Authorization • Eases the pains of AAA of Web Apps
  • 28. What’s new? - Au"entication •authenticate() •login() •logout()
  • 29. authenticate() public class AuthenticatingServlet extends HttpServlet { resp.setContentType(”text/html″); PrintWriter pw = response.getWriter(); protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { //Initiate the BASIC authentication dialog req.authenticate(resp); out.println(”Authentication Successful”); } finally { pw.close(); }
  • 30. login() & logout() ...... protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType(”text/html″); PrintWriter pw = response.getWriter(); try { String userName = req.getParameter(”UserName”); String passWord = req.getParameter(”Password”); try { req.login(userName , passWord); } catch(ServletException ex) { pw.println(”Login Failed” + ex.getMessage()); return; } } catch (Exception e) { throw new ServletException(e); } finally { req.logout(); out.close(); }
  • 32. getRemoteUser() String userName= request.getParameter(”UserName”); String passWord= request.getParameter(”Password”); try { request.login(userName, passWord); } catch(ServletException ex) { pw.println(”Login Failed” + ex.getMessage()); return; } pw.println(”The authenticated user is in Role: ” + req.isUserInRole(”cop”)); pw.println(”The authenticated remote username: ” + req.getRemoteUser()); pw.println(”The authenticated Principal name: ” + req.getUserPrincipal()); pw.println(”The authentication type: ” + req.getAuthType()); } catch (Exception e) { throw new ServletException(e); } finally { req.logout(); pw.close(); } }
  • 33. isUserInRole() String userName= request.getParameter(”UserName”); String passWord= request.getParameter(”Password”); try { request.login(userName, passWord); } catch(ServletException ex) { pw.println(”Login Failed” + ex.getMessage()); return; } if (req.isUserInRole(“cop”)){ //Do Something } else { //Do Something else..... } ..... pw.println(”The authenticated user is in Role: ” + req.isUserInRole(”cop”)); pw.println(”The authenticated remote username: ” + req.getRemoteUser()); pw.println(”The authenticated Principal name: ” + req.getUserPrincipal()); pw.println(”The authentication type: ” + req.getAuthType());
  • 34. getUserPrincipal() try { request.login(myUsername, myPassword); } catch(ServletException ex) { pw.println(”Login Failed” + ex.getMessage()); return; } pw.println(”The authenticated user Role is: ” + req.isUserInRole(”cop”)); pw.println(”The authenticated remote username: ” + req.getRemoteUser()); pw.println(”The authenticated Principal name: ” + req.getUserPrincipal()); pw.println(”The authentication type: ” + req.getAuthType()); } catch (Exception e) { throw new ServletException(e); } finally { req.logout(); pw.close(); } ......
  • 35. Secu)ty Annotations in Web A!s • Servlet 3.0 Specification provisions Security Annotations • Equivalent to those defined in the deployment descriptor (web.xml) • Easier to define roles, access control to HTTP methods, protection to Transport layer • @ServletSecurity annotation
  • 36. @ServletSecurity • Allows definition of security constraints as its fields • @HTTPConstraint to specify roles to methods to ensure transport layer security • @HTTPMethodConstraint applied to HTTP methods • @DeclareRoles allows security role definition • @RoleAllowed facilitates authorized role definition
  • 37. Servlet Annotation // Package Declaration // import declarations // Declaring Roles @DeclareRoles("customer","guest") // Declaring ServletSecurity Annotation @ServletSecurity(@HttpConstraint(rolesAllowed={"customer"})) public class ControlServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pw = resp.getWriter(); pw.println("Control Servlet Action"); ... // do something ... } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter pw = resp.getWriter(); ... // do something ... pw.close(); } }
  • 38. CSRF - Cross Site Request Forgery Attack www.bank.com/accounts/transfer.jsp?trTo=005301000201&amt=$2000.00
  • 39. CSRF - Cross Site Request Forgery Using Request Tokens www.bank.com/accounts/transfer.jsp?trTo=005301000201&amt=$2000.00
  • 40. Data protection • Encryption-Decryption • Hashing
  • 41. Crypto • No Home Grown Crypto! • Strong Algorithms for Encryption - AES, 3DES (128bit and above, RSA (1024bit and above) • One key per task • DEKS and KEKs for additional security over cryptographic materials
  • 42. More Crypto • Central, Application driven key management • Key Storage • No keys in Source Code • Non-Export mode for Private keys • Log any key changes • Password based keys must have strong password rules
  • 43. Even More Crypto • Transport keys across encrypted channels • Change keys periodically (annually) or upon compromise • Padding makes for easier crypto!
  • 44. Java+Crypto • Currently JCA + JCE are still popular libraries for Cryptography requirements • Java EE 6 has several new features for Cryptography / Encryption / Cypher requirements • Eases the Web App Crypto Security
  • 45. Crypto Features • JCA + JCE provides comprehensive API with support for a wide range of cryptographic services including digital signatures, message digests, ciphers (symmetric, asymmetric, stream & block), message authentication codes, key generators and key factories • These libraries also provide support for a wide range of standard algorithms such as RSA, DSA, AES, Triple DES, SHA, PKCS#5, RC2, and RC4. • PKCS#11 cryptographic token support
  • 46. New Crypto Features in Java EE 6 • Elliptic Curve Cryptography (ECC) in SunPKCS11 • Elliptic Curve CipherSuites in SunJSSE • Access Network Security Services (NSS) using SunPKCS11 • Cipher Text Stealing (CTS) mode added to SunJCE block ciphers • Removed the 2048 RSA keysize limit from local_policy.jar • Access to native PKI and cryptographic services on Microsoft Windows
  • 47. Ha.ing • Hashing is a One way street! • Strong Hash Algorithms - SHA-1 and upwards • Salt adds the right flavor to the hash - Entropy
  • 48. Logging • Logging -- no longer an after thought • We believe that it is a part of Security requirements! • Logging at the application level is oft-ignored • What should be logged? • Password Lockouts, Changes and Resets • Privileged Functions or Transactions • Admin Access to Critical Information Assets • Creation/Deletion of (Admin) Users & User Privileges
  • 49. Logging+Java • java.util.logging APIs facilitate the much needed software servicing / maintenance / security through log reports • APIs help in capturing information on security failures, along with other important information such as configuration errors, performance bottlenecks and bugs • Log reports can be appropriately formatted to suite the requirements • APIs are capable of interacting with the logging services that are existing on the host
  • 50. Secure Co+ng • Input Validation • Output Encoding • Secure Database Queries • Error Handling
  • 51. Input Validation • Remedy for several evils • Identify and Characterize all input • Regular Expressions • Server side • Whitelist is the Right List • Canonicalization • Validate early
  • 52. Input Validation fail! protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/ html;charset=UTF-8"); //Create or get the session object from the HTTPSession object HttpSession session = request.getSession(); Employee user = (Employee)session.getAttribute("currentEmployee"); PrintWriter out = response.getWriter(); String familyName = request.getParameter("familyName"); String givenName = request.getParameter("givenName"); String status = request.getParameter("status"); String pos = request.getParameter("positionGroup"); String email=request.getParameter("email"); String username = request.getParameter("user");
  • 53. continued... if (!dob.equals(null) && !dob.equals("")) { String revDob = dob.substring(6, dob.length()) + '-' + dob.substring(0, 2)+'-' + dob.substring(3, 5); sqlBirthDate = java.sql.Date.valueOf(revDob); newEmp.setBirthDate(sqlBirthDate); } if(!email.equals(null) && !email.equals("")) { newEmp.setEmail(email); } //More Insecure Code continues response.sendRedirect("webapp_user/updateUser.jsp? message=true&familyName=" + familyName +"&givenName=" + givenName + "&username=" + username + "&email=" + email + "&dob=" + dob + "&empId=" + empId + "&status=" + newEmp.getActive());
  • 54. Java + Input Validation •java.util.regex •java.text.Normalizer •javax.servlet.http.HttpServlet RequestWrapper •javax.servlet.Filter
  • 55. Input Validation public class ValidateRequest extends HttpServletRequestWrapper { public ValidateRequest(HttpServletRequest req) { super(req); } public String getParameter(String name) { HttpServletRequest req = (HttpServletRequest) super.getRequest(); return validate( name, req.getParameter( name ) ); } private Pattern pattern = Pattern.compile("^[a-zA-Z0-9]{0,20}$"); private String validate( String name, String input ) throws ValidationException { // canonicalize before validating String canonical = canonicalize( input ); // input matches whitelist character set if ( !pattern.matcher(canonical).matches() ) { throw new ValidationException( "Improper format in " + name + " field"; } return canonical;
  • 56. Input Validation ..... private String canonicalize( String input ) { String canonical = java.text.Normalizer.normalize(input, Normalizer.Form.NFD); return canonical; } ...... public class ValidationFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) { chain.doFilter(new ValidationRequest((HttpServletRequest)req),resp); } }
  • 57. Output Enco+ng • Identify all output - User, Web Services, Sockets, Command Line, etc • Defangs Injection attacks • Sanitization of malicious characters in output to render injection attacks unsuccessful
  • 58. Java + Output Enco+ng •java.net.URLEncoder •org.apache.commons.lang.String EscapeUtils •org.apache struts.util.Response . Utils
  • 61. Secure Database Access • Database Access • Prepared Statement • Error Handling • Custom Error Handling • Default Pages = TMI (Too much Information)
  • 62. Secu)ty Testing Web A!s • Testing for Security - As important as testing for functionality • Security Testing - The two Approaches • Black-boxing - Vulnerability Assessments and Penetration Tests • White-boxing - Code Reviews and Walkthroughs
  • 63. References • Secure Java: For Web Application Development - Abhay Bhargav and B.V.Kumar • OWASP Java Project • NIST SP 800-57 • JavaDocs • citadelnotes.blogspot.com • and more.....
  • 64. Presentation will be available @ www.secure-java.com
  • 65. Contacts • Abhay Bhargav • Email: abhay@we45.com • URL: www.we45.com • Blog: citadelnotes.blogspot.com • Linkedin: http://in.linkedin.com/in/abhaybhargav • Twitter: @abhaybhargav
  • 66. Contacts • Dr. B.V.Kumar • Email: kumar@altius-inc.com • URL: www.altius-inc.com • LinkedIn: http://in.linkedin.com/in/kumarbv • Twitter: @kumarbv
  • 67. $ank y*!! Don’t Applaud, Just Throw Money!!

Editor's Notes

  1. we45 Solutions is an Information Security consulting company.
  2. Abhay: Bangalore is known as the pub-city of India. There are probably more pubs here than there are people. Dr. Kumar: This talk evolved from a discussion we had in one of the many pubs in Bangalore. We were discussing the state of web security and web application security in general. Such nerdy behaviour is observed after a few drinks... Abhay: I had gone off on a tangent about a super-vulnerable web application I was testing and how the developers there seemed clueless about security Dr. Kumar: and I told him that my apps could not be hacked. Abhay: Which I found unbelievable. That naive confidence that he had in his app security skills was cute, but so wrong Dr. Kumar: So I challenged him. I told him that I would build an app Abhay: and I told him I would break it. Dr. Kumar: What do you mean by breaking an app? Abhay: By breaking an app, I mean that I will identify vulnerabilities and exploit them using proof-of-concept exploits for them.... Dr. Kumar: That&amp;#x2019;s why we are here. To tell you what this is all about.
  3. Abhay: Have any of you noticed that web apps have become the way of life all over the world today. We now have web apps that do everything. From booking our tickets, to scheduling our events and banking. This has resulted in a great deal of information stored, processed and transmitted by these web apps. Credit Card numbers, financial information, banking data and personal data are some examples of information that is stored, processed and transmitted by these web apps. Attackers always look for easier ways to steal valuable information and organizations that host these web applications are consistently making it easier for them to do so, because they deploy incredibly vulnerable web apps. According to studies, 70% of all web apps out there are vulnerable to attack. In my own experience with the web apps my company tests, we find 8 out of 10 web apps vulnerable to serious web application flaws.
  4. Abhay: and its getting worse. Web 2.0 is the biggest thing that is happening today. Ajax, mashups, web services, JSON are some of the words you hear when you say web 2.0. I hear one word. Client side. I love the fact that a lot of business logic is moved to the client side now, because that makes applications easier to exploit. Thereby making my job a whole lot easier. Now, one would thing that developers are supposed to know all of this. that it seems rudimentary and simple. However, that is far from the truth. Developers and architects are largely unaware of the web application security practices. in fact according to a Gartner study 75% of web apps are vulnerable due to flawed coding. Dr. Kumar: You are making bold statements. But tell me something, how are you actually planning to break my app??? Abhay: This is not the first time, I am breaking an app. Let me share some of my personal experiences on how easy it is to break apps..... Dr. Kumar: I have had some expertise with web application security. I will tell you three types of attacks and you tell me if you are able to do anything like this... Abhay: What are those? Dr. Kumar: Have you used Cross Site Scripting? Abhay: I love Cross Site Scripting. I have tons of Cross Site Scripting experience Dr. Kumar: What about SQL Injection? Abhay: SQL Injection is a great attack. Yes, I have injected SQL in several sites and have owned the database after that..... Dr. Kumar: What about Authentication and Authorization Bypass?? Abhay: Oh yes, I love breaking Access Control. I have story for that as well. Dr. Kumar: Ok then, tell me your stories.....
  5. Abhay: Before I delve into my hair-raising stories, let me tell you the consequences of a security breach. We all know that apps handle tons of information on a daily basis and a security breach can have serious consequences. Let us talk of some specifics. First of all, financial backlash is something that an organization suffers when it is hacked. Financial losses come from several areas, fines, loss of revenue, loss of customer faith - resulting in loss of revenue. Recently, a large credit card processor in the US was hit with a SQL injection attack, where over a 100 million credit cards were stolen from their databases. This cost the company over $32 million in losses, fines and fees. This is usually compounded with loss of reputation which precedes further financial losses. Dr. Kumar: Reputation - It takes 20 years to build a reputation and it takes 10 minutes to destroy it. Customers would think more than twice before offering your organization financial and personal information. Believe me Abhay: In the wake of several security breaches and high profile incidents, the government and governing bodies have realized that it is no longer a matter of comfort, but a matter of necessity to secure critical information assets. We have several security compliance requirements from the government, namely HIPAA - for Health Information, GLBA - for Financial Information, SB1386 - California Breach Security Act for Personal Information of users. We will discuss compliance at length in the next slide. Dr. Kumar: Hackers earlier, for the most part were individuals who did it for the fun of it or in some cases for individual personal gain. However, in the web2.0 world it has all changed. Large criminal rings and transnational criminal elements fund and support large scale hacking of financial data and personally sensitive information to fuel identity theft and financial theft. Hacking has taken an ugly turn.
  6. Abhay: Compliance is one of the driving forces for Web Application Security. Some of the important Security Requirements are as follows: PCI-DSS: PCI-DSS is the Payment Card Industry Data Security Standard. This is a standard laid down by the card payment brands like visa, mastercard, amex, jcb and discover. This standard mandates several specific application security requirements among other information security requirements. The standard mandates compliance for any entity, storing, processing or transmitting cardholder information. Merchants, service providers, banks and hosting providers are some of the entities that are under the purview of this standard. The HIPAA is an important compliance standard that is mandatory for entities handling personal health information. The act mandates security measures which may include web application security, as these apps handle a great volume of sensitive health information. The GLBA is an act driven to modernize the Financial Services industry. In its multiple requirements, GLBA also mandates entities handling personal financial information to have a stringent information security program. SOX is a law requiring listed entities to have internal control measures to ensure integrity of their financial statements. Now, in this age of computerized accounting and ERP, web applications play a major role in the preparation and creation of financial statements, thereby requring application security measures to be a part of the system.
  7. Now lets get to some of the case studies of Web Application attacks that we have lined up....
  8. Abhay: Our first case study is a personal experience of mine with an online educational services provider, let us call the company &amp;#x201C;Prudent Educational Services&amp;#x201D;. They were affected by a Cross Site Scripting vulnerability...
  9. Dr. BVK: For the benefit of some of the audience here, can you explain Cross Site Scripting....?? Abhay: Cross Site Scripting is a vulnerability where an attacker injects JavaScript into application input. If the application does not filter input and output, the application deems the input to be html code and executes the JavaScript on the user&amp;#x2019;s browser. This has multi-pronged effects. This could be used to steal user cookies, or even take over the user&amp;#x2019;s browser and feed him/her with malware. User Session Hijacking, Malicious redirection to another site, Denial of service, a crafted JavaScript could force the site to crash after a point. This has been seen with several sites like Myspace....
  10. So what happened at Prudent was this....They were a company that was upgrading their app to a newer app. They have several users accessing their online educational classes. We found Cross Site Scripting in certain sections of the site, but their developers were not convinced. So, we had a simple experiment. They hadnt gone live yet and they were testing, so we injected a JavaScript into the message board section of the application and hooked it up to a browser exploitation framework.
  11. What we can do with the browser exploitation framework is this. We identify the Cross Site Scripting flaw and have the framework run a cross site scripting against the application. This attack is intended to hook any user browser that executes the script in the vulnerable site. The browser exploitation framework hooks a user computer turning it into a zombie. Once hooked the attacker can do anything to the browser and in some cases the computer. Exploits can be fed, owning the computer. We did the same to Prudent&amp;#x2019;s testing team and by the end of the day 50 users were hooked. Let&amp;#x2019;s say they took things pretty seriously after that....
  12. Dr. BVK: For the benefit of some of the audience here, please explain this attack SQL Injection? Abhay: SQL Injection is an attack where an attacker passes SQL queries into the application&amp;#x2019;s input. If the application does not filter the input effectively, the query is executed and the attacker can gain access to sensitive database information and in some cases, can compromise the entire database.
  13. Notes: We will show you a demo of a SQL Injection attack. This is the site of an e-commerce where people can buy and sell items. Its a typical e-commerce site. We will show you how we identify SQL Injection vulnerabilities. We add a single quote to the HTTP GET request parameter. This is done to induce an error page. If the error page comes up, the parameter with the single quote is being parsed and the app is potentially vulnerable to SQLi We will show you how we use tools to exploit the given vulnerability. We fire up SQLmap to identify and exploit the given SQL Injection vulnerability. The tool is able to perform any kind of injection, including enumerating DB usernames and passwords
  14. What happened to the header?
  15. We will now show you an example of authentication authorization bypass. This is a login screen for a typical e-ticket booking website. In this case a bus booking site We dont have valid credentials on the site, we just improvise!! We use an innocuous parameter like chkRules and nullify all the values. We use an interception proxy to alter the param values on the fly Voila!! We gain access to a user account and use our access to pivot to other parts of the web app.
  16. Dr. BVK: Abhay, werent we discussing a formula for secure web apps? Abhay: Yup, here it is.... Dr. BVK: We will be exploring each of these elements that are summed up to make a secure web application.....
  17. The unifying process to build secure web applications is to have a Secure Software Development Lifecycle or SSDLC. Now, an SDLC is nothing but a typical SDLC with Security as a priority in every step of the SDLC. Dr. Kumar and I have covered a unique methodology for SSDLCs in great detail in our book Secure Java for Web Application Development. We will not go into Secure SDLC in this talk due to the paucity of time.
  18. Abhay: Authentication is probably considered the perimeter defense for web applications. If an attacker can authenticate into the web app, then the access can be used to do more damage to the web app. One of the primary authentication requirements is password management. The web app must enforce password strength requirements (atleast in the case of high risk applications like Banking and E-Commerce or Admin Consoles). Web Apps should also enforce password changes. Another important password feature is the password lockout. For high-risk applications accounts should be locked out of the application after say 4/5 failed authentication attempts. Oftentimes, it is seen that password bruteforcing is done extensively by attackers. Another major bone of contention is password reset questions. How many of you have come across Rudimentary questions when you do a password reset like &amp;#x201C;What is the name of your school?&amp;#x201D; or &amp;#x201C;What is your favourite hobby?&amp;#x201D;. I have a great answer to all these questions and it is called &amp;#x201C;Social Networking&amp;#x201D; Using the power of Social Networks, where you put up everything from your favourite shirt colour to your dog&amp;#x2019;s spouse&amp;#x2019;s name. Its easy to find the name of your highschool or your favourite hobby. In fact, a major telecom company had this particular password reset question. Which car do you own at home? with 4 options: Lamborghini, Lotus, Fiat or Honda. No prizes for guessing the correct answer. Many applications also implement Authentication parameters like isValidated() or isAuthenticated() and by setting these parameters to null or no, the attacker is able to gain access to the account. The key is to validate these parameters. Abhay: There is another attack called CSRF, which we will discuss at a later part of the presentation.
  19. Abhay: Authorization is the next important piece of the access control puzzle. Once a user is authenticated, he/she needs to have access to resources that she is allowed to access. The principle of &amp;#x201C;Least Privilege&amp;#x201D; governs an effective authorization system. Least Privilege dictates that resources should only be granted to users based on their need to know/use that resource. Abhay: Another important point of mention is that Authorization systems need to be driven by the server side. I have seen certain &amp;#x201C;Authorization systems&amp;#x201D; that have relied on either JavaScript or HTML commenting to enforce authorization to pages and disabled functionality. Authorization needs to be driven based on the sensitivity of the resource/function and the need for a user to access the resource/perform the function.
  20. Abhay: Session management is the glue that holds authentication, authorization and access control together in a web application. In most cases the default session token system implemented by the web/application server is cryptographically strong. It is strongly advised that developers not write their own session token scheme.... Applications must also enforce Session timeouts after a stipulated timeframe, say 15 minutes. In case of high-risk web apps like Banking, session timeout must be set to lower, like 5 minutes or so... Certain functions or actions in a web application are highly privileged functions, which are also highly at risk. For instance, transfer of funds in a banking web app is a highly critical function. In such cases, it is prudent to have the user reauthenticate with a different set of credentials or regenerate the session token for a higher privilege transaction. This may also be implemented for Application Administrators when they need to perform highly privileged functions in the web app. Session fixation attacks are common among several applications. Session fixation attacks rely on the fact that the application does not invalidate existing session tokens, when logging a user into the application, Thereby giving an attacker access to the user&amp;#x2019;s account on an older session. Existing sessions must be invalidated before giving a user access to the application.
  21. Abhay: So, What does the new Java EE has to offer for the Triple A?? Dr. Kumar: Authentication and authorization part of the java web applications can be handled using the Services and APIs of JAAS - The Java Authentication and Authorization Services part of the Java Platform. The JAAS has evolved since a long time along with the platform and has been easing the pains of the web application developers using the Java Platform for Application Access Control Implementation. We focus, in this particular talk, on the advanced features of Java EE 6 and of the security aspects as applicable to a web application.
  22. Dr. Kumar: (Continue) As we are focusing on the web application security part, we will restrict our time in understanding the web application development part of the new security features in Java EE 6.&amp;#xA0;Again we will filter-out the non-java part (on things such as http-method-omissions, Filter Mappings etc). We will elucidate the servlet security feature that was introduced in Java EE 6. There are essentially three items that we need to focus - the authenticate() method, the login() method and logout() method. Also, note that their implementation as a part of the new GlassFish V3 app is complete and tested for the new Java EE 6 version.
  23. Dr. Kumar: (Continue) The authenticate() method is provided in the javax.servlet.http.HttpServletRequest&amp;#xA0; interface. This method is one of the&amp;#xA0; examples of programmatic security (login, in particular) in Java EE 6. It can be used as an alternative to the &lt;auth-constraint&gt;. When used in a servlet or a JSP, it forces authentication, using the login-mechanism specified in web.xml even if no security-constraint element is specified in the web.xml. After a call to authenticate succeeds, the user credentials are validated using appropriate methods(). Abhay: Oh! What are these methods and how do they help?? Dr. Kumar: The following methods provide the desired results for authentication part of the web application: (i) getRemoteUser(), (ii) isUserInRole(), (iii) getUserPrincipal() We will discuss aout these methods a little later during the Authorization part of the presentation. The advantage of using the authenticate method is that it provides the flexibility to login in dynamically combined with the ability to be used with the configured&amp;#xA0; login-mechanism like BASIC. Here is a sample code that illustrates the use of the new authenticate() method. On deploying the war file and accessing the servlet (http://&lt;server-name&gt;:&lt;port-number&gt;/application/test , a BASIC authentication is forced by the&amp;#xA0; container, since the call to authenticate() is made in the service method of the servlet.
  24. Dr. Kumar: (Continue) The other two related methods are login() and logout(). Note that they also throw ServletException. Similar to the authenticate() method, the login() method serves to authenticate a given username and password programmatically. This method throws a ServletException when the validation of username, password provided fails or if the caller identity has been already established before a call to this method or if the configured login mechanism (in web.xml) is does not support username, password validation. A recent fix was made to have the authentication state in the existing session after a successful login. The session is created if it does not exist at this time to store the auth state. In the orthogonal HttpServletRequest.logout() method, this authentication state is cleared from the session. Please note the servers need to appropriately implement these new features. For example the new GlassFish V3 takes care of the same. Notice that the&amp;#xA0;login() method allows to programmatically collect with the provided username/password credentials (as an alternative to FORM-based authentication) and perform user authentication. Similarly, the logout() method performs logging out the user and resets the context.
  25. Abhay: You just now completed the Authentication part. How about Authorization part in the new Java EE 6?? Dr. Kumar: We have a few new methods introduced which are very useful in the Authorization part of the application. After a call to authenticate() method succeeds, the user credentials can be validated and the following methods provide the desired results: Recall we mentioned it earlier that there are three of them. They are: (i) getRemoteUser() (ii) isUserInRole() (iii) getUserPrincipal()&amp;#xA0;
  26. Abhay: Can you elaborate on these methods in brief?? Dr. Kumar: Sure. Lets go with the first one, the getRemoteUser() method. The method getRemoteUser() - provides the name of the remote user associated with the request, as highlighted here. In this code snippet, we are just printing the remote user name....
  27. Dr. Kumar: (Continue) The next method is the isUserInRole() Method: This method determines if the remote user (that is, the caller) associated with the request is in a specified security role - returns true after a successful authenticate, provided the role is specified. We have provided a snap shot of the usage of validating whether the user is in a given role or not in this if statement.
  28. Dr. Kumar: (Continued) FInally the getUserPrincipal() method: This method determines the principal name of the remote user (that is, the caller) and returns a java.security.Principal object corresponding to the remote user. Here is the usage of the getUserPrincipal() method.
  29. Abhay: What about Annotations in the new Java EE 6 for web application development?? Dr. Kumar: The annotations part of the java has enter the Servlet world now. Accordingly we also have security related annotations (and the corresponding deployment descriptors) taking care of Security requirements for web applications. With Servlet 3.0 implementation, we would able to use standard Java annotations for declaring security constraints as equivalent to those defined in a standard Web deployment descriptor (web.xml). With Security annotation you should able to define roles, access control to HTTP methods, transport-layer protection (for enforcing&amp;#xA0;SSL/TLS). To make use of security annotations in Servlets, Servlet 3.0 has introduced @ServletSecurity annotation to support defining security constraints.
  30. Abhay: What other Annotations are available for web application development?? Dr. Kumar: The @ServletSecurity annotation allows to define the security constraints as its fields - @HTTPConstraint, @HTTPMethodConstraint. @DeclareRoles and @RoleAllowed. Abhay: Can you briefly mention how these annotations are used in the web application for handling the security?? Dr. Kumar: For example&amp;#xA0;use @HttpConstraint(rolesAllowed to ensure that all HTTP methods (GET, POST, TRACE) are protected and access is allowed to security role &amp;#x201C;customer&amp;#x201D; and @HttpConstraint annotation to ensure the methods require SSL transport. Similarly, we can use HttpMethodConstraints&amp;#xA0; to ensure only authenticated users with security role is allowed to access HTTP POST method and transport-layer security/SSL is supported but not required. Finally, the @DeclareRoles and @ RoleAllowed are a no brainer
  31. Dr. Kumar: (Contiuned) A Typical usage of the Servlet Annotations and their fields are shown in this slide.
  32. Dr. Kumar: Hey, you said something about an attack called CSRF. What is that???? Abhay: Let me give you Scenario: Let us say an attacker wants to hack your bank account and steal some money. He sends you an email with a URL, actioning a transfer to his account. Let us assume that you are logged into your email and your bank account simultaneously. You click on the link of the malicious email and a request is raised to the bank. The bank does not know that it is a phantom request coming from a phantom source. For the bank, you a currently logged in and the request is legit. The funds are transferred because the bank&amp;#x2019;s site was vulnerable to CSRF.
  33. Dr Kumar: How can this be prevented?? Abhay: This can be prevented in a few ways. One of the most effective ways is to raise a cryptographically secure string and store it in every user&amp;#x2019;s session object. The string should be accessed and made as an HTML hidden form field and submitted with every request that the user makes to the application. On the server side, the token submitted must be matched against the string in the session object. If it matches, the request should be considered legit. Usage of Java&amp;#x2019;s SecureRandom is ideal for these implementations.
  34. Abhay: Data is the reason why we are actually talking about security. While Access control is important to protect unauthorized access to data, it is also important to secure data when it is stored and transported as there are several attacks which are attempted by attackers to extract data at rest and in transit. Let us talk about these four topics on Data Protection....
  35. Dr. Kumar: Abhay, Why dont you tell us something about Crypto implementations for Web Apps? Abhay: One of the primary mistakes people make is to believe that the cryptographic algorithms they develop are way better than the industry standard algorithms out there and design their own encryption schemes. Once, I came across a developer who wanted to encrypt credit card numbers in his app by subtracting with one set of digits and adding with another set of digits. Please do not write home grown crypto. Strong Encryption algorithms need to be used to protect data at rest. Preferably AES-128 bit or above) or 3DES or in case of asymmetric crypto, keylengths of atleast 1024 bit. Apart from key and key parameters, it is very important to ensure that a single encryption key performs a single task, for instance, a key used to encrypt data should not be used as a key used to encrypt transmissions. Higher usage of the key results in higher possibility of a key compromise. Ensure that data at rest is stored with a key and and that key is encrypted with another key called the Key Encrypting Key. The data encryption key is more likely to be compromised, therefore there is an additional layer of security with the key encrypting key. It has to be ensured that the DEK and KEK are not stored in the same location.
  36. It is ideal if the key management process is driven from the application. In some cases, organizations dedicate specific key management servers or devices for key management, but that is a luxury. One of the golden rules of thumb is to never ever store key or key strings in the source code. I was assessing a banking application, where the developer had written down the key value in a serverside comment and their application was also vulnerable to a source code disclosure attack, where I could enter arbitrary strings and gain access to their source code on my browser. Finding a key encrypting millions of personal records is like gold for an attacker.... Asymmetric crypto requires a public-private key pair. And the private key, as the word goes needs to be kept private. Export of the private key should be disallowed. In many cases, encryption keys are generated, in some other cases, the key is a password or passphrase which is created by the key custodian(s). In such cases, the quality of the password must be compulsorily specified by the organization to ensure that the quality of the encryption key remains paramount.
  37. It is a moot point, when you take a great deal of care to store, manage keys and transport these keys across an unencrypted channel. Anyone sniffing the wire is likely to find the key in the traffic. All key transport should be across encrypted traffic. Needless to say, keys need to be changed. After a certain point the possibilities of a key being compromised are high and have to be changed.
  38. Abhay: How can we implement using Java?? Dr. Kumar: We have the JCA / JCE coming to our rescue, as usually. You know it is not at all new. The new Java EE 6 introduces several new features for Cryptography, Cipher and Encryption which eases the web application data security. The JCA / JCE provides an extensible, full featured API for building secure applications which are Algorithm and implementation independent in a provider-based (pluggable) architecture
  39. Dr. Kumar: (Continue) We already know JCA and JCE provide a wide range of cryptographic services such as digital signatures, message digest, symmetric and symmetric ciphers, stream and block ciphers, message authentication codes, key generators and key factories. These rich libraries also provide support for standard algorithms such as RSA, DSA, AES, Triple DES, SHA, PKCS#5, RC2 and RC4
  40. Abhay: Fine, but what are the new features specific to Java EE 6?? Dr. Kumar: Some of the new features specific to Java EE 6 (and not necessarily web application focused) are: Elliptic Curve Cryptography (ECC) in SunPKCS11 Elliptic Curve CipherSuites in SunJSSE Access Network Security Services (NSS) using SunPKCS11 Cipher Text Stealing (CTS) mode added to SunJCE block ciphers Removed the 2048 RSA keysize limit from local_policy.jar Access to native PKI and cryptographic services on Microsoft Windows -------Additional notes in case there are questions on specifics ------------- Elliptic Curve Cryptography (ECC) in SunPKCS11 (For elaboration in case of question - The SunPKCS11 provider now exposes ECC algorithms if the underlying PKCS#11 token supports them. This include ECDSA signing and verification, ECDH key agreement, and generation of EC keypairs. For more information about the supported mechanisms, see the supported algorithms section in the PKCS#11 reference guide.) Elliptic Curve CipherSuites in SunJSSE (For elaboration in case of question - The SunJSSE now supports the ECC ciphersuites defined in RFC 4492, if a suitable crypto provider is available (for example, SunPKCS11 with an appropriate PKCS#11 library) Access Network Security Services (NSS) using SunPKCS11 (For elaboration in case of question - The SunPKCS11 provider supports new configuration directives which allow it to access the NSS security library. This enables Java applications to read keys stored in the NSS database files, use ECC algorithms, and to use the NSS Softtoken as a FIPS 140 compliant cryptography provider) Cipher Text Stealing (CTS) mode added to SunJCE block ciphers (For elaboration in case of question - CTS is described in Bruce Schneier&apos;s book &quot;Applied Cryptography-Second Edition&quot;, John Wiley and is used by some Kerberos implementations) Removed the 2048 RSA keysize limit from local_policy.jar (For elaboration in case of question - Implementations were previously restricted from obtaining RSA keys larger than 2048 bits without installing the unlimited crypto policy files) Access to native PKI and cryptographic services on Microsoft Windows Added the SunMSCAPI JCE provider which uses the Microsoft CryptoAPI (CAPI) to offer a variety of RSA cryptographic functions. It acts as a bridge between Java applications and the services offered by the default RSA cryptographic service provider available via CAPI. It provides access to X.509 certificates and RSA key pairs, it performs RSA encryption and decryption, and it creates and validates RSA signatures. It also supports a cryptographic random number generator)
  41. Dr. Kumar: Abhay, didnt you mention another data protection technique that you wanted to talk about? Abhay: Yes, Hashing is another important data protection technique for data at rest. Hashing as some of you may know, is a one way operation, in that the data once hashed cannot be regenerated as in the case of encryption. In many ways hashing is better as the data is subjected to a one-way procedure and it can be validated with queries and other processes. It is common practice to hash passwords in web apps. Having said that it is imperative that strong hashing algorithms upwards of SHA-1 be used. It was proved recently, that MD5 an extremely popular hash algorithm was broken and proven non-secure. So, please change your hashing algos if you are using MD5. A Salt is not for food in the case of hashing. Salt is a nonce or a string that is used to add a greater degree of randomness to the hash value. Adding a salt prevents collision of hash values of similar data, thereby adding an extra measure of security to the hashed information.
  42. Dr. Kumar: Abhay, what about Logging implementation for Web Apps? Abhay: Logging is considered by many to be an unnecessary resource. But imagine this, your application is hacked with a SQL Injection attack and the attacker consistently extracts information out of the database for 6 months and you finally figure it out and want to look for the source and starting point of this attack, the only thing that will tell you this are the logs. This story was a real life incident at one of the largest universities in california, not too far from here.... Logging currently is not a part of the Java Security Requirements. However, we believe that it should be and we have also made a special mention of the same in our book. What should be logged, (READ OUT)
  43. Abhay: Dr. Kumar, can you throw some light on the logging features of the new Java??Dr. Kumar: Sure. We already aware that the java.util.logging libraries can help in doing the necessary activities such as servicing, maintenance and security log report generation. These APIs help in capturing the information on security failures, configuration and other errors and exceptions, etc
  44. Abhay: Secure Coding is one of the most important facets of Secure Web Application Development, in fact, most attacks are successful against a web application due to the lack of secure coding practices used by developers of these apps. There are quite a few ways to write Secure Code, but we will explore some of the critical requirements from a Secure Coding standpoint and they are....
  45. Input validation is a swiss knife against web application attacks. It is a cure for most evils out there. Input validation essentially refers to the process of ensuring that the application receives consistent and correct input that ensures that the processing of the input is smooth and without hindrance. Injection attacks are mostly perpetrated due to lack of input validation where an attacker can enter malicious characters and carry out the attack. First step to input validation is to understand all the input to the application, whether it is from user or from a webservice, or other site, or file. All input needs to be identified, text input, checkboxes, radio buttons can all be manipulated to inject if note validated. Regular expressions should be used to validate input. Let us suppose that you want to validate an email address, a regular expression with the java.util.regex library can be used for creating the reg ex and validating the user input based on the regex. Need I say, that Input Validation has to be done server side and not client side with JavaScript because of that one word : Client side. There are 2 approaches to validating input. One is a black list where one needs to identify all the characters deemed as contraband and filter the application input based on these known bad characters. The other is the whitelist, which is a highly recommended approach. Whitelisting allows you to create a known-good set of characters that one can use to filter input. For instance if you would like to filter a username field, you would filter it to only allow letters, numbers and perhaps underscore. This is a better approach than blacklisting, because you cannot effectively ensure 100% protection against attacks in a blacklisting approach as there are several injection attacks that can be encoded differently for the attack to be successful.
  46. This is a clear example of a Input Validation fail. As you can see that the developer is just picking up raw input parameters here....
  47. and redirecting the same to another page without filtering anything on the server side.
  48. Abhay: Dr Kumar: For Input validation, we have the usual classes from the java.util.regex and the java.text libraries of the Java Standard edition which can be used as appropriately. The Matcher and Pattern classes of the java.util.regex package helps us in matching character sequences against patterns specified by regular expressions. Similarly, the Normalizer class in the java.text package provides the method normalize which transforms Unicode text into an equivalent composed or decomposed form, allowing for easier sorting and searching of text. The normalize method supports the standard normalization forms described in the Unicode Normalized forms. Specifically for the web components, we have the HttpServletRequestWrapper class, whose methods are useful in wrapping the given HTTPServletRequest object for processing the data input for validation. And, of-course, we have the Filter interface which can help us in designing a validating filter.
  49. Dr. Kumar: (Continued) Here are some examples of the HTTPServletRequest wrapper and the use of suitable methods for Input validation. In this example, the matches() method is used on the canonicalized input data.
  50. Output Encoding is a complementary control to Input Validation. Output when not encoded/inconsistently encoded, creates a scenario where the attacker&amp;#x2019;s script injection is executed because the application interprets the input as html and the browser executes the script. However, if the output is explicitly encoded and all special characters (malicious characters are encoded) then the script is taken to be regular input and the special characters will be replaced with the encoded character, thereby rendering a potentially deadly script injection attack useless.
  51. Abhay: (Question) Dr. Kumar: For Output encoding we have the URLEncoder class from the java.net package for the HTML form encoding. The static encode method converting a String object to the application/x-www-form-urlencoded MIME format. Although not a part of the Java EE 6 part we are discussing, we have some interesting libraries from apache.commons.lang whose StringEscapeUtils class provides a number of methods to Escapes and unescapes String objects for Java, Java Script, HTML, XML, and SQL. The ResponeUtils class of the Struts framework (of the yesteryears) can also be highlighted here. General purpose utility methods of this class is related to generating a servlet response in the Struts controller framework.
  52. Here are the results of an application without output encoding
  53. The scenario changes wildly when there is output encoding and the special characters are escaped.
  54. Databases are the most targeted sources of data today and SQL injection is the deadliest attack out there. Input Validation helps greatly in alleviating the problems of SQL Injection by filtering malicious SQL oriented input containing quotes and semicolons. However, as a complementary control it is necessary that all SQL queries of the app are done using PreparedStatements as opposed to dynamically generating a SQL query using the input parameters.