SlideShare una empresa de Scribd logo
1 de 41
PCI Security Requirements

                Haitham Raik
Agenda
   Overview
   Information leakage and improper error handling
   Cross Site Scripting (XSS)
   Injection Flaws
   Malicious File Execution
   Insecure Direct Object References
   Cross Site Request Forgery (CSRF)
   Failure to Restrict URL Access
   Broken Authentication and Session Management
Overview
   PCI DSS is a security standard that includes
    requirements for:
       security management,
       policies,
       procedures,
       network architecture,
       software design and other critical protective measures
   PCI DSS purpose: to help the organizations to
    protect customer account data.
   This session doesn‟t cover all the security
    requirements.
   This session covers only what has impact on our
    code.
Information Leakage and improper error
handling
   Definition: Providing too much information to the
    user when an error occurs.
   Examples:
       An error message with too much detail
           Stack trace
           Failed SQL statement
       Functions that produce different error messages/codes
        based upon different inputs
           Invalid username
           Invalid password
Information Leakage and improper error
handling Protection
   Write detailed error information to secure Log.
   Configure an exception handler in the web.xml for all
    un-handled exceptions
<error-page>
        <exception-type>java.lang.Throwable</exception-type>
        <location>/error.jsp</location>
</error-page>

   Always give generic error;
       “The username/password is not correct”.
       “Merchant Authentication Failed”
Cross Site Scripting (XSS)
   XSS: Describes the act of embedding malicious
    HTML/JavaScript code in dynamically generated
    pages based on invalidated input from untrustworthy
    sources.
Cross Site Scripting (XSS)
   XSS is the most common vulnerability
   XSS impact:
       Data on a page can be stolen and sent anywhere.
       Your Website behavior can be altered.
   Types of XSS
       Reflected XSS; reflects user input (manipulate user input)
out.writeln(“You input is:”+request.getParamter(“userInput”))

       Stored XSS; attackers script is stored on server (e.g.
        blogs)
out.writeln(“Comment: ”+blog.comment);
Cross Site Scripting (XSS) Protection
   Input Validation; Checking each input for validity
       Accept known good:
           Accept valid input types.
           Accept valid input lengths.
           Accept valid input patterns; e.g., phone pattern.
       Reject known bad
           Reject input values with bad characters and patterns; for
            example: <script>
       Sanitize
           Rather than accept or reject input, change the input to an
            acceptable format.
   Set the HTTPOnly flag on your session cookie
        Cookie with this flag cannot be accessed through client
        script
Cross-Site Scripting (XSS) Protection
   Output Escaping (Encoding): is a technique used to
    ensure that characters are treated as data, not as
    characters that are relevant to the interpreter's
    parser.
       HTML Escape: <body>...ESCAPE       UNTRUSTED DATA BEFORE
        PUTTING HERE...</body>
           (&  &amp;) (<  &lt;)   (>  &gt;)   (“  &quot;)   („ 
            &#x27; ) (/  &#x2F;)
       Attribute Escape: <div  attr='...ESCAPE UNTRUSTED DATA BEFORE
        PUTTING HERE...'>content</div>
       Javascript Escape: <script>x='...ESCAPE     UNTRUSTED DATA
        BEFORE PUTTING HERE...'</script>
       CSS Escape
       URL Escape: <a
        href="http://www.somesite.com?test=...ESCAPE UNTRUSTED
        DATA BEFORE PUTTING HERE...">link</a >
Cross-Site Scripting (XSS) Protection
   Input Validation using ESAPI:
boolean isValidFirstName =
ESAPI.validator().isValidInput("FirstName",
request.getParameter("FirstName"), "FirstNameRegex", 255,
false);

 Sanitize using AntiSamy
import org.owasp.validator.html.*;
Policy policy =
Policy.getInstance(POLICY_FILE_LOCATION);
AntiSamy as = new AntiSamy();
CleanResults cr = as.scan(dirtyInput, policy);
MyUserDAO.storeUserProfile(cr.getCleanHTML());
Cross-Site Scripting (XSS) Protection
   Set HttpOnly
       Before Servlet v3:
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid +
"; HttpOnly");
       Servlet v3:
<session-config>
    <cookie-config>
        <http-only>true</http-only>
    </cookie-config>
<session-config>


   Output Escaping using ESAPI:
<p>Hello, <%=name%></p>

//performing output encoding for the HTML context String
<p>Hello, <%=ESAPI.encoder().encodeForHTML(name)%></p>
Injection Flaws
   Definition: Attacker modifies a query/command that
    is executed by target interpreter
   Injection applies to:
       SQL injection
       XPATH injection
       LDAP injection
Injection Flaws
   SQL Injection:
       SQL Statement for Authentication: StringsqlString =
        "SELECT * FROM users WHERE fullname = '" +
        form.getFullName() + "' AND password = '" +
        form.getPassword() + "'";
       User Input:
        Case 1: full name: Haitham, password: 123pass
        Result: SELECT * FROM users WHERE username = „Haitham'
        AND password = '123pass'
        Case 2: full name: Ala' Ahmad, password: 123pass
        Result: SELECT * FROM users WHERE username = 'Ala'
        Ahmad' AND password = „13pass'
        Case 3: full name: blah, password: ' OR '1' = '1
        Result: SELECT * FROM users WHERE username = 'blah' AND
        password = '' OR '1' = '1'
Injection Flaws
   XPATH Injection
       XML file:
