Is my Web Application secure? OWASP Top Ten and Beyond (from Codemotion 2011)

Java & .NET always featured stronger security and reliability with respect to the common vulnerabilities (think of Buffer Overflows, etc… ) of the C/C++ world.

However, the power and also complexity increase of Rich Internet Applications (DHTML, JS, AJAX…) paves the way to new attack forms, from SQL Injection to Cross-Site Scripting and Request Forgery. In my talk at the 2011 Codemotion in Rome I discussed the main issues and principles in securing a modern Web Application, with specific reference to the OWASP Top Ten security risks for 2010.

Have a look at all the other presentations on Codemotion’s website.

JVM Management & Monitoring Power Tools: what is my JVM doing?

Unfortunately I was unable to present myself at the Javaday Rome 2010 because of a flu which kept me at home… and first of all many thanks to Fabrizio and Ugo for presenting on my behalf.

Here you are my slides on how to monitor and analyze JVM behavior with a number of tools which are hidden in plain sight inside the JDK, so useful and at the same time quite unknown to many developers.

We are so used to Java that we often forget what’s required behind the scenes to give us robustness, security, platform independence, performance, rich APIs and commercial/open source ecosystem.

But it is interesting (and sometimes necessary) to get a deeper look at what’s happening behind the scenes… The JVM gives us powerful tools to monitor, debug, tune & troubleshoot its internal mechanisms, including the Garbage Collector and dynamic Just in Time compiler.

As usual, a huge thank you to Mara Marzocchi and the entire JUG Roma team for organizing such a not-to-be missed and lively event.

What is my JVM doing? management and monitoring with JDK power tools

I am happy to announce that I will be speaking at the Javaday Rome 2010, the main Italian event for and by the Java community. An event not to be missed!

My talk will focus on the use of many power tools that are part of JDK since version 1.5, but are at the same time unknown to many developers; specifically, I will discuss how to

  • find active JVMs with jps
  • anaylze memory consumption and garbage collection behavior with jstat
  • get an overview of VM activities with jconsole
  • analyze in depth VM behavior with VisualVM, both in the case of local and remote Virtual Machines
  • analizzare i bottleneck prestazionali con i profiler di VisualVM
  • detect threading issues with the Thread Dump Analyzer
  • find causes of OutOfMemory errors and PermGen errors
  • detect memory leaks
  • trace and debug running applications in production with btrace

If you want to meet me at the event, drop by at my company (NIS) booth in the exhibition hall.

Speaking at Javaday 2010

Slides for the Maven2 in the real world talk @ Javaday 2009

I am back from the Javaday 2009 in Rome, which was definitely THE Java event of the year for Italy… Congratulations to Mara and the JUG Roma team for creating an interesting, lively, and incredibly well-organized event. I had the pleasure of attending several interesting presentations (slides for all talks will be published on the Javaday 2009 website in the next few days), and moreover to meet in person a number of contacts in the community.

Here you are my presentation on how to effectively use Maven2 on large projects. Hope you enjoy it! Please do not hesitate to contact me (details are on last slide) for any question.

View more presentations or upload your own. (tags: maven2 maven)

Runtime profiling and monitoring Java apps with btrace

A the latest Genova JUG meeting last week there was much discussion about performance tuning and optimization, particularly of web applications. My mention of the recently released BTrace profiling tool was met with significant interested and I was asked to provide more details and references…

BTrace (where the ‘B’ stands for bytecode) is an open source tool hosted on java.net, where you can find extensive documentation and samples. It is conceptually similar to the much-talked-about Solaris DTrace platform, but can be used on any Java platform/app.

The main BTrace concept is that of dynamically connecting to a running Java application (or server) to attach short “scripts” which log a range of events and infos such as

  • method calls;
  • execution times;
  • constructor invocation;
  • available memory;

Script execution is tied to several situations

  • reaching a specific line number;
  • invoking a given method;
  • returning from a method;
  • invoking system calls (e.g. exit);
  • recurring timer (period execution at fixed intervals);
  • and many more

In a way, BTrace scripts are very similar to AOP’s aspects, but can be attached to any existing Java code (or better, bytecode) at runtime and without any configuration or modification at development time.

The scripts are simply Java classes which take advantage of methods from the btrace API, and are configured by using simple but powerful annotations. Here you are an hello world script which traces session creation in hibernate:

// import BTrace annotations
import com.sun.btrace.annotations.*;
// import logging methods
import static com.sun.btrace.BTraceUtils.*;

@BTrace
public class HelloWorldTrace {

// probe the openSession() method of Hibernate SessionFactory
@OnMethod(
clazz="org.hibernate.SessionFactory",
method="openSession"
)
public static void onOpenSessionTrace() {
// you can only log using the stati println method from BTraceUtils
println("Hibernate: opening a new session...");
}
}

Btrace scripts are attached to the running process using the JVM’s instrumentation interface.

If you are using JDK 1.6, you can attach to any running jvm by simply specifying its pid obtained through the new jps command:

jps

18037 Demo.JAR
19032 jps
19025 tomcat

btrace 19025 HelloWorldTrace 

Hibernate: opening a new session...
Hibernate: opening a new session...

The last command is simply an utility batch file which actually compiles and attaches the script.: On the other hand, on previous JDKs it is necessary to enable tracing in a similar way to how you enable remote debugging.

As an example of BTrace power and ease of use, the following script from BTrace samples intercepts all calls to methods in classes which are annotated with @WebService (e.g. all JAX-WS web service classes) and logs theri execution times:

