Sunday, June 15, 2008

Java security in web application, typical attacks

 

This article gives an overview about different attack mechanisms against Java web applications and J2EE applications. It introduces available security concepts in Java like JAAS and Sandbox security. Furthermore, security related design patterns are explained

 

Remove Comments

Delete comments in deployed documents. An intruder could use this information to attack your side. You should not use any HTML comments in your JSP.

  <!--  HTML comment: looks up user data in table tuser -->

Even if you use a comment like the following in your JSP, there can be a situation, in which the JSP is not rendered and the comment is visible to a intruder (-> directory browsing).

  <% /* JSP comment: looks up user data in table user */ %>

Directory Browsing

Directory browsing allows other people to see all your JSP files without being rendered. They could retrieve valuable information about your application from these files. You have multiple options to protect your JSP files:

·         Deactive directory browsing on server and application level.

·         Protect the JSP directories with JAAS.

·         Change the default servlet coming with Tomcat. This servlet does provide the browsing feature.

Multiple Level of Security

Features like Directory Browsing, Session Time Out can be configured on server level and application level in the web.xml. You should have tight server level settings so that a incautious developer have a secure application by default.

Typical problems of web applications

·         Self made Session id

·         Incomplete validation of user input

·         Server configuration

Do not reinvent the Session handling. The session provided by nowadays application server should be secure. There might have been problems for some application servers in the early days but this is a long time ago.

Imagine you would use a timestamp as session. An intruder could easily take over an existing session by trying out current timestamps.

Normally a Tomcat session looks like

http://localhost/MyApplication/listUser.do;jsessionid=2CFB532547A143436A46727B3B4C7C0A

If you use a timestamp as session id you will have something like:

http://localhost/MyApplication/listUser.do;mySessionId=2006-05-25-19:31:050

Even if your session id is more complicated than a timestamp, you should keep in mind that an attacker could create a list of sessions in search for a pattern in your session id.

SQL Injection in Java Web applications

Imagine a login form in a web application where the user inputs a user name and a password.

Your application issues a SQL statement:

select username from user where username= 'Peter' and password = 'secret'

If the user inputs for password something like

secret' or '1'='1

Your query will be something like

select username from user where username= 'Peter' and password = 'secret' or '1'='1'

The same kind of injection can happen with any kind of search form. If a intruder wants to reduce your product prices he could input the following in your search form.

Blablub';update product set price = 1 where product_id=55 and '1'='1

Your search query will be something like

select from product where name = 'Blablub';update product set price = 1 where product_id=55 and '1'='1'

These kind of attacks are typical for applications using JDBC directly. A good protection is to use prepared statements or Object Relational Mapping solutions like Hibernate, EJB or JDO.

Java Script attacks

Cross side scripting

When a intruder can take over your session he is working with your account. Imagine somebody takes over your session in a Internet Shop and orders products. You will get a lot of problems.

An intruder could post links into a forum to a internet shop having very low prices. Once you click on this link the website is loaded into a frame. Outside the frame there is a Java script application sending input of your frame or your session to another website. Once the intruder has access to your session we will hold your session open to misuse it later or when you are not available.

This is not a problem specific to Java applications but to web applications in general.

You could enforce that your application is not running inside another frame, to solve this security problem.

Another approach to have a improved security is to enforce a maximum session life time. If your users can accept that their session is not living longer than two hours, you could invalidate all older sessions periodically. This makes it impossible for intruders to keep sessions alive for a longer time.

Attacking forms

If you validate forms using JavaScript or you keep information in your form with hidden fields you can be attacked easily. Let us assume that we have a multi page form and you save the customer level in a hidden field. Dependent on the customer level a customer gets a special discount.

Using a web proxy like Scarab you can easily rewrite hidden fields and get a special discount for your order.

Security Design Pattern

Secure Transport Object (STO)

In distributed environments you have to transport serialized objects from one application server to another. The transport item could be a message, a serialized object of a Remote EJB or any other kind of data on a enterprise service bus.