<?xml version="1.0" encoding="utf-8"?>
<employees>
          <employee id="AS1" firstname="John" salary=“100"/>
          <employee id="AS2" firstname=“Adam“ salary=“200"/>
</employees>
       XPATH expression:  String exp =
        “/employees/employee[@id=„”+form.getEID()+”']”
    User Input: Emp_ID=„ or '1'='1
    Result: /employees/employee[@id=„„ or '1'='1']
Injection Flaws Protection
   SQL Injection Protection using:
       Use prepared statements/parameterized queries (don‟t use
        concatenation while building the SQL stmt)
String stmt = “select * from emp where id=?”;
PreparedStatement pstmt = con.prepareStatement(stmt);
pstmt.setString(1, empId);
       Use stored procedures
       SQL Escape using ESAPI
Codec ORACLE_CODEC = new OracleCodec();
String query = "SELECT name FROM users WHERE id = "+
   ESAPI.encoder().encodeForSQL(ORACLE_CODEC, userId)+
   " AND date_created >= '"+
   ESAPI.encoder().encodeForSQL(ORACLE_CODEC, date)+
   "'";
myStmt = conn.createStatement(query);
Injection Flaws Protection
   Hibernate Injection Protection
       Use named parameters
       Use Criteria API
Injection Flaws Protection
   XPATH Injection Protection
      User input must not contain any of the following
       characters:
    ( ) = ' [ ] : , * / WHITESPACE
     XPATH Injection protection using ESAPI
    String exp = “/employees/employee[@id=„”+
    ESAPI.encoder().encodeForXPath(form.getEID())+
    ”']”
Malicious File Execution
   Definition: occurs when attacker's files are executed
    or processed by the web server.
   Expected Threats:
       Malicious file (e.g., script) can be executed on the
        application server
       Access to a configuration file
       Override a configuration file
       Fill up the filesystem
   This happen when
       Filename is accepted from the user without validation
       File is uploaded without validation
Malicious File Execution
   Example:
       Code Snippet
// get the absolute file path on the server's filesystem
String dir =
servlet.getServletContext().getRealPath("/ebanking")
// get input file name
String file = request.getParameter(“file”);
// Create a new File instance from pathname string
File f = new File((dir + "" + file).replaceAll("",
"/"));
    User Input: ../../web.xml
    Result: it will allow access to web server configuration file
Malicious File Execution Protection
   Filename Validation
   File Type Validation
   Size Validation
   Don‟t allow the user to influence the final filename.
   Upload files to a destination outside of the web
    application directory
Malicious File Execution Protection
   Filename and file type validation using ESAPI
ESAPI.validator().isValidFileName("upload", filename,
allowedExtensions, false));

   Size Validation using Commons-FileUpload:
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxBytes);
Direct Object References (DOR)
   DOR occurs when a developer exposes a reference
    to an internal implementation:
       Object
       File or Directory
       Database record
   Attacker can manipulate object references to access
    other objects without authorization.
   For Example:
       URL (or form parameter) to my banking account is:
        /accounts/viewDetail?id=3540
       What will happen if I changed this to
       /accounts/viewDetail?id=3541
Direct Object References (DOR) Protection
   Avoid exposing direct object references
       Use Indirect Object References
   Verify Authorization to all referenced objects
Direct Object References (DOR) Protection
 Indirect Object Reference using ESAPI
//create ESAPI random access reference map
AccessReferenceMap map = new
RandomAccessReferenceMap();

//get indirect reference using direct reference
String indirectReference =
map.addDirectReference(obj.getId());

//set indirect reference for each object - requires
your app object to have this method
obj.setIndirectReference(indirectReference);

// Store the map in the session
Direct Object References (DOR) Protection
   Verify Authorization
       For example:
           Before: select * from accounts where accNum = ?
           After: select * from accounts where accNum = ? And userId = ?
Direct Object References (DOR) Protection
   Authorization vs Indirect object reference
       Authorization:
           May require an extra DB hit
           Exposes actual ID
       Indirect object reference
           May not require an extra DB hit
           Hides actual ID
           Requires a bit of extra coding and some extra information
           Not very popular
Cross Site Request Forgery (CSRF)
   CSRF: forces logged-in victim to send a request to a
    vulnerable web application, which then performs
    action on behalf of the victim.
   Sample CSRF Scenario:
       A hacker posts to a blog containing an image tag (blog
        site allows XSS)
    <img
    src=“http://www.yourbank.com/transfer?to_acc=hacker_acc_
    num&amount=1000”/>
       User logs into yourbank.com (session is active for user)
       User visits the blog (without logging from yourbank.com)
       Loading the image will send request to the bank site
       The bank will transfer the user‟s money to hacker‟s
        account
Cross Site Request Forgery (CSRF)
Protection
   Make sure there are no XSS vulnerabilities in your
    application; refer to XSS protection slides.
   Do not use GET requests to perform transactional
    operations.
       Javascript can be used to create auto submit POST
        forms.
   Check the referrer header. Shows where the request
    originated
       This is optional and the user can disable it.
   For sensitive transactions, re-authenticate.
   Add a confirmation page.
Cross Site Request Forgery (CSRF)
Protection
   Insert custom random tokens into every form and
    URL
       Generate CSRF token
       Store user in http session
       On any form/URL add the token as a parameter/hidden
        field.
       On the server, check the submitted token matches the
        token form.
       On logout, the CSRF token is removed.
Cross Site Request Forgery (CSRF)
Protection
 Do not use GET requests
