4

I want to secure my application from SQL Injection attacks.

First question: What is better way to do it?

The first method: I convert every request to json here:

public JsonObject requestToJson(HttpServletRequest request) throws UnsupportedEncodingException{

        request.setCharacterEncoding("UTF-8");

        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) { /*report an error*/ }

        return new JsonParser().parse(jb.toString()).getAsJsonObject();
    }

If it is best way, to prevent it here, then second question: how to do it here?

The second method: It can be done by Hibernate level. Second question: how to do it?

annoirq
  • 825
  • 5
  • 18
  • 30
  • How would converting the request to JSON prevent SQL Injection? Why do you think HIbernate is vulnerable to SQL Injection? – Elliott Frisch Nov 18 '15 at 05:23
  • no, converting to json is not preventing injection of course. I mean, as I'm converting every request to json, I can put this validation in this function. – annoirq Nov 18 '15 at 05:25
  • I'm new in hibernate. I'm using several ways to generate SQL: JPARepository, CriteriaBuilder and HQL. My question is: "it's already preventing from SQL Injection"? – annoirq Nov 18 '15 at 05:27
  • See [this question](http://stackoverflow.com/questions/9596424/how-much-safe-from-sql-injection-if-using-hibernate) and [this question](http://stackoverflow.com/questions/3441193/are-sql-injection-attacks-possible-in-jpa). – Elliott Frisch Nov 18 '15 at 05:32
  • Ok, about HQL, JpaRepository I understood. But what about CriteriaBuilder. Is it safe? – annoirq Nov 18 '15 at 05:35
  • What *about* [CriteriaBuilder](http://stackoverflow.com/questions/15065906/does-hibernate-criteria-api-completely-protect-from-sql-injection)? – Elliott Frisch Nov 18 '15 at 05:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/95402/discussion-between-annoirq-and-elliott-frisch). – annoirq Nov 18 '15 at 05:38

1 Answers1

3

Thanks this user: Elliott Frisch. He answered in comment.

JPARepository like this already prevented from SQL Injection:

public interface UserRepository extends JpaRepository<User, Integer> {
    User findByPhoneNumber(String phoneNumber);
}

Just need to prevent if you using HQL:

String query1 = "select * from MyBean where id = "+ id;
String query2 = "select * from MyBean where id = :id";

Second one, will be secured.

Thanks, everyone.

annoirq
  • 825
  • 5
  • 18
  • 30