The connection between your application server could be insecure or your transport item could have to pass multiple intermediates.

In this situation the pattern Secure Transport Object is a good choice to protect your data. It is a Data Transfer Object (DTO) which is protected by encryption. The sender encrypts the data using a password or a public key. The STO passes any number of intermediates and reaches the target which decrypts the STO using the same password or a private key.


You could implement a more fine grained approach as well, allowing that only some attributes of an object are protected.

Intercepting Validator Pattern

In order to validate all input in a proper manner and to protect your application against JavaScript or SQL injection you can use the Intercepting Validation Pattern. Instead of validating input decentralized in your application you have a central mechanism to validate the user input.

Secure Based Action

This pattern defines a single point of entry for your application and enforces security restriction. For example, you could implement a Filter Servlet validating that you are allowed to call the specified method. In a Struts application you could overwrite the default controller and add the validation of security constraints

 

 

Thursday, May 22, 2008

Jsp buffer and autoFlush - Refresh

 

<%@ page buffer=sizekb %>

Gives the size of the page buffer in kb or none for no buffer. Default 8kb. If buffer is none, all output is immediately flushed.

JSP 1.0 gives page writers flexibility by buffering its output before sending the response to HTTP. The buffering allows error recovery and forwarding, even after generating some content. Once the buffer has filled, it will be flushed. So applications must still detect their errors early.

The following example generates an XML section (for variety). If the form's query is missing the 'name' parameter, it will redirect the results.

          <?xml version='1.0'?>
          <form>
          <%
          if (request.form["name"] == null)
          pageContext.forward("redo-form.jsp");
 
          for (var name in request.form) {
          out.print("<" + name + ">");
          out.print(request.form[name]);
          out.println("</" + name + ">");
          }
          %>
          </form>
        

<%@ page autoFlush="true" %>

Tells JSP to flush the page buffer when it fills. Default is true.

If autoFlush is false, the JSP engine will throw an exception if the buffer overflows.

 

Jsp and Html Comments

JSP and HTML Comments

In a jsp we should always try to use jsp- style comments unless you want the comments to appear in the HTML. Jsp comments are converted by the jsp engine into java comments in the source code of the servlet that implements the Jsp page. The jsp comment don't appear in the output produced by the jsp page when it runs. Jsp comments do not increase the size of the file,  jsp page are useful to increase the readability of the jsp page.

In Jsp two types of comments are allowed in the Jsp page:

1) Hidden comment: This comment will not appear in the output.

<%-- Hidden comment --%>

2) Output comment: This type of comment will appear in the output.

<!-- Output comment>

 

 

JSP - Not to Cache Jsp page in browser

 

JSP – Not to Cache Jsp page

 

<%

response.setHeader("Pragma","No-cache");

response.setHeader("Cache-Control","no-cache");

response.setHeader("Cache-Control","no-store" );

 

%>

 

Monday, May 19, 2008

Oracle DEFINE Command

Using the DEFINE Command with& Substitution Variable

 

Syntax:

 

 

 

Step 1:

 

Create the substitution variable using the DEFINE

command.

 

DEFINE employee_num = 200

 

 

Step 2:

Use a variable prefixed with an ampersand (&) to substitute the value in the SQL statement.

SELECT employee_id, last_name, salary, department_id

FROM employees

WHERE employee_id = &employee_num ;

 

Thursday, May 15, 2008

Oracle Constraints.(you might be knowing...just for refresh)

Oracle Constraints…

 

 

We can add, drop, enable and disable constraints in the Oracle…

 

 

Syntax for adding a constraint..

 

ALTER TABLE table

ADD [CONSTRAINT constraint] type (column);

 

 

e.g.

 

ALTER TABLE EMPLOYEE

ADD CONSTRAINT emp_manager_fk

FOREIGN KEY(manager_id) REFERENCES employee(employee_id)

 

 

 

Syntax for dropping a constraint…

 

 

ALTER TABLE EMPLOYEE

