242

Click here to load reader

Java Web Security Class

Embed Size (px)

DESCRIPTION

My latest Java Web Security Class

Citation preview

Page 1: Java Web Security Class

Java Web Security Coding

( The Open Source Way)

August 26, 2010BY RICH HELTON

Page 2: Java Web Security Class

Introduction See

http://oitplaza.colorado.gov:8080/oitplaza/how-to/security-training for some sample classes.

My personal website that contains some slides is http://www.s3curitys0lutions.com/

My background http://www.linkedin.com/pub/rich-helton/4/266/9a8

(Security and Java Certs, Masters in CS)

Page 3: Java Web Security Class

What motivates Hackers.

Page 4: Java Web Security Class

Which organizations are attacked.

Page 5: Java Web Security Class

The outcome can be expensive

Page 6: Java Web Security Class

http://www.zone-h.org/news/id/4735

Page 7: Java Web Security Class

There are many hacks….

And more are discovered every day. For 2010, the Open Web Application Security Project (OWASP) published the top ten web hacks, http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project :

1) Injection Flaws

2) Cross Site Scripting (XSS)

3) Broken Authentication and Session Management

4) Insecure Direct Object Reference

5) Cross Site Request Forgery (CSRF)

6) Security Misconfiguration

7) Insecure Cryptographic Storage

8) Failure to Restrict URL Access

9) Insufficient Transport Layer Protection

10) Unvalidated Redirects and Forwards

Page 8: Java Web Security Class

There are many Checklists….

Here are some checklists to help with the principles: The ASP.NET Security Checklist

http://msdn.microsoft.com/en-us/library/ff648269.aspx

WebAppSec Excel checklist http://img.a4apphack.com/dl/appsecchck-checklist.zip

SANs reading Web Security Checklist http://www.sans.org/reading_room/whitepapers/securecode/security-checklist-web-application-design_1389

The Open Web Application Security Project Application checklist is http://www.sans.org/reading_room/whitepapers/securecode/security-checklist-web-application-design_1389

Page 9: Java Web Security Class

Checklists Principles

All the checklists, regardless of programming languages, have many of the same principles:

Find and validate all input. This includes URL’s, JavaScript's, links, username and passwords, and especially any field calling a database.

Never trust data in files, the network or database to be secure. Encrypt anything important, passwords, SSN’s, configurations.

Never trust the source, be it customer or a service. Authenticate, Authorize and validate.

Whenever a abnormal behavior occurs, error check and log.

Keep testing, as people from all skills will be testing anything on line and may try common threats.

Page 10: Java Web Security Class

Finger Printing and Scanning

Page 11: Java Web Security Class

Spiders, Bots, and Crawlers! Oh my...

All web sites on the Internet are constantly scanned. They are bots (automated scanners) from Virus vendors,

Security organizations, search engines and more cataloging all web sites.

There is the famous GoogleBot, http://en.wikipedia.org/wiki/Googlebot, that will look for the local robots.txt, see http://www.robotstxt.org/ , to define what to search for on the web site. Hackers usually don’t respect these gentlemen agreements on the Internet.

There are so many scans on the Internet that many consider it white noise and careers have been built dedicated on sifting through the network traffics white noise.

Hackers specializing in Google API’s (Google Hacking), search for hidden files, like etc/passwd, pdf’s, job announcements and more to define the web site coding.

Page 12: Java Web Security Class

Sometimes the spiders do damage

Page 13: Java Web Security Class

Google Hacking

Google can be used to find out information about a web site using the Google API.

A well known site containing a database of various keywords is found at http://www.hackersforcharity.org/ghdb/ .

For example, “ext:asp” can be used to find pages ending in asp.

For example,“ Hacking filetype:pdf” can be used to find PDFs that are about hacking.

For example, “restaurants inanchor:menu” will find restaurants with menu links in them.

intitle:index.of "web hacking”

Page 14: Java Web Security Class

Google Webcams

Google “165.127 inurl:/view/index.shtml” for Colorado Web Cams:

Page 15: Java Web Security Class

Web sites watching Web sites….

Netcraft.com is one among many websites that will keep track of your uptime and server versions rather you know it or not:

Page 16: Java Web Security Class

Just because you changed the web site, doesn’t mean it went away, see www.archive.org,

Page 17: Java Web Security Class

Wget (Open Source Web downloaders)

Open Source utilities, like wget, or VisualWget http://www.bebits.com/app/299 , provide a means to download all available URL’s on a Web Site:

Page 18: Java Web Security Class

Wget (Open Source Web downloaders)

Results:

Page 19: Java Web Security Class

Skipfish

Skipfish does web crawling, fuzzing, and tests for many issues like XSS and SQL Injection.

There are many Web Application Scanners, WebScarab from OWASP, Nikto, Wikto, and many more listed at http://sectools.org/web-scanners.html

For simplicity and use of Open Source, I will use Google’s Skipfish.

The down side of Skipfish is that it was primarily created for Linux written in gcc and uses BSD Sockets. It can be compiled for Windows using cygwin.

My demonstrations will be down in Hackme Books because it was written in J2EE and can be run on a local machine.

For Windows http://www.shortinfosec.net/2010/03/compiling-latest-skipfish-for-windows.html

Page 20: Java Web Security Class

SkipFish

Skipfish is a fully automated web application security reconnaissance tools, http://code.google.com/p/skipfish/ :

Page 21: Java Web Security Class

WebScarab

The test site, Hacme Books, has documented issues. It is a good practice to use a few tools, and even some manual hacking, because the tool Skipfish didn’t find all the issues.

Another tool that I use, of course Open Source, is a Web proxy instead of a scanner from OWASP called WebScarab.

WebScarab sits between a browser and the web site, or web service, as a proxy and reads the packets going across. You can also spider the URLs once the initial one is captured to the web site to scan.

WebScarab will read cookies, XSS issues, and spider the site as the browser accesses the pages.

Page 22: Java Web Security Class

WebScarab

WebScarab can be started through Java Web Start at http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project. After starting, set the proxy settings in browser that will be calling the web sites at port 8008 default:

Page 23: Java Web Security Class

WebScarab, a Proxy Scanner

Page 24: Java Web Security Class

Grendel-scan

Grendel-scan is an Java Open Source Web Security Scanner built from Apache Commons and HTTP Components frameworks, http://grendel-scan.com/ :

Page 25: Java Web Security Class

A Grendel-scan result

Page 26: Java Web Security Class

Practicing the Web Hack….

There are many web server download builds to use that are intentionally broken for the purpose to practice web hacking.

Some download applications to practice web hacking locally are: OWASP WebGoat (JSPs/Servlets) -

http://www.owasp.org/index.php/OWASP_WebGoat_Project

Hackme Bank (.Net) - http://www.foundstone.com/us/resources/proddesc/hacmebank.htm

Hackme Books (JSPs/Servlets) – http://www.foundstone.com/us/resources/proddesc/hacmebooks.htm

SecuriBench (Java Code) –

http://suif.stanford.edu/~livshits/securibench/

Page 27: Java Web Security Class

Live sites…

There are also live web sites that simulate banks and other businesses to practice web hacking and test hacking tools against. They include: Spi Dynamics - http://zero.webappsecurity.com/ Cenzic -

http://crackme.cenzic.com/Kelev/view/home.php WatchFire - http://demo.testfire.net/ HackThisSite - http://www.hackthissite.org/ NTO - http://hackme.ntobjectives.com/ Accunetix - http://testaspnet.acunetix.com/login.aspx

Page 28: Java Web Security Class

Hacker Game/Challenge Sites

http://www.hackerskills.com/ http://www.hackthissite.org/missions/basic/ http://hackme.ntobjectives.com/ http://www.astalavista.com/index.php?app=hackingchal

lenge http://hax.tor.hu/ A list can be found at http://www.wechall.net/sites.php

Page 29: Java Web Security Class

Error Handling

Page 30: Java Web Security Class

Has my system been compromised?

Logging and Error handling is one of the most important concept in Security.

When an incident happens, the first questions are always “How did they get in?” and “What data was compromised?”.

The least favorite answer is usually “No one knows.” With efficient logging of authorization, access to secure

information, and any anomalous interaction with the system, a proper recovery of the system is usually insured.

The logs should be store into a different system in case the Web system is ever compromised, one where the Web system sends them but never asks for them back.

Logging is a fundamental API that comes with the Java and .NET languages.

Page 31: Java Web Security Class

Logging the Java way….

Here’s some Java code that will save messages into a file:

Output:

import java.util.logging.*;import java.io.*;public class TestLog { public static void main(String args[]) { try{ Logger logger = Logger.getLogger("TestLog"); FileHandler fh = new FileHandler("mylog.txt"); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); logger.severe("my severe message"); logger.warning("my warning message"); logger.info("my info message"); } catch (IOException e) {e.printStackTrace(); }}}

Mar 25, 2008 8:43:48 PM TestLog mainSEVERE: my severe messageMar 25, 2008 8:43:49 PM TestLog mainWARNING: my warning messageMar 25, 2008 8:43:49 PM TestLog mainINFO: my info message