@BTrace public class WebServiceTracker {
// store webservice entry time in this thread local
@TLS private static long startTime;

@OnMethod(
clazz="@javax.jws.WebService",
method="@javax.jws.WebMethod"
)
public static void onWebserviceEntry() {
print("entering webservice ");
println(strcat(strcat(name(probeClass()), "."), probeMethod()));
startTime = timeMillis();
}

@OnMethod(
clazz="@javax.jws.WebService",
method="@javax.jws.WebMethod",
location=@Location(Kind.RETURN)
)
public static void onWebserviceReturn() {
println(strcat("Time taken (msec) ", str(timeMillis() - startTime)));
println("==========================");
}

}

Note the use of BTrace built-in strcat function, which is needed to avoid the overhead of string concatenation. Obviously, the script code must be as lightweight as possible to avoid influencing tracing results with its own execution times, and thus the BTrace API provides efficient implementations of basic logging tasks.

Stay tuned for more tracing examples…

Java IDE day 2008: big success in Genova!

Just a quick post while we recover from the organization effort… I will write a more detailed report as soon as possible. The IDE day was a success, with a participation level that definitely went beyond our best expectations, both in terms of attendance (about 130 people!) and in term of audience interaction (the speakers were overwhelmed with questions!).

Presentation slides will be loaded on the http://www.ideday.org website in the next few days.

In the meantime I publish this picture of the speakers with the organizing group for Genova, which give me the opportunity to say a huge THANK YOU to everyone who made this event possible.

[photopress:IMG_7888.jpg,thumb,centered]

Java IDE day 2008 is coming!

Thanks to a fruitful collaboration between the Genova Java User Group and Rome Java User Group the first Italian Java IDE day is a reality…

If you are interested in Java development (but not just java, as these IDEs interestingly support a range of languages) you can’t miss the event that will take place

  • monday 10 march 2008 in Genova
  • wednesday 12 march 2008 in Rome

where  international experts including Roman Strobl (Sun), Paolo Ramasso (Oracle) and Vaclav Pech (Jetbrains) will discuss the most advanced features of Java IDEs and their future evolution.

The event is free and open to all! for more information (and to register) visit http://www.ideday.org

See you there!

How to programmatically define Spring beans

The Spring framework is well know both for its powerful architecture and its often barely tolerated XML configuration syntax.So there are cases where you would like to take advantage of Spring features (Dependency Injection, scope management, AOP, Transaction Management) in a set of beans without having to declare all of them in XML. This is particularly the case where you need to define a non-trivial number of similar beans (e.g. DAOs, backing beans in a JSF application, etc.).

In practice, we want to be able to write something like

ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
SampleService s = (SampleService) context.getBean("sampleService");

(or the equivalent code in a webapp or servlet with a WebApplicationContext) so that s get initialized by Spring in the right scope without actually declaring sampleService in application.xml.

Thanks to Spring modularity, there are several ways of achieving this:

  • define the bean through annotations;
  • define a custom BeanDefinitionReader that reads from a property/configuration file instead of XML;
  • define the bean programmatically.

I will now describe how to do it with the third approach. With most kinds of ApplicationContexts, it is possible to use the BeanDefinitionRegistry interface to dynamically and programmatically declare beans:

BeanDefinition definition = new RootBeanDefinition(SampleService.class);
//optionally configure all bean properties, like scope, prototype/singleton, etc
context.registerBeanDefinition("sampleService", definition);

This allows you to manually add a bean definition to the context.

In order to fully automatize the configuration, we can define a BeanFactoryPostProcessor that is automatically invoked after the standard xml file is read, being thus able to automatically add more bean definitions. The bean definitions can be for instance created by scanning classes for custom annotations, scanning custom configuration files, or any other custom criteria.

The following example will create a bean for each *.service file in the config directory

import java.io.IOException;
import org.springframework.beans.BeansException;
 import org.springframework.beans.factory.config.BeanDefinition;
 import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
 import org.springframework.beans.factory.support.BeanDefinitionRegistry;
 import org.springframework.beans.factory.support.RootBeanDefinition;
 import org.springframework.context.ApplicationContext;
 import org.springframework.context.ApplicationContextAware;
 import org.springframework.context.ResourceLoaderAware;
 import org.springframework.core.io.Resource;
 import org.springframework.core.io.ResourceLoader;
public class AutoBeanDeclarer implements BeanFactoryPostProcessor, ApplicationContextAware
 {
      private ApplicationContext mainContext;
public void postProcessBeanFactory(ConfigurableListableBeanFactory context)
        throws BeansException
{
BeanDefinitionRegistry registry = ((BeanDefinitionRegistry)context);
Resource[] fileList = null;

 fileList = mainContext.getResources("config/*.service");
for (Resource file : fileList)
{
System.out.println("File found: "+file.getFilename());
BeanDefinition definition = new RootBeanDefinition(SampleServiceImpl.class);
registry.registerBeanDefinition(file.getFilename(), definition);
}
public void setApplicationContext(ApplicationContext mainContext)
 {
      this.mainContext = mainContext;
}
}

The BeanFactoryPostProcessor can then be simply added to the main application.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.0.xsd

http://www.springframework.org/schema/aop

 http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- note: no definition of SampleService  -->
<bean id="autoConfigurer" class="AutoBeanDeclarer"/>
</beans>

Spring will then automatically activate the PostProcessor after reading all configuration files.

A possible use in a web application could be that of automatically defining a bean for each html page/component. More examples will appear in future posts…

Thank you for your time! I hope you enjoyed this post. You can find more materials on Spring on the JUG Genova website.