SlideShare une entreprise Scribd logo
1  sur  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
Дякую!

Contenu connexe

Tendances

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

Tendances (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...
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

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
 
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
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Dernier (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
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...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
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
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

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