public void doGet(HttpServletRequest req,
HttpServletResponse resp) {
       throw new Exception(“Invalid operation”);
}
   Check the referrer header using
    HTTPServletRequest:
String referer = request.getHeader(“Referer”);
if (referer != null && referer != “our trusted
link”) {
      session.invalidate();
      throw new Exception();
}
Cross Site Request Forgery (CSRF)
Protection
   Implementing CSRF tokens using ESAPI
// To generate CSRF token
String csrfToken = ESAPI.randomizer().getRandomString(8,
DefaultEncoder.CHAR_ALPHANUMERICS);


// After user authentication, add token to user‟s session
request.getSession().setAttribute(“csrfToken”, csrfToken);


// To Validate a Token; this code can be added a filter
String requestToken = request.getParameter(“csrfToken”);
String sessionToken = session.getAttribute(“csrfToken”);
if (!requestToken.equals(sessionToken)) {
    throw new Exception(“Invalid CSRF Token”);
}
Cross Site Request Forgery (CSRF)
Protection
// At logout, delete the session which removes its content
HttpSession session = request.getSession(false);
if (session != null) {
        session.invalidate();
}


   Implementing CSRF tokens using CSRFGuard
    project via ServletFilters
       Tokens are automatically generated, managed, verified,
        and inserted
           Copy Owasp.CsrfGuard.jar file to your application‟s classpath
           Declate CsrfGuard in web.xml
           Configure the Owasp.CsrfGuard.properties file as you see fit
Failure to Restrict URL Access
   Attacker, who is an authorized user, simply changes
    the URL to a privileged page.
       URL is not protected with authorization.
   Just because your URL is hard to guess, doesn‟t
    mean it can‟t be found!
   Example:
       “hidden” URLs rendered only to admins
        /admin/adduser.do
           Attacker can find unprotected URLs
       Test pages deployed in production
       “hidden” files such as system reports
Failure to Restrict URL Access Protection
   Create Access Control Matrix for your Application:
                            Function 1    Function 2    Function 3
           PG Admin         Read, write   Read, Write   Read,
                                                        Write
           Acquirer Admin   Read          Read, Write   Read,
                                                        Write
       Access Control Matrix shouldReadeasily configured
           Bank Admin                be          Read,
   For each request, ensure that the userWrite
                                              is authorized
    to access that function.
   Block access to all file types that your application
    should never serve
   Put all your UI files under /WEB-INF
Broken Authentication & Session
Management
   Flaws in this area most frequently involve the failure
    to protect credentials and session tokens through
    their lifecycle
   If this issue is not properly addressed, many issues
    arise:
       Account hijacked
       Credentials stolen
       Privacy violation
Broken Authentication & Session
Management Protection
   Use the build-in session management
       Utilize SSL / TLS Session identifier
   With regards to authentication:
       Use a single authentication point
       Invalidate the HttpSession before login and after login to
        prevent session fixation
   Make sure logout function invalidate the session
   Add a session time-out
   Do not expose any session identifiers in URLs or
    logs
   Check the old password when the user changes to a
    new password
Broken Authentication & Session
Management Protection
   Prevent brute force attacks by limiting the number of
    attempts
   Destroy session if Referrer is suspicious (see CSRF)
   Regenerate session if remote IP changed
   Regenerate session if user agent changed
Broken Authentication & Session
Management Protection
 Invalidate Session:
request.getSession(false).invalidate();
   Session Timeout:
       Programmatically:
session.setMaxInactiveInterval(20*60);
       Using web.xml:
<web-app ...>
    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>
</web-app>
Broken Authentication & Session
Management Protection
    Regenerate session if remote IP changed
String preRemoteIP = session.getAttribute(“RemoteIP”);
String remoteIP = request.getRemoteAddr();
if (!preRemoteIP.equals(remoteIP)) {//read atts
session.invalidate();
}
session = request.getSession(true);//write atts


String preRemoteIP = session.getAttribute(“RemoteIP”);
String remoteIP = request.getRemoteAddr();
if (!preRemoteIP.equals(remoteIP)) {
    HTTPUtilities esapiHTTPUtilities = ESAPI.httpUtilities();
    esapiHTTPUtilities.setCurrentHTTP(request, response);
    esapiHTTPUtilities.changeSessionIdentifier();
}
Broken Authentication & Session
Management Protection
    Regenerate session if user agent changed
String preUserAgent = session.getAttribute(“UserAgent”);
String userAgent = request.getHeader("user-agent");
if (! preUserAgent.equals(userAgent)) {
    HTTPUtilities esapiHTTPUtilities = ESAPI.httpUtilities();
    esapiHTTPUtilities.setCurrentHTTP(request, response);
    esapiHTTPUtilities.changeSessionIdentifier();
}
   What is Next?

Más contenido relacionado

La actualidad más candente

Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesCarol McDonald
 
Steps to mitigate Top 5 OWASP Vulnerabilities 2013
Steps to mitigate Top 5 OWASP Vulnerabilities 2013Steps to mitigate Top 5 OWASP Vulnerabilities 2013
Steps to mitigate Top 5 OWASP Vulnerabilities 2013Jayasree Veliyath
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10bilcorry
 
OWASP Serbia - A3 broken authentication and session management
OWASP Serbia - A3 broken authentication and session managementOWASP Serbia - A3 broken authentication and session management
OWASP Serbia - A3 broken authentication and session managementNikola Milosevic
 