DROP CONSTRAINT emp_manager_fk

 

 

 

 

Syntax for enabling and disabling a constraint…

 

ALTER TABLE EMPLOYEE

DISABLE CONSTRAINT emp_manager_fk

 

ALTER TABLE EMPLOYEE

ENABLE  CONSTRAINT emp_manager_fk

 

 

 

 

Call stored procedures with IN, OUT, and IN/OUT parameters.

his example demonstrates how to call stored procedures with IN, OUT, and IN/OUT parameters.

 
 
    CallableStatement cs;
    try {
      // Call a procedure with no parameters
        cs = connection.prepareCall("{call myproc}");
        cs.execute();
    
   
 
 
     // Call a procedure with one IN parameter
        cs = connection.prepareCall("{call myprocin(?)}");
    
        // Set the value for the IN parameter
        cs.setString(1, "a string");
    
        // Execute the stored procedure
        cs.execute();
    
    
 
 
 
 
     // Call a procedure with one OUT parameter
        cs = connection.prepareCall("{call myprocout(?)}");
    
        // Register the type of the OUT parameter
        cs.registerOutParameter(1, Types.VARCHAR);
    
        // Execute the stored procedure and retrieve the OUT value
        cs.execute();
        String outParam = cs.getString(1);     // OUT parameter
    
  
 
 
    // Call a procedure with one IN/OUT parameter
        cs = connection.prepareCall("{call myprocinout(?)}");
    
        // Register the type of the IN/OUT parameter
        cs.registerOutParameter(1, Types.VARCHAR);
    
        // Set the value for the IN/OUT parameter
        cs.setString(1, "a string");
    
        // Execute the stored procedure and retrieve the IN/OUT value
        cs.execute();
        outParam = cs.getString(1);            // OUT parameter
    } catch (SQLException e) {
    }

 

 

 

Wednesday, May 14, 2008

FW: Simple Stored Procedure and How to call from Java

Simple Oracle Procedure:

 

create procedure set_death_age(poet VARCHAR2, poet_age NUMBER)
    poet_id NUMBER;
begin
  SELECT id INTO poet_id FROM poets WHERE name = poet;
  INSERT INTO deaths (mort_id, age) VALUES (poet_id, poet_age);
end set_death_age;

 

 

 

Calling simple procedure from Java

 

   Connection con = null;
   CallableStatement proc = null;
 
   try
   {
      con  = connectionPool.getConnection();
      proc = con.prepareCall("{ call set_death_age(?, ?) }");
      proc.setString(1, dyingBard.getName());
      proc.setInt(2, age);
      proc.execute();
   }
   finally
   {
      try
      {
         proc.close();
      }
      catch (SQLException e) {}
      con.close();
   }

 

Sunday, May 11, 2008

Synonyms - Oracle

Synonyms

 

 

Simplify access to objects by creating a synonym (another name for an object). With synonyms, you can:

 

Ease referring to a table owned by another user

Shorten lengthy object names

 

Query syntax

 

CREATE [PUBLIC] SYNONYM synonym

FOR object;

Eg:

CREATE PUBLIC SYNONYM dept

FOR alice.departments;

 

Thursday, May 8, 2008

To find out Date, Time and Characterset format of Oracle server.

To find out Date, Time and Characterset format of Oracle server.

 

 

select * from v$nls_parameters;

 

 

 

 

NLS_LANGUAGE                                                     AMERICAN                                                        

NLS_TERRITORY                                                    AMERICA                                                          

NLS_CURRENCY                                                     $                                                               

NLS_ISO_CURRENCY                                                 AMERICA                                                          

NLS_NUMERIC_CHARACTERS                                           .,                                                              

NLS_CALENDAR                                                     GREGORIAN                                                        

NLS_DATE_FORMAT                                                  DD-MON-RR                                                       

NLS_DATE_LANGUAGE                                                AMERICAN                                                        

NLS_CHARACTERSET                                                 UTF8                                                            

NLS_SORT                                                         BINARY                                                          

