SlideShare a Scribd company logo
1 of 44
Download to read offline
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”!
Now
verified
by runbot!
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

More Related Content

What's hot

Securing a Web App with Passwordless Web Authentication
Securing a Web App with Passwordless Web AuthenticationSecuring a Web App with Passwordless Web Authentication
Securing a Web App with Passwordless Web AuthenticationFIDO Alliance
 
OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020
OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020
OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020OpenID Foundation Japan
 
Microsoft's Implementation Roadmap for FIDO2
Microsoft's Implementation Roadmap for FIDO2Microsoft's Implementation Roadmap for FIDO2
Microsoft's Implementation Roadmap for FIDO2FIDO Alliance
 
FIDO2 Specifications Overview
FIDO2 Specifications OverviewFIDO2 Specifications Overview
FIDO2 Specifications OverviewFIDO Alliance
 
How to Develop your own in App-Purchase Service in Odoo
How to Develop your own in App-Purchase Service in OdooHow to Develop your own in App-Purchase Service in Odoo
How to Develop your own in App-Purchase Service in OdooOdoo
 
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...Celine George
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency InjectionNir Kaufman
 
OAuth認証再考からのOpenID Connect #devlove
OAuth認証再考からのOpenID Connect #devloveOAuth認証再考からのOpenID Connect #devlove
OAuth認証再考からのOpenID Connect #devloveNov Matake
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injectionEyal Vardi
 
Using runbot to test all your developments automatically
Using runbot to test all your developments automaticallyUsing runbot to test all your developments automatically
Using runbot to test all your developments automaticallyOdoo
 
FIDO Authentication Technical Overview
FIDO Authentication Technical OverviewFIDO Authentication Technical Overview
FIDO Authentication Technical OverviewFIDO Alliance
 
Introduction to OpenID Connect
Introduction to OpenID Connect Introduction to OpenID Connect
Introduction to OpenID Connect Nat Sakimura
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOdoo
 
FIDO and the Future of User Authentication
FIDO and the Future of User AuthenticationFIDO and the Future of User Authentication
FIDO and the Future of User AuthenticationFIDO Alliance
 
Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)Abhishek Koserwal
 
CAS, OpenID, Shibboleth, SAML : concepts, différences et exemples
CAS, OpenID, Shibboleth, SAML : concepts, différences et exemplesCAS, OpenID, Shibboleth, SAML : concepts, différences et exemples
CAS, OpenID, Shibboleth, SAML : concepts, différences et exemplesClément OUDOT
 
SIngle Sign On with Keycloak
SIngle Sign On with KeycloakSIngle Sign On with Keycloak
SIngle Sign On with KeycloakJulien Pivotto
 

What's hot (20)

Webauthn Tutorial
Webauthn TutorialWebauthn Tutorial
Webauthn Tutorial
 
Securing a Web App with Passwordless Web Authentication
Securing a Web App with Passwordless Web AuthenticationSecuring a Web App with Passwordless Web Authentication
Securing a Web App with Passwordless Web Authentication
 
OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020
OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020
OpenIDファウンデーション・ジャパンKYC WGの活動報告 - OpenID Summit 2020
 
JSON Web Token
JSON Web TokenJSON Web Token
JSON Web Token
 
Microsoft's Implementation Roadmap for FIDO2
Microsoft's Implementation Roadmap for FIDO2Microsoft's Implementation Roadmap for FIDO2
Microsoft's Implementation Roadmap for FIDO2
 
FIDO2 Specifications Overview
FIDO2 Specifications OverviewFIDO2 Specifications Overview
FIDO2 Specifications Overview
 
How to Develop your own in App-Purchase Service in Odoo
How to Develop your own in App-Purchase Service in OdooHow to Develop your own in App-Purchase Service in Odoo
How to Develop your own in App-Purchase Service in Odoo
 
OpenID for SSI
OpenID for SSIOpenID for SSI
OpenID for SSI
 
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
What are Wizards - Defining and Launching in Odoo 15Wizards - Defining and La...
 
Angular Dependency Injection
Angular Dependency InjectionAngular Dependency Injection
Angular Dependency Injection
 
OAuth認証再考からのOpenID Connect #devlove
OAuth認証再考からのOpenID Connect #devloveOAuth認証再考からのOpenID Connect #devlove
OAuth認証再考からのOpenID Connect #devlove
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Using runbot to test all your developments automatically
Using runbot to test all your developments automaticallyUsing runbot to test all your developments automatically
Using runbot to test all your developments automatically
 
FIDO Authentication Technical Overview
FIDO Authentication Technical OverviewFIDO Authentication Technical Overview
FIDO Authentication Technical Overview
 
Introduction to OpenID Connect
Introduction to OpenID Connect Introduction to OpenID Connect
Introduction to OpenID Connect
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
FIDO and the Future of User Authentication
FIDO and the Future of User AuthenticationFIDO and the Future of User Authentication
FIDO and the Future of User Authentication
 
Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)Draft: building secure applications with keycloak (oidc/jwt)
Draft: building secure applications with keycloak (oidc/jwt)
 
CAS, OpenID, Shibboleth, SAML : concepts, différences et exemples
CAS, OpenID, Shibboleth, SAML : concepts, différences et exemplesCAS, OpenID, Shibboleth, SAML : concepts, différences et exemples
CAS, OpenID, Shibboleth, SAML : concepts, différences et exemples
 
SIngle Sign On with Keycloak
SIngle Sign On with KeycloakSIngle Sign On with Keycloak
SIngle Sign On with Keycloak
 

Similar to 10 Rules for Safer Code [Odoo Experience 2016]

Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code HardeningOdoo
 
Slides
SlidesSlides
Slidesvti
 
DevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first SecurityDevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first SecurityCoverity
 
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 programsAleksandr Yampolskiy
 
OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019OWASP Top 10 - DrupalCon Amsterdam 2019
OWASP Top 10 - DrupalCon Amsterdam 2019Ayesh Karunaratne
 
Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-onAndrea Valenza
 
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 MeetupAndy Maleh
 
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 processguest3379bd
 
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 ...appsec
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And AnishOSSCube
 
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 2019Balázs Tatár
 

Similar to 10 Rules for Safer Code [Odoo Experience 2016] (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
 
Rails and security
Rails and securityRails and security
Rails and security
 
Sql injection
Sql injectionSql injection
Sql injection
 
Asp
AspAsp
Asp
 
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
 
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
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
Sq linjection
Sq linjectionSq linjection
Sq linjection
 
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
 
PHPUG Presentation
PHPUG PresentationPHPUG Presentation
PHPUG Presentation
 
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
 
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 ...
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
 
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
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 

10 Rules for Safer Code [Odoo Experience 2016]

  • 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”! Now verified by runbot!
  • 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