Session10-PHP Misconfiguration
Session10-PHP MisconfigurationSession10-PHP Misconfiguration
Session10-PHP Misconfigurationzakieh alizadeh
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Brian Huff
 
OWASP Serbia - A5 cross-site request forgery
OWASP Serbia - A5 cross-site request forgeryOWASP Serbia - A5 cross-site request forgery
OWASP Serbia - A5 cross-site request forgeryNikola Milosevic
 
Wakanda and the top 5 security risks - JS.everyrwhere(2012) Europe
Wakanda and the top 5 security risks - JS.everyrwhere(2012) EuropeWakanda and the top 5 security risks - JS.everyrwhere(2012) Europe
Wakanda and the top 5 security risks - JS.everyrwhere(2012) EuropeAlexandre Morgaut
 
OWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsOWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsKaty Anton
 
OWASP top 10-2013
OWASP top 10-2013OWASP top 10-2013
OWASP top 10-2013tmd800
 
Web Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or SucceedWeb Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or SucceedPrathan Phongthiproek
 
Secure code practices
Secure code practicesSecure code practices
Secure code practicesHina Rawal
 
Top 10 Web Application vulnerabilities
Top 10 Web Application vulnerabilitiesTop 10 Web Application vulnerabilities
Top 10 Web Application vulnerabilitiesTerrance Medina
 
Cross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with JavaCross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with JavaJim Manico
 

La actualidad más candente (20)

Top 10 Web Security Vulnerabilities
Top 10 Web Security VulnerabilitiesTop 10 Web Security Vulnerabilities
Top 10 Web Security Vulnerabilities
 
Steps to mitigate Top 5 OWASP Vulnerabilities 2013
Steps to mitigate Top 5 OWASP Vulnerabilities 2013Steps to mitigate Top 5 OWASP Vulnerabilities 2013
Steps to mitigate Top 5 OWASP Vulnerabilities 2013
 
2013 OWASP Top 10
2013 OWASP Top 102013 OWASP Top 10
2013 OWASP Top 10
 
Owasp webgoat
Owasp webgoatOwasp webgoat
Owasp webgoat
 
OWASP Serbia - A3 broken authentication and session management
OWASP Serbia - A3 broken authentication and session managementOWASP Serbia - A3 broken authentication and session management
OWASP Serbia - A3 broken authentication and session management
 
Session10-PHP Misconfiguration
Session10-PHP MisconfigurationSession10-PHP Misconfiguration
Session10-PHP Misconfiguration
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
OWASP Serbia - A5 cross-site request forgery
OWASP Serbia - A5 cross-site request forgeryOWASP Serbia - A5 cross-site request forgery
OWASP Serbia - A5 cross-site request forgery
 
Owasp top 10 2013
Owasp top 10 2013Owasp top 10 2013
Owasp top 10 2013
 
Wakanda and the top 5 security risks - JS.everyrwhere(2012) Europe
Wakanda and the top 5 security risks - JS.everyrwhere(2012) EuropeWakanda and the top 5 security risks - JS.everyrwhere(2012) Europe
Wakanda and the top 5 security risks - JS.everyrwhere(2012) Europe
 
OWASP Top 10 Proactive Controls
OWASP Top 10 Proactive ControlsOWASP Top 10 Proactive Controls
OWASP Top 10 Proactive Controls
 
S5-Authorization
S5-AuthorizationS5-Authorization
S5-Authorization
 
Session4-Authentication
Session4-AuthenticationSession4-Authentication
Session4-Authentication
 
OWASP top 10-2013
OWASP top 10-2013OWASP top 10-2013
OWASP top 10-2013
 
Owasp top 10_-_2010 presentation
Owasp top 10_-_2010 presentationOwasp top 10_-_2010 presentation
Owasp top 10_-_2010 presentation
 
Web Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or SucceedWeb Application Firewall: Suckseed or Succeed
Web Application Firewall: Suckseed or Succeed
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 
Attques web
Attques webAttques web
Attques web
 
Top 10 Web Application vulnerabilities
Top 10 Web Application vulnerabilitiesTop 10 Web Application vulnerabilities
Top 10 Web Application vulnerabilities
 
Cross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with JavaCross Site Scripting (XSS) Defense with Java
Cross Site Scripting (XSS) Defense with Java
 

Destacado

A insolvência e o direito dos trabalhadores
A insolvência e o direito dos trabalhadoresA insolvência e o direito dos trabalhadores
A insolvência e o direito dos trabalhadoresPaulo Susano
 
Írások kapásból - Orbán Viktor és a székely Berde Mózsa
Írások kapásból - Orbán Viktor és a székely Berde MózsaÍrások kapásból - Orbán Viktor és a székely Berde Mózsa
Írások kapásból - Orbán Viktor és a székely Berde MózsaNagy Attila (Mihai)
 
Economia politica-alimentaria-2 Diana laura cortez quiroz
Economia politica-alimentaria-2 Diana laura cortez  quiroz Economia politica-alimentaria-2 Diana laura cortez  quiroz
Economia politica-alimentaria-2 Diana laura cortez quiroz yosehlim96
 
Повышение конкуренции на рынке труда: как остаться востребованным специалисто...
Повышение конкуренции на рынке труда: как остаться востребованным специалисто...Повышение конкуренции на рынке труда: как остаться востребованным специалисто...
Повышение конкуренции на рынке труда: как остаться востребованным специалисто...Cisco Russia
 
Changing active to passive voice
Changing active to passive voiceChanging active to passive voice
Changing active to passive voiceJoey Valdriz
 