NLS_TIME_FORMAT                                                  HH.MI.SSXFF AM                                                  

NLS_TIMESTAMP_FORMAT                                             DD-MON-RR HH.MI.SSXFF AM                                        

NLS_TIME_TZ_FORMAT                                               HH.MI.SSXFF AM TZR                                              

NLS_TIMESTAMP_TZ_FORMAT                                          DD-MON-RR HH.MI.SSXFF AM TZR                                    

NLS_DUAL_CURRENCY                                                $                                                               

NLS_NCHAR_CHARACTERSET                                           AL16UTF16                                                       

NLS_COMP                                                         BINARY                                                          

NLS_LENGTH_SEMANTICS                                             BYTE                                                            

NLS_NCHAR_CONV_EXCP                                              FALSE                                                           

 

Wednesday, May 7, 2008

formdef.plugin.util.FormUtils-------Automating Conversion from Action Form to Java Business Objects/Value Objects

FormUtils.setFormValues()


   
FormUtils.setFormValues() can be used to initialize a form bean with values from a business object:

    DynaActionForm dynaForm = (DynaActionForm) 
            FormDefUtil.setFormValues("employeeForm", employee,
                    this, mapping, request);
            

The first parameter identifies the form definition that will be used.
The second parameter is the business object which contains the values that will be used to populate the form bean.
The last three parameters are the current Action object, the current action mapping, and the request being processed.

FormUtils.setFormValues() returns the populated form bean. This can then be placed by the caller in the proper scope with the proper name so that Struts can find it when rendering an HTML form.

 

  FormUtils.getFormValues()


   
FormUtils.getFormValues() can be used to create a populated business object from a form bean:

    Employee employee = (Employee)
            FormDefUtil.getFormValues(form, this, mapping, request);
            

The first parameter is the form passed by Struts to the action object.
The next three parameters are the current Action object, the current action mapping, and the request being processed.

getFormValues() returns the business object populated with values from the form bean. If a factory is associated with the form definition, it is called to create the business object that will be populated. Otherwise, the business object's no-arg constructor will be used to create the object.

What is a foreign key?

What is a foreign key?

A foreign key means that values in one table must also appear in another table.

The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table.

A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.

 

Using a CREATE TABLE statement

The syntax for creating a foreign key using a CREATE TABLE statement is:

CREATE TABLE table_name
(column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
  FOREIGN KEY (column1, column2, ... column_n)
  REFERENCES parent_table (column1, column2, ... column_n)
);

 

For example:

CREATE TABLE supplier

(

supplier_id

numeric(10)

not null,

 

supplier_name

varchar2(50)

not null,

 

contact_name

varchar2(50),

 

 

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)

);

 

CREATE TABLE products

(

product_id

numeric(10)

not null,

 

supplier_id

numeric(10)

not null,

 

CONSTRAINT fk_supplier

 

  FOREIGN KEY (supplier_id)

 

  REFERENCES supplier(supplier_id)

);

In this example, we've created a primary key on the supplier table called supplier_pk. It consists of only one field - the supplier_id field. Then we've created a foreign key called fk_supplier on the products table that references the supplier table based on the supplier_id field.

Putting text on the status bar

Putting text on the status bar

example demonstrates how to manipulate text on the status bar. When you move the cursor over a hyperlink, the statusbar shows the destination URL. This is not very helpful. Fortunately, it is very easy to put our own brief description there.

The normal HTML code for a hyperlink might be something like this:

<A HREF="mylink.htm">Click here</A>

To display something on the status bar when the mouse is moved over this link, you need to add a little more:

<A HREF="mylink.htm" onMouseOver="window.status='Click
here to know more about me'; return true;" onMouseOut="window.status=''; ">Click here</A>

 

Monday, May 5, 2008

Simple query to find out the version of Oracle..

Simple query to find out the version of Oracle..

Select * from v$version;

what is Oracle Schema

Schema

 

 

A schema is a collection of objects, such as tables, views, database user and has the same name as that user.

 

 