Page 32: Java Web Security Class

Java Exception Handling

Java exception handling has helped debugging immensely. It allows a programmer to code for anomalies and handle a bizarre behavior.

There are 3 components of handling an exception, and they are the “try”, “catch” and “finally” blocks.

The “try” block will throw an exception from normal code, the “catch” block will catch the exception and handle it, and the “finally” block will process the cleanup afterwards.

The “catch” block can log the anomaly, stop the program, or process it in a hundred different ways.

You can write your own custom exception classes to trace specific pieces of code.

Page 33: Java Web Security Class

Java Exception Handling code

public class TestException { public static void main(String[] args) throws Exception { FileReader myReader = null;

try { // constructor will throw FileNotFoundException myReader = new FileReader("IamNotHere.txt"); } catch (FileNotFoundException e) { System.out.println("FileNotFoundException was " + e.getMessage()); } catch (IOException e) { System.out.println("IOException was " + e.getMessage()); } finally { if(myReader != null){ try { myReader.close(); } catch (IOException e) { System.out.println("IOException was " + e.getMessage()); }} }}Output-> FileNotFoundException was IamNotHere.txt (The system cannot find the file specified)

Page 34: Java Web Security Class

Log4j

The previous logging and exception handling example has many hard coded pieces. Java provides decoupling with its frameworks. Log4j provides more decoupling.

Even though the basic JDK logging framework can accept changes on destination through its Handler in the “logging.properties”, Log4j offers more advanced features in its XML use of its Appender class.

Log4j supports XML configuration and a text configuration in log4j.properties.

Page 35: Java Web Security Class

Log4j JSP code

<%@ page import="org.apache.log4j.Logger" %><html><head>   <title>Demonstration log4j usage in jsp</title></head><body><%Logger log = Logger.getLogger("com.demo.test");log.debug("Show DEBUG message");log.info("Show INFO message");log.warn("Show WARN message");log.error("Show ERROR message");log.fatal("Show FATAL message");%><b>   The log messages are shown in the Tomcat console and in the   ${catalina.home}/logs/demo.log file.</b></body></html>

Page 36: Java Web Security Class

Log4j demo.log

2008-08-11 20:03:43,379 [com.demo.test] DEBUG - Show DEBUG message.2008-08-11 20:03:43,409 [com.demo.test] INFO - Show INFO message.2008-08-11 20:03:43,409 [com.demo.test] WARN - Show WARN message.2008-08-11 20:03:43,409 [com.demo.test] ERROR - Show ERROR message.2008-08-11 20:03:43,419 [com.demo.test] FATAL - Show FATAL message.

Page 37: Java Web Security Class

SMTP Appender

An Appender is configured in the log4j.properties to define the loggers. Here is a sample of an logger to send email logs:

Page 38: Java Web Security Class

Error Pages

Default Error pages may display unintentional information. For instance, some error pages may display database information in an exception.

An error page giving details, like a database or table name, may be more than enough to give an attacker enough information launch an attack at the website.

To correct bad error handling in pages, Tomcat, Struts and other Web engines will allow default configurations to throw a specific error page for any unknown exceptions. For instance, many Web Application Firewalls (WAFs) will generate a error page 500 “Internal Server Error” for blocking an attack.

Page 39: Java Web Security Class

Hackme Books(Bad error handling)

Page 40: Java Web Security Class

Custom Error Pages

To send errors 404 and 500 to a custom JSP Error page, the web.xml file for Apache Tomcat:

<web-app> <error-page>

<error-code>500</error-code> <location>/server_error.html</

location> </error-page> <error-page>

<error-code>404</error-code> <location>/file_not_found.html</

location> </error-page>

</web-app>

Page 41: Java Web Security Class

SQL Injection(Most common Injection

Flaw)

Page 42: Java Web Security Class

Intro to SQL Injection…

Many web pages communicate directly to a backend database for processing.

For example, a username and password is asked for on the Web page and the web page will pass it to the database to validate the information.

Some applications will not validate the field adequately before passing it to the database, and the database will process whatever it will receive.

Hackers will pass SQL commands directly to the database, and in some cases tables like “passwords” are returned because the SQL commands are not being filtered adequately.

SQL may return errors in the web page that even lists the correct tables to query so that the hacker may make more accurate attempts to get data.

Page 43: Java Web Security Class

SQL Injection

SQL Injection is the ability to inject malicious SQL commands into the backend code.

For example:

SELECT * FROM users WHERE username = ‘USRTEXT ' AND password = ‘PASSTEXT’

Passing ' OR 1=1-- in the USRTEXT field generates:

SELECT * FROM users WHERE username = ‘’ OR 1=1 -- '

AND password = ‘PASSTEXT’ The OR 1=1 returns true and the rest is commented

out

Page 44: Java Web Security Class

ASP.NET Hacme Bank(Let’s try it)

Page 45: Java Web Security Class

ASP.NET Hacme BankAuthentication without username/password

Page 46: Java Web Security Class

Types of SQL Injection…

There are really two types of SQL injection, “Blind” SQL Injection and “Directed” SQL Injection.

Blind SQL Injection is performed when a hacker passes SQL commands into the web form and generic errors are returned to the user, for instance a “404” Error page or page not found. The hacker has to make more extensive guesses on the database behind the web server.

Directed SQL Injection is when the web server returns SQL errors to the user that give information about the table that has issue processing the SQL command. Some web pages may return “users.password table incorrect SQL query”, which gives the hacker the name of the database to launch the attack against.

Page 47: Java Web Security Class

Common attack strings

‘ or 27(hex) – delineates SQL string values.“ or 22 (hex) – also delineates SQL string values.; or 3B (hex) - terminates statements.# or 23(hex) - also terminates a statement. (Access DB)/* or 2F2A (hex) - comment delimiter.-- or 2D2D (hex) – also comment delimiter.( or 28 (hex) or ) or 29 (hex) – logical sub clauses.{ or 7B (hex) or } or 7D (hex) – terminates a question.exec – used to call MS-SQL stored procedures.

union – a SQL command very common to SQL injection.

Page 48: Java Web Security Class

HackmeBooks SQL Injection(shows org.hsqldb.jdbc connection)

Page 49: Java Web Security Class

HackmeBooks SQL Injection(attacking)

HSQL DB, uses a SHUTDOWN to shut down the database, since the SEARCH field uses straight SQL commands, typing in ‘;+SHUTDOWN;-- will add ‘%’; SHUTDOWN; --%’ in the SQL statement, thus shutting down the database:

Session is now closed because we shutdown the database:

Page 50: Java Web Security Class

Real life example

Start by identifying the SQL Server version, table name and fields in the error page:

We see that it is SQL Server, and an “id” field into the “business.dbo.urltracking” table. An Attacker can now try inserting into the table.

Page 51: Java Web Security Class

Common fixes to SQL Injection…

Validate the form field to only accept specific input for the fields. For example, for login name use ^[0-9a-zA-Z]*$, which is

Regular expressions for an alpha-numerical field.

For Apache Struts, use the org.apache.struts.validator.ValidatorPlugin, http://www.owasp.org/index.php/Data_Validation_(Code_Review) .

For JSPs/Servlets, validate in the Servlet using the with the “java.utile.regex” framework in a similar manner.

Don’t use SQL Use Prepared Statements, or Hibernate, to call the database.

http://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java

Page 52: Java Web Security Class

What is a prepared statement?

A prepared SQL statement is precompiled and stored in a

PreparedStatement object.

An example of a PreparedStatement object is:

PreparedStatement pstmt = con.prepareStatement("update Orders set pname = ? where Prod_Id = ?");pstmt.setInt(2, 100);pstmt.setString(1, "Bob");pstmt.executeUpdate();

Page 53: Java Web Security Class

XSS(Cross Site Scripting)

Page 54: Java Web Security Class

XSS

Javascript is a scripting language originally from Netscape to provide browser side scripting in the HTML.

The problem with using Javascript is the same as its purpose, the script can execute any script in the HTML browser, however, it may also execute any script put into its place.

Hackers can use Javascript to alert the browser to go to a different website, input some extra data, or even access data on the browser itself like browser cookies or the session information in the browser.

The hacker takes advantage of changing the information in the <script> … </script> tags.

The Javascript can be told to encode its programming to avoid taking information from other sources than the web server.

Page 55: Java Web Security Class

XSS…

While not an exhaustive list, the following commonly used HTML tags could allow a malicious user to inject script code: <applet> <body> <embed> <frame> <script> <frameset> <html> <iframe> <img> <style> <layer> <link> <ilayer> <meta> <object>

Page 56: Java Web Security Class

Hacme Books XSS…

This URL is scripting a page from an Acunetix site as input.

Page 57: Java Web Security Class

Insecure Web App XSS…

This URL is does an alert when the mouse moves over the email box:

Page 58: Java Web Security Class

Looking at Java XSS…

XSS is an issue in the HTML page, but fixing it usually requires a library from ASP.NET, PHP, or a Java framework.

The syntax of the JSP is slightly different but the HTML code and issues remain the same.

The HtmlEncode does not exist in the default packages of Java, but JTidy is used often for HTML parsing from http://sourceforge.net/projects/jtidy.

include org.w3c.tidy.servlet.util.HtmlEncode;

…..

string Name = HtmlEncode.encode(Request.QueryString[“Name”]);

….

Page 59: Java Web Security Class

Common fixes to XSS

Don’t use Javascript.

A more practical approach is “HTML entity encoding”. This basically encodes the HTML to not execute external

commands.

Using the Jtidy framework, http://jtidy.sourceforge.net/ , you can encode a URL link as follows: <input type="text" name="url" value="<%=HTMLEncode.encode(userURL)%>" size="50"><br/>

http://www.owasp.org/index.php/How_to_perform_HTML_entity_encoding_in_Java

Page 60: Java Web Security Class

Cross Site Request Forgery

Page 61: Java Web Security Class

There seems to be some issues in my sample Web Apps

My Test App has some built-in bugs, but I really need to clean it up and get rid of some of the Cross Site Request Forgery (CSRF), also known as XSRF, http://en.wikipedia.org/wiki/CSRF .

Page 62: Java Web Security Class

CSRF

CSRF is when a hacker tricks a user into injecting a small request (Request Forgery), like an image, into a victim’s browser to redirect a portion of the victim's browser to a vulnerable site while they are still logged onto their original site (the Cross Site).

The benefit to the attacker, is that if a hidden image is injected into a user’s browser, and their browser currently has their bank authentication cookie, then the hacker may hijack the victims authentication.

Let’s try a test on a Sample Web site….

Page 63: Java Web Security Class

OWASP’s CSRF Guard Tester

First, I will generate some sample data with the OWASP CSRF Tester.

This tool is simply a browser proxy, built from WebScarab, that will just grab data from some websites as I browse them. Later, I will use these sites to generate the “IMG” (images), “Links”, “Forms”, etc, for attack CSRF segments.

The CSRF usually uses a IMG link to redirect the browser to a website, for example

Page 64: Java Web Security Class

Browsing with CSRFTester….

I will generate some “img” snippets from visiting websites.

Page 65: Java Web Security Class

Generated CSRF attacks

This is an HTML that the CSRF Tester generated for IMG attack snippets. I will use the Apache site instead of a bank hijacking site.

Page 66: Java Web Security Class

Injecting the RF

Submitting “Rich<img src="http://www.apache.org:80/?" width="0" height="0"

border="0"/>” in the name field of the HelloWorld Test App will execute…

Did anything happen? Has the original page changed?

Page 67: Java Web Security Class

Injecting the RF

Since width and height were “0”, there was nothing to display, let’s increase the image “Rich<img src="http://www.apache.org:80/?" width=”80" height=”80" border=”20”/>”

The Apache website was called with the current browser settings (including the session cookie).

Page 68: Java Web Security Class

What’s Happening…

Page 69: Java Web Security Class

The Fix

Applying OWASP’s CSFGuard, http://www.owasp.org/index.php/Category:OWASP_CSRFGuard_Project , as a Servlet Filter.

It will scrub the input before the HelloWorld Servlet receives it.

Simply install the CSFGuard JAR (Java Archive) file in the Tomcat’s Web project and add the filtering rules to the web.xml.

Page 70: Java Web Security Class

Filtering rules (web.xml)

Note that I only changed the Helloworld Servlet, not all the pages, as a sample.

Page 71: Java Web Security Class

Testing the Fix

Let’s submit the larger IMG going to Apache again…

The IMG didn’t process in the Servlet output. There is no Apache image border.

Page 72: Java Web Security Class

What does Skipfish say …

Before the filter

After the filter

Page 73: Java Web Security Class

Broken Session Management

Page 74: Java Web Security Class

Session Management

HTTP is a stateless protocol, so the protocol, by default, doesn’t allow a server to keep an open and constant communication with the browser. Each GET and POST will require a new TCP connection.

Servers use Session Management to schemes to maintain the current conversation between the browser and the server by using cookies or transferring session token.

Keep in mind that session state may be seen by others if transferred in clear text. Avoid any predictable or guessable information.

If a session timeout is lengthy, it will allow an attacker more time to guess at the session information.

Page 75: Java Web Security Class

Session Management(configurable)

Server provide a configurable solution for JSPs/Servlets/Struts in the web.xml (Tomcat, WebSphere and WebLogic):

<security-constraint> <web-resource-collection>

<web-resource-name>placeorder</web-resource-name>

<url-pattern>/control/placeorder</url-pattern>

<http-method>POST</http-method> <http-method>GET</http-method>

</web-resource-collection> <auth-constraint>

<role-name>customer</role-name> </auth-constraint> </security-constraint>

Page 76: Java Web Security Class

Session Management(programmatic)

Code can be added in the pages to check the user:getRemoteUser() – returns the authenticated name of the user.getUserPrincipal() – returns the current authenticated principal. isUserInRole() – returns true if the current authenticated user matches the role.

Example:// Method in servlet or struts action classpublic void approveAssignment(HttpServletRequest req, WorkOrder workOrder) { if ((req.isUserInRole(“MaintWorker”) && req.isUserInRole(“MaintSuper”)) || req.isUserInRole(“Manager”) { workOrder.approveWorkAssignment(); } else { throw new SecurityException(“...”); } ...}

Page 77: Java Web Security Class

Security Realms

After a user has logged into a Form, a session can use the roles from the Application Server’s Security Realm.

A Realm is a “database” of usernames and passwords that identify valid users of a web application plus their roles.

The Application Servers, i.e. WebLogic or WebSphere, have GUI interfaces and and even custom frameworks for managing Security Realms. For example, to get an existing user:

weblogic.security. acl.User u = realm. getUser(userName) ;

Page 78: Java Web Security Class

Encryption

Page 79: Java Web Security Class

Who’s seeing your data?

Data at rest and in transient can be at risk to prying eyes. When a system is in production, and especially on the

Internet, there is no guarantee that you know who is watching the data transmitted between the user and the server. This may also apply to the Local Area Network as well.

Never take it for granted that access cannot be broken. Always, use common algorithms that come with Java.

Common algorithms are tested well and are vetted by millions.

Keep the keys as secure as the data, because they can unlock the data.

Homemade encryptions algorithms may end up costing more than standard encryptions if broken.

Page 80: Java Web Security Class

One-way Hash Algorithms

There are two common types of one-way hash algorithms, Message Digest 5 (md5), and Secure Hash Algorithm 1 (sha1).

The one-way hash generates a fixed size hash some given any size data.

The data cannot be reversed engineered from the hash, hence one-way.

The same data generates the same hash sum.Different data generates different hash sums.

(Note: In rare cases, collisions, different data generates the same sum).

Page 81: Java Web Security Class

Md5

Message Digest 5 (md5) will take data input and generate 128 bit hash sum.

The 128 bit hash sum can be used to ensure if there has been tampering of data or a file.

A common comparison is to store passwords in a table, and instead of checking the password, compare the hash of the password, so that the password does not have to be stored.

Page 82: Java Web Security Class

Md5, Java code

import java.security.*;

import javax.crypto.*;

public class MD5Example {

public static void main (String[] args) throws Exception {

// Get a message digest object using the MD5 algorithm

MessageDigest md = MessageDigest.getInstance("MD5");

// Print out the provider used

System.out.println( "\n" + md.getProvider().getInfo() );

String str = new String("abcdefghijklmnopqrstuvwxyz0123456789");

// Calculate the digest and print it out

System.out.println( new String( md.digest(str.getBytes()), "UTF8") );

}}

C:\>m"?0↕eQ/☺???♀?

Page 83: Java Web Security Class

Sha1

Secure Hashing Algorithm 1 (Sha1) will take any size byte array and produce a 160 bit hash sum, sometimes called a message digest.

Other SHA’s are SHA224,SHA256,SHA384, and SHA512, each one denoting the size in bits of the message digest.

Page 84: Java Web Security Class

Sha1, Java code

import java.security.*;

import javax.crypto.*;

public class SHA1Example {

public static void main (String[] args) throws Exception {

// Get a message digest object using the SHA1 algorithm

MessageDigest md = MessageDigest.getInstance("SHA");

String str = new String("abcdefghijklmnopqrstuvwxyz0123456789");

//

// Calculate the digest and print it out

System.out.println( new String( md.digest(str.getBytes()), "UTF8") );

}

}

C:\>??PI?w??????H ?f?:

Page 85: Java Web Security Class

AES

The National Security Agency (NSA) updated their algorithm in 2001 to the Advanced Encryption Algorithm (AES) for Top Secret information from the Data Encryption Standard in 1975.

The Rijndael algorithm was selected, developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.

The NIST adapted the variable key space into 128, 192, or 256 bits as FIPS 197 and called it AES.

AES is a symmetric key algorithm, meaning that the same key is used to both encrypt and decrypt.

Page 86: Java Web Security Class

AES Java Code

public static void main(String[] args) throws Exception {

String message="Secret Message";

// Get the KeyGenerator

KeyGenerator kgen = KeyGenerator.getInstance("AES");

kgen.init(128); // 192 and 256 bits may not be available

// Generate the secret key specs.

SecretKey skey = kgen.generateKey();

byte[] raw = skey.getEncoded();

SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

// Instantiate the cipher

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = cipher.doFinal(message.getBytes());

System.out.println("ciphertext: " + new String(encrypted));

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

System.out.println("plaintext : " + new String(cipher.doFinal(encrypted))); }

Page 87: Java Web Security Class

AES, output

This program generates the following:

ciphertext: 7=~↑╫‼Äε{▐ç≤■ßJ%

plaintext : Secret Message

Some key functions to keep track of:

1) “KeyGenerator.getInstance("AES");” will be used to get the algorithm to generate the key.

2) “Cipher.getInstance("AES");” will be used to get the algorithm of the encryption algorithm.

3) “cipher.init(Cipher.ENCRYPT_MODE, skeySpec)” will set the algorithm into encryption mode with the generated key.

4) “cipher.doFinal(message.getBytes());” will encrypt/decrypt the message depending on the algorithm mode.