Bioq, da lactaçao
Bioq, da lactaçaoBioq, da lactaçao
Bioq, da lactaçaocamila felix
 

Destacado (12)

Presentation1
Presentation1Presentation1
Presentation1
 
3
33
3
 
A insolvência e o direito dos trabalhadores
A insolvência e o direito dos trabalhadoresA insolvência e o direito dos trabalhadores
A insolvência e o direito dos trabalhadores
 
Írások kapásból - Orbán Viktor és a székely Berde Mózsa
Írások kapásból - Orbán Viktor és a székely Berde MózsaÍrások kapásból - Orbán Viktor és a székely Berde Mózsa
Írások kapásból - Orbán Viktor és a székely Berde Mózsa
 
sunu
sunusunu
sunu
 
Economia y politica alimentaria
Economia y politica alimentariaEconomia y politica alimentaria
Economia y politica alimentaria
 
Economia politica-alimentaria-2 Diana laura cortez quiroz
Economia politica-alimentaria-2 Diana laura cortez  quiroz Economia politica-alimentaria-2 Diana laura cortez  quiroz
Economia politica-alimentaria-2 Diana laura cortez quiroz
 
Повышение конкуренции на рынке труда: как остаться востребованным специалисто...
Повышение конкуренции на рынке труда: как остаться востребованным специалисто...Повышение конкуренции на рынке труда: как остаться востребованным специалисто...
Повышение конкуренции на рынке труда: как остаться востребованным специалисто...
 
my ppt IMP
my ppt IMPmy ppt IMP
my ppt IMP
 
SM-Twittometro KEIKO FUJIMORI
SM-Twittometro KEIKO FUJIMORISM-Twittometro KEIKO FUJIMORI
SM-Twittometro KEIKO FUJIMORI
 
Changing active to passive voice
Changing active to passive voiceChanging active to passive voice
Changing active to passive voice
 
Bioq, da lactaçao
Bioq, da lactaçaoBioq, da lactaçao
Bioq, da lactaçao
 

Similar a PCI Security Requirements - secure coding

Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code HardeningOdoo
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And AnishOSSCube
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009mirahman
 
Protecting Your Web Site From SQL Injection & XSS
Protecting Your Web SiteFrom SQL Injection & XSSProtecting Your Web SiteFrom SQL Injection & XSS
Protecting Your Web Site From SQL Injection & XSSskyhawk133
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application SecurityRob Ragan
 
Application Security
Application SecurityApplication Security
Application Securitynirola
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Securityjemond
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applicationsDevnology
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web AppsFrank Kim
 
Security Testing For Web Applications
Security Testing For Web ApplicationsSecurity Testing For Web Applications
Security Testing For Web ApplicationsVladimir Soghoyan
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web SecurityChris Shiflett
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net ProgrammingAdam Getchell
 
04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encodingEoin Keary
 
Secure Code Warrior - Insufficient data encoding
Secure Code Warrior - Insufficient data encodingSecure Code Warrior - Insufficient data encoding
Secure Code Warrior - Insufficient data encodingSecure Code Warrior
 

Similar a PCI Security Requirements - secure coding (20)

Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
ASP.NET Web Security
ASP.NET Web SecurityASP.NET Web Security
ASP.NET Web Security
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
 
Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009Php & Web Security - PHPXperts 2009
Php & Web Security - PHPXperts 2009
 
Protecting Your Web Site From SQL Injection & XSS
Protecting Your Web SiteFrom SQL Injection & XSSProtecting Your Web SiteFrom SQL Injection & XSS
Protecting Your Web Site From SQL Injection & XSS
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application Security
 
XSS
XSSXSS
XSS
 
Application Security
Application SecurityApplication Security
Application Security
 
General Principles of Web Security
General Principles of Web SecurityGeneral Principles of Web Security
General Principles of Web Security
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Securing Java EE Web Apps
Securing Java EE Web AppsSecuring Java EE Web Apps
Securing Java EE Web Apps
 
Security Testing For Web Applications
Security Testing For Web ApplicationsSecurity Testing For Web Applications
Security Testing For Web Applications
 
Evolution Of Web Security
Evolution Of Web SecurityEvolution Of Web Security
Evolution Of Web Security
 
State management
State managementState management
State management
 
Web Security 101
Web Security 101Web Security 101
Web Security 101
 
Secure Dot Net Programming
Secure Dot Net ProgrammingSecure Dot Net Programming
Secure Dot Net Programming
 
04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encoding
 
Secure Code Warrior - Insufficient data encoding
Secure Code Warrior - Insufficient data encodingSecure Code Warrior - Insufficient data encoding
Secure Code Warrior - Insufficient data encoding
 
Rails Security
Rails SecurityRails Security
Rails Security
 

Más de Haitham Raik

History of Software Architecture
History of Software ArchitectureHistory of Software Architecture
History of Software ArchitectureHaitham Raik
 
Unified Microservices Patterns List
Unified Microservices Patterns ListUnified Microservices Patterns List
Unified Microservices Patterns ListHaitham Raik
 
Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2Haitham Raik
 
Red hat linux essentials
Red hat linux essentialsRed hat linux essentials
Red hat linux essentialsHaitham Raik
 
Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Haitham Raik
 
Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1Haitham Raik
 
IBM OOAD Part1 Summary
IBM OOAD Part1 SummaryIBM OOAD Part1 Summary
IBM OOAD Part1 SummaryHaitham Raik
 
