<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
		<id>https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Aldosolis</id>
		<title>OWASP - User contributions [en]</title>
		<link rel="self" type="application/atom+xml" href="https://wiki.owasp.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Aldosolis"/>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php/Special:Contributions/Aldosolis"/>
		<updated>2026-05-06T10:09:25Z</updated>
		<subtitle>User contributions</subtitle>
		<generator>MediaWiki 1.27.2</generator>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=45931</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=45931"/>
				<updated>2008-11-05T18:46:25Z</updated>
		
		<summary type="html">&lt;p&gt;Aldosolis: /* Passwords in the hibernate.cfg.xml in plain text */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. &lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  &lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
=== Don't use load() to determine existence ===&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
=== Passwords in the hibernate.cfg.xml in plain text ===&lt;br /&gt;
Sensitive information such as passwords should be encrypted to prevent attacks like connecting directly to the database, you can extend Hibernate functionality to implement password encryption.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;br /&gt;
[[Category:OWASP Java Project]]&lt;br /&gt;
[[Category:Java]]&lt;/div&gt;</summary>
		<author><name>Aldosolis</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=45930</id>
		<title>Hibernate-Guidelines</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Hibernate-Guidelines&amp;diff=45930"/>
				<updated>2008-11-05T18:45:49Z</updated>
		
		<summary type="html">&lt;p&gt;Aldosolis: /* Simple */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Status ==&lt;br /&gt;