5) “cipher.init(Cipher.DECRYPT_MODE, skeySpec)” will set the algorithm into decryption mode with the generated key.

Page 88: Java Web Security Class

RSA

The most important Asymmetric algorithm to undertsand is the Rivest-Shamir-Adleman (RSA). So named after the MIT mathematician inventors in 1978.

The Asymmetric algorithm can generate key pairs, one private key for encrypting, and its pair is handed out for decryption to more people, the public key.

The key pair are formulated from a pair of prime numbers using a modulus equation that become linked to each other.

Page 89: Java Web Security Class

RSA generate key pair

public class KeyPairExample {

public static void main(String[] args) throws Exception {

// Get an RSA Key Generator Instance

KeyPairGenerator generator =KeyPairGenerator.getInstance("RSA");

// Initialize the Key Size to 1024

generator.initialize(1024);

// Generate the Key Pair

KeyPair myKeyPair = generator.generateKeyPair();

// Print the Public Key

System.out.println(myKeyPair.getPublic());

// Print the Private Key

System.out.println(myKeyPair.getPrivate());

}

}

Page 90: Java Web Security Class

RSA Encryption/Decryption Java (Looks a little different than AES code)

// Instantiate the cipher

String message="Secret Message";

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, myKeyPair.getPrivate());

byte[] encrypted = cipher.doFinal(message.getBytes());