Check this link for more info

http://www.oracle.com/technology/obe/2day_dba/schema/schema.htm#t1

Sunday, April 27, 2008

Learnings: Hibernate basics and QuickStart

General Information

Hibernate is a powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. The Hibernate Query Language, designed as a "minimal" object-oriented extension to SQL, provides an elegant bridge between the object and relational worlds. Hibernate also allows you to express queries using native SQL or Java-based Criteria and Example queries. Hibernate is now the most popular object/relational mapping solution for Java.

Who should use Hibernate?

Intended users for Hibernate are developers trying to separate the regular code from the database code. Hibernate provides a cleaner way of separating the two layers, leaving the user to interact with just java-beans.

Installation

 

How can I obtain Hibernate in Linux?

Select Hibernate component in the installer. The required libraries should be installed into <install.root>/lib/hibernate directory.

What do I need to use Hibernate?

The library files (jar files) installed with spike-installer are to be used to write specific applications.

How do I install Hibernate in Linux?

1.       Installation from Download

o                   Download the shell script installer to a temporary location and run. You must be root to install SpikeSource Release 1.6.0. The file is of the form corestack-<version>.<architecture>-<platform>.bin, for example, % sh <download directory>/corestack-1.4 .ix86-fedora1.bin.

2.       Installation from CD

o                   Open a shell window and invoke the shell script installer on the cdrom

o                   % cd /mnt/cdrom

o                   % sh ./corestack-1.4 .ix86-fedora1.bin.

Choose to install Hibernate during the initial steps of installation.

After installation the directory/file layout will be:

<OSS_HOME> (default is /opt/oss)

install root

etc/rc.d

rc.hibernate run-command script (for post-install usability check)

lib/hibernate

hibernate core and runtime files

How can i uninstall Hibernate in Linux?

% cd <OSS_HOME>
% source ./env.sh
% su
% openpkg rpm -e --nodeps hibernate (--nodeps will remove a product without removing the installed dependencies. To perform a full uninstall, where dependencies are automatically removed where no conflict exists, remove the --nodeps parameter option.)

How can i install / uninstall Hibernate in Windows?

Installing / Uninstalling Hibernate is done automatically when a database stack is installed / uninstalled

After installation the directory/file layout will be:

<OSS_HOME> (default is C:\Program Files\SpikeSource\oss)

install root

hibernate\

jar files needed for Hibernate.

 

Configuration

 

Hibernate can be configured in 2 ways:

Property file:

example file attached: hibernate.properties

Important parameters are:

    //dialect to be used
    hibernate.dialect net.sf.hibernate.dialect.HSQLDialect
    //driver used
    hibernate.connection.driver_class org.hsqldb.jdbcDriver
    //username
    hibernate.connection.username sa
    hibernate.connection.password secret
    hibernate.connection.url jdbc:hsqldb:hsql://localhost
    hibernate.connection.url jdbc:hsqldb:test
    hibernate.connection.url jdbc:hsqldb:.
    


Xml file:
 example file attached: hibernate.cfg.xml

 <hibernate-configuration>

    <session-factory>

        <property name="connection.url">jdbc:mysql://yangtze/test</property>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="connection.username"></property>

        <property name="connection.password"></property>

        <property name="connection.pool_size">12</property>

  

        <property name="show_sql">false</property>

        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>

  

        <!-- Mapping files -->

        <!--mapping resource="Cat.hbm.xml"/-->

        <mapping resource="dis_forums.hbm.xml"/>

    </session-factory>

  </hibernate-configuration>

Programmatic configuration:
http://www.hibernate.org/hib_docs/reference/en/html/session-configuration.html

 

Getting Started

 

Hibernate is a simple tool to use, and the configurations are simple.

Example: Populate a 'Cat database' and query for results

1.       Create the mapping xml - Cat.hbm.xml

