SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Top 5 Magento Secure
Coding Best Practices
Alex Zarichnyi, Magento ECG
Security in Magento
• Dedicated team
Security in Magento
• Dedicated team
• External audits
Security in Magento
• Dedicated team
• External audits
• Awareness about
OWASP Top 10
Security in Magento
http://magento.com/security
• Bug bounty program
• Dedicated team
• External audits
• Awareness about
OWASP Top 10
up to
$10.000
Security in Magento
• Built-in security
mechanisms
• Bug bounty program
• Dedicated team
• External audits
• Awareness about
OWASP Top 10
Top 5 Secure Coding
Practices
#1. Validate input as strictly as
possible
Input Validation
Do not trust:
• all input parameters
• cookie names and values
• HTTP header content
• Some $_SERVER parameters (e.g.
HTTP_X_FORWARDED, HTTP_X_FORWARD
ED_FOR)
Zend_Validate
• Alpha-numeric values
• Credit Carts
• Host names
• IPs
• Custom validators
(Mage_Core_Model_Url_Validator)
• and many more
$attributeCode = $this->getRequest()->getParam('attribute_code');
$validator = new Zend_Validate_Regex(array(
'pattern' => '/^[a-z][a-z_0-9]{1,254}$/'));
if (!$validator->isValid($attributeCode)) {
//stop execution and add a session error
}
Validate attribute code
1.
2. $attributeCode = $this->getRequest()->getParam('attribute_code');
$validatorChain = new Zend_Validate();
$validatorChain->addValidator(new Zend_Validate_StringLength(
array('min' => 1, 'max' => 254)))
->addValidator(new Zend_Validate_Alnum());
if (!$validatorChain->isValid($attributeCode)) {
//stop execution and add a session error
}
$email = $this->getRequest()->getParam('email');
if (Zend_Validate::is($email, 'EmailAddress')) {
//continue execution
} else {
$this->_getSession()->addError($this->__('Invalid email address.'));
//redirect back
}
Validate email
#2. Use parameterized queries
(?, :param1)
Working with Data in Magento
$id = $this->getRequest()->getParam(‘id’);
$model->load($id);
$q = $this->getRequest()->getParam(‘q’);
$collection->addFieldToFilter(‘name’, ‘%’ . $q . ‘%’));
secure
secure
$select->where("region.code = '{$requestParam}'");
$res = $this->_getReadAdapter()->fetchRow($select);
$select->where('region.code = ?', $requestParam);
$res = $this->_getReadAdapter()->fetchRow($select);
Bad code
Good code
1.
$select->where('region.code= :regionCode');
$bind = array('regionCode' => $requestParam);
$res = $this->getReadAdapter()->fetchRow($select, $bind));
2.
name' ); UPDATE admin_user
SET password =
'34e159c98148ff85036e23986
6a8e053:v6' WHERE
username = 'admin';
$select->joinInner(
array('i' => $this->getTable('enterprise_giftregistry/item')),
'e.entity_id = i.entity_id AND i.item_id = ' . $requestParam,
array()
);
$select->joinInner(
array('i' => $this->getTable('enterprise_giftregistry/item')),
'e.entity_id = i.entity_id AND i.item_id = ' . (int) $requestParam,
array()
);
Bad code
Good code
1; DROP TABLE customer_entity;
$result = "IF (COUNT(*) {$operator} {$requestParam}, 1, 0)";
$select->from(
array('order' => $this->getResource()->getTable('sales/order')),
array(new Zend_Db_Expr($result)
);
$value = $select->getAdapter()->quote($requestParam);
$result = "IF (COUNT(*) {$operator} {$value}, 1, 0)";
$select->from(
array('order' => $this->getResource()->getTable('sales/order')),
array(new Zend_Db_Expr($result))
);
Bad code
Good code
#3. Escape user input
SQL Query Parameters Escaping
$db->quoteInto("WHERE date <
?", "2005-01-02")
WHERE date < '2005-01-02’
Zend_Db_Adapter_Abstract
quote($value, $type = null)
quoteInto($text, $value, $type = null, $count = null)
quoteIdentifier($ident, $auto=false)
quoteColumnAs($ident, $alias, $auto=false)
quoteTableAs($ident, $alias = null, $auto = false)
$db->quote("O'Reilly"); O'Reilly
$db->quote("' or '1'='1' -- “, Zend_Db::FLOAT_TYPE); 0.000000
Mage::helper(‘core’)->escapeHtml($data, $allowedTags = null)
Mage_Core_Block_Abstract::escapeHtml($data, $allowedTags = null)
String Replacement
& &amp;
" &quot;
' &#039;
< &lt;
> &gt;
HTML Special Characters Escaping
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
Never insert untrusted data except in allowed locations
Use both on frontend & backend
#4. Use CSRF tokens (form
keys)
<form name="myForm" id="myForm" method="post" action="...">
<?php echo $this->getBlockHtml('formkey')?>
<!-- ... -->
</form>
public function saveAction()
{
if (!$this->_validateFormKey()) {
//stop and throw an exception or redirect back
}
}
<input type="hidden"
value="Bcp957eKYP48XL0Y"
name="form_key">
in template
in controller
#5. Use security headers
HTTP security headers
https://www.owasp.org/index.php/List_of_useful_HTTP_headers
Header Description Example
X-XSS-Protection Protects from XSS X-XSS-Protection: 1;
mode=block
X-Frame-Options Protects from Clickjacking X-Frame-Options: deny
X-Content-Type-
Options
Prevents Internet Explorer and
Google Chrome from MIME-
sniffing a response away from the
declared content-type
X-Content-Type-Options:
nosniff
Content-Security-
Policy,
X-WebKit-CSP
Lets you specify a policy for
where content can be loaded
Lets you put restrictions on script
execution
X-WebKit-CSP: default-src
'self'
/**
* Add security headers to the response
*
* @listen controller_action_predispatch
* @param Varien_Event_Observer $observer
*/
public function processPreDispatch(Varien_Event_Observer $observer)
{
$response = $observer->getControllerAction()->getResponse();
$response->setHeader(‘X-XSS-Protection’, ‘1; mode=block’)
->setHeader(‘X-Frame-Options’, ‘DENY’)
->setHeader(‘X-Content-Type-Options’, ‘nosniff’);
}
Additional Resources
• https://www.owasp.org – The Open Web Application Security
Project
• http://websec.io/ – Securing PHP-based applications
• http://cwe.mitre.org/ – Common Weakness Enumeration
• https://www.youtube.com/watch?v=aGnV7P8NXtA –Magento
Security Presentation, Imagine 2012
• http://www.developers-paradise.com/wp-
content/uploads/eltrino-paradise-2013-roman_stepanov.pdf -
Magento Security and Vulnerabilities Presentation, Magento
Developer Paradise 2013
zlik
ozarichnyi@ebay.com
linkedin.com/in/ozarichnyi
Дякую!

Weitere ähnliche Inhalte

Was ist angesagt?

Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
Technopark
 

Was ist angesagt? (20)

Disregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_FormDisregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_Form
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
Os Nixon
Os NixonOs Nixon
Os Nixon
 
Developing for Business
Developing for BusinessDeveloping for Business
Developing for Business
 
TDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for BusinessTDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for Business
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examples
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Apex 5 plugins for everyone version 2018
Apex 5 plugins for everyone   version 2018Apex 5 plugins for everyone   version 2018
Apex 5 plugins for everyone version 2018
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
 
Laravel admin20170819
Laravel admin20170819Laravel admin20170819
Laravel admin20170819
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
Backbone - TDC 2011 Floripa
Backbone - TDC 2011 FloripaBackbone - TDC 2011 Floripa
Backbone - TDC 2011 Floripa
 
Web весна 2013 лекция 6
Web весна 2013 лекция 6Web весна 2013 лекция 6
Web весна 2013 лекция 6
 
Deploying Straight to Production
Deploying Straight to ProductionDeploying Straight to Production
Deploying Straight to Production
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
 

Andere mochten auch

Project Management Plan - Odogu & Siersma
Project Management Plan - Odogu & SiersmaProject Management Plan - Odogu & Siersma
Project Management Plan - Odogu & Siersma
TEGA ODOGU
 
Alpha Case Study - Project Management Plan Sample
Alpha Case Study - Project Management Plan SampleAlpha Case Study - Project Management Plan Sample
Alpha Case Study - Project Management Plan Sample
Agatha Maia Duarte de Assis
 
Project Management Plan - Cafe Au Lait.PDF
Project Management Plan - Cafe Au Lait.PDFProject Management Plan - Cafe Au Lait.PDF
Project Management Plan - Cafe Au Lait.PDF
Geoff Penhorwood
 
Restaurant project
Restaurant projectRestaurant project
Restaurant project
Arun Kabra
 
Business project plan
Business project planBusiness project plan
Business project plan
Ahmed Shafie
 
PROJECT ON NEW BUSINESS PLAN
PROJECT ON NEW BUSINESS PLANPROJECT ON NEW BUSINESS PLAN
PROJECT ON NEW BUSINESS PLAN
VisualBee.com
 
Sample project plan
Sample project planSample project plan
Sample project plan
mamoonnift
 

Andere mochten auch (20)

The Project Management Plan in 20 steps
The Project Management Plan in 20 stepsThe Project Management Plan in 20 steps
The Project Management Plan in 20 steps
 
PMI Project Management Principles
PMI Project Management PrinciplesPMI Project Management Principles
PMI Project Management Principles
 
LCE13: Introduction to Jira - Linaro's Project Management Application
LCE13: Introduction to Jira - Linaro's Project Management ApplicationLCE13: Introduction to Jira - Linaro's Project Management Application
LCE13: Introduction to Jira - Linaro's Project Management Application
 
Project Management Plan - Odogu & Siersma
Project Management Plan - Odogu & SiersmaProject Management Plan - Odogu & Siersma
Project Management Plan - Odogu & Siersma
 
Project Management in nutshell
Project Management in nutshellProject Management in nutshell
Project Management in nutshell
 
Process Improvement and Change Management, 29th October 2015
Process Improvement and Change Management, 29th October 2015Process Improvement and Change Management, 29th October 2015
Process Improvement and Change Management, 29th October 2015
 
Alpha Case Study - Project Management Plan Sample
Alpha Case Study - Project Management Plan SampleAlpha Case Study - Project Management Plan Sample
Alpha Case Study - Project Management Plan Sample
 
Advertising Media Plan Project "Axe"
Advertising Media Plan Project "Axe"Advertising Media Plan Project "Axe"
Advertising Media Plan Project "Axe"
 
Online shopping portal: Software Project Plan
Online shopping portal: Software Project PlanOnline shopping portal: Software Project Plan
Online shopping portal: Software Project Plan
 
Project Management Plan - Cafe Au Lait.PDF
Project Management Plan - Cafe Au Lait.PDFProject Management Plan - Cafe Au Lait.PDF
Project Management Plan - Cafe Au Lait.PDF
 
Restaurant project
Restaurant projectRestaurant project
Restaurant project
 
Business plan - Entrepreneurship Project - Shivam Jaiswal
Business plan - Entrepreneurship Project - Shivam JaiswalBusiness plan - Entrepreneurship Project - Shivam Jaiswal
Business plan - Entrepreneurship Project - Shivam Jaiswal
 
Cafe construction project report
Cafe construction project reportCafe construction project report
Cafe construction project report
 
Online shopping ppt by rohit jain
Online shopping ppt by rohit jainOnline shopping ppt by rohit jain
Online shopping ppt by rohit jain
 
Business project plan
Business project planBusiness project plan
Business project plan
 
PROJECT ON NEW BUSINESS PLAN
PROJECT ON NEW BUSINESS PLANPROJECT ON NEW BUSINESS PLAN
PROJECT ON NEW BUSINESS PLAN
 
Wedding project management
Wedding project managementWedding project management
Wedding project management
 
Sample project plan
Sample project planSample project plan
Sample project plan
 
Project Management Concepts (from PMBOK 5th Ed)
Project Management Concepts (from PMBOK 5th Ed)Project Management Concepts (from PMBOK 5th Ed)
Project Management Concepts (from PMBOK 5th Ed)
 
Project planning and project work plan
Project planning and project work planProject planning and project work plan
Project planning and project work plan
 

Ähnlich wie Top 5 Magento Secure Coding Best Practices

Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
Pavel Novitsky
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
cfc
 

Ähnlich wie Top 5 Magento Secure Coding Best Practices (20)

Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learnedMoving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
Moving a high traffic ZF1 Enterprise Application to SF2 - Lessons learned
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Jakość dostarczanego oprogramowania oparta o testy
Jakość dostarczanego oprogramowania oparta o testyJakość dostarczanego oprogramowania oparta o testy
Jakość dostarczanego oprogramowania oparta o testy
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
 
Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)Meet Magento Belarus debug Pavel Novitsky (eng)
Meet Magento Belarus debug Pavel Novitsky (eng)
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101Geek Sync | Rewriting Bad SQL Code 101
Geek Sync | Rewriting Bad SQL Code 101
 
TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0
 
Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片Contagion的Ruby/Rails投影片
Contagion的Ruby/Rails投影片
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Top 5 Magento Secure Coding Best Practices

  • 1. Top 5 Magento Secure Coding Best Practices Alex Zarichnyi, Magento ECG
  • 2. Security in Magento • Dedicated team
  • 3. Security in Magento • Dedicated team • External audits
  • 4. Security in Magento • Dedicated team • External audits • Awareness about OWASP Top 10
  • 5. Security in Magento http://magento.com/security • Bug bounty program • Dedicated team • External audits • Awareness about OWASP Top 10 up to $10.000
  • 6. Security in Magento • Built-in security mechanisms • Bug bounty program • Dedicated team • External audits • Awareness about OWASP Top 10
  • 7. Top 5 Secure Coding Practices
  • 8. #1. Validate input as strictly as possible
  • 9. Input Validation Do not trust: • all input parameters • cookie names and values • HTTP header content • Some $_SERVER parameters (e.g. HTTP_X_FORWARDED, HTTP_X_FORWARD ED_FOR)
  • 10. Zend_Validate • Alpha-numeric values • Credit Carts • Host names • IPs • Custom validators (Mage_Core_Model_Url_Validator) • and many more
  • 11. $attributeCode = $this->getRequest()->getParam('attribute_code'); $validator = new Zend_Validate_Regex(array( 'pattern' => '/^[a-z][a-z_0-9]{1,254}$/')); if (!$validator->isValid($attributeCode)) { //stop execution and add a session error } Validate attribute code 1. 2. $attributeCode = $this->getRequest()->getParam('attribute_code'); $validatorChain = new Zend_Validate(); $validatorChain->addValidator(new Zend_Validate_StringLength( array('min' => 1, 'max' => 254))) ->addValidator(new Zend_Validate_Alnum()); if (!$validatorChain->isValid($attributeCode)) { //stop execution and add a session error }
  • 12. $email = $this->getRequest()->getParam('email'); if (Zend_Validate::is($email, 'EmailAddress')) { //continue execution } else { $this->_getSession()->addError($this->__('Invalid email address.')); //redirect back } Validate email
  • 13. #2. Use parameterized queries (?, :param1)
  • 14. Working with Data in Magento $id = $this->getRequest()->getParam(‘id’); $model->load($id); $q = $this->getRequest()->getParam(‘q’); $collection->addFieldToFilter(‘name’, ‘%’ . $q . ‘%’)); secure secure
  • 15. $select->where("region.code = '{$requestParam}'"); $res = $this->_getReadAdapter()->fetchRow($select); $select->where('region.code = ?', $requestParam); $res = $this->_getReadAdapter()->fetchRow($select); Bad code Good code 1. $select->where('region.code= :regionCode'); $bind = array('regionCode' => $requestParam); $res = $this->getReadAdapter()->fetchRow($select, $bind)); 2. name' ); UPDATE admin_user SET password = '34e159c98148ff85036e23986 6a8e053:v6' WHERE username = 'admin';
  • 16. $select->joinInner( array('i' => $this->getTable('enterprise_giftregistry/item')), 'e.entity_id = i.entity_id AND i.item_id = ' . $requestParam, array() ); $select->joinInner( array('i' => $this->getTable('enterprise_giftregistry/item')), 'e.entity_id = i.entity_id AND i.item_id = ' . (int) $requestParam, array() ); Bad code Good code 1; DROP TABLE customer_entity;
  • 17. $result = "IF (COUNT(*) {$operator} {$requestParam}, 1, 0)"; $select->from( array('order' => $this->getResource()->getTable('sales/order')), array(new Zend_Db_Expr($result) ); $value = $select->getAdapter()->quote($requestParam); $result = "IF (COUNT(*) {$operator} {$value}, 1, 0)"; $select->from( array('order' => $this->getResource()->getTable('sales/order')), array(new Zend_Db_Expr($result)) ); Bad code Good code
  • 19. SQL Query Parameters Escaping $db->quoteInto("WHERE date < ?", "2005-01-02") WHERE date < '2005-01-02’ Zend_Db_Adapter_Abstract quote($value, $type = null) quoteInto($text, $value, $type = null, $count = null) quoteIdentifier($ident, $auto=false) quoteColumnAs($ident, $alias, $auto=false) quoteTableAs($ident, $alias = null, $auto = false) $db->quote("O'Reilly"); O'Reilly $db->quote("' or '1'='1' -- “, Zend_Db::FLOAT_TYPE); 0.000000
  • 20. Mage::helper(‘core’)->escapeHtml($data, $allowedTags = null) Mage_Core_Block_Abstract::escapeHtml($data, $allowedTags = null) String Replacement & &amp; " &quot; ' &#039; < &lt; > &gt; HTML Special Characters Escaping https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet Never insert untrusted data except in allowed locations Use both on frontend & backend
  • 21. #4. Use CSRF tokens (form keys)
  • 22. <form name="myForm" id="myForm" method="post" action="..."> <?php echo $this->getBlockHtml('formkey')?> <!-- ... --> </form> public function saveAction() { if (!$this->_validateFormKey()) { //stop and throw an exception or redirect back } } <input type="hidden" value="Bcp957eKYP48XL0Y" name="form_key"> in template in controller
  • 23. #5. Use security headers
  • 24. HTTP security headers https://www.owasp.org/index.php/List_of_useful_HTTP_headers Header Description Example X-XSS-Protection Protects from XSS X-XSS-Protection: 1; mode=block X-Frame-Options Protects from Clickjacking X-Frame-Options: deny X-Content-Type- Options Prevents Internet Explorer and Google Chrome from MIME- sniffing a response away from the declared content-type X-Content-Type-Options: nosniff Content-Security- Policy, X-WebKit-CSP Lets you specify a policy for where content can be loaded Lets you put restrictions on script execution X-WebKit-CSP: default-src 'self'
  • 25. /** * Add security headers to the response * * @listen controller_action_predispatch * @param Varien_Event_Observer $observer */ public function processPreDispatch(Varien_Event_Observer $observer) { $response = $observer->getControllerAction()->getResponse(); $response->setHeader(‘X-XSS-Protection’, ‘1; mode=block’) ->setHeader(‘X-Frame-Options’, ‘DENY’) ->setHeader(‘X-Content-Type-Options’, ‘nosniff’); }
  • 26. Additional Resources • https://www.owasp.org – The Open Web Application Security Project • http://websec.io/ – Securing PHP-based applications • http://cwe.mitre.org/ – Common Weakness Enumeration • https://www.youtube.com/watch?v=aGnV7P8NXtA –Magento Security Presentation, Imagine 2012 • http://www.developers-paradise.com/wp- content/uploads/eltrino-paradise-2013-roman_stepanov.pdf - Magento Security and Vulnerabilities Presentation, Magento Developer Paradise 2013