3

By the moment, I know four kinds of doing transactions with hibernate:

  1. Using objects
  2. Using HQL
  3. Using DB-specific SQL
  4. Using criteria (QBE)

Well, regarding how strong are they against injections, I think these are (correct me if I'm wrong):

  1. Secure, because the internal SQL call is parameterized.
  2. Secure if the query is parameterized, insecure otherwise.
  3. Same as #2 but not as portable.
  4. Insecure?

My question is about #4, Query by Example, because i've found it is also vulnerable. Example:

    Account a = new Account(); //POJO class       
    a.setId("1' OR '1'='1");

    //s is a org.hibernate.Session instance
    Criteria crit = s.createCriteria(Account.class);
    crit.add(Example.create(a));
    List results = crit.list();  //table dump!

That snippet selects the whole accounts table. Is there any way to prevent injection? How?

NOTE: I'm using Hibernate 3.6.5 final, the testing database is HSQLDB.

UPDATE: Seems like a bug to me too, and indeed may be not related to the injected SQL. Tried setting the id with a nonexistent value and also returns all the rows. Tried the injection with '5'='5' instead of '1'='1' and the 5 is not propagated to the SQL call. It keeps using (1=1) as where clause.

UPDATE 2: Solved. See the answer below.

Mister Smith
  • 27,417
  • 21
  • 110
  • 193
  • 1
    That looks like a bug to me. You should probably post that to hibernate. In general HQL/SQL parameterization is the way to go (IMHO). – Adam Gent Jul 19 '11 at 11:55
  • @Adam Gent I know it is possible to do the same with HQL, but QBE is less verbose, and you don't have to check the nullity of the fields you're not interested in. – Mister Smith Jul 19 '11 at 12:07
  • I see your point but I still prefer HQL as I am used to SQL and so are the others I work with (hence the IMHO). – Adam Gent Jul 19 '11 at 19:00

2 Answers2

1

Hibernate QBE ignores the id (mapped to PK) fields. Seems that this is done because an id filter would return only a row, and this can be achieved with a get() or a load(). I wonder what if I want to use a like condition on the id???

Related posts on hibernate official forum:

https://forum.hibernate.org/viewtopic.php?t=927063

https://forum.hibernate.org/viewtopic.php?t=938036

Mister Smith
  • 27,417
  • 21
  • 110
  • 193
0

You can sanitize your input E.g. in your code you should make sure you set a Long value to the ID field.

bpgergo
  • 15,669
  • 5
  • 44
  • 68