Advanced Hibernate
Advanced HibernateAdvanced Hibernate
Advanced HibernateHaitham Raik
 

Más de Haitham Raik (11)

History of Software Architecture
History of Software ArchitectureHistory of Software Architecture
History of Software Architecture
 
Unified Microservices Patterns List
Unified Microservices Patterns ListUnified Microservices Patterns List
Unified Microservices Patterns List
 
GIT In Detail
GIT In DetailGIT In Detail
GIT In Detail
 
Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2
 
Red hat linux essentials
Red hat linux essentialsRed hat linux essentials
Red hat linux essentials
 
Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2Object Oriented Analysis and Design with UML2 part2
Object Oriented Analysis and Design with UML2 part2
 
Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1Object Oriented Analysis and Design with UML2 part1
Object Oriented Analysis and Design with UML2 part1
 
IBM OOAD Part1 Summary
IBM OOAD Part1 SummaryIBM OOAD Part1 Summary
IBM OOAD Part1 Summary
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
JMX
JMXJMX
JMX
 
Advanced Hibernate
Advanced HibernateAdvanced Hibernate
Advanced Hibernate
 

Último

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

PCI Security Requirements - secure coding

  • 2. Agenda  Overview  Information leakage and improper error handling  Cross Site Scripting (XSS)  Injection Flaws  Malicious File Execution  Insecure Direct Object References  Cross Site Request Forgery (CSRF)  Failure to Restrict URL Access  Broken Authentication and Session Management
  • 3. Overview  PCI DSS is a security standard that includes requirements for:  security management,  policies,  procedures,  network architecture,  software design and other critical protective measures  PCI DSS purpose: to help the organizations to protect customer account data.  This session doesn‟t cover all the security requirements.  This session covers only what has impact on our code.
  • 4. Information Leakage and improper error handling  Definition: Providing too much information to the user when an error occurs.  Examples:  An error message with too much detail  Stack trace  Failed SQL statement  Functions that produce different error messages/codes based upon different inputs  Invalid username  Invalid password
  • 5. Information Leakage and improper error handling Protection  Write detailed error information to secure Log.  Configure an exception handler in the web.xml for all un-handled exceptions <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.jsp</location> </error-page>  Always give generic error;  “The username/password is not correct”.  “Merchant Authentication Failed”
  • 6. Cross Site Scripting (XSS)  XSS: Describes the act of embedding malicious HTML/JavaScript code in dynamically generated pages based on invalidated input from untrustworthy sources.
  • 7. Cross Site Scripting (XSS)  XSS is the most common vulnerability  XSS impact:  Data on a page can be stolen and sent anywhere.  Your Website behavior can be altered.  Types of XSS  Reflected XSS; reflects user input (manipulate user input) out.writeln(“You input is:”+request.getParamter(“userInput”))  Stored XSS; attackers script is stored on server (e.g. blogs) out.writeln(“Comment: ”+blog.comment);
  • 8. Cross Site Scripting (XSS) Protection  Input Validation; Checking each input for validity  Accept known good:  Accept valid input types.  Accept valid input lengths.  Accept valid input patterns; e.g., phone pattern.  Reject known bad  Reject input values with bad characters and patterns; for example: <script>  Sanitize  Rather than accept or reject input, change the input to an acceptable format.  Set the HTTPOnly flag on your session cookie  Cookie with this flag cannot be accessed through client script
  • 9. Cross-Site Scripting (XSS) Protection  Output Escaping (Encoding): is a technique used to ensure that characters are treated as data, not as characters that are relevant to the interpreter's parser.  HTML Escape: <body>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</body>  (&  &amp;) (<  &lt;) (>  &gt;) (“  &quot;) („  &#x27; ) (/  &#x2F;)  Attribute Escape: <div attr='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'>content</div>  Javascript Escape: <script>x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'</script>  CSS Escape  URL Escape: <a href="http://www.somesite.com?test=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">link</a >
  • 10. Cross-Site Scripting (XSS) Protection  Input Validation using ESAPI: boolean isValidFirstName = ESAPI.validator().isValidInput("FirstName", request.getParameter("FirstName"), "FirstNameRegex", 255, false);  Sanitize using AntiSamy import org.owasp.validator.html.*; Policy policy = Policy.getInstance(POLICY_FILE_LOCATION); AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(dirtyInput, policy); MyUserDAO.storeUserProfile(cr.getCleanHTML());
  • 11. Cross-Site Scripting (XSS) Protection  Set HttpOnly  Before Servlet v3: response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");  Servlet v3: <session-config> <cookie-config> <http-only>true</http-only> </cookie-config> <session-config>  Output Escaping using ESAPI: <p>Hello, <%=name%></p> //performing output encoding for the HTML context String <p>Hello, <%=ESAPI.encoder().encodeForHTML(name)%></p>
  • 12. Injection Flaws  Definition: Attacker modifies a query/command that is executed by target interpreter  Injection applies to:  SQL injection  XPATH injection  LDAP injection
  • 13. Injection Flaws  SQL Injection:  SQL Statement for Authentication: StringsqlString = "SELECT * FROM users WHERE fullname = '" + form.getFullName() + "' AND password = '" + form.getPassword() + "'";  User Input: Case 1: full name: Haitham, password: 123pass Result: SELECT * FROM users WHERE username = „Haitham' AND password = '123pass' Case 2: full name: Ala' Ahmad, password: 123pass Result: SELECT * FROM users WHERE username = 'Ala' Ahmad' AND password = „13pass' Case 3: full name: blah, password: ' OR '1' = '1 Result: SELECT * FROM users WHERE username = 'blah' AND password = '' OR '1' = '1'
  • 14. Injection Flaws  XPATH Injection  XML file: <?xml version="1.0" encoding="utf-8"?> <employees> <employee id="AS1" firstname="John" salary=“100"/> <employee id="AS2" firstname=“Adam“ salary=“200"/> </employees>  XPATH expression: String exp = “/employees/employee[@id=„”+form.getEID()+”']” User Input: Emp_ID=„ or '1'='1 Result: /employees/employee[@id=„„ or '1'='1']
  • 15. Injection Flaws Protection  SQL Injection Protection using:  Use prepared statements/parameterized queries (don‟t use concatenation while building the SQL stmt) String stmt = “select * from emp where id=?”; PreparedStatement pstmt = con.prepareStatement(stmt); pstmt.setString(1, empId);  Use stored procedures  SQL Escape using ESAPI Codec ORACLE_CODEC = new OracleCodec(); String query = "SELECT name FROM users WHERE id = "+ ESAPI.encoder().encodeForSQL(ORACLE_CODEC, userId)+ " AND date_created >= '"+ ESAPI.encoder().encodeForSQL(ORACLE_CODEC, date)+ "'"; myStmt = conn.createStatement(query);
  • 16. Injection Flaws Protection  Hibernate Injection Protection  Use named parameters  Use Criteria API
  • 17. Injection Flaws Protection  XPATH Injection Protection  User input must not contain any of the following characters: ( ) = ' [ ] : , * / WHITESPACE  XPATH Injection protection using ESAPI String exp = “/employees/employee[@id=„”+ ESAPI.encoder().encodeForXPath(form.getEID())+ ”']”
  • 18. Malicious File Execution  Definition: occurs when attacker's files are executed or processed by the web server.  Expected Threats:  Malicious file (e.g., script) can be executed on the application server  Access to a configuration file  Override a configuration file  Fill up the filesystem  This happen when  Filename is accepted from the user without validation  File is uploaded without validation
  • 19. Malicious File Execution  Example:  Code Snippet // get the absolute file path on the server's filesystem String dir = servlet.getServletContext().getRealPath("/ebanking") // get input file name String file = request.getParameter(“file”); // Create a new File instance from pathname string File f = new File((dir + "" + file).replaceAll("", "/")); User Input: ../../web.xml Result: it will allow access to web server configuration file
  • 20. Malicious File Execution Protection  Filename Validation  File Type Validation  Size Validation  Don‟t allow the user to influence the final filename.  Upload files to a destination outside of the web application directory
  • 21. Malicious File Execution Protection  Filename and file type validation using ESAPI ESAPI.validator().isValidFileName("upload", filename, allowedExtensions, false));  Size Validation using Commons-FileUpload: ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxBytes);
  • 22. Direct Object References (DOR)  DOR occurs when a developer exposes a reference to an internal implementation:  Object  File or Directory  Database record  Attacker can manipulate object references to access other objects without authorization.  For Example:  URL (or form parameter) to my banking account is: /accounts/viewDetail?id=3540  What will happen if I changed this to  /accounts/viewDetail?id=3541
  • 23. Direct Object References (DOR) Protection  Avoid exposing direct object references  Use Indirect Object References  Verify Authorization to all referenced objects
  • 24. Direct Object References (DOR) Protection  Indirect Object Reference using ESAPI //create ESAPI random access reference map AccessReferenceMap map = new RandomAccessReferenceMap(); //get indirect reference using direct reference String indirectReference = map.addDirectReference(obj.getId()); //set indirect reference for each object - requires your app object to have this method obj.setIndirectReference(indirectReference); // Store the map in the session
  • 25. Direct Object References (DOR) Protection  Verify Authorization  For example:  Before: select * from accounts where accNum = ?  After: select * from accounts where accNum = ? And userId = ?
  • 26. Direct Object References (DOR) Protection  Authorization vs Indirect object reference  Authorization:  May require an extra DB hit  Exposes actual ID  Indirect object reference  May not require an extra DB hit  Hides actual ID  Requires a bit of extra coding and some extra information  Not very popular
  • 27. Cross Site Request Forgery (CSRF)  CSRF: forces logged-in victim to send a request to a vulnerable web application, which then performs action on behalf of the victim.  Sample CSRF Scenario:  A hacker posts to a blog containing an image tag (blog site allows XSS) <img src=“http://www.yourbank.com/transfer?to_acc=hacker_acc_ num&amount=1000”/>  User logs into yourbank.com (session is active for user)  User visits the blog (without logging from yourbank.com)  Loading the image will send request to the bank site  The bank will transfer the user‟s money to hacker‟s account
  • 28. Cross Site Request Forgery (CSRF) Protection  Make sure there are no XSS vulnerabilities in your application; refer to XSS protection slides.  Do not use GET requests to perform transactional operations.  Javascript can be used to create auto submit POST forms.  Check the referrer header. Shows where the request originated  This is optional and the user can disable it.  For sensitive transactions, re-authenticate.  Add a confirmation page.
  • 29. Cross Site Request Forgery (CSRF) Protection  Insert custom random tokens into every form and URL  Generate CSRF token  Store user in http session  On any form/URL add the token as a parameter/hidden field.  On the server, check the submitted token matches the token form.  On logout, the CSRF token is removed.
  • 30. Cross Site Request Forgery (CSRF) Protection  Do not use GET requests public void doGet(HttpServletRequest req, HttpServletResponse resp) { throw new Exception(“Invalid operation”); }  Check the referrer header using HTTPServletRequest: String referer = request.getHeader(“Referer”); if (referer != null && referer != “our trusted link”) { session.invalidate(); throw new Exception(); }
  • 31. Cross Site Request Forgery (CSRF) Protection  Implementing CSRF tokens using ESAPI // To generate CSRF token String csrfToken = ESAPI.randomizer().getRandomString(8, DefaultEncoder.CHAR_ALPHANUMERICS); // After user authentication, add token to user‟s session request.getSession().setAttribute(“csrfToken”, csrfToken); // To Validate a Token; this code can be added a filter String requestToken = request.getParameter(“csrfToken”); String sessionToken = session.getAttribute(“csrfToken”); if (!requestToken.equals(sessionToken)) { throw new Exception(“Invalid CSRF Token”); }
  • 32. Cross Site Request Forgery (CSRF) Protection // At logout, delete the session which removes its content HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); }  Implementing CSRF tokens using CSRFGuard project via ServletFilters  Tokens are automatically generated, managed, verified, and inserted  Copy Owasp.CsrfGuard.jar file to your application‟s classpath  Declate CsrfGuard in web.xml  Configure the Owasp.CsrfGuard.properties file as you see fit
  • 33. Failure to Restrict URL Access  Attacker, who is an authorized user, simply changes the URL to a privileged page.  URL is not protected with authorization.  Just because your URL is hard to guess, doesn‟t mean it can‟t be found!  Example:  “hidden” URLs rendered only to admins /admin/adduser.do  Attacker can find unprotected URLs  Test pages deployed in production  “hidden” files such as system reports
  • 34. Failure to Restrict URL Access Protection  Create Access Control Matrix for your Application: Function 1 Function 2 Function 3 PG Admin Read, write Read, Write Read, Write Acquirer Admin Read Read, Write Read, Write  Access Control Matrix shouldReadeasily configured Bank Admin be Read,  For each request, ensure that the userWrite is authorized to access that function.  Block access to all file types that your application should never serve  Put all your UI files under /WEB-INF
  • 35. Broken Authentication & Session Management  Flaws in this area most frequently involve the failure to protect credentials and session tokens through their lifecycle  If this issue is not properly addressed, many issues arise:  Account hijacked  Credentials stolen  Privacy violation
  • 36. Broken Authentication & Session Management Protection  Use the build-in session management  Utilize SSL / TLS Session identifier  With regards to authentication:  Use a single authentication point  Invalidate the HttpSession before login and after login to prevent session fixation  Make sure logout function invalidate the session  Add a session time-out  Do not expose any session identifiers in URLs or logs  Check the old password when the user changes to a new password
  • 37. Broken Authentication & Session Management Protection  Prevent brute force attacks by limiting the number of attempts  Destroy session if Referrer is suspicious (see CSRF)  Regenerate session if remote IP changed  Regenerate session if user agent changed
  • 38. Broken Authentication & Session Management Protection  Invalidate Session: request.getSession(false).invalidate();  Session Timeout:  Programmatically: session.setMaxInactiveInterval(20*60);  Using web.xml: <web-app ...> <session-config> <session-timeout>20</session-timeout> </session-config> </web-app>
  • 39. Broken Authentication & Session Management Protection  Regenerate session if remote IP changed String preRemoteIP = session.getAttribute(“RemoteIP”); String remoteIP = request.getRemoteAddr(); if (!preRemoteIP.equals(remoteIP)) {//read atts session.invalidate(); } session = request.getSession(true);//write atts String preRemoteIP = session.getAttribute(“RemoteIP”); String remoteIP = request.getRemoteAddr(); if (!preRemoteIP.equals(remoteIP)) { HTTPUtilities esapiHTTPUtilities = ESAPI.httpUtilities(); esapiHTTPUtilities.setCurrentHTTP(request, response); esapiHTTPUtilities.changeSessionIdentifier(); }
  • 40. Broken Authentication & Session Management Protection  Regenerate session if user agent changed String preUserAgent = session.getAttribute(“UserAgent”); String userAgent = request.getHeader("user-agent"); if (! preUserAgent.equals(userAgent)) { HTTPUtilities esapiHTTPUtilities = ESAPI.httpUtilities(); esapiHTTPUtilities.setCurrentHTTP(request, response); esapiHTTPUtilities.changeSessionIdentifier(); }
  • 41. What is Next?

Notas del editor

  1. Showing the same error message with different codes is another type of leaking the information
  2. Secure Log means, only authorized people can see its content
  3. HttpOnly is not supported by safari
  4. ESAPI is a free, open source, web application security control library that makes it easier for programmers to write lower-risk applications
  5. XSS and Injection flaws are similar in the concept; XSS for browsers while injection for data sources
  6. Case 1: no problemsCase 2: SQL ExceptionCase 3: user is authenticated
  7. Returns all the employees
  8. JDBC driver escape the dangers characters
  9. isValidFileName(String context, String input, List&lt;String&gt; allowedExtensions, boolean allowNull) 
  10. To Fetch the direct reference using the indirect reference use:map.getDirectReference()setIndirectReference can be supported by using a super class for all the entities
  11. Session hijacking: - Predictable session key  use Build-in Session management to generate random and v. long key - Session Fixation Regenerate session id after login - Sniffing:  use Https - Steal the session key (XSS)  refer to XSS