System.out.println("ciphertext: " + encrypted);

cipher.init(Cipher.DECRYPT_MODE, myKeyPair.getPublic());

System.out.println("plaintext : " + new

String(cipher.doFinal(encrypted)));}}

Page 91: Java Web Security Class

RSA, the output….. (Done, Pretty complicated Algorithm)

Sun RSA public key, 1024 bits modulus: 980107411139423484217818965832939064883293636629854742201705822779824

79737095178477032660683112587771793192378734732281828808342667685391007276408051384835230617179129503971262219557378459014061761340387456533909811872836106693706757181056046976680271903140634016603122723693693471582356428163104781169896669

public exponent: 65537Sun RSA private CRT key, 1024 bits

modulus: 980107411139423484217818965832939064883293636629854742201705822779824797370951784770326606831125877717931923787347322818288083426676853910072764080513848352306171791295039712622195573784590140617613403874565339098118728361066937067571810560469766802719031406340166031227236936934715823564281631047811

69896669 public exponent: 65537

private exponent: 202580755776044532359042612740482362221479402502220308190248364669965160217692492431738471644024461595237893703150996153265031632478823612094628411960275677514004333251131310958688752270521879160104059996315586918817557594522477753401095330548399831868982416589194228412863300855787519292546186394656

05294593 prime p: 112183660941098142693053525005462603286228086568859187637878

08138585464910152407417125784827816324713265751926473733527313588720643015199183638384157158849

prime q: 87366324375349754488467269065475892627716284565712370568494616829286853416192792812440215576947371094036285391021671838144160919503269398947

34767205105181 prime exponent p: 101372180365179564344192178530425573786009636002478141372091

76278669603696295767576324917272504242883322567325902939915178266286604513528401578478541451457

prime exponent q: 47337811901195809724056223576224864537745170894738030103410956308771780289134474766464013536435923944477600351483582815394344481004029729109

05772059344873 crt coefficient: 707486534583127697912952059521861679657709263528129871969054

8049988269513555964023296114708685230108297568261242663865655734818323204740365213569010769473

