PCI Security Requirements                Haitham Raik
Agenda   Overview   Information leakage and improper error handling   Cross Site Scripting (XSS)   Injection Flaws   ...
Overview   PCI DSS is a security standard that includes    requirements for:       security management,       policies,...
Information Leakage and improper errorhandling   Definition: Providing too much information to the    user when an error ...
Information Leakage and improper errorhandling Protection   Write detailed error information to secure Log.   Configure ...
Cross Site Scripting (XSS)   XSS: Describes the act of embedding malicious    HTML/JavaScript code in dynamically generat...
Cross Site Scripting (XSS)   XSS is the most common vulnerability   XSS impact:       Data on a page can be stolen and ...
Cross Site Scripting (XSS) Protection   Input Validation; Checking each input for validity       Accept known good:     ...
Cross-Site Scripting (XSS) Protection   Output Escaping (Encoding): is a technique used to    ensure that characters are ...
Cross-Site Scripting (XSS) Protection   Input Validation using ESAPI:boolean isValidFirstName =ESAPI.validator().isValidI...
Cross-Site Scripting (XSS) Protection   Set HttpOnly       Before Servlet v3:response.setHeader("SET-COOKIE", "JSESSIONI...
Injection Flaws   Definition: Attacker modifies a query/command that    is executed by target interpreter   Injection ap...
Injection Flaws   SQL Injection:       SQL Statement for Authentication: StringsqlString =        "SELECT * FROM users W...
Injection Flaws   XPATH Injection       XML file:<?xml version="1.0" encoding="utf-8"?><employees>          <employee id...
Injection Flaws Protection   SQL Injection Protection using:       Use prepared statements/parameterized queries (don‟t ...
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       char...
Malicious File Execution   Definition: occurs when attackers files are executed    or processed by the web server.   Exp...
Malicious File Execution   Example:       Code Snippet// get the absolute file path on the servers filesystemString dir ...
Malicious File Execution Protection   Filename Validation   File Type Validation   Size Validation   Don‟t allow the u...
Malicious File Execution Protection   Filename and file type validation using ESAPIESAPI.validator().isValidFileName("upl...
Direct Object References (DOR)   DOR occurs when a developer exposes a reference    to an internal implementation:      ...
Direct Object References (DOR) Protection   Avoid exposing direct object references       Use Indirect Object References...
Direct Object References (DOR) Protection Indirect Object Reference using ESAPI//create ESAPI random access reference map...
Direct Object References (DOR) Protection   Verify Authorization       For example:           Before: select * from acc...
Direct Object References (DOR) Protection   Authorization vs Indirect object reference       Authorization:           M...
Cross Site Request Forgery (CSRF)   CSRF: forces logged-in victim to send a request to a    vulnerable web application, w...
Cross Site Request Forgery (CSRF)Protection   Make sure there are no XSS vulnerabilities in your    application; refer to...
Cross Site Request Forgery (CSRF)Protection   Insert custom random tokens into every form and    URL       Generate CSRF...
Cross Site Request Forgery (CSRF)Protection Do not use GET requestspublic void doGet(HttpServletRequest req,HttpServletRe...
Cross Site Request Forgery (CSRF)Protection   Implementing CSRF tokens using ESAPI// To generate CSRF tokenString csrfTok...
Cross Site Request Forgery (CSRF)Protection// At logout, delete the session which removes its contentHttpSession session =...
Failure to Restrict URL Access   Attacker, who is an authorized user, simply changes    the URL to a privileged page.    ...
Failure to Restrict URL Access Protection   Create Access Control Matrix for your Application:                           ...
Broken Authentication & SessionManagement   Flaws in this area most frequently involve the failure    to protect credenti...
Broken Authentication & SessionManagement Protection   Use the build-in session management       Utilize SSL / TLS Sessi...
Broken Authentication & SessionManagement Protection   Prevent brute force attacks by limiting the number of    attempts...
Broken Authentication & SessionManagement Protection Invalidate Session:request.getSession(false).invalidate();   Sessio...
Broken Authentication & SessionManagement Protection    Regenerate session if remote IP changedString preRemoteIP = sessi...
Broken Authentication & SessionManagement Protection    Regenerate session if user agent changedString preUserAgent = ses...
   What is Next?
Upcoming SlideShare
Loading in …5
×

PCI Security Requirements - secure coding

1,130 views
915 views

Published on

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,130
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • Showing the same error message with different codes is another type of leaking the information
  • Secure Log means, only authorized people can see its content
  • HttpOnly is not supported by safari
  • ESAPI is a free, open source, web application security control library that makes it easier for programmers to write lower-risk applications
  • XSS and Injection flaws are similar in the concept; XSS for browsers while injection for data sources
  • Case 1: no problemsCase 2: SQL ExceptionCase 3: user is authenticated
  • Returns all the employees
  • JDBC driver escape the dangers characters
  • isValidFileName(String context, String input, List&lt;String&gt; allowedExtensions, boolean allowNull) 
  • 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
  • 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
  • PCI Security Requirements - secure coding

    1. 1. PCI Security Requirements Haitham Raik
    2. 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. 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. 4. Information Leakage and improper errorhandling 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. 5. Information Leakage and improper errorhandling 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. 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. 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. 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. 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 interpreters parser.  HTML Escape: <body>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</body>  (&  &amp;) (<  &lt;) (>  &gt;) (“  &quot;) („  ' ) (/  /)  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. 10. Cross-Site Scripting (XSS) Protection Input Validation using ESAPI:boolean isValidFirstName =ESAPI.validator().isValidInput("FirstName",request.getParameter("FirstName"), "FirstNameRegex", 255,false); Sanitize using AntiSamyimport 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. 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. 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. 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. 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. 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 ESAPICodec 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. 16. Injection Flaws Protection Hibernate Injection Protection  Use named parameters  Use Criteria API
    17. 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. 18. Malicious File Execution Definition: occurs when attackers 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. 19. Malicious File Execution Example:  Code Snippet// get the absolute file path on the servers filesystemString dir =servlet.getServletContext().getRealPath("/ebanking")// get input file nameString file = request.getParameter(“file”);// Create a new File instance from pathname stringFile f = new File((dir + "" + file).replaceAll("","/")); User Input: ../../web.xml Result: it will allow access to web server configuration file
    20. 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. 21. Malicious File Execution Protection Filename and file type validation using ESAPIESAPI.validator().isValidFileName("upload", filename,allowedExtensions, false)); Size Validation using Commons-FileUpload:ServletFileUpload upload = new ServletFileUpload(factory);upload.setSizeMax(maxBytes);
    22. 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. 23. Direct Object References (DOR) Protection Avoid exposing direct object references  Use Indirect Object References Verify Authorization to all referenced objects
    24. 24. Direct Object References (DOR) Protection Indirect Object Reference using ESAPI//create ESAPI random access reference mapAccessReferenceMap map = newRandomAccessReferenceMap();//get indirect reference using direct referenceString indirectReference =map.addDirectReference(obj.getId());//set indirect reference for each object - requiresyour app object to have this methodobj.setIndirectReference(indirectReference);// Store the map in the session
    25. 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. 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. 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. 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. 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. 30. Cross Site Request Forgery (CSRF)Protection Do not use GET requestspublic 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 trustedlink”) { session.invalidate(); throw new Exception();}
    31. 31. Cross Site Request Forgery (CSRF)Protection Implementing CSRF tokens using ESAPI// To generate CSRF tokenString csrfToken = ESAPI.randomizer().getRandomString(8,DefaultEncoder.CHAR_ALPHANUMERICS);// After user authentication, add token to user‟s sessionrequest.getSession().setAttribute(“csrfToken”, csrfToken);// To Validate a Token; this code can be added a filterString requestToken = request.getParameter(“csrfToken”);String sessionToken = session.getAttribute(“csrfToken”);if (!requestToken.equals(sessionToken)) { throw new Exception(“Invalid CSRF Token”);}
    32. 32. Cross Site Request Forgery (CSRF)Protection// At logout, delete the session which removes its contentHttpSession 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. 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. 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. 35. Broken Authentication & SessionManagement 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. 36. Broken Authentication & SessionManagement 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. 37. Broken Authentication & SessionManagement 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. 38. Broken Authentication & SessionManagement 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. 39. Broken Authentication & SessionManagement Protection Regenerate session if remote IP changedString preRemoteIP = session.getAttribute(“RemoteIP”);String remoteIP = request.getRemoteAddr();if (!preRemoteIP.equals(remoteIP)) {//read attssession.invalidate();}session = request.getSession(true);//write attsString preRemoteIP = session.getAttribute(“RemoteIP”);String remoteIP = request.getRemoteAddr();if (!preRemoteIP.equals(remoteIP)) { HTTPUtilities esapiHTTPUtilities = ESAPI.httpUtilities(); esapiHTTPUtilities.setCurrentHTTP(request, response); esapiHTTPUtilities.changeSessionIdentifier();}
    40. 40. Broken Authentication & SessionManagement Protection Regenerate session if user agent changedString 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. 41.  What is Next?

    ×