SlideShare a Scribd company logo
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
Дякую!

More Related Content

PPTX
Top 5 magento secure coding best practices Alex Zarichnyi
PDF
PHPunit and you
PDF
PHPUnit Episode iv.iii: Return of the tests
PDF
Dealing with Legacy PHP Applications
PDF
Manipulating Magento - Meet Magento Netherlands 2018
PDF
Dealing With Legacy PHP Applications
PDF
Introduction to Zend Framework web services
PPTX
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Top 5 magento secure coding best practices Alex Zarichnyi
PHPunit and you
PHPUnit Episode iv.iii: Return of the tests
Dealing with Legacy PHP Applications
Manipulating Magento - Meet Magento Netherlands 2018
Dealing With Legacy PHP Applications
Introduction to Zend Framework web services
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2

What's hot (20)

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

Viewers also liked (20)

PDF
The Project Management Plan in 20 steps
PPTX
PMI Project Management Principles
PDF
LCE13: Introduction to Jira - Linaro's Project Management Application
PDF
Project Management Plan - Odogu & Siersma
PDF
Project Management in nutshell
PDF
Process Improvement and Change Management, 29th October 2015
PDF
Alpha Case Study - Project Management Plan Sample
PDF
Advertising Media Plan Project "Axe"
PDF
Online shopping portal: Software Project Plan
PDF
Project Management Plan - Cafe Au Lait.PDF
PPTX
Restaurant project
PPTX
Business plan - Entrepreneurship Project - Shivam Jaiswal
DOCX
Cafe construction project report
PPT
Online shopping ppt by rohit jain
PPTX
Business project plan
PPTX
PROJECT ON NEW BUSINESS PLAN
PPTX
Wedding project management
DOC
Sample project plan
PDF
Project Management Concepts (from PMBOK 5th Ed)
PPTX
Project planning and project work plan
The Project Management Plan in 20 steps
PMI Project Management Principles
LCE13: Introduction to Jira - Linaro's Project Management Application
Project Management Plan - Odogu & Siersma
Project Management in nutshell
Process Improvement and Change Management, 29th October 2015
Alpha Case Study - Project Management Plan Sample
Advertising Media Plan Project "Axe"
Online shopping portal: Software Project Plan
Project Management Plan - Cafe Au Lait.PDF
Restaurant project
Business plan - Entrepreneurship Project - Shivam Jaiswal
Cafe construction project report
Online shopping ppt by rohit jain
Business project plan
PROJECT ON NEW BUSINESS PLAN
Wedding project management
Sample project plan
Project Management Concepts (from PMBOK 5th Ed)
Project planning and project work plan
Ad

Similar to Top 5 Magento Secure Coding Best Practices (20)

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

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PDF
cuic standard and advanced reporting.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Electronic commerce courselecture one. Pdf
PDF
KodekX | Application Modernization Development
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Empathic Computing: Creating Shared Understanding
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
Spectral efficient network and resource selection model in 5G networks
cuic standard and advanced reporting.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Agricultural_Statistics_at_a_Glance_2022_0.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Electronic commerce courselecture one. Pdf
KodekX | Application Modernization Development
Mobile App Security Testing_ A Comprehensive Guide.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.
MYSQL Presentation for SQL database connectivity
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Empathic Computing: Creating Shared Understanding
The AUB Centre for AI in Media Proposal.docx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
20250228 LYD VKU AI Blended-Learning.pptx

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