ciphertext: ??ç-- =Táçߦ-$~µûá$¦¦?ó¦¬c5?Ygbc·+vßYj÷ﶪ--u?¢H!¦¦½Gp¯y»/·+(?¢mE/fz{>+-?"J!kCI5n óE?,:)k+

plaintext : Secret Message

Page 92: Java Web Security Class

Digital certificates

Page 93: Java Web Security Class

Beyond Encryption

Now that we can encrypt and provide message digests, let’s do more by putting the pieces together.

A larger, combined, piece is the Digital Certificate. A Digital Certificate is a protocol X509 structure that

contains verification of the certificate, Non-repudiation (proof of receipt), and third party authentication through a Certificate Authority.

The Digital Certificate is the heart of Hypertext Transfer Protocol over Secure Socket Layer (HTTPS) and Public Key Infrastructure (PKI).

PKI is the process of authentication through a trusted party called Certificate Authority (CA). This could be a third party or self signed internally through a domain controller.

HTTPS allows secure transport over Web Services and Web Servers, and in some cases secure file transport services.

Page 94: Java Web Security Class

Java Tools

Java was an early adopter of Digital Certificates and has tools for storing, like keystore, and for generating, keytool, Digital Certificates.

Again, once a key is stolen, then the encrypted text can be compromised, so a secure storage of certificates is important.

keystore is a protected database that holds keys and certificates for an enterprise. The file is password protected by who creates it.

Page 95: Java Web Security Class

Let’s generate some certs……

Using the Java keytool utility:C:\>keytool -genkey –alias mydomain -keypass richkeypasswd -keystore keystore.jks

Enter keystore password:

Re-enter new password:

What is your first and last name?

[Unknown]: Rich Helton

What is the name of your organizational unit?

[Unknown]: CDLE

What is the name of your organization?

[Unknown]: CDLE

What is the name of your City or Locality?

[Unknown]: Denver

What is the name of your State or Province?

[Unknown]: CO

What is the two-letter country code for this unit?

[Unknown]: US

Is CN=Rich Helton, OU=CDLE, O=CDLE, L=Denver, ST=CO, C=US correct?

[no]: y

Page 96: Java Web Security Class

Let’s see the cert……

Using the Java keytool utility to read the user’s home keystore file, we can generate a certfle.cer file that we can import into Internet Explorer :

C:\>keytool –list –v –keystore.jks

Page 97: Java Web Security Class

Let’s see the cert……

Using the Java keytool utility to read the user’s home keystore file, we can generate a certfle.cer file that we can import into Internet Explorer or pass it around in HTTPS:

C:\>keytool -export –keystore keystore.jks -alias mydomain -file certfile.cer

Enter keystore password:

Certificate stored in file <certfile.cer>

Page 98: Java Web Security Class

Let’s print the cert file……

public class PrintCert {

public static void main(String[] args) throws Exception {

// Get the cert file

FileInputStream fin = new FileInputStream("certfile.cer");

// Get the X509 instance

CertificateFactory factory =

CertificateFactory.getInstance("X.509");

// Get the cert

X509Certificate cert =

(X509Certificate)factory.generateCertificate(fin);

System.out.println(cert);

}

Page 99: Java Web Security Class

The output of the certificate(raw format)

[[

Version: V3 Subject: CN=Rich Helton, OU=CDLE, O=CDLE, L=Denver, ST=CO, C=US

Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3

Key: Sun DSA Public Key Parameters:DSA

p: fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669

455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7 6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb

83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7 q: 9760508f 15230bcc b292b982 a2eb840b f0581cf5

g: f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267

5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1 3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a

y: d78219ab 6ca89423 e7f3f412 7d6d4664 61cba86a 40452899 1f977b9e 7e60bb27 e7eabaab 54334bab c19c9999 d9976905 379de8b3 b99a9ba0 6efc1c73 e2b3437a

c92aaf0e 4daada30 6792f298 d8a0ff60 7b5e1d3b 66ee3675 b77bfcdf 39efd06e e79ccbd9 ffd7ec65 cf50fe90 fbb0d6c7 851dcd2a 5c6b1472 7840d702 9c7250fa

Validity: [From: Tue Mar 25 19:06:00 MDT 2008, To: Mon Jun 23 19:06:00 MDT 2008]

Issuer: CN=Rich Helton, OU=CDLE, O=CDLE, L=Denver, ST=CO, C=US SerialNumber: [ 47e9a178]

] Algorithm: [SHA1withDSA]

Signature:0000: 30 2E 02 15 00 8C 77 26 B7 60 EA AF 14 DF 91 BF 0.....w&.`......0010: 3B A6 00 7A 6F 99 D9 47 21 02 15 00 88 99 96 A5 ;..zo..G!.......

0020: CC 6A 41 1E 83 E9 72 A7 9B A8 45 D9 EA 0D B3 63 .jA...r...E....c

]

Page 100: Java Web Security Class

Cleaning it up…

Page 101: Java Web Security Class

Better printout…

Page 102: Java Web Security Class

A word about passwords

Never use default passwords or simple passwords. Websites can get accessed by typing in “admin” “admin”

at times, and auditors try a range of default and well known logins.

Use complex and different passwords, if its hard to keep track of them then use something like keepass. http://keepass.info/

Page 103: Java Web Security Class

Web Services

Page 104: Java Web Security Class

Intro to SOA

Web Services are a Application Programming Interface (API), Web APIs, that are accessed via Hypertext Transfer Protocol (HTTP) and executed on remote system hosting the requested services.

The eXtensible Markup Language (XML) defines the interfaces and content of the message.

A Service Oriented Architecture (SOA) is a flexible set of design principles to define a architecture to provide a loosely-integrated suite of services that can be used in multiple business domains. This architecture makes extensive use of XML.

Page 105: Java Web Security Class

SOA Stack

Page 106: Java Web Security Class

Steps in Web Services

The first step when a client seeks to interface to a Web Service, is that it must find the Web Service, for this purpose, UDDI is used.

UDDI provides for discovery of services and retrieval of their WSDL descriptions as a directory service. This service may require authentication and encrypt the HTTP protocol.

The UDDI will return the WSDL and forward the client to the proxy that will contain the service, usually in the form of a URL.

The WSDL will define the acceptable interface into the SOA. The client SOAP call will format the acceptable XML. SOAP

will act as an envelope to the SOA. The SOA will accept the call if it meets the WSDL criteria and

process the call. The SOA will respond based on the SOAP call to the

corresponding client.

Page 107: Java Web Security Class

Steps to Web Services

Page 108: Java Web Security Class

wsgen

There are several tools included in JDK 6 to help generate Web Service files, like wsimport and wsgen.

These tools were originally part of Sun’s Glassfish MetroProject and more information can be found at https://jax-ws.dev.java.net/ .

The wsgen tool generates JAX-WS portable artifacts used in JAX-WS web services.

The tool reads the we service endpoint class and generates all the required artifacts for web service deployment, and invocation.

Here is an example to generate the wrapper class needed for StockService annotated with the @WebService inside the stock directory:

wsgen –d stock –cp myclasspath stock.StockService

Page 109: Java Web Security Class

StockService.java(snippet)

Page 110: Java Web Security Class

JAX-WS Tools(creating server side files)

Page 111: Java Web Security Class

JAX-WS Tools(creating client side files)

Page 112: Java Web Security Class

SOAP

Simple Object Access Protocol (SOAP) is a protocol specification for exchanging structured information in Web Services.

SOAP will normally have a Envelope of XML text that usually consists of a SOAP Header and SOAP Body. SOAP will also require a transport mechanism like HTTPS to transport the XML.

Page 113: Java Web Security Class

SOAP

Page 114: Java Web Security Class

WS-Security

WS-Security (Web Services Security, or WSS for short) is an extension to SOAP to apply security to Web Services.

Apache has an Open Source version of WS-Security called WSS4j http://ws.apache.org/wss4j/

In order to use WSS4J, the Apache implementation of SOAP has to be used, called Apache Axis, http://ws.apache.org/axis2/

Page 115: Java Web Security Class

Apache Axis2

Apache Axis is an open source, XML based Web service framework.

It consists of a Java, and a C++, implementation of a SOAP server, and various utilities for APIs for generating and deploying Web Service applications.

Some of the tools include a Maven plugin to generate WSDL from Java.

It can be used to create the JWS (Java Web Service) file that exposes the web service. This file is exposed on a server like Apache Tomcat.

http://localhost:8080/axis/Calculator.jws

The deployment requires a specific deployment descriptor called a WSDD (Web Service Deployment Descriptor).

Axis2 also has API’s to integrate the XML into the Spring framework http://ws.apache.org/axis2/1_5_1/spring.html .

Page 116: Java Web Security Class

WSS4J Signature creation(Java)

Page 117: Java Web Security Class

WSS4J Signature creation(XML)

Page 118: Java Web Security Class

SOAP User Token(Java)

Page 119: Java Web Security Class

SOAP User Token(XML)

Page 120: Java Web Security Class

SOAP Server CallbackPassword Sample

Many of the samples could be either on the client or server, the client is initiating the call, and the server is responding.

The Server could implement a simple Callback routine to check that the user and password is correct when it receives the SOAP call:

Page 121: Java Web Security Class

Hacking Web Services

Page 122: Java Web Security Class

Intro to Hacking SOA

Web Services are means to interface and transport SOAP calls through XML.

The difference between hacking Web Services, is that the attacks are transmitted in the XML field, which is similar to HTML, instead of an HTML form field.

In other words, the XML must be parsed out to enter an attack in the “username” text field in the XML format instead of the “username” GUI form field in HTML.

Many of the attacks in Web Services are designed to attack the backend server application code that may not be validating.

Page 123: Java Web Security Class

SQL Injection with SOAP

Just as SQL Injection can be passed in the form field, it can also be passed in a SOAP call. Here is an example with passing a “ in the field:

Page 124: Java Web Security Class

XPATH Injection with SOAP

Xpath (XML Path Language) is a language defined to find information in an XML document.

It uses path to traverse traverse through the nodes of an XML document to look for specific information.

Xpath injection is similar to SQL injection except that the query strings are slightly different and it uses XML as its attack vector.

One example is to pass ‘ or 1=1 or ‘ ‘=‘ as the username to fake the database into a valid username: string(//user[name/text()='' or 1=1 or ''=''

and password/text()='foobar']/account/text())

Page 125: Java Web Security Class

LDAP Injection with SOAP

The Lightweight Directory Access Protocol (LDAP) is a protocol for storing directory services for an organization that usually includes user, group and machine policies. An example of an LDAP server is Microsoft’s Active Directory.

LDAP injection tries to get returned user information, or server information returning information in the error using “(“ in this example:

Page 126: Java Web Security Class

HTTPS

Page 127: Java Web Security Class

Https

Https (Http Secure) is a protocol designed to implement the Secure Socket Library (SSL), or Transport Layer Security (TLS), at port 443.

It is designed to provide a encrypted port, validate the Http Server, and in some cased validate the Http Client.

Page 128: Java Web Security Class

HttpsURLConnection Class

The HttpsURLConnection class supports HTTPS connections:

Page 129: Java Web Security Class

HttpsURLConnection Class

Page 130: Java Web Security Class

White Box Testing( in Open Source)

Page 131: Java Web Security Class

White Box Testing

White-Box testing is testing the system based on the internal perspective of the system.

In this case, this is also known as Static Analysis. These tools can find issues with the source code before

the code is actually executed. A list of tools can be found at

http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis

Page 132: Java Web Security Class

FindBugs on WebGoat

Page 133: Java Web Security Class

FindBugs on WebGoat, example 2

Page 134: Java Web Security Class

FindBugs (SQE Netbeans IDE) on Basic1 securibench micro

Page 135: Java Web Security Class

PMD (SQE Netbeans IDE) on Basic1 securibench micro

Page 136: Java Web Security Class

Java Grey Box Testing

Page 137: Java Web Security Class

Grey Box Testing

Grey Box is a combination of Black Box Testing and White Box Testing.

Knowing the code structure of applications and also knowing the implications of Web Security, a programmer can write customizable Web routines to test their applications.

Many of these Java Web Frameworks were created from JUnit, the Java Unit Testing Framework.

HTTPUnit is one such framework written on top of JUnit that can test HTTP’s Request, Responses, button clicks, Java Scripts, cookies and more without a browser.

Page 138: Java Web Security Class

HttpUnit Test (Successful Test of an HTTP Request/Response)

Page 139: Java Web Security Class

What about the HTML?

HTTPUnit is great for HTTP Requests and Responses, but what if I want to parse the HTML code directly from the Web Server and examine the HTML before doing any work.

HTMLUnit allows a “getPage()” routine to examine the HTML source code. This allows the walking through of “HREF”, images, and others

pieces of the HTML code before executing on the item.

Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin. This allows a recording of the browser actions that can be played

back execute buttons being pushed and actions inside the browser. Assertions can be executed on the HTML pages itself for checking

specific information. The test itself can be exported into Junit Java code to execute in Java.

Page 140: Java Web Security Class

HtmlUnit Test (Successful Test)(getting the CookBook anchor)

Page 141: Java Web Security Class

Selenium IDE Test

Page 142: Java Web Security Class

Does the framework matter?

JWebUnit wraps both HTMLUnit and Selenium so that code can be written for either framework using a unified framwork.

This way code can once in a single framework and executed using multiple HTML frameworks. http://jwebunit.sourceforge.net/

Page 143: Java Web Security Class

JWebUnit Test (Successful Test)

Page 144: Java Web Security Class

JWebUnit Test (Failed Test)

Page 145: Java Web Security Class

Validation

Page 146: Java Web Security Class

MVC

The Model-View-Controller is the most common design pattern in Software Architecture.

Here are the pieces:

Page 147: Java Web Security Class

MVC (model 2 JSP/Servlet)

1) The browser calls the servlet.

2) The servlet instantiates a Java bean that is connected to a database.

3) The servlet communicates with a JSP page.

4) The JSP page communicates with the Java bean.

5) The JSP page responds to the browser.

Page 148: Java Web Security Class

j_security_check Servlet

The JSP that will call the Servlet requires j_username and j_password:

<form method=post action="j_security_check" >

<input type="text" name= "j_username" >

<input type="password" name= "j_password" >

</form> The form is defined in the web.xml.

 <login-config>

<auth-method>FORM</auth-method>

<form-login-config>

<form-login-page>/login.jsp</form-login-page>

<form-error-page>/loginError.jsp</form-error-page>

</form-login-config>

</login-config>

 

Page 149: Java Web Security Class

MVC (model 2 Struts)

1) The browser calls the ActionServlet.

2) The servlet instantiates a FormBean that is connected to a database.

3) The servlet communicates with a JSP page.

4) The JSP page communicates with the Java bean.

5) The JSP page responds to the browser.

Page 150: Java Web Security Class

The ActionServlet

The ActionServlet gets it’s Actions (an object) to perform based on it’s configuration, thus saving a lot of coding.

Page 151: Java Web Security Class

Benefits of Struts

1) Declarative control that maps between the requests between the MVC.

2) Automated Request Dispatching using an ActioForward to request a specific ActionServlet.

3) Struts can provide DataSource management.

4) Struts provide custom tags.

5) Struts provide Internationalization Support.

6) Struts provide declarative error handling specific to application code.

7) Struts provide a declarative validation mechanism.

8) Struts provide a Plug-In interface.

Page 152: Java Web Security Class

Struts XSS vulnerability

Passing in am alert message <script>alert(123)</script>:

Page 153: Java Web Security Class

Struts XSS vulnerable

Page 154: Java Web Security Class

Struts Validation

Struts uses a combination of a Validator Plugin, a Validation ActionForm and the validation rules: A validator-rules.xml file in the WEB-INF folder. A validator.xml in the WEB-INF folder. All ActionForms should extend

org.apache.struts.validator.ValidatorForm or org.apache.struts.validator.ValidatorActionForm instead of org.apache.struts.action.ActionForm.

The commons-validator.jar in WEB-INF. The Validator plug-in should be enabled in struts-config.xml:

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">

<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validator.xml"/></plug-in>

Page 155: Java Web Security Class

As easy as Validation.xml doing Regex

<formset>

<form name="nameBean">

<field

property="name"

depends="required,mask">

<arg key="nameBean.name"/>

<var>

<var-name>mask</var-name>

<var-value>^[a-zA-Z]*$</var-value>

</var>

</field>

</form>

</formset>

Page 156: Java Web Security Class

Regex

The Java String has regex functionality:public class CheckLogin {

public static void main(String[] args) {

String firstTry= "RichH1";

if(firstTry.matches("^[a-zA-Z]*$"))

System.out.println("Matches");

else

System.out.println("Doesn't Match");

}

}

Console:Doesn't Match

Page 157: Java Web Security Class

^[a-zA-Z]*$

[a-zA-Z] is the range of characters in upper or lower case ^ and $ match the positions at the beginning and end of

the string, which mean search the entire string for the specific patter.

* mean Matches zero or more occurrences of the patter [a-zA-Z].

“RichH1” has a “1” that “Doesn’t Match”.

Page 158: Java Web Security Class

Struts XSS NOT-vulnerable

Page 159: Java Web Security Class

Java Server Faces (JSF)

JSF is a Java Web application framework intended to simplify development for web-based user interfaces. JSF allows reusable component objects that map to the tags on the JSP page. Managed JavaBeans components are used to encapsulate the data and application-specific functionality of the components.

Page 160: Java Web Security Class

Apache Tomahawk

Apache Tomahawk has extra features for extended the standard JSF specification, http://myfaces.apache.org/tomahawk/index.html.Here is an example in the JSF for a credit card, the code itself for the validation will be defined in a managed bean, here’s a sample of the tag from org.apache.myfaces.custom.creditcardvalidator.CreditCardValidator:

Page 161: Java Web Security Class

Apache Tomahawk

A piece of org.apache.myfaces.custom.creditcardvalidator.CreditCardValidator:

Page 162: Java Web Security Class

JSF Designer

Many IDE’s have a JSF Designer that includes Validators like JDeveloper:

Page 163: Java Web Security Class

Ajax

Asynchronous JavaScript and XML (Ajax) is a method of employing JavaScript, DHTML, and the XML Http behavior in a browser to provide truly dynamic content on a Web page without a page refresh. Data is usually retrieved using the XMLHttpRequest (XHR) object from the server asynchronously. Javascript (ECMAScript) is used for local processing, and the Document Object Model (DOM) is used to access the data inside the page or read XML from the server. Ajax is not a technology in itself, but a group of technologies.

Page 164: Java Web Security Class

Ajax (a walk through-javascript)

Let’s start by calling a validate() function in JavaScript with the onkeyup method:

<input type="text” size="20” id="userid” name="id” onkeyup="validate();">The validate() creates a XMLHttpRequest to pass to the server:

var req;

function validate() {

var idField = document.getElementById("userid");

var url = "validate?id=" + encodeURIComponent(idField.value);

if (typeof XMLHttpRequest != "undefined") {

req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.XMLHTTP"); }

req.open("GET", url, true);

req.onreadystatechange = callback;

req.send(null);}

Page 165: Java Web Security Class

Ajax (a walk through – Http POST)

The XMLHttpRequest is sent to the server, preferably using an “encodeURIComponent( )” method to preferably to mask the URI, and a Http POST method by setting the Content-Type header in the XMLHttpRequest:

req.setRequestHeader("Content-Type", "application/x-www-form- urlencoded");

req.send("id=" + encodeURIComponent(idTextField.value)); The “decodeURIComponent( )” will decode the URI from the browser. The browser has to interpret the Javascript regardless of how it is encoded and decoded. If a browser can read the Javascript, then the Javascript can be debugged/monitored and manipulated using a JavaScript reverser to intercept the functions. The defense is to validate the Server code.

Page 166: Java Web Security Class

Ajax (a walk through – ValidateServlet)

The request is now on the server and is processed by the ValidateServlet:

Page 167: Java Web Security Class

Ajax (a walk through – Return to Browser)

The ValidateServlet will return an XML document with the results.The XMLHttpRequest will call the “callback” function in the Html browser to start updating the HTML:

The HTML will have it’s XML DOM updated, to refresh the page, or a portion of the HTML page:

Page 168: Java Web Security Class

Ajax Frameworks

How you program Ajax will depend on which Ajax framework you use, but most J2EE Servers will support some form of Ajax. The Dojo Toolkit http://dojotoolkit.org/ is the Swiss army knife of Java script libraries containing APIs and widgets for web applications. Dynamic Web Remoting (DWR), https://dwr.dev.java.net/ , which uses RPC from the client side JavaScript to Plain Old Java objects (POJO) in a J2EE web container. The Google Web Toolkit (GWT), http://code.google.com/webtoolkit/ , that allows a developer to write an Ajax application in pure Java. Oracle Application Framework (ADF) Faces Rich Client framework with more than 150 JSF components with built-in Ajax capabilities.

http://www.oracle.com/technetwork/developer-tools/adf/overview/index.html

Page 169: Java Web Security Class

ADF Task Flow Designer

JDeveloper has an ADF Task Flow Designer to assist in its ADF View Flow:

Page 170: Java Web Security Class

Adobe Flex

Adobe Flex is a Software Development Kit from Adobe to create Rich Internet Applications (RIA) that plug into the Web Browser’s Flash plugin. Flex uses MXML, the Macromedia XML, as a declarative layout of the interfaces to compile into the SWF file that is deployed. To extend the MXML, Flex uses a language called ActionScript, which is similar to Java. ActionScript can be called from the MXML file using the <mx:script> tag.

<mx:script source = “code.as”/>

Page 171: Java Web Security Class

MXML Hello World Example

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundGradientColors="[#000011, #333333]"> <mx:Label text="Hello World!" verticalCenter="0" horizontalCenter="0" fontSize="48" letterSpacing="1"> <mx:filters>

<mx:GlowFilter color="#ffffdd"/> </mx:filters> </mx:Label>

</mx:Application>

Page 172: Java Web Security Class

FlexBuilder 3 Example

Page 173: Java Web Security Class

Example <mx:CreditCardValidator> tag

Page 174: Java Web Security Class

Object-Relational Mapping (ORM)

Struts can use XML configurations for mapping validation and rules. Hibernate, can now be added, as a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java, or .NET, objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks. The main advantages of Hibernate is that maps database entities to objects and hides the details of the data access from the business logic.Hibernate uses prepared statements, so it is protected from direct SQL injection, but it could still be vulnerable to injecting HQL statements.

Page 175: Java Web Security Class

Sample Customer Mapping

Page 176: Java Web Security Class

Hibernate Validator

Hibernate has it’s own Validator plugin http://www.hibernate.org/subprojects/validator.html .This validator will not only validate the values but can also validate the size of the data before being persisted. Sample validator annotations:

public class Car {

@NotNull

private String manufacturer; // Cannot be null

@NotNull

@Size(min = 2, max = 14)

@CheckCase(CaseMode.UPPER)

private String licensePlate; // must be upper case between 2-14 chars

Page 177: Java Web Security Class

Spring Framework, AOP and IoC

Aspect Oriented Programming takes Object Oriented Programming one step further by separating out the cross-cutting concerns and assigning them to the framework. An example of a cross-cutting concern is Transaction management.The Spring framework is an Open source framework that introduces AOP by managing, or taking care of the plumbing, of the business objects. http://www.springsource.com/Spring introduces the concept of Inversion of Control (IoC), which simply means instead of having the application call the framework, the framework will call the components defined by the application. I like to think of IoC as collecting the application pieces in modular blocks. The IoC knows how to manage the blocks when it needs to deal with them correctly.Spring provides the "Spring Security" framework that allows different implementations to be connected seamlessly to the application.

Page 178: Java Web Security Class

Spring Security

Spring also uses annotation security for authentication and authorization.Here is an example that a user must be logged in and validated before being allowed to change a password:public interface IUserService {

@PreAuthorize("hasRole('ROLE_USER')") public void changePassword(String username, String password); }

Otherwise:

Page 179: Java Web Security Class

Spring Security

Spring also uses annotation security for authentication and authorization.Here is an example that a user must be logged in and validated before being allowed to change a password:public interface IUserService {

@PreAuthorize("hasRole('ROLE_USER')") public void changePassword(String username, String password); }

Otherwise:

Page 180: Java Web Security Class

Seam Framework, bi-injection

The project lead of JBoss, Gavin King, founded the Seam project in September 2005. Seam is packaged by default with JBoss, an Open Source Java Application Service, owned and packaged with Red Hat. The Seam framework is bi-injection framework to bridge the gap between Java Server Faces (JSF) and the Java Persistence API (JPA) of EJB 3. It can be thought of as the glue between the JSF and EJB3, using @In, for injection, and @Out for reverse injection.

Page 181: Java Web Security Class

Seam Annotations

Seam annotations are similar to Spring and Hibernate annotations, here is a minimum and maximum annotation:

Page 182: Java Web Security Class

Putting it all together

Page 183: Java Web Security Class

Web Application Firewalls(A supplemental fix)

Page 184: Java Web Security Class

WAF ( A quick fix)

Instead of rewriting code, some potentially quicker methods is to put an application to intercept the HTTP traffic ahead of the HTTP server known as a Web Application Firewall (WAF).

The WAF takes configurations like a normal firewall on what traffic to pass and reject. The difference is that it is responding specifically to an HTTP server like Apache or IIS.

For Apache, the most popular approach is to use its Open Source plugin called mod_security.

For IIS, WebKnight from AQTronix, http://aqtronix.com/?PageID=99 is the most popular Open Source solution.

Not everything can be covered by a WAF, especially session hijacking flaws, but XSS and SQL Inj can be mitigated. http://www.owasp.org/index.php/Category:OWASP_Best_Practices:_Use_of_Web_Application_Firewalls

Page 185: Java Web Security Class

WAF ( Not just a server fix)

WAFs are filters that sit in front of the Web Application. To understand WAF’s is to understand validation filtering

as it approaches the Web site. WAFs are similar to the J2EE filter Stinger http://www.owasp.org/index.php/Category:OWASP_Stinger_Project

Depending on their configuration, they will deny, or log, validated information from the Internet into the Application.

They are a good source in auditing the information that is hitting the Web site and the scans that are constantly taking place.

Page 186: Java Web Security Class

Why IIS and Apache

Apache, an Open Source Web Server, is used by many companies, from 2007-2009, it went from 20% to 30% used by Fortune 500 companies.

Page 187: Java Web Security Class
Page 188: Java Web Security Class

ASP.NET Hacme Bank (SQL Injection)

Page 189: Java Web Security Class

Accepted SQL Injection

Page 190: Java Web Security Class

With WebKnight Installed

Page 191: Java Web Security Class

Tomcat will need Apache

Page 192: Java Web Security Class

Tomcat will need Apache

To link Tomcat and Apache, the mod_jk module will need to be installed, see http://tomcat.apache.org/connectors-doc/ . Also known as the Tomcat Connector.

Note: Tomcat can also use Microsoft’s IIS, instead of Apache, utilizing the Microsoft ISAPI plugin. The easiest way to install the mod_jk connector is to have

Tomcat generate “conf/auto/mod_jk.conf” from its Container and have Apache reference it from its “conf/httpd.conf” file: LoadModule jk_module modules/mod_jk.so

Include C:/Apache2/apache-tomcat-6.0.28/conf/auto/mod_jk.conf

See http://www.johnturner.com/howto/apache2-tomcat4129-jk-winxp-howto.html

Page 193: Java Web Security Class

Apache mod_security

The mod_security module information can be found at http://www.modsecurity.org/

Load the mod_security and unique id modules (this example is XP) in conf/httpd.conf: LoadModule security2_module modules/mod_security2.so

LoadModule unique_id_module modules/mod_unique_id.so

Add the base configuration and some of the base rules: Include conf/mod_security.conf

Include conf/base_rules/modsecurity_crs_41_xss_attacks.conf

Include conf/base_rules/modsecurity_crs_23_request_limits.conf

Include conf/base_rules/modsecurity_crs_35_bad_robots.conf

Include conf/base_rules/modsecurity_crs_40_generic_attacks.conf

Include conf/base_rules/modsecurity_crs_41_sql_injection_attacks.conf

Page 194: Java Web Security Class

Now try the Struts XSS

Page 195: Java Web Security Class

XSS still there?

Page 196: Java Web Security Class

What do the audit logs say?

It looks like the rules for XSS fired for <script>, alert, and </script>:

Page 197: Java Web Security Class

What does the rule say?

In the modsecurity_crs_41_xss_attacks.conf, it says pass and audit:

Page 198: Java Web Security Class

Change the rule to deny

After changing “pass” to “deny”, we get the following screen now for the XSS attack to successfully block XSS:

Page 199: Java Web Security Class

Change the rule to deny

Another way is to set the default Security rule. When the following is added, we are including all base

rules, and setting the default return status to “500”, which is an “Internal Server Error”:

Include conf/mod_security.conf

SecDefaultAction "phase:Any,log,deny,status:500"

Include conf/base_rules/*.conf

The audit.log shows the 500 execution:

HTTP/1.1 500 Internal Server Error

Content-Length: 537

Connection: close

Content-Type: text/html; charset=iso-8859-1

Page 200: Java Web Security Class

The 500 XSS displayed

Page 201: Java Web Security Class

Reference

The Open Web Application Security Project (OWASP) provides and updated set of rules for the mod_security at http://www.owasp.org/index.php/Category:OWASP_ModSecurity_Core_Rule_Set_Project

It provides installation instructions as well as installing the configuration in httpd.conf:<IfModule security2_module>

Include conf/modsecurity_crs/*.conf

Include conf/modsecurity_crs/base_rules/*.conf

</IfModule>

Page 202: Java Web Security Class

What about WebLogic?

WebLogic can still use Apache to proxy the mod_security firewall.

It will use the WebLogic mod_wl to have Apache talk to Weblogic directly instead of the mod_jk. See http://download.oracle.com/docs/cd/E13222_01/wls/docs81/plugins/apache.html#101251

Page 203: Java Web Security Class

What about WebSphere?

WebSphere uses the was_ap22_module for Apache 2.2., the was_ap20_module for Apache 2.0, etc. The module

Installtion instructions can be found at http://www-01.ibm.com/support/docview.wss?rs=180&uid=swg21268651

Page 204: Java Web Security Class

What about other servers (like Domino)?

If the server doesn’t have a plugin, like Tomcat to talk to the Application’s Server Listener/Handler, Apache can be set up as a proxy to just observe and pass the protocol to the Server. This is the mod_proxy module for Apache.

Page 205: Java Web Security Class

What about Denial of Service?

Apache also provides a plugin for Denial of Service, this is the mod_evasive plugin.

Mod_evasive will slow down the number of hits from the same client to the same URL to ten seconds per hit. This is based in the following configuration:<IfModule mod_evasive20.c>

DOSHashTableSize 3097 # Size of memory for Hashing

DOSPageCount 2 # Number of request to same page

DOSSiteCount 50 # Blacklist after 50 times

DOSPageInterval 1 # 1 second interval for the page

DOSSiteInterval 1 # 1 second interval for the site

DOSBlockingPeriod 10 # Number of seconds to block

</IfModule>

Page 206: Java Web Security Class

Conclusion

Pro’s: Installing a WAF is quicker, in most cases, than changing code and re-

deploying a Web Application.

WAF’s may find issues, by using its rule sets, that the code may not be prepared to find. This is because WAFs have thousands of rules generated by industry experts.

Con’s:WAFs are limited by the rules that are installed in them. Therefore, if the rule is not there, it cannot protect against it.

Validation is a better protection, because form level validation will use white-listing on what input is allowed, versus black-listing on the input that is denied.

Page 207: Java Web Security Class

Revisiting Common Fixes

Some of the techniques of security are just a frame of mind. Encrypt the tunnel, simply using SSLv3 and Point-to-Point

VPN tunneling that comes with Servers and Firewalls can alleviate many encryption issues.

Use only common encryption algorithms that come with Java and have been tested by thousands of uses like AES.

Use common libraries, and if possible, open source, that can be reviewed for concerns.

Test as much as possible for abnormal cases, and automate the testing as much as possible so that the testing can be done again and again.

Use the most standard principles and frameworks, as possible, because programs always require upgrades to new security threats.

Page 208: Java Web Security Class

Final Thoughts

Page 209: Java Web Security Class

Final Thoughts

Are there any Questions? Feel free to contact me at [email protected] Also, always only try these tools with your own

test site or with permission of the system owner.

Page 210: Java Web Security Class

Extra:Secure FTP programming

Page 211: Java Web Security Class

JFtp– Java Network Browser

We will start with a program framework. The program can be found at http://j-ftp.sourceforge.net/ The source code can be found at

http://sourceforge.net/projects/j-ftp/files/.

Page 212: Java Web Security Class

Benefits of JFtp

Can run the Java code from the browser through “Web Start”.

Can download the JAR file and run it locally. Cross Platform. Runs easily on Mac OSX, Linux, Windows,

etc. Runs multiple protocols, SFTP, SMB, NFS, HTTP, and

various transfer protocols. Open Source so the code can be used to execute batch

jobs. Free to use. We will change it for batch programming.

Page 213: Java Web Security Class

To Launch or Download

JFtp can be run directly from the browser or downloaded.

Page 214: Java Web Security Class

To Launch

Clicking on “Launch via Java Web Start” will launch the JFtp from the browser.

Java must be able to run from the local Browser. If so a Security Warning will pop up:

Page 215: Java Web Security Class

To Launch

After clicking the “Run” button. JFtp Starts:

Page 216: Java Web Security Class

To Launch

Clicking on File->Connect to SFTP Server….. SFTP Configuration Starts:

Page 217: Java Web Security Class

Matching

When configuring SFTP, the ports, encryption, and authentication must match the server configuration for handshaking.

The source for the dialog box can be found at http://kickjava.com/src/net/sf/jftp/gui/hostchooser/SftpHostChooser.java.htm

Page 218: Java Web Security Class

Testing

One method to test locally is to pull down OpenSSH on a test machine.

OpenSSH can be found at http://www.openssh.com/ . Using OpenSSH, users and groups can be created using: C:\Program Files\OpenSSH\bin>mkpasswd -l -u RichH >> ..\etc\passwd

C:\Program Files\OpenSSH\bin>mkgroup -l >> ..\etc\group

Starting open SSH is done with:

Verify it is started:

Page 219: Java Web Security Class

Testing

Let’s connect through SFTP:

If Successful, the log window will tell you:

Page 220: Java Web Security Class

Testing SSH

Let’s connect SSH through Tools->SSH Shell…:

If Successful, the SSH Shell will appear:

Page 221: Java Web Security Class

JAR File

Instead of running from the “Web Start”, a JAR file can be used to run it using the “java –jar jtp.jar” command.

If Java is configured correctly, the JFtp will run in a Java Console that works like the “Web Start” version.

Some information about the GUI may be displayed:

Page 222: Java Web Security Class

Compiling Java

Page 223: Java Web Security Class

Compiling at the JFtp Code

The source code can be found at http://sourceforge.net/projects/j-ftp/files/.

Unzip the source, cd to j-ftp and ensure that the build.xml file is present:

Build.xml is the build file, similar to a “make” file for “C”, that Apache Ant will use to build and deploy the files.

Page 224: Java Web Security Class

ANT

Ant is a Java library and command-line tool. Ant's mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications.

It can be found http://ant.apache.org/

Another tool to use is Maven.

Page 225: Java Web Security Class

Building

After installing Ant, run it in the build.xml directory:

Page 226: Java Web Security Class

Running

The build will create a jtfp.jar file in the builds/jars directory.

This file can be run with the “java –jar jftp.jar” command.

Page 227: Java Web Security Class

Editing JFTP

Page 228: Java Web Security Class

Looking at the JFtp Code

The review Java Code, I usually use Jedit, because it is a simpler editor, found at http://www.jedit.org/ .

Eclipse is also one of the most Java Editor, found at http://www.eclipse.org/ . More information can be found at http://en.wikipedia.org/wiki/Eclipse_ide .

These editors are Open Source with any plugins for coding.

The main file will be found at “src\java\net\sf\jftp\JFtp.java”.

Notice that the “package” name is “net.sf.jftp” which will define where the file has to live as well, as will as where the files will be placed in the JAR.

Page 229: Java Web Security Class

Looking at the JFtp Code

Jedit on JFtp.java:

Page 230: Java Web Security Class

Looking at the JFtp Code

To get UML diagrams of the code, ArgoUML can be used to parse the code to display the diagrams.

ArgoUML is an Open Source UML Modeler found at http://argouml.tigris.org/ .

Page 231: Java Web Security Class

ArgoUML of JFtp

Page 232: Java Web Security Class

Javadocs

Javadocs is a document generating tool that is part of Java that generates HTML files describing the Java code. Referenced from http://en.wikipedia.org/wiki/Javadocs .

This is a way to self document the code. Inserting macros and comments in the code will create an HTML browse able view of the code:

Page 233: Java Web Security Class

Free Samples, as always

JFtp provides free sample code if you don’t want to use the GUI.

Under the doc directory, FTPDownload.java provides a download examples, and FTPUpload.java provides a upload example.

The “Web Start” code can also be found in this directory in the code “jftp.jnlp”

Information on the Java Network Launching Protocol can be found at http://en.wikipedia.org/wiki/.jnlp .

Page 234: Java Web Security Class

Compiling FtpDownload

Make sure that the jftp.jar is in the classpath and compile the FtpDownload.java.

Page 235: Java Web Security Class

JFtp Libraries

Page 236: Java Web Security Class

JFtp makes use of 2 different Java Libraries

JFtp uses a library for Jcraft’s “jsch” library, which is their Java Secure Shell, when the “Use JSch instead of j2ssh” is selected:

Page 237: Java Web Security Class

JSch

The JSch package is found at http://www.jcraft.com/jsch/ Otherwise the standard j2ssh library is used found at

http://sourceforge.net/projects/sshtools/ . Both libraries support the Secure Copy Protocol (SCP) for

copying files through SSH. JFtp creates wrappers in its net.sf.jtp.net.wrappers for use

of such classes as SftpConnection, NfsConnection, HttpTransfer, Sftp2Connection, etc. that does the connection, downloading, uploading, change directory, remove directory and other work.

Page 238: Java Web Security Class

JSch

The JSch package is found at http://www.jcraft.com/jsch/ Otherwise the standard j2ssh library is used found at

http://sourceforge.net/projects/sshtools/ . Both libraries support the Secure Copy Protocol (SCP) for

copying files through SSH. JFtp creates wrappers in its net.sf.jtp.net.wrappers for use

of such classes as SftpConnection, NfsConnection, HttpTransfer, Sftp2Connection, etc. that does the connection, downloading, uploading, change directory, remove directory and other work.

Page 239: Java Web Security Class

Sftp2Connection Class

One of the wrapper classes that uses the Jsch library is the Sftp2Connection class.

This class has functionality for login, setLocalPath, upload, download, and more.

Page 240: Java Web Security Class

Sftp2Connection upload snippet( A batch program)

public static void main(String[] args) {

String username = "RichH";

String password = ”password";

Sftp2Connection conn = new Sftp2Connection("localhost", ""+22, null);

conn.login(username,password);

System.out.println("PWD:" +conn.getPWD());

System.out.println("Local Path:"+conn.getLocalPath());

conn.setLocalPath("/jars");

System.out.println("Local Path:"+conn.getLocalPath());

conn.upload("jftp.jar");

conn.disconnect();

}

Page 241: Java Web Security Class

Sftp2Connection Upload snippet

The code snippet will create a secure connection for the Sftp2Connection class.

Then the login( ) function will authenticate using the username and password.

The Local directory will be the root directory as well as the remote directory, so the local directory is changed to “C:\jars”.

This directory contains “C:\jars\jftp.jar” that is uploaded with the upload ( ) function.

If there is any error along the way, an exception will happen pointing at the stack where the error code appeared.

Page 242: Java Web Security Class

Sftp2Connection Upload snippet

Running through JFtp manually, you can observe if the file is uploaded: