SlideShare una empresa de Scribd logo
1 de 44
Descargar para leer sin conexión
10 RULES
FOR
SAFER
CODEOlivier Dony
@odony
Yet another
security issue?!
RULE #1
EVAL is EVIL
Don’t trust strings supposed to contain expressions or code
(even your own!)
“eval” breaks the barrier between
code and data
Is this safe?
Maybe… it depends.
Is it a good idea?
No, because eval() is not necessary!
There are safer and smarter ways
to parse data in PYTHON
“42” int(x)
float(x)
Parse it
like this
“[1,2,3,true]”
json.loads(x)
‘{“widget”: “monetary”}’
“[1,2,3,True]” ast.literal_eval(x)
”{‘widget’: ‘monetary’}”
Given this
string
There are safer and smarter ways
to parse data in JAVASCRIPT
“42” parseInt(x)
parseFloat(x)
Given this
string Parse it
like this
“[1,2,3,true]”
JSON.parse(x)
‘{“widget”: “monetary”}’
If you must eval parameters
use a safe eval method
# YES
from odoo.tools import safe_eval
res = safe_eval(’foo’, {’foo’: 42});
# NO
from odoo.tools import safe_eval as eval
res = eval(’foo’, {’foo’: 42});
PYTHON
Alias built-in eval as ”unsafe_eval”
Show your meaning!
# YES
unsafe_eval = eval
res = unsafe_eval(trusted_code);
# NO!
res = eval(trusted_code);
Import as ”safe_eval”, not as ”eval”!
If you must eval parameters
use a safe eval method
JAVASCRIPT
// py.js is included by default
py.eval(’foo’, {’foo’: 42});
// require(”web.pyeval”) for
// domains/contexts/groupby evaluation
pyeval.eval(’domains’, my_domain);
Do not use the built-in JS eval!
50%of vulnerabilities found every year include
remote code execution injected via
unsafe eval
RULE #2
YOU SHALL NOT
PICKLE
Don’t use it. Ever. Use JSON.
“Warning: The pickle module is not intended 
to be secure against erroneous or maliciously 
constructed data. Never unpickle data 
received from an untrusted or 
unauthenticated source.
Python’s pickle serialization is:
+unsafe +not portable
+human-unreadable
pickle.dumps({“widget”:“monetary”}) == "(dp0nS'widget'np1nS'monetary'np2ns."
Actually a
stack-based
language!
Pickle is unsafe
Seriously.
>>> yummy = "cosnsystemn(S'cat /etc/shadow | head -n 5'ntR.'ntR."
>>> pickle.loads(yummy)
root:$6$m7ndoM3p$JRVXomVQFn/KH81DEePpX98usSoESUnml3e6Nlf.:14951:0:99999:7:::
daemon:x:14592:0:99999:7:::
(…)
>>>
Use JSON instead!
json.dumps({“widget”:“monetary”}) == '{"widget": "monetary"}'
+safe +portable
+human-readable
RULE #3
USE THE CURSOR
WISELY
Use the ORM API. And when you can’t, use query parameters.
SQL injection is a classical privilege
escalation vector
self.search(domain)The ORM is here to help you build safe
queries:
Psycopg can also help you do that , if you tell
it what is code and what is data:
query = ”””SELECT * FROM res_partner
WHERE id IN %s”””
self._cr.execute(query, (tuple(ids),))
SQL code
SQL data parameters
Learn the API to avoid hurting
yourself
and
other people!
This method is vulnerable
to SQL injection
def compute_balance_by_category(self, categ=’in’):
query = ”””SELECT sum(debit-credit)
FROM account_invoice_line l
JOIN account_invoice i ON (l.invoice_id = i.id)
WHERE i.categ = ’%s_invoice’
GROUP BY i.partner_id ”””
self._cr.execute(query % categ)
return self._cr.fetchall()
What if someone calls it with
categ = ”””in_invoice’; UPDATE res_users
SET password = ’god’ WHERE id=1; SELECT
sum(debit-credit) FROM account_invoice_line
WHERE name = ’”””
This method is still vulnerable
to SQL injection
def _compute_balance_by_category(self, categ=’in’):
query = ”””SELECT sum(debit-credit)
FROM account_invoice_line l
JOIN account_invoice i ON (l.invoice_id = i.id)
WHERE i.categ = ’%s_invoice’
GROUP BY i.partner_id ”””
self._cr.execute(query % categ)
return self._cr.fetchall()
Better, but it could still be called
indirectly!
Now
private!
This method is safe against
SQL injection
def _compute_balance_by_category(self, categ=’in’):
categ = ’%s_invoice’ % categ
query = ”””SELECT sum(debit-credit)
FROM account_invoice_line l
JOIN account_invoice i ON (l.invoice_id = i.id)
WHERE i.categ = %s
GROUP BY i.partner_id ”””
self._cr.execute(query, (categ,))
return self._cr.fetchall()
Separates code
and parameters!
RULE #4
Fight XSS
So many XSS vectors – gotta watch ’em all
Browsers blur the distinction between
code and data!
Most XSS errors are trivial:
QWeb templates
t-raw vs t-esc / t-field
Only use it to insert HTML code
that has been prepared and
escaped by the framework.
Never use it to insert text.
For everything else, use:
• t-esc: variables, URL parameters, …
• t-field: record data
Most XSS errors are trivial:
DOM manipulations (JQuery)
$elem.html(value) vs $elem.text(value)
Only use it to insert HTML code
that has been prepared and
escaped by the framework.
Never use it to insert text.
For everything else, use:
• t-esc: variables, URL parameters, …
• t-field: record data
    @http.route('/web/binary/upload', type='http', auth="user")
    @serialize_exception
    def upload(self, callback, ufile):
        out = """<script language="javascript" type="text/javascript">
                    var win = window.top.window;
                    win.jQuery(win).trigger(%s, %s);
                </script>"""
  # (...)      
        return out % (json.dumps(callback), json.dumps(args))