'''In progress'''&lt;br /&gt;
&lt;br /&gt;
== Important ==&lt;br /&gt;
=== SQL Injection ===&lt;br /&gt;
&lt;br /&gt;
It is commonly thought that ORM layers, like Hibernate are immune to SQL injection. This is not the case as Hibernate includes a subset of SQL called HQL, and allows &amp;quot;native&amp;quot; SQL queries. Often the ORM layer only minimally manipulates the inbound query before handing it off to the database for processing.&lt;br /&gt;
&lt;br /&gt;
=== Transaction Scope ===&lt;br /&gt;
&lt;br /&gt;
All database communication should occur within the scope of a Transaction. &lt;br /&gt;
&lt;br /&gt;
=== Persisting Tainted Data ===&lt;br /&gt;
&lt;br /&gt;
If an application sets tainted properties in an object, then makes that object persistent, it is highly likely that data will be accessed at some point and displayed.  If database values are never displayed to the user then obviously this is nullified.  Better yet if we could figure out which values from the db are tainted but I have a feeling it's not a feasible scan.  &lt;br /&gt;
&lt;br /&gt;
=== Rollback === &lt;br /&gt;
&lt;br /&gt;
When an exception occurs, roll back the Transaction and close the Session. If you don't, Hibernate can't guarantee that in-memory state accurately represents persistent state.  &lt;br /&gt;
If your Session is bound to the application, you have to stop the application. Rolling back the database transaction doesn't put your business objects back into the state they were at the start of the transaction, so the database state and the business objects do get out of sync.  Objects that are manipulated after a rollback as if they were synchronized.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Simple ==&lt;br /&gt;
&lt;br /&gt;
=== Don't use load() to determine existence ===&lt;br /&gt;
Do not use Session.load() to determine if an instance with the given identifier exists on the database; use Session.get() or a query instead.  This is a poss&lt;br /&gt;
&lt;br /&gt;
=== Constructing Query Strings ===&lt;br /&gt;
Hibernate has a set of functions that are used internally to construct their query strings, but there is no limit to using them in application code - what if they were used with tainted data?  This is pretty self explanatory.&lt;br /&gt;
&lt;br /&gt;
=== Place each class mapping in its own file ===&lt;br /&gt;
Don't use a single monolithic mapping document. Map com.eg.Foo in the file com/eg/Foo.hbm.xml. This makes particularly good sense in a team environment.  Nothing more than a app dev good practice.  &lt;br /&gt;
&lt;br /&gt;
=== Use bind variables ===&lt;br /&gt;
As in JDBC, always replace non-constant values by &amp;quot;?&amp;quot;. Never use string manipulation to bind a nonconstant value in a query! Even better, consider using named parameters in queries.&lt;br /&gt;
&lt;br /&gt;
=== Load mappings as resources  ===&lt;br /&gt;
Deploy the mappings along with the classes they map.&lt;br /&gt;
&lt;br /&gt;
=== Passwords in the hibernate.cfg.xml in plain text ===&lt;br /&gt;
Sensitive information such passwords should be encrypted to prevent attacks connecting directly to the database, you can extend Hibernate functionality to implement password encryption.&lt;br /&gt;
&lt;br /&gt;
----&lt;br /&gt;
&lt;br /&gt;
== Detailed ==&lt;br /&gt;
&lt;br /&gt;
=== Transaction Timeout ===&lt;br /&gt;
*Transaction timeouts ensure that no misbehaving transaction can indefinitely tie up resources while returning no response to the user. &lt;br /&gt;
*Outside a managed (JTA) environment, Hibernate cannot fully provide this functionality. However, Hibernate can at least control data access operations, ensuring that database level deadlocks and queries with huge result sets are limited by a defined timeout. &lt;br /&gt;
*In a managed environment, Hibernate can delegate transaction timeout to JTA.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Session sess = factory.openSession();&lt;br /&gt;
try {&lt;br /&gt;
     //set transaction timeout to 3 seconds&lt;br /&gt;
     sess.getTransaction().setTimeout(3);&lt;br /&gt;
     sess.getTransaction().begin();&lt;br /&gt;
     // do some work&lt;br /&gt;
          ...&lt;br /&gt;
     sess.getTransaction().commit()&lt;br /&gt;
}&lt;br /&gt;
catch (RuntimeException e) {&lt;br /&gt;
     sess.getTransaction().rollback();&lt;br /&gt;
     throw e; // or display error message&lt;br /&gt;
}&lt;br /&gt;
finally {&lt;br /&gt;
     sess.close();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Identify natural keys  ===&lt;br /&gt;
*Even though we recommend the use of surrogate keys as primary keys, you should still try to identify natural keys for all entities. &lt;br /&gt;
*A natural key is a property or combination of properties that is unique and non-null. If it is also immutable, even better. &lt;br /&gt;
*Map the properties of the natural key inside the &amp;lt;natural-id&amp;gt; element. Hibernate will generate the necessary unique key and nullability constraints, and your mapping will be more selfdocumenting.&lt;br /&gt;
*We strongly recommend that you implement equals() and hashCode() to compare the natural key properties of the entity.&lt;br /&gt;
*This mapping is not intended for use with entities with natural primary keys..  &lt;br /&gt;
&lt;br /&gt;
Example in hbm.xml:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 &amp;lt;natural-id mutable=&amp;quot;true|false&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;property ... /&amp;gt;&lt;br /&gt;
     &amp;lt;many-to-one ... /&amp;gt;&lt;br /&gt;
     ......&lt;br /&gt;
 &amp;lt;/natural-id&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Parameter Binding ===&lt;br /&gt;
&lt;br /&gt;
Hibernate parameter binding works like prepared statements.  An edge case it is, but say you had an already tainted string, and then used Query setters to bind more parameters to the &amp;quot;?&amp;quot; placeholders.  &lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.createQuery(&amp;quot;from DomesticCat cat where cat.name = ?&amp;quot;);&lt;br /&gt;
     q.setString(0, &amp;quot;Izi&amp;quot;);&lt;br /&gt;
     Iterator cats = q.iterate();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Improper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Insert insert = new Insert(dialect);&lt;br /&gt;
     insert.setComment(taint);&lt;br /&gt;
     insert.addSelectColumn(columnName, alias);&lt;br /&gt;
     String sql = insert.toQueryString();&lt;br /&gt;
           ....&lt;br /&gt;
     Query query = sess.createQuery(sql); /*B00*///creating a Query with an already tainted string&lt;br /&gt;
     query.setString(position, val); //this doesn't cleanse the damage that's been done.&lt;br /&gt;
           ....&lt;br /&gt;
     transaction.commit(); //sink the ship      &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Declare identifier properties on persistent classes ===&lt;br /&gt;
&lt;br /&gt;
Hibernate makes identifier properties optional. There are all sorts of reasons why you should use them. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance.  This is the easiest and most recommended route.&lt;br /&gt;
{{{&lt;br /&gt;
&amp;lt;class name=&amp;quot;Summary&amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;subselect&amp;gt;&lt;br /&gt;
		select item.name, max(bid.amount), count(*)&lt;br /&gt;
		from item&lt;br /&gt;
		join bid on bid.item_id = item.id&lt;br /&gt;
		group by item.name&lt;br /&gt;
	&amp;lt;/subselect&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;item&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;synchronize table=&amp;quot;bid&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;id&lt;br /&gt;
		 name=&amp;quot;propertyName&amp;quot; (1)&lt;br /&gt;
		 type=&amp;quot;typename&amp;quot; (2)&lt;br /&gt;
		 column=&amp;quot;column_name&amp;quot; (3)&lt;br /&gt;
		 unsaved-value=&amp;quot;null|any|none|undefined|id_value&amp;quot; (4)&lt;br /&gt;
		 access=&amp;quot;field|property|ClassName&amp;quot;&amp;gt; (5)&lt;br /&gt;
		 node=&amp;quot;element-name|@attribute-name|element/@attribute|.&amp;quot;&lt;br /&gt;
		 &amp;lt;generator class=&amp;quot;generatorClass&amp;quot;/&amp;gt;&lt;br /&gt;
	&amp;lt;/id&amp;gt;&lt;br /&gt;
&amp;lt;/class&amp;gt;&lt;br /&gt;
}}}&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Don't use session.find() ===&lt;br /&gt;
This pretty much looks like a duplicate of sql injection but using the deprecated method find() instead.  This rule was pulled straight from the best practice list from the reference manual.&lt;br /&gt;
&lt;br /&gt;
If using Hibernate, do not use the depreciated session.find() method without using one of the query binding overloads. Using session.find() with direct user input allows the user input to be passed directly to the underlying SQL engine and will result in SQL injections on all supported RDBMS.  &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  Payment payment = (Payment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = &amp;quot; + paymentIds.get(i));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above Hibernate HQL will allow SQL injection from paymentIds, which are obtained from the user. A safer way to express this is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  int pId = paymentIds.get(i);&lt;br /&gt;
&lt;br /&gt;
  TsPayment payment = (TsPayment) session.&lt;br /&gt;
       find(&amp;quot;from com.example.Payment as payment where payment.id = ?&amp;quot;, pId, StringType);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Cache Management and !OutOfMemoryException ===&lt;br /&gt;
&lt;br /&gt;
*The Session caches every object that is in persistent state (watched and checked for dirty state by Hibernate).&lt;br /&gt;
*Whenever you pass an object to save(), update() or saveOrUpdate() and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session.&lt;br /&gt;
*When flush() or commit() is subsequently called, the state of that object will be synchronized with the database.&lt;br /&gt;
*Otherwise it grows endlessly until you get an OutOfMemoryException, if you keep it open for a long time or simply load too much data. &lt;br /&gt;
*One solution for this is to call clear() and evict() to manage the Session cache, but you most likely should consider a Stored Procedure if you need mass data operations. &lt;br /&gt;
*Some solutions are shown in Chapter 13, Batch processing. Keeping a Session open for the duration of a user session also means a high probability of stale data.&lt;br /&gt;
&lt;br /&gt;
In this example, it would fall over with an OutOfMemoryException somewhere around the 50 000th row. That's because Hibernate caches all the newly inserted Customer instances in the session-level cache.     &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
     Customer customer = new Customer(.....);&lt;br /&gt;
     session.save(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
When making new objects persistent, you must flush() and then clear() the session regularly, to control the&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     size of the first-level cache.&lt;br /&gt;
     Session session = sessionFactory.openSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
     for ( int i=0; i&amp;lt;100000; i++ ) {&lt;br /&gt;
          Customer customer = new Customer(.....);&lt;br /&gt;
          session.save(customer);&lt;br /&gt;
          if ( i % 20 == 0 ) { //20, same as the JDBC batch size&lt;br /&gt;
               //flush a batch of inserts and release memory:&lt;br /&gt;
               session.flush();&lt;br /&gt;
               session.clear();&lt;br /&gt;
          }&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== About StatelessSession ===&lt;br /&gt;
*A StatelessSession has no persistence context associated with it and does not provide many of the higher-level life cycle semantics. In particular, a stateless session does not implement a first-level cache nor interact with any second-level or query cache.&lt;br /&gt;
*This may be used as a solution for the cache out of memory problem.&lt;br /&gt;
*Operations performed using a stateless session do not ever cascade to associated instances. Collections are ignored by a stateless session.&lt;br /&gt;
*The insert(), update() and delete() operations defined by the StatelessSession interface are considered&lt;br /&gt;
to be direct database row-level operations, which result in immediate execution of a SQL INSERT, UPDATE or&lt;br /&gt;
DELETE respectively.&lt;br /&gt;
&lt;br /&gt;
Example of proper use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     StatelessSession session = sessionFactory.openStatelessSession();&lt;br /&gt;
     Transaction tx = session.beginTransaction();&lt;br /&gt;
&lt;br /&gt;
     ScrollableResults customers = session.getNamedQuery(&amp;quot;GetCustomers&amp;quot;)&lt;br /&gt;
          .scroll(ScrollMode.FORWARD_ONLY);&lt;br /&gt;
     while ( customers.next() ) {&lt;br /&gt;
          Customer customer = (Customer) customers.get(0);&lt;br /&gt;
          customer.updateStuff(...);&lt;br /&gt;
          session.update(customer);&lt;br /&gt;
     }&lt;br /&gt;
     tx.commit();&lt;br /&gt;
     session.close();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Aboot POJOs ===&lt;br /&gt;
* You can tell what objects are the persistent ones by looking at the xxx.hbm.xml files.&lt;br /&gt;
* Persistent objects are usually POJO's with a default no-arg constructor so that Hibernate can instantiate them using Constructor.newInstance().&lt;br /&gt;
* It is recommended that these POJO's have a property that is explicitly mapped as a primary key.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;hibernate-mapping&amp;gt;&lt;br /&gt;
   &amp;lt;class entity-name=&amp;quot;Customer&amp;quot;&amp;gt;&lt;br /&gt;
      &amp;lt;id name=&amp;quot;id&amp;quot;&lt;br /&gt;
         type=&amp;quot;long&amp;quot;&lt;br /&gt;
         column=&amp;quot;ID&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;generator class=&amp;quot;sequence&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/id&amp;gt;&lt;br /&gt;
         ......&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Accessors and mutators should be declared for persistent fields - it is optional but is good practice because Hibernate persists JavaBeans style properties.&lt;br /&gt;
&lt;br /&gt;
=== Session and Concurrency issues ===&lt;br /&gt;
&lt;br /&gt;
*A Session is not thread-safe. &lt;br /&gt;
*Things which are supposed to work concurrently, like HTTP requests, session beans, or Swing workers, will cause race conditions if a Session instance would be shared. &lt;br /&gt;
*If you keep your Hibernate Session in your HttpSession, you should consider synchronizing access to your Http session. &lt;br /&gt;
*Otherwise, a user that clicks reload fast enough may use the same Session in two concurrently running threads.&lt;br /&gt;
&lt;br /&gt;
=== The equals() and hashCode() problem:  === &lt;br /&gt;
 &lt;br /&gt;
*Most Java objects provide a built-in equals() and hashCode() based on the object's identity; so each new() object will be different from all others.  &lt;br /&gt;
*If all your objects are in memory, this is a fine model, but Hibernate's whole job, of course, is to move your objects out of memory.  &lt;br /&gt;
* Hibernate uses the Hibernate session to manage this uniqueness. When you create an object with new(), and then save it into a session, Hibernate now knows that whenever you query for an object and find that particular object, Hibernate should return you that instance of the object.  &lt;br /&gt;
* However, once you close the Hibernate session, all bets are off. If you keep holding onto an object that you either created or loaded in a Hibernate session that you have now closed, Hibernate has no way to know about those objects. &lt;br /&gt;
* So if you open another session and query for &amp;quot;the same&amp;quot; object, Hibernate will return you a new instance. Hence, if you keep collections of objects around between sessions, you will start to experience odd behavior (duplicate objects in collections, mainly).&lt;br /&gt;
* '''Long story short equals() and hashCode() should be implemented to compare object properties and not just compare on the basis of identifier (the property mapped as the primary key see the above example).  The problem is discussed in detail [http://www.hibernate.org/109.html here].'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Cat {&lt;br /&gt;
...&lt;br /&gt;
 public boolean equals(Object other) {&lt;br /&gt;
   if (this == other) return true;&lt;br /&gt;
   if ( !(other instanceof Cat) ) return false;&lt;br /&gt;
   final Cat cat = (Cat) other;&lt;br /&gt;
   if ( !cat.getLitterId().equals( getLitterId() ) ) return false;&lt;br /&gt;
   if ( !cat.getMother().equals( getMother() ) ) return false;&lt;br /&gt;
   return true;&lt;br /&gt;
 }&lt;br /&gt;
 public int hashCode() {&lt;br /&gt;
   int result;&lt;br /&gt;
   result = getMother().hashCode();&lt;br /&gt;
   result = 29 * result + getLitterId();&lt;br /&gt;
   return result;&lt;br /&gt;
 }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Using Detached Objects ===&lt;br /&gt;
*In a three tiered architecture, consider using detached objects.&lt;br /&gt;
*When using a servlet / session bean architecture, you could pass persistent objects loaded in the session&lt;br /&gt;
bean to and from the servlet / JSP layer. &lt;br /&gt;
*Use a new session to service each request. &lt;br /&gt;
*Use Session.merge() or Session.saveOrUpdate() to synchronize objects with the database.&lt;br /&gt;
Usually update() or saveOrUpdate() are used in the following scenario:&lt;br /&gt;
*the application loads an object in the first session&lt;br /&gt;
*the object is passed up to the UI tier&lt;br /&gt;
*some modifications are made to the object&lt;br /&gt;
*the object is passed back down to the business logic tier&lt;br /&gt;
*the application persists these modifications by calling update() in a second session&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// in the first session&lt;br /&gt;
Cat cat = (Cat) firstSession.load(Cat.class, catID);&lt;br /&gt;
// in a higher tier of the application&lt;br /&gt;
Cat mate = new Cat();&lt;br /&gt;
cat.setMate(mate);&lt;br /&gt;
// later, in a new session&lt;br /&gt;
secondSession.saveOrUpdate(cat); // update existing state (cat has a non-null id)&lt;br /&gt;
secondSession.saveOrUpdate(mate); // save the new instance (mate has a null id)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Consider externalising query strings ===&lt;br /&gt;
&lt;br /&gt;
This is a good practice if your queries call non-ANSI-standard SQL functions. Externalising the query&lt;br /&gt;
strings to mapping files will make the application more portable.&lt;br /&gt;
It also decreases the likelihood of injection because the Query objects let you set individual parameters but not the entire query string - you can only do that when you pass the string into the Query implementation constructor or call Session.createQuery.  &lt;br /&gt;
==== Edge cases are still possibilities! ====&lt;br /&gt;
*Basically the application would have to be messy enough to be binding parameters here, and concatenating variables there to the same query string.&lt;br /&gt;
*You can extract the query string using Query.getQueryString(), and although you can't manipulate the string and 'add' it back to the Query object, you could theoretically taint it and use it in another instance of Query.  Dumb? yes.  Possible?  Yes.&lt;br /&gt;
&lt;br /&gt;
==== So how to externalize? ====&lt;br /&gt;
You may define named queries in the mapping document. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  &amp;lt;query name=&amp;quot;ByNameAndMaximumWeight&amp;quot;&amp;gt;&amp;lt;![CDATA[&lt;br /&gt;
     from eg.DomesticCat as cat&lt;br /&gt;
     where cat.name = ?&lt;br /&gt;
     and cat.weight &amp;gt; ?&lt;br /&gt;
     ] ]&amp;gt;&amp;lt;/query&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Parameter binding and executing is done programatically:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
     Query q = sess.getNamedQuery(&amp;quot;ByNameAndMaximumWeight&amp;quot;);&lt;br /&gt;
     q.setString(0, name);&lt;br /&gt;
     q.setInt(1, minWeight);&lt;br /&gt;
     List cats = q.list();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Note that the actual program code is independent of the query language that is used, you may also define native&lt;br /&gt;
SQL queries in metadata, or migrate existing queries to Hibernate by placing them in mapping files.&lt;br /&gt;
*Also note that a query declaration inside a &amp;lt;hibernate-mapping&amp;gt; element requires a global unique name for the&lt;br /&gt;
query, while a query declaration inside a &amp;lt;class&amp;gt; element is made unique automatically by prepending the&lt;br /&gt;
fully qualified name of the class, for example eg.Cat.ByNameAndMaximumWeight.&lt;br /&gt;
&lt;br /&gt;
[[Category:Hibernate]]&lt;br /&gt;
[[Category:OWASP Java Project]]&lt;br /&gt;
[[Category:Java]]&lt;/div&gt;</summary>
		<author><name>Aldosolis</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Reviewing_Code_for_Error_Handling&amp;diff=22074</id>
		<title>Reviewing Code for Error Handling</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Reviewing_Code_for_Error_Handling&amp;diff=22074"/>
				<updated>2007-10-03T14:01:02Z</updated>
		
		<summary type="html">&lt;p&gt;Aldosolis: /* JAVA */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[[OWASP Code Review Guide Table of Contents]]__TOC__&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Error, Exception handling &amp;amp; Logging. ==&lt;br /&gt;
&lt;br /&gt;
An important aspect of secure application development is to prevent information leakage. Error messages give an attacker great insight into the inner workings of an application. &lt;br /&gt;
&lt;br /&gt;
The purpose of reviewing the Error Handling code is to assure the application fails safely under all possible error conditions, expected and unexpected. No sensitive information is presented to the user when an error occurs.&lt;br /&gt;
&lt;br /&gt;
For example SQL injection is much tougher to successfully pull off without some healthy error messages. It lessens the attack footprint and our attacker would have to resort to use “blind SQL injection” which is more difficult and time consuming.&lt;br /&gt;
&lt;br /&gt;
A well-planned error/exception handling strategy is important for three reasons:&lt;br /&gt;
&lt;br /&gt;
#	Good error handling does not give an attacker any information which is a means to an end, attacking the application&lt;br /&gt;
#	A proper centralised error strategy is easier to maintain and reduces the chance of any uncaught errors “Bubbling up” to the front end of an application.&lt;br /&gt;
#	Information leakage can lead to social engineering exploits.&lt;br /&gt;
&lt;br /&gt;
Some development languages provide checked exceptions which mean that the compiler shall complain if an exception for a particular API call is not caught Java and C# are good examples of this.&lt;br /&gt;
Languages like C++ and C do not provide this safety net. Languages with checked exception handling still are prone to information leakage as not all types of error are checked for.&lt;br /&gt;
&lt;br /&gt;
When an exception or error is thrown we also need to log this occurrence. Sometimes this is due to bad development, but it can be the result of an attack or some other service your application relies on failing.&lt;br /&gt;
&lt;br /&gt;
All code paths that can cause an exception to be thrown should check for success in order for the exception not to be thrown.&lt;br /&gt;
&lt;br /&gt;
To avoid a NullPointerException we should check is the object being accessed is not null.&lt;br /&gt;
&lt;br /&gt;
==Generic error messages==&lt;br /&gt;
&lt;br /&gt;
We should use a localized description string in every exception, a friendly error reason such as “System Error – Please try again later”. When the user sees an error message, it will be derived from this description string of the exception that was thrown, and never from the exception class which may contain a stack trace, line number where the error occurred, class name or method name.&lt;br /&gt;
&lt;br /&gt;
Do not expose sensitive information in exception messages. Information such as paths on the local file system is considered privileged information; any system internal information should be hidden from the user. As mentioned before an attacker could use this information to gather private user information from the application or components that make up the app.&lt;br /&gt;
&lt;br /&gt;
Don’t put people’s names or any internal contact information in error messages. Don’t put any “human” information, which would lead to a level of familiarity and a social engineering exploit.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==How to locate the potentially vulnerable code==&lt;br /&gt;
&lt;br /&gt;
===JAVA===&lt;br /&gt;
&lt;br /&gt;
In java we have the concept of an error object, the Exception object.&lt;br /&gt;
This lives in the java package java.lang and is derived from the Throwable object&lt;br /&gt;
Exceptions are thrown when an abnormal occurrence has occurred. Another object derived from Throwable is the Error object, which is thrown when something more serious occurs.&lt;br /&gt;
&lt;br /&gt;
Information leakage can occur when developers use some exception methods, which ‘bubble’ to the user UI due to a poor error handling strategy.&lt;br /&gt;
The methods are as follows:&lt;br /&gt;
printStackTrace()&lt;br /&gt;
getStackTrace()&lt;br /&gt;
&lt;br /&gt;
Also is important to know that the output of these methods is printed in System console, the same as System.out.println(e) where e is an Exception. Be sure to not redirect the outputStream to PrintWriter object of JSP, by convention called &amp;quot;out&amp;quot;. Ex. printStackTrace(out);&lt;br /&gt;
&lt;br /&gt;
Also another object to look at is the java.lang.system package:&lt;br /&gt;
&lt;br /&gt;
setErr() and the System.err field.&lt;br /&gt;
&lt;br /&gt;
===.NET===&lt;br /&gt;
&lt;br /&gt;
In .NET a System.Exception object exists. Commonly used child objects such as ApplicationException and SystemException are used.&lt;br /&gt;
It is not recommended that you throw or catch a SystemException this is thrown by runtime.&lt;br /&gt;
&lt;br /&gt;
When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error, similar to java. Once thrown, an exception is handled by the application or by the default exception handler.&lt;br /&gt;
This Exception object contains similar methods to the java implementation such as:&lt;br /&gt;
&lt;br /&gt;
StackTrace &lt;br /&gt;
Source&lt;br /&gt;
Message&lt;br /&gt;
HelpLink&lt;br /&gt;
&lt;br /&gt;
In .NET we need to look at the error handling strategy from the point of view of global error handling and the handling of unexpected errors. This can be done in many ways and this article is not an exhaustive list.&lt;br /&gt;
Firstly an Error Event is thrown when an unhandled exception is thrown. This is part of the TemplateControl class.&lt;br /&gt;
&lt;br /&gt;
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUITemplateControlClassErrorTopic.asp&lt;br /&gt;
&lt;br /&gt;
==Error handling can be done in three ways in .NET==&lt;br /&gt;
&lt;br /&gt;
*In the web.config file's customErrors section. &lt;br /&gt;
*In the global.asax file's Application_Error sub. &lt;br /&gt;
*On the aspx or associated codebehind page in the Page_Error sub&lt;br /&gt;
&lt;br /&gt;
The order of error handling events in .NET is as follows: &lt;br /&gt;
#	On the Page in the Page_Error sub.&lt;br /&gt;
#	The global.asax Application_Error sub &lt;br /&gt;
#	The web.config file &lt;br /&gt;
&lt;br /&gt;
It is recommended to look in these areas to understand the error strategy of the application.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Vulnerable Patterns for Error Handling==&lt;br /&gt;
&lt;br /&gt;
===Page_Error===&lt;br /&gt;
&lt;br /&gt;
Page_Error is page level handling which is run on the server side.&lt;br /&gt;
Below is an example but the error information is a little too informative and hence bad practice.&lt;br /&gt;
&lt;br /&gt;
'''FIXME: code formatting'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;script language=&amp;quot;C#&amp;quot; runat=&amp;quot;server&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sub Page_Error(Source As Object, E As EventArgs)&lt;br /&gt;
&lt;br /&gt;
Dim message As String = &amp;quot;&amp;lt;font face=verdana color=red&amp;gt;&amp;lt;h1&amp;gt;&amp;quot; &amp;amp; Request.Url.ToString()&amp;amp; &amp;quot;&amp;lt;/h1&amp;gt;&amp;quot; &amp;amp;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;&amp;lt;pre&amp;gt;&amp;lt;font color='red'&amp;gt;&amp;quot; &amp;amp; Server.GetLastError().ToString()&amp;amp; &amp;quot;&amp;lt;/pre&amp;gt;&amp;lt;/font&amp;gt;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Response.Write(message) // display message&lt;br /&gt;
&lt;br /&gt;
End Sub&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The red text in the example above has a number of issues:&lt;br /&gt;
Firstly it redisplays the HTTP request to the user in the form of Request.Url.ToString() Assuming there has been no data validation prior to this point we are vulnerable to cross site scripting attacks!! Secondly the error message and stack trace is displayed to the user using Server.GetLastError().ToString() which divulges internal information regarding the application.&lt;br /&gt;
&lt;br /&gt;
After the Page_Error is called, the Application_Error sub is called:&lt;br /&gt;
&lt;br /&gt;
===Global.asax===&lt;br /&gt;
&lt;br /&gt;
When an error occurs, the Application_Error sub is called. In this method we can&lt;br /&gt;
log the error and redirect to another page.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;%@ Import Namespace=&amp;quot;System.Diagnostics&amp;quot; %&amp;gt;&lt;br /&gt;
   &amp;lt;script language=&amp;quot;C#&amp;quot; runat=&amp;quot;server&amp;quot;&amp;gt;&lt;br /&gt;
     void Application_Error(Object sender, EventArgs e) {&lt;br /&gt;
          String Message = &amp;quot;\n\nURL: http://localhost/&amp;quot; + Request.Path&lt;br /&gt;
                           + &amp;quot;\n\nMESSAGE:\n &amp;quot; + Server.GetLastError().Message&lt;br /&gt;
                           + &amp;quot;\n\nSTACK TRACE:\n&amp;quot; + Server.GetLastError().StackTrace;&lt;br /&gt;
          // Insert into Event Log&lt;br /&gt;
          EventLog Log = new EventLog();&lt;br /&gt;
          Log.Source = LogName;&lt;br /&gt;
          Log.WriteEntry(Message, EventLogEntryType.Error);&lt;br /&gt;
        Server.Redirect(Error.htm) // this shall also clear the error&lt;br /&gt;
     }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Above is an example of code in Global.asax and the Application_Error method.&lt;br /&gt;
The error is logged and then the user is redirected. Unvalidated parameters are being&lt;br /&gt;
logged here in the form of Request.Path. Care must be taken not to log or redisplay &lt;br /&gt;
unvalidated input from any external source. &lt;br /&gt;
&lt;br /&gt;
===Web.config===&lt;br /&gt;
Web.config has a custom errors tag which can be used to handle errors. This is called last and if Page_error or Application_error  called and has functionality that functionality shall be executed first. As long as the previous two handling mechanisms do not redirect or clear (Response.Redirect or a Server.ClearError) this shall be called. And you shall be forwarded to the page defined in web.config&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;customErrors defaultRedirect=&amp;quot;error.html&amp;quot; mode=&amp;quot;On|Off|RemoteOnly&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;error statusCode=&amp;quot;statuscode&amp;quot; redirect=&amp;quot;url&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/customErrors&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “On&amp;quot; directive means that custom errors are enabled. If no defaultRedirect is specified, users see a generic error. &lt;br /&gt;
&amp;quot;Off&amp;quot; directive means that custom errors are disabled. This allows display of detailed errors. &lt;br /&gt;
&amp;quot;RemoteOnly&amp;quot; specifies that custom errors are shown only to remote clients, and ASP.NET errors are shown to the local host. This is the default. &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;customErrors mode=&amp;quot;On&amp;quot; defaultRedirect=&amp;quot;error.html&amp;quot;&amp;gt;&lt;br /&gt;
     &amp;lt;error statusCode=&amp;quot;500&amp;quot; redirect=&amp;quot;err500.aspx&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;error statusCode=&amp;quot;404&amp;quot; redirect=&amp;quot;notHere.aspx&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;error statusCode=&amp;quot;403&amp;quot; redirect=&amp;quot;notAuthz.aspx&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/customErrors&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
== Best Practices for Error Handling ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Try &amp;amp; Catch (Java/ .NET)===&lt;br /&gt;
&lt;br /&gt;
Code that might throw exceptions should be in a try block and code that handles exceptions in a catch block. &lt;br /&gt;
The catch block is a series of statements beginning with the keyword catch, followed by an exception type and an action to be taken. These are very similar in Java and .NET&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
Java Try-Catch:&lt;br /&gt;
&lt;br /&gt;
 public class DoStuff {&lt;br /&gt;
     public static void Main() {&lt;br /&gt;
         try {&lt;br /&gt;
             StreamReader sr = File.OpenText(&amp;quot;stuff.txt&amp;quot;);&lt;br /&gt;
             Console.WriteLine(&amp;quot;Reading line {0}&amp;quot;, sr.ReadLine());    &lt;br /&gt;
         }&lt;br /&gt;
         catch(Exception e) {&lt;br /&gt;
             Console.WriteLine(&amp;quot;An error occurred. Please leave to room”);&lt;br /&gt;
 	 logerror(“Error: “, e);&lt;br /&gt;
         }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
.NET try – catch&lt;br /&gt;
&lt;br /&gt;
 public void run() {&lt;br /&gt;
             while (!stop) {&lt;br /&gt;
                 try {&lt;br /&gt;
 &lt;br /&gt;
                     // Perform work here&lt;br /&gt;
 &lt;br /&gt;
                 } catch (Throwable t) {&lt;br /&gt;
                     // Log the exception and continue&lt;br /&gt;
 		WriteToUser(“An Error has occurred, put the kettle on”);&lt;br /&gt;
                     logger.log(Level.SEVERE, &amp;quot;Unexception exception&amp;quot;, t);&lt;br /&gt;
                 }&lt;br /&gt;
             }&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
In general, it is best practice to catch a specific type of exception rather than use the basic catch(Exception) or catch(Throwable) statement in the case of Java.&lt;br /&gt;
&lt;br /&gt;
===Releasing resources and good housekeeping===&lt;br /&gt;
&lt;br /&gt;
If the language in question has a finally method use it. The finally method is guaranteed to always be called. The finally method can be used to release resources referenced by the method that threw the exception. This is very important. An example would be if a method gained a database connection from a pool of connections and an exception occurred without finally the connection object shall not be returned to the pool for some time (until the timeout). This can lead to pool exhaustion. finally() is called even if no exception is thrown.&lt;br /&gt;
&lt;br /&gt;
 try {&lt;br /&gt;
        System.out.println(&amp;quot;Entering try statement&amp;quot;);&lt;br /&gt;
        out = new PrintWriter(new FileWriter(&amp;quot;OutFile.txt&amp;quot;));&lt;br /&gt;
      //Do Stuff….&lt;br /&gt;
 &lt;br /&gt;
    } catch (Exception e) {&lt;br /&gt;
        System.err.println(&amp;quot;Error occurred!”);&lt;br /&gt;
 &lt;br /&gt;
    } catch (IOException e) {&lt;br /&gt;
        System.err.println(&amp;quot;Input exception &amp;quot;);&lt;br /&gt;
 &lt;br /&gt;
    } finally {&lt;br /&gt;
 &lt;br /&gt;
        if (out != null) { &lt;br /&gt;
            out.close(); // RELEASE RESOURCES&lt;br /&gt;
        } &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
A Java example showing finally() being used to release system resources.&lt;br /&gt;
&lt;br /&gt;
===Centralised exception handling (Struts Example)===&lt;br /&gt;
&lt;br /&gt;
Building an infrastructure for consistent error reporting proves more difficult than error handling.&lt;br /&gt;
Struts provides the ActionMessages &amp;amp; ActionErrors classes for maintaining a stack of error messages to be reported, which can be used with JSP tags like &amp;lt;html: error&amp;gt; to display these error messages to the user. &lt;br /&gt;
&lt;br /&gt;
To report a different severity of a message in a different manner (like error, warning, or information) the following tasks are required: &lt;br /&gt;
&lt;br /&gt;
* Register, instantiate the errors under the appropriate severity&lt;br /&gt;
* Identify these messages and show them in a constant manner.&lt;br /&gt;
&lt;br /&gt;
Struts ActionErrors class makes error handling quite easy:&lt;br /&gt;
&lt;br /&gt;
 ActionErrors errors = new ActionErrors()&lt;br /&gt;
 errors.add(&amp;quot;fatal&amp;quot;, new ActionError(&amp;quot;....&amp;quot;)); &lt;br /&gt;
 errors.add(&amp;quot;error&amp;quot;, new ActionError(&amp;quot;....&amp;quot;)); &lt;br /&gt;
 errors.add(&amp;quot;warning&amp;quot;, new ActionError(&amp;quot;....&amp;quot;));&lt;br /&gt;
 errors.add(&amp;quot;information&amp;quot;, new ActionError(&amp;quot;....&amp;quot;)); &lt;br /&gt;
 saveErrors(request,errors); // Important to do this&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we have added the errors we display them by using tags in the HTML page.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;logic:messagePresent property=&amp;quot;error&amp;quot;&amp;gt; &lt;br /&gt;
 &amp;lt;html:messages property=&amp;quot;error&amp;quot; id=&amp;quot;errMsg&amp;quot; &amp;gt;&lt;br /&gt;
     &amp;lt;bean:write name=&amp;quot;errMsg&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/html:messages&amp;gt;&lt;br /&gt;
 &amp;lt;/logic:messagePresent &amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:OWASP Code Review Project]]&lt;/div&gt;</summary>
		<author><name>Aldosolis</name></author>	</entry>

	<entry>
		<id>https://wiki.owasp.org/index.php?title=Reviewing_Code_for_Error_Handling&amp;diff=22063</id>
		<title>Reviewing Code for Error Handling</title>
		<link rel="alternate" type="text/html" href="https://wiki.owasp.org/index.php?title=Reviewing_Code_for_Error_Handling&amp;diff=22063"/>
				<updated>2007-10-02T22:25:12Z</updated>
		
		<summary type="html">&lt;p&gt;Aldosolis: /* JAVA */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[[OWASP Code Review Guide Table of Contents]]__TOC__&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Error, Exception handling &amp;amp; Logging. ==&lt;br /&gt;
&lt;br /&gt;
An important aspect of secure application development is to prevent information leakage. Error messages give an attacker great insight into the inner workings of an application. &lt;br /&gt;
&lt;br /&gt;
The purpose of reviewing the Error Handling code is to assure the application fails safely under all possible error conditions, expected and unexpected. No sensitive information is presented to the user when an error occurs.&lt;br /&gt;
&lt;br /&gt;
For example SQL injection is much tougher to successfully pull off without some healthy error messages. It lessens the attack footprint and our attacker would have to resort to use “blind SQL injection” which is more difficult and time consuming.&lt;br /&gt;
&lt;br /&gt;
A well-planned error/exception handling strategy is important for three reasons:&lt;br /&gt;
&lt;br /&gt;
#	Good error handling does not give an attacker any information which is a means to an end, attacking the application&lt;br /&gt;
#	A proper centralised error strategy is easier to maintain and reduces the chance of any uncaught errors “Bubbling up” to the front end of an application.&lt;br /&gt;
#	Information leakage can lead to social engineering exploits.&lt;br /&gt;
&lt;br /&gt;
Some development languages provide checked exceptions which mean that the compiler shall complain if an exception for a particular API call is not caught Java and C# are good examples of this.&lt;br /&gt;
Languages like C++ and C do not provide this safety net. Languages with checked exception handling still are prone to information leakage as not all types of error are checked for.&lt;br /&gt;
&lt;br /&gt;
When an exception or error is thrown we also need to log this occurrence. Sometimes this is due to bad development, but it can be the result of an attack or some other service your application relies on failing.&lt;br /&gt;
&lt;br /&gt;
All code paths that can cause an exception to be thrown should check for success in order for the exception not to be thrown.&lt;br /&gt;
&lt;br /&gt;
To avoid a NullPointerException we should check is the object being accessed is not null.&lt;br /&gt;
&lt;br /&gt;
==Generic error messages==&lt;br /&gt;
&lt;br /&gt;
We should use a localized description string in every exception, a friendly error reason such as “System Error – Please try again later”. When the user sees an error message, it will be derived from this description string of the exception that was thrown, and never from the exception class which may contain a stack trace, line number where the error occurred, class name or method name.&lt;br /&gt;
&lt;br /&gt;
Do not expose sensitive information in exception messages. Information such as paths on the local file system is considered privileged information; any system internal information should be hidden from the user. As mentioned before an attacker could use this information to gather private user information from the application or components that make up the app.&lt;br /&gt;
&lt;br /&gt;
Don’t put people’s names or any internal contact information in error messages. Don’t put any “human” information, which would lead to a level of familiarity and a social engineering exploit.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==How to locate the potentially vulnerable code==&lt;br /&gt;
&lt;br /&gt;
===JAVA===&lt;br /&gt;
&lt;br /&gt;
In java we have the concept of an error object, the Exception object.&lt;br /&gt;
This lives in the java package java.lang and is derived from the Throwable object&lt;br /&gt;
Exceptions are thrown when an abnormal occurrence has occurred. Another object derived from Throwable is the Error object, which is thrown when something more serious occurs.&lt;br /&gt;
&lt;br /&gt;
Information leakage can occur when developers use some exception methods, which ‘bubble’ to the user UI due to a poor error handling strategy.&lt;br /&gt;
The methods are as follows:&lt;br /&gt;
printStackTrace()&lt;br /&gt;
getStackTrace()&lt;br /&gt;
&lt;br /&gt;
Also is important to know that by default the output of these methods is printed in System console, the same as System.out.println(e) where e is an Exception. Be sure to not redirect the outputStream to PrintWriter object of JSP, by convention called &amp;quot;out&amp;quot;. Ex. printStackTrace(out);&lt;br /&gt;
&lt;br /&gt;
Also another object to look at is the java.lang.system package:&lt;br /&gt;
&lt;br /&gt;
setErr() and the System.err field.&lt;br /&gt;
&lt;br /&gt;
===.NET===&lt;br /&gt;
&lt;br /&gt;
In .NET a System.Exception object exists. Commonly used child objects such as ApplicationException and SystemException are used.&lt;br /&gt;
It is not recommended that you throw or catch a SystemException this is thrown by runtime.&lt;br /&gt;
&lt;br /&gt;
When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error, similar to java. Once thrown, an exception is handled by the application or by the default exception handler.&lt;br /&gt;
This Exception object contains similar methods to the java implementation such as:&lt;br /&gt;
&lt;br /&gt;
StackTrace &lt;br /&gt;
Source&lt;br /&gt;
Message&lt;br /&gt;
HelpLink&lt;br /&gt;
&lt;br /&gt;
In .NET we need to look at the error handling strategy from the point of view of global error handling and the handling of unexpected errors. This can be done in many ways and this article is not an exhaustive list.&lt;br /&gt;
Firstly an Error Event is thrown when an unhandled exception is thrown. This is part of the TemplateControl class.&lt;br /&gt;
&lt;br /&gt;
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUITemplateControlClassErrorTopic.asp&lt;br /&gt;
&lt;br /&gt;
==Error handling can be done in three ways in .NET==&lt;br /&gt;
&lt;br /&gt;
*In the web.config file's customErrors section. &lt;br /&gt;
*In the global.asax file's Application_Error sub. &lt;br /&gt;
*On the aspx or associated codebehind page in the Page_Error sub&lt;br /&gt;
&lt;br /&gt;
The order of error handling events in .NET is as follows: &lt;br /&gt;
#	On the Page in the Page_Error sub.&lt;br /&gt;
#	The global.asax Application_Error sub &lt;br /&gt;
#	The web.config file &lt;br /&gt;
&lt;br /&gt;
It is recommended to look in these areas to understand the error strategy of the application.&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
==Vulnerable Patterns for Error Handling==&lt;br /&gt;
&lt;br /&gt;
===Page_Error===&lt;br /&gt;
&lt;br /&gt;
Page_Error is page level handling which is run on the server side.&lt;br /&gt;
Below is an example but the error information is a little too informative and hence bad practice.&lt;br /&gt;
&lt;br /&gt;
'''FIXME: code formatting'''&lt;br /&gt;
&lt;br /&gt;
&amp;lt;nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;script language=&amp;quot;C#&amp;quot; runat=&amp;quot;server&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sub Page_Error(Source As Object, E As EventArgs)&lt;br /&gt;
&lt;br /&gt;
Dim message As String = &amp;quot;&amp;lt;font face=verdana color=red&amp;gt;&amp;lt;h1&amp;gt;&amp;quot; &amp;amp; Request.Url.ToString()&amp;amp; &amp;quot;&amp;lt;/h1&amp;gt;&amp;quot; &amp;amp;&lt;br /&gt;
&lt;br /&gt;
&amp;quot;&amp;lt;pre&amp;gt;&amp;lt;font color='red'&amp;gt;&amp;quot; &amp;amp; Server.GetLastError().ToString()&amp;amp; &amp;quot;&amp;lt;/pre&amp;gt;&amp;lt;/font&amp;gt;&amp;quot;&lt;br /&gt;
&lt;br /&gt;
Response.Write(message) // display message&lt;br /&gt;
&lt;br /&gt;
End Sub&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The red text in the example above has a number of issues:&lt;br /&gt;
Firstly it redisplays the HTTP request to the user in the form of Request.Url.ToString() Assuming there has been no data validation prior to this point we are vulnerable to cross site scripting attacks!! Secondly the error message and stack trace is displayed to the user using Server.GetLastError().ToString() which divulges internal information regarding the application.&lt;br /&gt;
&lt;br /&gt;
After the Page_Error is called, the Application_Error sub is called:&lt;br /&gt;
&lt;br /&gt;
===Global.asax===&lt;br /&gt;
&lt;br /&gt;
When an error occurs, the Application_Error sub is called. In this method we can&lt;br /&gt;
log the error and redirect to another page.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;%@ Import Namespace=&amp;quot;System.Diagnostics&amp;quot; %&amp;gt;&lt;br /&gt;
   &amp;lt;script language=&amp;quot;C#&amp;quot; runat=&amp;quot;server&amp;quot;&amp;gt;&lt;br /&gt;
     void Application_Error(Object sender, EventArgs e) {&lt;br /&gt;
          String Message = &amp;quot;\n\nURL: http://localhost/&amp;quot; + Request.Path&lt;br /&gt;
                           + &amp;quot;\n\nMESSAGE:\n &amp;quot; + Server.GetLastError().Message&lt;br /&gt;
                           + &amp;quot;\n\nSTACK TRACE:\n&amp;quot; + Server.GetLastError().StackTrace;&lt;br /&gt;
          // Insert into Event Log&lt;br /&gt;
          EventLog Log = new EventLog();&lt;br /&gt;
          Log.Source = LogName;&lt;br /&gt;
          Log.WriteEntry(Message, EventLogEntryType.Error);&lt;br /&gt;
        Server.Redirect(Error.htm) // this shall also clear the error&lt;br /&gt;
     }&lt;br /&gt;
 &amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Above is an example of code in Global.asax and the Application_Error method.&lt;br /&gt;
The error is logged and then the user is redirected. Unvalidated parameters are being&lt;br /&gt;
logged here in the form of Request.Path. Care must be taken not to log or redisplay &lt;br /&gt;
unvalidated input from any external source. &lt;br /&gt;
&lt;br /&gt;
===Web.config===&lt;br /&gt;
Web.config has a custom errors tag which can be used to handle errors. This is called last and if Page_error or Application_error  called and has functionality that functionality shall be executed first. As long as the previous two handling mechanisms do not redirect or clear (Response.Redirect or a Server.ClearError) this shall be called. And you shall be forwarded to the page defined in web.config&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;customErrors defaultRedirect=&amp;quot;error.html&amp;quot; mode=&amp;quot;On|Off|RemoteOnly&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;error statusCode=&amp;quot;statuscode&amp;quot; redirect=&amp;quot;url&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/customErrors&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “On&amp;quot; directive means that custom errors are enabled. If no defaultRedirect is specified, users see a generic error. &lt;br /&gt;
&amp;quot;Off&amp;quot; directive means that custom errors are disabled. This allows display of detailed errors. &lt;br /&gt;
&amp;quot;RemoteOnly&amp;quot; specifies that custom errors are shown only to remote clients, and ASP.NET errors are shown to the local host. This is the default. &lt;br /&gt;
&lt;br /&gt;
 &amp;lt;customErrors mode=&amp;quot;On&amp;quot; defaultRedirect=&amp;quot;error.html&amp;quot;&amp;gt;&lt;br /&gt;
     &amp;lt;error statusCode=&amp;quot;500&amp;quot; redirect=&amp;quot;err500.aspx&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;error statusCode=&amp;quot;404&amp;quot; redirect=&amp;quot;notHere.aspx&amp;quot;/&amp;gt;&lt;br /&gt;
     &amp;lt;error statusCode=&amp;quot;403&amp;quot; redirect=&amp;quot;notAuthz.aspx&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/customErrors&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &lt;br /&gt;
== Best Practices for Error Handling ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Try &amp;amp; Catch (Java/ .NET)===&lt;br /&gt;
&lt;br /&gt;
Code that might throw exceptions should be in a try block and code that handles exceptions in a catch block. &lt;br /&gt;
The catch block is a series of statements beginning with the keyword catch, followed by an exception type and an action to be taken. These are very similar in Java and .NET&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
Java Try-Catch:&lt;br /&gt;
&lt;br /&gt;
 public class DoStuff {&lt;br /&gt;
     public static void Main() {&lt;br /&gt;
         try {&lt;br /&gt;
             StreamReader sr = File.OpenText(&amp;quot;stuff.txt&amp;quot;);&lt;br /&gt;
             Console.WriteLine(&amp;quot;Reading line {0}&amp;quot;, sr.ReadLine());    &lt;br /&gt;
         }&lt;br /&gt;
         catch(Exception e) {&lt;br /&gt;
             Console.WriteLine(&amp;quot;An error occurred. Please leave to room”);&lt;br /&gt;
 	 logerror(“Error: “, e);&lt;br /&gt;
         }&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
.NET try – catch&lt;br /&gt;
&lt;br /&gt;
 public void run() {&lt;br /&gt;
             while (!stop) {&lt;br /&gt;
                 try {&lt;br /&gt;
 &lt;br /&gt;
                     // Perform work here&lt;br /&gt;
 &lt;br /&gt;
                 } catch (Throwable t) {&lt;br /&gt;
                     // Log the exception and continue&lt;br /&gt;
 		WriteToUser(“An Error has occurred, put the kettle on”);&lt;br /&gt;
                     logger.log(Level.SEVERE, &amp;quot;Unexception exception&amp;quot;, t);&lt;br /&gt;
                 }&lt;br /&gt;
             }&lt;br /&gt;
         }&lt;br /&gt;
&lt;br /&gt;
In general, it is best practice to catch a specific type of exception rather than use the basic catch(Exception) or catch(Throwable) statement in the case of Java.&lt;br /&gt;
&lt;br /&gt;
===Releasing resources and good housekeeping===&lt;br /&gt;
&lt;br /&gt;
If the language in question has a finally method use it. The finally method is guaranteed to always be called. The finally method can be used to release resources referenced by the method that threw the exception. This is very important. An example would be if a method gained a database connection from a pool of connections and an exception occurred without finally the connection object shall not be returned to the pool for some time (until the timeout). This can lead to pool exhaustion. finally() is called even if no exception is thrown.&lt;br /&gt;
&lt;br /&gt;
 try {&lt;br /&gt;
        System.out.println(&amp;quot;Entering try statement&amp;quot;);&lt;br /&gt;
        out = new PrintWriter(new FileWriter(&amp;quot;OutFile.txt&amp;quot;));&lt;br /&gt;
      //Do Stuff….&lt;br /&gt;
 &lt;br /&gt;
    } catch (Exception e) {&lt;br /&gt;
        System.err.println(&amp;quot;Error occurred!”);&lt;br /&gt;
 &lt;br /&gt;
    } catch (IOException e) {&lt;br /&gt;
        System.err.println(&amp;quot;Input exception &amp;quot;);&lt;br /&gt;
 &lt;br /&gt;
    } finally {&lt;br /&gt;
 &lt;br /&gt;
        if (out != null) { &lt;br /&gt;
            out.close(); // RELEASE RESOURCES&lt;br /&gt;
        } &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
A Java example showing finally() being used to release system resources.&lt;br /&gt;
&lt;br /&gt;
===Centralised exception handling (Struts Example)===&lt;br /&gt;
&lt;br /&gt;
Building an infrastructure for consistent error reporting proves more difficult than error handling.&lt;br /&gt;
Struts provides the ActionMessages &amp;amp; ActionErrors classes for maintaining a stack of error messages to be reported, which can be used with JSP tags like &amp;lt;html: error&amp;gt; to display these error messages to the user. &lt;br /&gt;
&lt;br /&gt;
To report a different severity of a message in a different manner (like error, warning, or information) the following tasks are required: &lt;br /&gt;
&lt;br /&gt;
* Register, instantiate the errors under the appropriate severity&lt;br /&gt;
* Identify these messages and show them in a constant manner.&lt;br /&gt;
&lt;br /&gt;
Struts ActionErrors class makes error handling quite easy:&lt;br /&gt;
&lt;br /&gt;
 ActionErrors errors = new ActionErrors()&lt;br /&gt;
 errors.add(&amp;quot;fatal&amp;quot;, new ActionError(&amp;quot;....&amp;quot;)); &lt;br /&gt;
 errors.add(&amp;quot;error&amp;quot;, new ActionError(&amp;quot;....&amp;quot;)); &lt;br /&gt;
 errors.add(&amp;quot;warning&amp;quot;, new ActionError(&amp;quot;....&amp;quot;));&lt;br /&gt;
 errors.add(&amp;quot;information&amp;quot;, new ActionError(&amp;quot;....&amp;quot;)); &lt;br /&gt;
 saveErrors(request,errors); // Important to do this&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now we have added the errors we display them by using tags in the HTML page.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;logic:messagePresent property=&amp;quot;error&amp;quot;&amp;gt; &lt;br /&gt;
 &amp;lt;html:messages property=&amp;quot;error&amp;quot; id=&amp;quot;errMsg&amp;quot; &amp;gt;&lt;br /&gt;
     &amp;lt;bean:write name=&amp;quot;errMsg&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/html:messages&amp;gt;&lt;br /&gt;
 &amp;lt;/logic:messagePresent &amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:OWASP Code Review Project]]&lt;/div&gt;</summary>
		<author><name>Aldosolis</name></author>	</entry>

	</feed>