SlideShare une entreprise Scribd logo
1  sur  242
Java Web Security Coding ( The Open Source Way) August 26, 2010 BY RICH HELTON
Introduction ,[object Object]
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)
What motivates Hackers.
Which organizations are attacked.
The outcome can be expensive
http://www.zone-h.org/news/id/4735
There are many hacks…. ,[object Object],Injection Flaws Cross Site Scripting (XSS) Broken Authentication and Session Management Insecure Direct Object  Reference Cross Site Request Forgery (CSRF) Security Misconfiguration Insecure Cryptographic Storage Failure to Restrict URL Access Insufficient Transport Layer Protection Unvalidated Redirects and Forwards
There are many Checklists…. ,[object Object]
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,[object Object]
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. ,[object Object]
Spiders, Bots, and Crawlers! Oh my... ,[object Object]
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. ,[object Object]
Google Hacking ,[object Object]
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”,[object Object],[object Object],[object Object]
Wget (Open Source Web downloaders) ,[object Object],[object Object],[object Object]
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,[object Object],[object Object]
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. ,[object Object],[object Object]
Grendel-scan ,[object Object],[object Object]
Practicing the Web Hack…. ,[object Object]
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/
Live sites… ,[object Object]
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,[object Object]
http://www.hackthissite.org/missions/basic/
http://hackme.ntobjectives.com/
http://www.astalavista.com/index.php?app=hackingchallenge
http://hax.tor.hu/
A list can be found at http://www.wechall.net/sites.php,[object Object]
Has my system been compromised? ,[object Object]
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. ,[object Object]
Output:import java.util.logging.*; import java.io.*; public class TestLog { public static void main(Stringargs[]) {     try{     	Logger logger = Logger.getLogger("TestLog"); FileHandlerfh = new FileHandler("mylog.txt"); fh.setFormatter(newSimpleFormatter()); logger.addHandler(fh); logger.severe("my severe message"); logger.warning("my warning message"); logger.info("my info message");     } catch (IOExceptione) {e.printStackTrace(); }}} Mar 25, 2008 8:43:48 PM TestLog main SEVERE: my severe message Mar 25, 2008 8:43:49 PM TestLog main WARNING: my warning message Mar 25, 2008 8:43:49 PM TestLog main INFO: my info message
Java Exception Handling ,[object Object]
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. ,[object Object]
Log4j ,[object Object]
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. ,[object Object]
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.
SMTP Appender ,[object Object],[object Object]
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.  ,[object Object]
Custom Error Pages ,[object Object],<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>
SQL Injection (Most common Injection Flaw)
Intro to SQL Injection… ,[object Object]
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.,[object Object]
For example: SELECT * FROM users WHERE username = ‘USRTEXT ' 
AND password = ‘PASSTEXT’ ,[object Object],SELECT * FROM users WHERE username = ‘’ OR 1=1 -- ' 
AND password = ‘PASSTEXT’ ,[object Object],[object Object]
ASP.NET HacmeBankAuthentication without username/password
Types of SQL Injection… ,[object Object]
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. ,[object Object]
HackmeBooks SQL Injection(shows org.hsqldb.jdbc connection)
HackmeBooks SQL Injection(attacking) ,[object Object]
Session is now closed because we shutdown the database:,[object Object]
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. ,[object Object]
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,[object Object]
XSS (Cross Site Scripting)
XSS ,[object Object]
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. ,[object Object]
Hacme Books XSS… ,[object Object],[object Object],[object Object]
Common fixes to XSS ,[object Object]
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,[object Object]
There seems to be some issues in my sample Web Apps ,[object Object],[object Object]
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….,[object Object]
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 ,[object Object],[object Object],[object Object]
Did anything happen? Has the original page changed?,[object Object]
The Apache website was called with the current browser settings (including the session cookie). ,[object Object]
The Fix ,[object Object]
It will scrub the input before the HelloWorldServlet 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.  ,[object Object]
Testing the Fix ,[object Object]
The IMG didn’t process in the Servlet output. There is no Apache image border. ,[object Object]
After the filter,[object Object]
Session Management	 ,[object Object]
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. ,[object Object]
Session Management(programmatic)	 ,[object Object],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.  ,[object Object],// Method in servlet or struts action class public void approveAssignment(HttpServletRequestreq,   WorkOrderworkOrder) {       if ((req.isUserInRole(“MaintWorker”) &&               req.isUserInRole(“MaintSuper”)) ||           req.isUserInRole(“Manager”) {       workOrder.approveWorkAssignment();       } else {       throw new SecurityException(“...”);    }    ... }
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.Useru = realm. getUser(userName) ;
Encryption
Who’s seeing your data? 	 ,[object Object]
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. ,[object Object]
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).
Md5 ,[object Object]
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. ,[object Object]
Sha1 ,[object Object]
Other SHA’s are SHA224,SHA256,SHA384, and SHA512, each one denoting the size in bits of the message digest. ,[object Object]
AES ,[object Object]
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.,[object Object]
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.
RSA ,[object Object]
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.,[object Object]
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)));}}
RSA, the output….. (Done,  Pretty complicated Algorithm)
Digital certificates
Beyond Encryption ,[object Object]
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. ,[object Object]
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. ,[object Object]
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:gt;keytool –list –v –keystore.jks
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:gt;keytool -export –keystorekeystore.jks -aliasmydomain-file certfile.cer Enter keystore password: Certificate stored in file <certfile.cer>
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); }
The output of the certificate(raw format)
Cleaning it up…
Better printout…
A word about passwords ,[object Object]
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/,[object Object]
Intro to SOA	 ,[object Object]
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. ,[object Object]
Steps in Web Services ,[object Object]
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. ,[object Object]
wsgen ,[object Object]
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 myclasspathstock.StockService
StockService.java(snippet)
JAX-WS Tools(creating server side files)
JAX-WS Tools(creating client side files)
SOAP ,[object Object]
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.  ,[object Object]
WS-Security ,[object Object]
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/,[object Object]
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 ,[object Object]
Axis2 also has API’s to integrate the XML into the Spring framework http://ws.apache.org/axis2/1_5_1/spring.html . ,[object Object]
WSS4J Signature creation(XML)
SOAP User Token(Java)
SOAP User Token(XML)
SOAP Server CallbackPassword Sample ,[object Object]
The Server could implement a simple Callback routine to check that the user and password is correct when it receives the SOAP call:,[object Object]
Intro to Hacking SOA	 ,[object Object]
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.  ,[object Object],[object Object]
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())
LDAP Injection with SOAP	 ,[object Object]
LDAP injection tries to get returned user information, or server information returning information in the error using “(“ in this example:,[object Object]
Https ,[object Object]
It is designed to provide a encrypted port, validate the Http Server, and in some cased validate the Http Client. ,[object Object],[object Object]
White Box Testing ( in Open Source)
White Box Testing ,[object Object]
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,[object Object]
FindBugs on WebGoat, example 2
FindBugs (SQE Netbeans IDE) on Basic1 securibench micro
PMD (SQE Netbeans IDE) on Basic1 securibench micro
Java Grey Box Testing
Grey Box Testing ,[object Object]
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.  ,[object Object]
What about the HTML? ,[object Object]
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. ,[object Object]
Selenium IDE Test
Does the framework matter? ,[object Object]
This way code can once in a single framework and executed using multiple HTML frameworks. http://jwebunit.sourceforge.net/,[object Object]
JWebUnit Test (Failed Test)
Validation

Contenu connexe

Tendances

Attack Chaining: Advanced Maneuvers for Hack Fu
Attack Chaining: Advanced Maneuvers for Hack FuAttack Chaining: Advanced Maneuvers for Hack Fu
Attack Chaining: Advanced Maneuvers for Hack FuRob Ragan
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraMathias Karlsson
 
BruCon 2011 Lightning talk winner: Web app testing without attack traffic
BruCon 2011 Lightning talk winner: Web app testing without attack trafficBruCon 2011 Lightning talk winner: Web app testing without attack traffic
BruCon 2011 Lightning talk winner: Web app testing without attack trafficAbraham Aranguren
 
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...joaomatosf_
 
Defending against Java Deserialization Vulnerabilities
 Defending against Java Deserialization Vulnerabilities Defending against Java Deserialization Vulnerabilities
Defending against Java Deserialization VulnerabilitiesLuca Carettoni
 
Bug bounties - cén scéal?
Bug bounties - cén scéal?Bug bounties - cén scéal?
Bug bounties - cén scéal?Ciaran McNally
 
Abusing Java Remote Interfaces
Abusing Java Remote InterfacesAbusing Java Remote Interfaces
Abusing Java Remote Interfacesjuanvazquezslides
 
Django Web Application Security
Django Web Application SecurityDjango Web Application Security
Django Web Application Securitylevigross
 
Java script, security and you - Tri-Cities Javascript Developers Group
Java script, security and you - Tri-Cities Javascript Developers GroupJava script, security and you - Tri-Cities Javascript Developers Group
Java script, security and you - Tri-Cities Javascript Developers GroupAdam Caudill
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.Mikhail Egorov
 
Securing AEM webapps by hacking them
Securing AEM webapps by hacking themSecuring AEM webapps by hacking them
Securing AEM webapps by hacking themMikhail Egorov
 
OWASP OWTF - Summer Storm - OWASP AppSec EU 2013
OWASP OWTF - Summer Storm - OWASP AppSec EU 2013OWASP OWTF - Summer Storm - OWASP AppSec EU 2013
OWASP OWTF - Summer Storm - OWASP AppSec EU 2013Abraham Aranguren
 
Same Origin Policy Weaknesses
Same Origin Policy WeaknessesSame Origin Policy Weaknesses
Same Origin Policy Weaknesseskuza55
 
from 33 to 0 - A journey to be root
from 33 to 0 - A journey to be rootfrom 33 to 0 - A journey to be root
from 33 to 0 - A journey to be rootAmmar WK
 
MITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveMITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveGreenD0g
 
Everybody loves html5,h4ck3rs too
Everybody loves html5,h4ck3rs tooEverybody loves html5,h4ck3rs too
Everybody loves html5,h4ck3rs tooNahidul Kibria
 
Think Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack VectorsThink Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack VectorsMark Ginnebaugh
 
Two scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesSpin Lai
 
Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018
Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018
Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018Andy Davies
 

Tendances (20)

Attack Chaining: Advanced Maneuvers for Hack Fu
Attack Chaining: Advanced Maneuvers for Hack FuAttack Chaining: Advanced Maneuvers for Hack Fu
Attack Chaining: Advanced Maneuvers for Hack Fu
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 
BruCon 2011 Lightning talk winner: Web app testing without attack traffic
BruCon 2011 Lightning talk winner: Web app testing without attack trafficBruCon 2011 Lightning talk winner: Web app testing without attack traffic
BruCon 2011 Lightning talk winner: Web app testing without attack traffic
 
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
 
Defending against Java Deserialization Vulnerabilities
 Defending against Java Deserialization Vulnerabilities Defending against Java Deserialization Vulnerabilities
Defending against Java Deserialization Vulnerabilities
 
Bug bounties - cén scéal?
Bug bounties - cén scéal?Bug bounties - cén scéal?
Bug bounties - cén scéal?
 
Abusing Java Remote Interfaces
Abusing Java Remote InterfacesAbusing Java Remote Interfaces
Abusing Java Remote Interfaces
 
Django Web Application Security
Django Web Application SecurityDjango Web Application Security
Django Web Application Security
 
Java script, security and you - Tri-Cities Javascript Developers Group
Java script, security and you - Tri-Cities Javascript Developers GroupJava script, security and you - Tri-Cities Javascript Developers Group
Java script, security and you - Tri-Cities Javascript Developers Group
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
 
Securing AEM webapps by hacking them
Securing AEM webapps by hacking themSecuring AEM webapps by hacking them
Securing AEM webapps by hacking them
 
OWASP OWTF - Summer Storm - OWASP AppSec EU 2013
OWASP OWTF - Summer Storm - OWASP AppSec EU 2013OWASP OWTF - Summer Storm - OWASP AppSec EU 2013
OWASP OWTF - Summer Storm - OWASP AppSec EU 2013
 
Same Origin Policy Weaknesses
Same Origin Policy WeaknessesSame Origin Policy Weaknesses
Same Origin Policy Weaknesses
 
from 33 to 0 - A journey to be root
from 33 to 0 - A journey to be rootfrom 33 to 0 - A journey to be root
from 33 to 0 - A journey to be root
 
MITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another PerspectiveMITM Attacks on HTTPS: Another Perspective
MITM Attacks on HTTPS: Another Perspective
 
Htaccess info
Htaccess infoHtaccess info
Htaccess info
 
Everybody loves html5,h4ck3rs too
Everybody loves html5,h4ck3rs tooEverybody loves html5,h4ck3rs too
Everybody loves html5,h4ck3rs too
 
Think Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack VectorsThink Like a Hacker - Database Attack Vectors
Think Like a Hacker - Database Attack Vectors
 
Two scoops of Django - Security Best Practices
Two scoops of Django - Security Best PracticesTwo scoops of Django - Security Best Practices
Two scoops of Django - Security Best Practices
 
Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018
Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018
Inspecting iOS App Traffic with JavaScript - JSOxford - Jan 2018
 

En vedette

Mongo db rev001.
Mongo db rev001.Mongo db rev001.
Mongo db rev001.Rich Helton
 
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1Rich Helton
 
Python For Droid
Python For DroidPython For Droid
Python For DroidRich Helton
 
Spring Roo Rev005
Spring Roo Rev005Spring Roo Rev005
Spring Roo Rev005Rich Helton
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
Secure Ftp Java Style Rev004
Secure Ftp  Java Style Rev004Secure Ftp  Java Style Rev004
Secure Ftp Java Style Rev004Rich Helton
 
Learning C# iPad Programming
Learning C# iPad ProgrammingLearning C# iPad Programming
Learning C# iPad ProgrammingRich Helton
 
Entity frameworks101
Entity frameworks101Entity frameworks101
Entity frameworks101Rich Helton
 
NServicebus WCF Integration 101
NServicebus WCF Integration 101NServicebus WCF Integration 101
NServicebus WCF Integration 101Rich Helton
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02Rich Helton
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for MainframersRich Helton
 
First Steps in Android
First Steps in AndroidFirst Steps in Android
First Steps in AndroidRich Helton
 
Tumbleweed intro
Tumbleweed introTumbleweed intro
Tumbleweed introRich Helton
 
C#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalC#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalRich Helton
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101Rich Helton
 

En vedette (20)

Mongo db rev001.
Mongo db rev001.Mongo db rev001.
Mongo db rev001.
 
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1LEARNING	 iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
LEARNING  iPAD STORYBOARDS IN OBJ-­‐C LESSON 1
 
Python For Droid
Python For DroidPython For Droid
Python For Droid
 
Spring Roo Rev005
Spring Roo Rev005Spring Roo Rev005
Spring Roo Rev005
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
Secure Ftp Java Style Rev004
Secure Ftp  Java Style Rev004Secure Ftp  Java Style Rev004
Secure Ftp Java Style Rev004
 
Adobe Flex4
Adobe Flex4 Adobe Flex4
Adobe Flex4
 
Learning C# iPad Programming
Learning C# iPad ProgrammingLearning C# iPad Programming
Learning C# iPad Programming
 
Entity frameworks101
Entity frameworks101Entity frameworks101
Entity frameworks101
 
NServicebus WCF Integration 101
NServicebus WCF Integration 101NServicebus WCF Integration 101
NServicebus WCF Integration 101
 
I pad uicatalog_lesson02
I pad uicatalog_lesson02I pad uicatalog_lesson02
I pad uicatalog_lesson02
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
First Steps in Android
First Steps in AndroidFirst Steps in Android
First Steps in Android
 
Tumbleweed intro
Tumbleweed introTumbleweed intro
Tumbleweed intro
 
Azure rev002
Azure rev002Azure rev002
Azure rev002
 
C#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 FinalC#Web Sec Oct27 2010 Final
C#Web Sec Oct27 2010 Final
 
NServiceBus
NServiceBusNServiceBus
NServiceBus
 
Jira Rev002
Jira Rev002Jira Rev002
Jira Rev002
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
Python Final
Python FinalPython Final
Python Final
 

Similaire à Java Web Security Class

C# Security Testing and Debugging
C# Security Testing and DebuggingC# Security Testing and Debugging
C# Security Testing and DebuggingRich Helton
 
Watir Presentation Sumanth Krishna. A
Watir Presentation   Sumanth Krishna. AWatir Presentation   Sumanth Krishna. A
Watir Presentation Sumanth Krishna. ASumanth krishna
 
Web Browser Basics, Tips & Tricks Draft 17
Web Browser Basics, Tips & Tricks Draft 17Web Browser Basics, Tips & Tricks Draft 17
Web Browser Basics, Tips & Tricks Draft 17msz
 
Web application penetration testing lab setup guide
Web application penetration testing lab setup guideWeb application penetration testing lab setup guide
Web application penetration testing lab setup guideSudhanshu Chauhan
 
Web Application Firewall intro
Web Application Firewall introWeb Application Firewall intro
Web Application Firewall introRich Helton
 
Browser Horror Stories
Browser Horror StoriesBrowser Horror Stories
Browser Horror StoriesEC-Council
 
Pentesting for startups
Pentesting for startupsPentesting for startups
Pentesting for startupslevigross
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Brian Huff
 
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfEN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfGiorgiRcheulishvili
 
Google Hacking Lab ClassNameDate This is an introducti.docx
Google Hacking Lab ClassNameDate This is an introducti.docxGoogle Hacking Lab ClassNameDate This is an introducti.docx
Google Hacking Lab ClassNameDate This is an introducti.docxwhittemorelucilla
 
Mutillidae and the OWASP Top 10 by Adrian Crenshaw aka Irongeek
Mutillidae and the OWASP Top 10 by Adrian Crenshaw aka IrongeekMutillidae and the OWASP Top 10 by Adrian Crenshaw aka Irongeek
Mutillidae and the OWASP Top 10 by Adrian Crenshaw aka IrongeekMagno Logan
 
Search Engine Spiders
Search Engine SpidersSearch Engine Spiders
Search Engine SpidersCJ Jenkins
 
Web Security - Introduction
Web Security - IntroductionWeb Security - Introduction
Web Security - IntroductionSQALab
 
Web Security - Introduction v.1.3
Web Security - Introduction v.1.3Web Security - Introduction v.1.3
Web Security - Introduction v.1.3Oles Seheda
 

Similaire à Java Web Security Class (20)

C# Security Testing and Debugging
C# Security Testing and DebuggingC# Security Testing and Debugging
C# Security Testing and Debugging
 
Romulus OWASP
Romulus OWASPRomulus OWASP
Romulus OWASP
 
Building Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 FeaturesBuilding Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 Features
 
Watir Presentation Sumanth Krishna. A
Watir Presentation   Sumanth Krishna. AWatir Presentation   Sumanth Krishna. A
Watir Presentation Sumanth Krishna. A
 
Web Browser Basics, Tips & Tricks Draft 17
Web Browser Basics, Tips & Tricks Draft 17Web Browser Basics, Tips & Tricks Draft 17
Web Browser Basics, Tips & Tricks Draft 17
 
Web application penetration testing lab setup guide
Web application penetration testing lab setup guideWeb application penetration testing lab setup guide
Web application penetration testing lab setup guide
 
Web Application Firewall intro
Web Application Firewall introWeb Application Firewall intro
Web Application Firewall intro
 
Browser Horror Stories
Browser Horror StoriesBrowser Horror Stories
Browser Horror Stories
 
Pentesting for startups
Pentesting for startupsPentesting for startups
Pentesting for startups
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfEN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
 
2 . web app s canners
2 . web app s canners2 . web app s canners
2 . web app s canners
 
Google Hacking Lab ClassNameDate This is an introducti.docx
Google Hacking Lab ClassNameDate This is an introducti.docxGoogle Hacking Lab ClassNameDate This is an introducti.docx
Google Hacking Lab ClassNameDate This is an introducti.docx
 
Mutillidae and the OWASP Top 10 by Adrian Crenshaw aka Irongeek
Mutillidae and the OWASP Top 10 by Adrian Crenshaw aka IrongeekMutillidae and the OWASP Top 10 by Adrian Crenshaw aka Irongeek
Mutillidae and the OWASP Top 10 by Adrian Crenshaw aka Irongeek
 
Search Engine Spiders
Search Engine SpidersSearch Engine Spiders
Search Engine Spiders
 
OWASP Zed Attack Proxy
OWASP Zed Attack ProxyOWASP Zed Attack Proxy
OWASP Zed Attack Proxy
 
Advanced Java
Advanced JavaAdvanced Java
Advanced Java
 
Web Security - Introduction
Web Security - IntroductionWeb Security - Introduction
Web Security - Introduction
 
Web Security - Introduction v.1.3
Web Security - Introduction v.1.3Web Security - Introduction v.1.3
Web Security - Introduction v.1.3
 
dJango
dJangodJango
dJango
 

Java Web Security Class

  • 1. Java Web Security Coding ( The Open Source Way) August 26, 2010 BY RICH HELTON
  • 2.
  • 3. My personal website that contains some slides is http://www.s3curitys0lutions.com/
  • 7. The outcome can be expensive
  • 9.
  • 10.
  • 11. The ASP.NET Security Checklist http://msdn.microsoft.com/en-us/library/ff648269.aspx
  • 12. WebAppSec Excel checklist http://img.a4apphack.com/dl/appsecchck-checklist.zip
  • 13. SANs reading Web Security Checklist http://www.sans.org/reading_room/whitepapers/securecode/security-checklist-web-application-design_1389
  • 14.
  • 15. Find and validate all input. This includes URL’s, JavaScript's, links, username and passwords, and especially any field calling a database.
  • 16. Never trust data in files, the network or database to be secure. Encrypt anything important, passwords, SSN’s, configurations.
  • 17. Never trust the source, be it customer or a service. Authenticate, Authorize and validate.
  • 18. Whenever a abnormal behavior occurs, error check and log.
  • 19.
  • 20.
  • 21. They are bots (automated scanners) from Virus vendors, Security organizations, search engines and more cataloging all web sites.
  • 22. 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.
  • 23. 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.
  • 24.
  • 25.
  • 26. A well known site containing a database of various keywords is found at http://www.hackersforcharity.org/ghdb/ .
  • 27. For example, “ext:asp” can be used to find pages ending in asp.
  • 28. For example,“ Hacking filetype:pdf” can be used to find PDFs that are about hacking.
  • 29. For example, “restaurants inanchor:menu” will find restaurants with menu links in them.
  • 30.
  • 31.
  • 32. There are many Web Application Scanners, WebScarab from OWASP, Nikto, Wikto, and many more listed at http://sectools.org/web-scanners.html
  • 33. For simplicity and use of Open Source, I will use Google’s Skipfish.
  • 34. 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.
  • 35. My demonstrations will be down in Hackme Books because it was written in J2EE and can be run on a local machine.
  • 36.
  • 37. Another tool that I use, of course Open Source, is a Web proxy instead of a scanner from OWASP called WebScarab.
  • 38. 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.
  • 39.
  • 40.
  • 41.
  • 42. Some download applications to practice web hacking locally are:
  • 43. OWASP WebGoat (JSPs/Servlets) - http://www.owasp.org/index.php/OWASP_WebGoat_Project
  • 44. Hackme Bank (.Net) - http://www.foundstone.com/us/resources/proddesc/hacmebank.htm
  • 45. Hackme Books (JSPs/Servlets) – http://www.foundstone.com/us/resources/proddesc/hacmebooks.htm
  • 46. SecuriBench (Java Code) – http://suif.stanford.edu/~livshits/securibench/
  • 47.
  • 48. Spi Dynamics - http://zero.webappsecurity.com/
  • 53.
  • 58.
  • 59.
  • 60. When an incident happens, the first questions are always “How did they get in?” and “What data was compromised?”.
  • 61. The least favorite answer is usually “No one knows.”
  • 62. 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.
  • 63. 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.
  • 64.
  • 65. Output:import java.util.logging.*; import java.io.*; public class TestLog { public static void main(Stringargs[]) { try{ Logger logger = Logger.getLogger("TestLog"); FileHandlerfh = new FileHandler("mylog.txt"); fh.setFormatter(newSimpleFormatter()); logger.addHandler(fh); logger.severe("my severe message"); logger.warning("my warning message"); logger.info("my info message"); } catch (IOExceptione) {e.printStackTrace(); }}} Mar 25, 2008 8:43:48 PM TestLog main SEVERE: my severe message Mar 25, 2008 8:43:49 PM TestLog main WARNING: my warning message Mar 25, 2008 8:43:49 PM TestLog main INFO: my info message
  • 66.
  • 67. There are 3 components of handling an exception, and they are the “try”, “catch” and “finally” blocks.
  • 68. 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.
  • 69. The “catch” block can log the anomaly, stop the program, or process it in a hundred different ways.
  • 70.
  • 71.
  • 72. 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.
  • 73.
  • 74. 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.
  • 75.
  • 76. 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.
  • 77.
  • 78.
  • 79. SQL Injection (Most common Injection Flaw)
  • 80.
  • 81. 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.
  • 82. Some applications will not validate the field adequately before passing it to the database, and the database will process whatever it will receive.
  • 83. 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.
  • 84.
  • 85.
  • 87.
  • 88. 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.
  • 89.
  • 90. HackmeBooks SQL Injection(shows org.hsqldb.jdbc connection)
  • 91.
  • 92.
  • 93.
  • 94. For example, for login name use ^[0-9a-zA-Z]*$, which is Regular expressions for an alpha-numerical field.
  • 95. For Apache Struts, use the org.apache.struts.validator.ValidatorPlugin, http://www.owasp.org/index.php/Data_Validation_(Code_Review) .
  • 96. For JSPs/Servlets, validate in the Servlet using the with the “java.utile.regex” framework in a similar manner.
  • 98.
  • 99. XSS (Cross Site Scripting)
  • 100.
  • 101. 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.
  • 102. 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.
  • 103. The hacker takes advantage of changing the information in the <script> … </script> tags.
  • 104.
  • 105.
  • 106.
  • 107. A more practical approach is “HTML entity encoding”.
  • 108. This basically encodes the HTML to not execute external commands.
  • 109. 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/>
  • 110.
  • 111.
  • 112. 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.
  • 113.
  • 114. 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.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119. It will scrub the input before the HelloWorldServlet receives it.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125. Servers use Session Management to schemes to maintain the current conversation between the browser and the server by using cookies or transferring session token.
  • 126. Keep in mind that session state may be seen by others if transferred in clear text. Avoid any predictable or guessable information.
  • 127.
  • 128.
  • 129. 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.Useru = realm. getUser(userName) ;
  • 131.
  • 132. 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.
  • 133. Never take it for granted that access cannot be broken.
  • 134. Always, use common algorithms that come with Java. Common algorithms are tested well and are vetted by millions.
  • 135. Keep the keys as secure as the data, because they can unlock the data.
  • 136.
  • 137. The one-way hash generates a fixed size hash some given any size data.
  • 138. The data cannot be reversed engineered from the hash, hence one-way.
  • 139. The same data generates the same hash sum.
  • 140. Different data generates different hash sums.(Note: In rare cases, collisions, different data generates the same sum).
  • 141.
  • 142. The 128 bit hash sum can be used to ensure if there has been tampering of data or a file.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147. The Rijndael algorithm was selected, developed by two Belgian cryptographers, Joan Daemen and Vincent Rijmen.
  • 148. The NIST adapted the variable key space into 128, 192, or 256 bits as FIPS 197 and called it AES.
  • 149.
  • 150. 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.
  • 151.
  • 152. 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.
  • 153.
  • 154. 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)));}}
  • 155. RSA, the output….. (Done, Pretty complicated Algorithm)
  • 157.
  • 158. A larger, combined, piece is the Digital Certificate.
  • 159. 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.
  • 160. The Digital Certificate is the heart of Hypertext Transfer Protocol over Secure Socket Layer (HTTPS) and Public Key Infrastructure (PKI).
  • 161. 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.
  • 162.
  • 163. Again, once a key is stolen, then the encrypted text can be compromised, so a secure storage of certificates is important.
  • 164.
  • 165. 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:gt;keytool –list –v –keystore.jks
  • 166. 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:gt;keytool -export –keystorekeystore.jks -aliasmydomain-file certfile.cer Enter keystore password: Certificate stored in file <certfile.cer>
  • 167. 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); }
  • 168. The output of the certificate(raw format)
  • 171.
  • 172. Websites can get accessed by typing in “admin” “admin” at times, and auditors try a range of default and well known logins.
  • 173.
  • 174.
  • 175. The eXtensible Markup Language (XML) defines the interfaces and content of the message.
  • 176.
  • 177.
  • 178. 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.
  • 179. 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.
  • 180. The WSDL will define the acceptable interface into the SOA.
  • 181. The client SOAP call will format the acceptable XML. SOAP will act as an envelope to the SOA.
  • 182. The SOA will accept the call if it meets the WSDL criteria and process the call.
  • 183.
  • 184.
  • 185. These tools were originally part of Sun’s Glassfish MetroProject and more information can be found at https://jax-ws.dev.java.net/ .
  • 186. The wsgen tool generates JAX-WS portable artifacts used in JAX-WS web services.
  • 187. The tool reads the we service endpoint class and generates all the required artifacts for web service deployment, and invocation.
  • 188. Here is an example to generate the wrapper class needed for StockService annotated with the @WebService inside the stock directory: wsgen –d stock –cp myclasspathstock.StockService
  • 192.
  • 193.
  • 194.
  • 195. Apache has an Open Source version of WS-Security called WSS4j http://ws.apache.org/wss4j/
  • 196.
  • 197. 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.
  • 198. Some of the tools include a Maven plugin to generate WSDL from Java.
  • 199.
  • 200.
  • 204.
  • 205.
  • 206.
  • 207. 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.
  • 208. 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.
  • 209.
  • 210. It uses path to traverse traverse through the nodes of an XML document to look for specific information.
  • 211. Xpath injection is similar to SQL injection except that the query strings are slightly different and it uses XML as its attack vector.
  • 212. One example is to pass ‘ or 1=1 or ‘ ‘=‘ as the username to fake the database into a valid username:
  • 213. string(//user[name/text()='' or 1=1 or ''='' and password/text()='foobar']/account/text())
  • 214.
  • 215.
  • 216.
  • 217.
  • 218. White Box Testing ( in Open Source)
  • 219.
  • 220. In this case, this is also known as Static Analysis.
  • 221. These tools can find issues with the source code before the code is actually executed.
  • 222.
  • 223. FindBugs on WebGoat, example 2
  • 224. FindBugs (SQE Netbeans IDE) on Basic1 securibench micro
  • 225. PMD (SQE Netbeans IDE) on Basic1 securibench micro
  • 226. Java Grey Box Testing
  • 227.
  • 228. 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.
  • 229. Many of these Java Web Frameworks were created from JUnit, the Java Unit Testing Framework.
  • 230.
  • 231.
  • 232. HTMLUnit allows a “getPage()” routine to examine the HTML source code.
  • 233. This allows the walking through of “HREF”, images, and others pieces of the HTML code before executing on the item.
  • 234. Selenium IDE is another Open Source concept that is a Integrated Development Environment running on top of the FireFox browser as a plugin.
  • 235. This allows a recording of the browser actions that can be played back execute buttons being pushed and actions inside the browser.
  • 236. Assertions can be executed on the HTML pages itself for checking specific information.
  • 237.
  • 239.
  • 240.
  • 243.
  • 244. 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.
  • 245.
  • 246. 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.
  • 247. The ActionServlet The ActionServlet gets it’s Actions (an object) to perform based on it’s configuration, thus saving a lot of coding.
  • 248. Benefits of Struts Declarative control that maps between the requests between the MVC. Automated Request Dispatching using an ActioForward to request a specific ActionServlet. Struts can provide DataSource management. Struts provide custom tags. Struts provide Internationalization Support. Struts provide declarative error handling specific to application code. Struts provide a declarative validation mechanism. Struts provide a Plug-In interface.
  • 249. Struts XSS vulnerability Passing in am alert message <script>alert(123)</script>:
  • 251.
  • 252. A validator-rules.xml file in the WEB-INF folder.
  • 253. A validator.xml in the WEB-INF folder.
  • 254. All ActionForms should extend org.apache.struts.validator.ValidatorForm or org.apache.struts.validator.ValidatorActionForm instead of org.apache.struts.action.ActionForm.
  • 256. 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>
  • 257. 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>
  • 258.
  • 259.
  • 260. ^ and $ match the positions at the beginning and end of the string, which mean search the entire string for the specific patter.
  • 261. * mean Matches zero or more occurrences of the patter [a-zA-Z].
  • 262.
  • 263.
  • 264. JSF allows reusable component objects that map to the tags on the JSP page.
  • 265.
  • 266.
  • 267. JSF Designer Many IDE’s have a JSF Designer that includes Validators like JDeveloper:
  • 268.
  • 269. Data is usually retrieved using the XMLHttpRequest (XHR) object from the server asynchronously.
  • 270. 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.
  • 271.
  • 272.
  • 273. 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.
  • 274.
  • 275. The XMLHttpRequest will call the “callback” function in the Html browser to start updating the HTML:
  • 276.
  • 277. The Dojo Toolkit http://dojotoolkit.org/ is the Swiss army knife of Java script libraries containing APIs and widgets for web applications.
  • 278. 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.
  • 279. The Google Web Toolkit (GWT), http://code.google.com/webtoolkit/ , that allows a developer to write an Ajax application in pure Java.
  • 280. 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
  • 281. ADF Task Flow Designer JDeveloper has an ADF Task Flow Designer to assist in its ADF View Flow:
  • 282.
  • 283. Flex uses MXML, the Macromedia XML, as a declarative layout of the interfaces to compile into the SWF file that is deployed.
  • 284. 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.
  • 285.
  • 288.
  • 289. 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.
  • 290. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
  • 291. The main advantages of Hibernate is that maps database entities to objects and hides the details of the data access from the business logic.
  • 292.
  • 293.
  • 294. This validator will not only validate the values but can also validate the size of the data before being persisted.
  • 295. 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
  • 296.
  • 297. 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/
  • 298. 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.
  • 299. 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.
  • 300.
  • 301. 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:
  • 302.
  • 303. 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:
  • 304.
  • 305. 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.
  • 306.
  • 307. Web Application Firewalls (A supplemental fix)
  • 308.
  • 309. 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.
  • 310. For Apache, the most popular approach is to use its Open Source plugin called mod_security.
  • 311. For IIS, WebKnight from AQTronix, http://aqtronix.com/?PageID=99 is the most popular Open Source solution.
  • 312.
  • 313. 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
  • 314. Depending on their configuration, they will deny, or log, validated information from the Internet into the Application.
  • 315.
  • 316.
  • 317. ASP.NET Hacme Bank (SQL Injection)
  • 320. Tomcat will need Apache
  • 321.
  • 322. Note: Tomcat can also use Microsoft’s IIS, instead of Apache, utilizing the Microsoft ISAPI plugin.
  • 323. 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:
  • 326.
  • 327. Load the mod_security and unique id modules (this example is XP) in conf/httpd.conf:
  • 330. Add the base configuration and some of the base rules:
  • 336.
  • 338.
  • 339.
  • 340. The 500 XSS displayed
  • 341.
  • 342. 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>
  • 343.
  • 344.
  • 345.
  • 346. 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>
  • 347.
  • 348. Installing a WAF is quicker, in most cases, than changing code and re-deploying a Web Application.
  • 349. 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.
  • 351. WAFs are limited by the rules that are installed in them. Therefore, if the rule is not there, it cannot protect against it.
  • 352.
  • 353. Encrypt the tunnel, simply using SSLv3 and Point-to-Point VPN tunneling that comes with Servers and Firewalls can alleviate many encryption issues.
  • 354. Use only common encryption algorithms that come with Java and have been tested by thousands of uses like AES.
  • 355. Use common libraries, and if possible, open source, that can be reviewed for concerns.
  • 356. 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.
  • 357.
  • 358.
  • 359. Feel free to contact me at rich.helton@state.co.us
  • 360.
  • 361.
  • 362. The program can be found at http://j-ftp.sourceforge.net/
  • 363.
  • 364. Can download the JAR file and run it locally.
  • 365. Cross Platform. Runs easily on Mac OSX, Linux, Windows, etc.
  • 366. Runs multiple protocols, SFTP, SMB, NFS, HTTP, and various transfer protocols.
  • 367. Open Source so the code can be used to execute batch jobs.
  • 369.
  • 370. Java must be able to run from the local Browser.
  • 371.
  • 372.
  • 373.
  • 374.
  • 375. OpenSSH can be found at http://www.openssh.com/ .
  • 376.
  • 377.
  • 378.
  • 379.
  • 380. If Java is configured correctly, the JFtp will run in a Java Console that works like the “Web Start” version.
  • 381.
  • 382.
  • 383. Unzip the source, cd to j-ftp and ensure that the build.xml file is present:
  • 384.
  • 385.
  • 386.
  • 387.
  • 388. 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 .
  • 389. These editors are Open Source with any plugins for coding.
  • 390. The main file will be found at “srcavaetfftpFtp.java”.
  • 391.
  • 392.
  • 393.
  • 394.
  • 395. Under the doc directory, FTPDownload.java provides a download examples, and FTPUpload.java provides a upload example.
  • 396. The “Web Start” code can also be found in this directory in the code “jftp.jnlp”
  • 397.
  • 398.
  • 399. Otherwise the standard j2ssh library is used found at http://sourceforge.net/projects/sshtools/ .
  • 400. Both libraries support the Secure Copy Protocol (SCP) for copying files through SSH.
  • 401.
  • 402. Otherwise the standard j2ssh library is used found at http://sourceforge.net/projects/sshtools/ .
  • 403. Both libraries support the Secure Copy Protocol (SCP) for copying files through SSH.
  • 404.
  • 405.
  • 406.
  • 407. Then the login( ) function will authenticate using the username and password.
  • 408. The Local directory will be the root directory as well as the remote directory, so the local directory is changed to “C:ars”.
  • 409. This directory contains “C:arsftp.jar” that is uploaded with the upload ( ) function.
  • 410.