2.              <hibernate-mapping>
3.                  <class name="Cat" table="CAT">
4.                      <!-- the unique identifier for the cat -->
5.                      <id name="id" type="string" unsaved-value="null" >
6.                          <column name="CAT_ID" sql-type="char(32)" not-null="true"/>
7.                          <generator class="uuid.hex"/>
8.                      </id>
9.           
10.                  <!-- name for the cat -->
11.                  <property name="name">
12.                      <column name="NAME" sql-type="varchar(16)" not-null="true"/>
13.                  </property>
14.       
15.                  <!-- Sex -->
16.                  <property name="sex" type="char"/>
17.       
18.                  <!-- Weight -->
19.                  <property name="weight" type="float"/>
20.              </class>
21.          </hibernate-mapping>
            

22.    Register the mapping xml in the hibernate.cfg.xml file

23.          <hibernate-configuration>
24.              <session-factory>
25.       
26.                  ... other parameters ...
27.       
28.                  <!-- Mapping files -->
29.                  <mapping resource="Cat.hbm.xml"/>
30.       
31.              </session-factory>
32.          </hibernate-configuration>
        

33.    Getting hibernate session: HibernateUtil.java

34.       
35.          public class HibernateUtil {
36.              private static final SessionFactory sessionFactory;
37.       
38.              static {
39.                  try {
40.                      // this will pickup the hibernate.cfg.xml by default.
41.                      // you can specify a different file-name to be used,
42.                      // or build the configuration programatically
43.                      sessionFactory = new Configuration().configure().buildSessionFactory();
44.                  } catch (HibernateException ex) {
45.                      throw new RuntimeException("Exception building SessionFactory: "
46.                              + ex.getMessage(), ex);
47.                  }
48.              }
49.       
50.              public static final ThreadLocal session = new ThreadLocal();
51.              public static Session currentSession() throws HibernateException {
52.                  Session s = (Session) session.get();
53.                  // Open a new Session, if this Thread has none yet
54.                  if (s == null) {
55.                      s = sessionFactory.openSession();
56.                      session.set(s);
57.                  }
58.                  return s;
59.              }
60.       
61.              public static void closeSession() throws HibernateException {
62.                  Session s = (Session) session.get();
63.                  session.set(null);
64.                  if (s != null)
65.                      s.close();
66.              }
67.          }
        

68.    Saving a cat

69.          public void addCat(String name, char sex, float weight) {
70.              Session session = HibernateUtil.currentSession();
71.              Transaction tx= hibernateSession.beginTransaction();
72.       
73.              Cat cat = new Cat();
74.              cat.setName("NewCat" + suffix);
75.              cat.setSex('F');
76.              cat.setWeight(5.5);
77.       
78.              hibernateSession.save(cat);
79.              tx.commit();
80.              HibernateUtil.closeSession();
81.          }
            

82.    Query for cat

83.          public void queryCat() throws Exception {
84.              Session hibernateSession = HibernateUtil.currentSession();
85.              Transaction tx= hibernateSession.beginTransaction();
86.              String selectQuery = "select cat from Cat as cat";
87.              Query query = hibernateSession.createQuery(selectQuery);
88.              System.out.println("Results:");
89.              for (java.util.Iterator it = query.iterate(); it.hasNext();) {
90.                  Cat cat = (Cat) it.next();
91.                  System.out.println(cat.getName());
92.                  Iterator nickNames = cat.getNickNames().iterator();
93.                  while (nickNames.hasNext()) {
94.                      System.out.println("    " + nickNames.next());
95.                  }
96.                  //hibernateSession.delete(cat);
97.              }
98.              tx.commit();
99.              HibernateUtil.closeSession();
100.      }
            

101. Classpath

The class path should point to Cat.hbm.xml, hibernate.cfg.xml, hibernate2.jar and the runtime libraries.

For more implementation details, please refer to the example.

To test if hibernate is installed correctly, and is usable, follow the steps

    % cd <OSS_HOME>
    % su
    % source ./env.sh
    % openpkg rc hibernate status
    

The output hibernate_usable="yes" should confirm that hibernate is installed properly.