Some XSS are less obvious: callbacks
JSON escaping is not sufficient to prevent XSS,
because of the way browsers parse documents!
/web/binary/upload?callback=</script><script>alert(’This works!');//
Users can often upload arbitrary files : contact forms, email
gateway, etc.
Upon download, browsers will happily detect the file type and
execute anything that remotely looks like HTML, even if
you return it with an image mime-type !
Some XSS are less obvious: uploads
<svg xmlns="http://www.w3.org/2000/svg">
<script type="text/javascript">alert(’XSS!!’);</script>
</svg>A valid
SVG image
file!
RULE #5
GUARD PASSWORDS
& tokens fiercely
Secure all user and API tokens, and don’t leak them
Where should we store precious tokens for
external APIs?
On the res.users record of the user!
On the res.company record!
On the record representing the API
endpoint, like the acquirer record!
In the ir.config_parameter
table!
Wherever it makes the most sense, as long as it’s
not readable by anyone!
(field-level group, ACLs, ICP groups, etc.)
Avoid leaking
user cookies
and Session ID
Do not over-Sudo IT
RULE #6
Review 2x your sudo() usage, particularly controllers/public methods
Do you think this form is safe?
Not if it blindly takes the form POST
parameters and calls write() in
sudo mode!
RULE #7
CSRF tokens FOR
website forms
HTTP Posts require CSRF tokens since v9.0
Do you think this form is safe
from CSRF attacks?
As of Odoo 9, HTTP POST controllers
are CSRF-protected
Do not bypass it with GET controllers
that act like POST!
RULE #8
MASTER thE RULES
Odoo ACL and Rules are not trivial, be sure to understand them
Odoo ACLs are not always trivial
user

group B

group A
data
 C
 R
 U
 D
 C
 R
 U
 D
 C
 R
 U
 D
Group
Access Rights
(ir.model.access)
Group
Access Rule
(ir.rule)
Global
Access Rule
(ir.rule)
  123
Per-modelPer-record
ACCESS
DENIED
Odoo ACLs are not always trivial
user

group B

group A
data  C
 R
 U
 D
 C
 R
 U
 D
 C
 R
 U
 D
Group
Access Rule
(ir.rule)
Global
Access Rule
(ir.rule)
  123
Per-modelPer-record
ACCESS
GRANTED
Group
Access Rights
(ir.model.access)
Odoo ACLs are not always trivial
user

group B

group A
data
 C
 R
 U
 D
 C
 R
 U
 D
Group
Access Rule
(ir.rule)
Global
Access Rule
(ir.rule)
  123
Per-modelPer-record
ACCESS
GRANTED
Group
Access Rights
(ir.model.access)
Odoo ACLs are not always trivial
user

group B

group A
data
 C
 R
 U
 D
 C
 R
 U
 D
Group
Access Rule
(ir.rule)
Global
Access Rule
(ir.rule)
  123
Per-modelPer-record
 C
 R
 U
 D
ACCESS
DENIED
Group
Access Rights
(ir.model.access)
Odoo ACLs are not always trivial
user

group B

group A
data
 C
 R
 U
 D
Group
Access Rule
(ir.rule)
Global
Access Rule
(ir.rule)
  123
Per-modelPer-record
ACCESS
GRANTED
Group
Access Rights
(ir.model.access)
RULE #9
There are better and safer alternatives
Getattr is NOT
YOUR FRIEND
Do NOT do this:
def _get_it(self, field=’partner_id’):
return getattr(record, field)
Try this instead:
def _get_it(self, field=’partner_id’):
return record[field]
By passing arbitrary field values, an
attacker could gain access to dangerous
methods!
This will only work with valid field values
RULE #10
Do NOT open(), urlopen(), requests.post(), … an arbitrary URL/Path!
OPEN WITH CARE
Summary
1. Eval is evil
2. You shall not pickle
3. Use the cursor wisely
4.Fight XSS
5. Guard passwords & tokens fiercely
6.Do not over-sudo it
7.CSRF tokens for weBsite forms
8.master THE rules
9.Getattr is not your friend
10.OPEN WITH care
security@odoo.com

Más contenido relacionado

La actualidad más candente

SQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington BeachSQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington Beach
Jeff Prom
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionDefcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injection
Ahmed AbdelSatar
 
Rabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPressRabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPress
wpnepal
 
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksJSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
Mario Heiderich
 

La actualidad más candente (20)

SQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington BeachSQL Injections - 2016 - Huntington Beach
SQL Injections - 2016 - Huntington Beach
 
Time-Based Blind SQL Injection
Time-Based Blind SQL InjectionTime-Based Blind SQL Injection
Time-Based Blind SQL Injection
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
 
What is advanced SQL Injection? Infographic
What is advanced SQL Injection? InfographicWhat is advanced SQL Injection? Infographic
What is advanced SQL Injection? Infographic
 
New methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applicationsNew methods for exploiting ORM injections in Java applications
New methods for exploiting ORM injections in Java applications
 
03. sql and other injection module v17
03. sql and other injection module v1703. sql and other injection module v17
03. sql and other injection module v17
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacks
 
Defcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injectionDefcon 17-joseph mccray-adv-sql_injection
Defcon 17-joseph mccray-adv-sql_injection
 
Rabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPressRabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPress
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksJSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
 
Sql Injection and XSS
Sql Injection and XSSSql Injection and XSS
Sql Injection and XSS
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
Sql Injection V.2
Sql Injection V.2Sql Injection V.2
Sql Injection V.2
 
Php Security
Php SecurityPhp Security
Php Security
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Practical Approach towards SQLi ppt
Practical Approach towards SQLi pptPractical Approach towards SQLi ppt
Practical Approach towards SQLi ppt
 
Asp
AspAsp
Asp
 

Similar a 10 Rules for Safer Code

Slides
SlidesSlides
Slides
vti
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
Aleksandr Yampolskiy
 
Application Security
Application SecurityApplication Security
Application Security
florinc
 

Similar a 10 Rules for Safer Code (20)

Web Security 101
Web Security 101Web Security 101
Web Security 101
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
Slides
SlidesSlides
Slides
 
Sql injection
Sql injectionSql injection
Sql injection
 
Rails and security
Rails and securityRails and security
Rails and security
 
DevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first SecurityDevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first Security
 
PHP Secure Programming
PHP Secure ProgrammingPHP Secure Programming
PHP Secure Programming
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
 
PHPUG Presentation
PHPUG PresentationPHPUG Presentation
PHPUG Presentation
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-on
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Sq linjection
Sq linjectionSq linjection
Sq linjection
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the process
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019
 
07 application security fundamentals - part 2 - security mechanisms - data ...
07   application security fundamentals - part 2 - security mechanisms - data ...07   application security fundamentals - part 2 - security mechanisms - data ...
07 application security fundamentals - part 2 - security mechanisms - data ...
 
Becoming a SOC2 Ruby Shop - Montreal.rb November, 5, 2022 Ruby Meetup
Becoming a SOC2 Ruby Shop - Montreal.rb November, 5, 2022 Ruby MeetupBecoming a SOC2 Ruby Shop - Montreal.rb November, 5, 2022 Ruby Meetup
Becoming a SOC2 Ruby Shop - Montreal.rb November, 5, 2022 Ruby Meetup
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Application Security
Application SecurityApplication Security
Application Security
 

Más de Quang Ngoc

Hướng dẫn sử dụng hệ điều hành Ubuntu
Hướng dẫn sử dụng hệ điều hành UbuntuHướng dẫn sử dụng hệ điều hành Ubuntu
Hướng dẫn sử dụng hệ điều hành Ubuntu
Quang Ngoc
 
Tính giá thành sản phẩm
Tính giá thành sản phẩmTính giá thành sản phẩm
Tính giá thành sản phẩm
Quang Ngoc
 
Manage IT as a Business
Manage IT as a BusinessManage IT as a Business
Manage IT as a Business
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sống
Hạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sốngHạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sống
Hạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sống
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gian
Hạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gianHạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gian
Hạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gian
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 9 - Vượt qua thử thách
Hạt Giống Tâm Hồn - Tập 9 - Vượt qua thử tháchHạt Giống Tâm Hồn - Tập 9 - Vượt qua thử thách
Hạt Giống Tâm Hồn - Tập 9 - Vượt qua thử thách
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sốngHạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sống
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sốngHạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sống
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sốngHạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sống
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sốngHạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sống
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình Dị
Hạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình DịHạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình Dị
Hạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình Dị
Quang Ngoc
 
Hạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dị
Hạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dịHạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dị
Hạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dị
Quang Ngoc
 

Más de Quang Ngoc (20)

Bản Đồ Thành Công
Bản Đồ Thành CôngBản Đồ Thành Công
Bản Đồ Thành Công
 
Odoo Implementation Methodology
Odoo Implementation MethodologyOdoo Implementation Methodology
Odoo Implementation Methodology
 
The Agile BA (Business Analyst)
The Agile BA (Business Analyst)The Agile BA (Business Analyst)
The Agile BA (Business Analyst)
 
Hướng dẫn sử dụng hệ điều hành Ubuntu
Hướng dẫn sử dụng hệ điều hành UbuntuHướng dẫn sử dụng hệ điều hành Ubuntu
Hướng dẫn sử dụng hệ điều hành Ubuntu
 
Hướng dẫn sử dụng Outlook 2010
Hướng dẫn sử dụng Outlook 2010Hướng dẫn sử dụng Outlook 2010
Hướng dẫn sử dụng Outlook 2010
 
Hướng dẫn sử dụng Power Point 2010
Hướng dẫn sử dụng Power Point 2010Hướng dẫn sử dụng Power Point 2010
Hướng dẫn sử dụng Power Point 2010
 
Hướng dẫn sử dụng Excel 2010
Hướng dẫn sử dụng  Excel 2010Hướng dẫn sử dụng  Excel 2010
Hướng dẫn sử dụng Excel 2010
 
Hướng dẫn sử dụng Word 2010
Hướng dẫn sử dụng Word 2010Hướng dẫn sử dụng Word 2010
Hướng dẫn sử dụng Word 2010
 
Tính giá thành sản phẩm
Tính giá thành sản phẩmTính giá thành sản phẩm
Tính giá thành sản phẩm
 
Manage IT as a Business
Manage IT as a BusinessManage IT as a Business
Manage IT as a Business
 
Tóm tắt lệnh Ubuntu
Tóm tắt lệnh UbuntuTóm tắt lệnh Ubuntu
Tóm tắt lệnh Ubuntu
 
Hạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sống
Hạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sốngHạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sống
Hạt Giống Tâm Hồn - Tập 11 - Những trải nghiệm cuộc sống
 
Hạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gian
Hạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gianHạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gian
Hạt Giống Tâm Hồn - Tập 10 - Theo dòng thời gian
 
Hạt Giống Tâm Hồn - Tập 9 - Vượt qua thử thách
Hạt Giống Tâm Hồn - Tập 9 - Vượt qua thử tháchHạt Giống Tâm Hồn - Tập 9 - Vượt qua thử thách
Hạt Giống Tâm Hồn - Tập 9 - Vượt qua thử thách
 
Hạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sốngHạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 8 - Những câu chuyện cuộc sống
 
Hạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sốngHạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sống
Hạt Giống Tâm Hồn - Tập 7 - Những câu chuyện cuộc sống
 
Hạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sốngHạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 6 - Ý nghĩa cuộc sống
 
Hạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sốngHạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sống
Hạt Giống Tâm Hồn - Tập 5 - Ý nghĩa cuộc sống
 
Hạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình Dị
Hạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình DịHạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình Dị
Hạt Giống Tâm Hồn - Tập 4 - Từ Những Điều Bình Dị
 
Hạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dị
Hạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dịHạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dị
Hạt Giống Tâm Hồn - Tập 3 - Từ những điều bình dị
 

Último

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 

Último (20)

%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

10 Rules for Safer Code

  • 3. RULE #1 EVAL is EVIL Don’t trust strings supposed to contain expressions or code (even your own!)
  • 4. “eval” breaks the barrier between code and data Is this safe? Maybe… it depends. Is it a good idea? No, because eval() is not necessary!
  • 5. There are safer and smarter ways to parse data in PYTHON “42” int(x) float(x) Parse it like this “[1,2,3,true]” json.loads(x) ‘{“widget”: “monetary”}’ “[1,2,3,True]” ast.literal_eval(x) ”{‘widget’: ‘monetary’}” Given this string
  • 6. There are safer and smarter ways to parse data in JAVASCRIPT “42” parseInt(x) parseFloat(x) Given this string Parse it like this “[1,2,3,true]” JSON.parse(x) ‘{“widget”: “monetary”}’
  • 7. If you must eval parameters use a safe eval method # YES from odoo.tools import safe_eval res = safe_eval(’foo’, {’foo’: 42}); # NO from odoo.tools import safe_eval as eval res = eval(’foo’, {’foo’: 42}); PYTHON Alias built-in eval as ”unsafe_eval” Show your meaning! # YES unsafe_eval = eval res = unsafe_eval(trusted_code); # NO! res = eval(trusted_code); Import as ”safe_eval”, not as ”eval”!
  • 8. If you must eval parameters use a safe eval method JAVASCRIPT // py.js is included by default py.eval(’foo’, {’foo’: 42}); // require(”web.pyeval”) for // domains/contexts/groupby evaluation pyeval.eval(’domains’, my_domain); Do not use the built-in JS eval!
  • 9. 50%of vulnerabilities found every year include remote code execution injected via unsafe eval
  • 10. RULE #2 YOU SHALL NOT PICKLE Don’t use it. Ever. Use JSON.
  • 12. Python’s pickle serialization is: +unsafe +not portable +human-unreadable pickle.dumps({“widget”:“monetary”}) == "(dp0nS'widget'np1nS'monetary'np2ns." Actually a stack-based language!
  • 13. Pickle is unsafe Seriously. >>> yummy = "cosnsystemn(S'cat /etc/shadow | head -n 5'ntR.'ntR." >>> pickle.loads(yummy) root:$6$m7ndoM3p$JRVXomVQFn/KH81DEePpX98usSoESUnml3e6Nlf.:14951:0:99999:7::: daemon:x:14592:0:99999:7::: (…) >>>
  • 14. Use JSON instead! json.dumps({“widget”:“monetary”}) == '{"widget": "monetary"}' +safe +portable +human-readable
  • 15. RULE #3 USE THE CURSOR WISELY Use the ORM API. And when you can’t, use query parameters.
  • 16. SQL injection is a classical privilege escalation vector self.search(domain)The ORM is here to help you build safe queries: Psycopg can also help you do that , if you tell it what is code and what is data: query = ”””SELECT * FROM res_partner WHERE id IN %s””” self._cr.execute(query, (tuple(ids),)) SQL code SQL data parameters
  • 17. Learn the API to avoid hurting yourself and other people!
  • 18. This method is vulnerable to SQL injection def compute_balance_by_category(self, categ=’in’): query = ”””SELECT sum(debit-credit) FROM account_invoice_line l JOIN account_invoice i ON (l.invoice_id = i.id) WHERE i.categ = ’%s_invoice’ GROUP BY i.partner_id ””” self._cr.execute(query % categ) return self._cr.fetchall() What if someone calls it with categ = ”””in_invoice’; UPDATE res_users SET password = ’god’ WHERE id=1; SELECT sum(debit-credit) FROM account_invoice_line WHERE name = ’”””
  • 19. This method is still vulnerable to SQL injection def _compute_balance_by_category(self, categ=’in’): query = ”””SELECT sum(debit-credit) FROM account_invoice_line l JOIN account_invoice i ON (l.invoice_id = i.id) WHERE i.categ = ’%s_invoice’ GROUP BY i.partner_id ””” self._cr.execute(query % categ) return self._cr.fetchall() Better, but it could still be called indirectly! Now private!
  • 20. This method is safe against SQL injection def _compute_balance_by_category(self, categ=’in’): categ = ’%s_invoice’ % categ query = ”””SELECT sum(debit-credit) FROM account_invoice_line l JOIN account_invoice i ON (l.invoice_id = i.id) WHERE i.categ = %s GROUP BY i.partner_id ””” self._cr.execute(query, (categ,)) return self._cr.fetchall() Separates code and parameters!
  • 21. RULE #4 Fight XSS So many XSS vectors – gotta watch ’em all
  • 22. Browsers blur the distinction between code and data!
  • 23. Most XSS errors are trivial: QWeb templates t-raw vs t-esc / t-field Only use it to insert HTML code that has been prepared and escaped by the framework. Never use it to insert text. For everything else, use: • t-esc: variables, URL parameters, … • t-field: record data
  • 24. Most XSS errors are trivial: DOM manipulations (JQuery) $elem.html(value) vs $elem.text(value) Only use it to insert HTML code that has been prepared and escaped by the framework. Never use it to insert text. For everything else, use: • t-esc: variables, URL parameters, … • t-field: record data
  • 25.     @http.route('/web/binary/upload', type='http', auth="user")     @serialize_exception     def upload(self, callback, ufile):         out = """<script language="javascript" type="text/javascript">                     var win = window.top.window;                     win.jQuery(win).trigger(%s, %s);                 </script>"""   # (...)               return out % (json.dumps(callback), json.dumps(args)) Some XSS are less obvious: callbacks JSON escaping is not sufficient to prevent XSS, because of the way browsers parse documents! /web/binary/upload?callback=</script><script>alert(’This works!');//
  • 26. Users can often upload arbitrary files : contact forms, email gateway, etc. Upon download, browsers will happily detect the file type and execute anything that remotely looks like HTML, even if you return it with an image mime-type ! Some XSS are less obvious: uploads <svg xmlns="http://www.w3.org/2000/svg"> <script type="text/javascript">alert(’XSS!!’);</script> </svg>A valid SVG image file!
  • 27. RULE #5 GUARD PASSWORDS & tokens fiercely Secure all user and API tokens, and don’t leak them
  • 28. Where should we store precious tokens for external APIs? On the res.users record of the user! On the res.company record! On the record representing the API endpoint, like the acquirer record! In the ir.config_parameter table! Wherever it makes the most sense, as long as it’s not readable by anyone! (field-level group, ACLs, ICP groups, etc.)
  • 30. Do not over-Sudo IT RULE #6 Review 2x your sudo() usage, particularly controllers/public methods
  • 31. Do you think this form is safe? Not if it blindly takes the form POST parameters and calls write() in sudo mode!
  • 32. RULE #7 CSRF tokens FOR website forms HTTP Posts require CSRF tokens since v9.0
  • 33. Do you think this form is safe from CSRF attacks? As of Odoo 9, HTTP POST controllers are CSRF-protected Do not bypass it with GET controllers that act like POST!
  • 34. RULE #8 MASTER thE RULES Odoo ACL and Rules are not trivial, be sure to understand them
  • 35. Odoo ACLs are not always trivial user  group B  group A data  C  R  U  D  C  R  U  D  C  R  U  D Group Access Rights (ir.model.access) Group Access Rule (ir.rule) Global Access Rule (ir.rule)   123 Per-modelPer-record ACCESS DENIED
  • 36. Odoo ACLs are not always trivial user  group B  group A data  C  R  U  D  C  R  U  D  C  R  U  D Group Access Rule (ir.rule) Global Access Rule (ir.rule)   123 Per-modelPer-record ACCESS GRANTED Group Access Rights (ir.model.access)
  • 37. Odoo ACLs are not always trivial user  group B  group A data  C  R  U  D  C  R  U  D Group Access Rule (ir.rule) Global Access Rule (ir.rule)   123 Per-modelPer-record ACCESS GRANTED Group Access Rights (ir.model.access)
  • 38. Odoo ACLs are not always trivial user  group B  group A data  C  R  U  D  C  R  U  D Group Access Rule (ir.rule) Global Access Rule (ir.rule)   123 Per-modelPer-record  C  R  U  D ACCESS DENIED Group Access Rights (ir.model.access)
  • 39. Odoo ACLs are not always trivial user  group B  group A data  C  R  U  D Group Access Rule (ir.rule) Global Access Rule (ir.rule)   123 Per-modelPer-record ACCESS GRANTED Group Access Rights (ir.model.access)
  • 40. RULE #9 There are better and safer alternatives Getattr is NOT YOUR FRIEND
  • 41. Do NOT do this: def _get_it(self, field=’partner_id’): return getattr(record, field) Try this instead: def _get_it(self, field=’partner_id’): return record[field] By passing arbitrary field values, an attacker could gain access to dangerous methods! This will only work with valid field values
  • 42. RULE #10 Do NOT open(), urlopen(), requests.post(), … an arbitrary URL/Path! OPEN WITH CARE
  • 43. Summary 1. Eval is evil 2. You shall not pickle 3. Use the cursor wisely 4.Fight XSS 5. Guard passwords & tokens fiercely 6.Do not over-sudo it 7.CSRF tokens for weBsite forms 8.master THE rules 9.Getattr is not your friend 10.OPEN WITH care