SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Top 5 Magento Secure
Coding Best Practices
Alex Zarichnyi, Magento ECG
About Me
zlik
ozarichnyi@ebay.com
linkedin.com/in/ozarichnyi
From 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 (X-Forwarded-For)
Blacklist vs. Whitelist Validation
‘
1=1
<script></script> ^d{5}(-d{4})?$
^(AA|AE|AP|AL|AK|AS|AZ|AR|CA|CO|CT|DE|D
C|FM|FL|GA|GU|
HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|
MN|MS|MO|MT|NE|
NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW
|PA|PR|RI|SC|SD|TN|
TX|UT|VT|VI|VA|WA|WV|WI|WY)$
Zip Code
U.S. State
O’Brian
<sCrIpT></sCrIpT>
Attack patterns
What if?
Zend_Validate
• Alnum values
• Credit Carts
• Host names
• IPs
• Custom validators
(Mage_Core_Model_Url_Validator)
• and many more
$email = $this->getRequest()->getParam('email');
if (!empty($email) && Zend_Validate::is($email, 'EmailAddress')) {
//continue execution
} else {
$this->_getSession()->addError($this->__('Invalid email address.'));
}
Validate email
$attributeCode = $this->getRequest()->getParam('attribute_code');
$validator = new Zend_Validate_Regex(array(
'pattern' => '/^[a-z][a-z_0-9]{1,254}$/'));
if (!$validato->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
}
#2. Use parameterized queries
(?, :param1)
$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 aaa_test;
$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(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. 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
Q&A

Weitere ähnliche Inhalte

Was ist angesagt?

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 2018Alan Arentsen
 
Django REST Framework における API 実装プラクティス | PyCon JP 2018
Django REST Framework における API 実装プラクティス | PyCon JP 2018Django REST Framework における API 実装プラクティス | PyCon JP 2018
Django REST Framework における API 実装プラクティス | PyCon JP 2018Masashi Shibata
 
Dealing With Legacy PHP Applications
Dealing With Legacy PHP ApplicationsDealing With Legacy PHP Applications
Dealing With Legacy PHP ApplicationsViget Labs
 
Web Automation Testing Using Selenium
Web Automation Testing Using SeleniumWeb Automation Testing Using Selenium
Web Automation Testing Using SeleniumPete Chen
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesMarcello Duarte
 
Oracle APEX Performance
Oracle APEX PerformanceOracle APEX Performance
Oracle APEX PerformanceScott Wesley
 
CodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPCodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPSteeven Salim
 
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)James Titcumb
 
Roboconf DSL Advanced Software Engineering
Roboconf DSL Advanced Software EngineeringRoboconf DSL Advanced Software Engineering
Roboconf DSL Advanced Software EngineeringMohammad Shaker
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With PhpJeremy Coates
 
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Atwix
 
Best ways to use the ShareASale API
Best ways to use the ShareASale APIBest ways to use the ShareASale API
Best ways to use the ShareASale APIericnagel
 
Selenide review and how to start using it in legacy Selenium tests
Selenide review and how to start using it in legacy Selenium testsSelenide review and how to start using it in legacy Selenium tests
Selenide review and how to start using it in legacy Selenium testsProvectus
 
TDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for BusinessTDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for Businesstdc-globalcode
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::ManagerJay Shirley
 

Was ist angesagt? (20)

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
 
Django REST Framework における API 実装プラクティス | PyCon JP 2018
Django REST Framework における API 実装プラクティス | PyCon JP 2018Django REST Framework における API 実装プラクティス | PyCon JP 2018
Django REST Framework における API 実装プラクティス | PyCon JP 2018
 
Seasion5
Seasion5Seasion5
Seasion5
 
Dealing With Legacy PHP Applications
Dealing With Legacy PHP ApplicationsDealing With Legacy PHP Applications
Dealing With Legacy PHP Applications
 
Web Automation Testing Using Selenium
Web Automation Testing Using SeleniumWeb Automation Testing Using Selenium
Web Automation Testing Using Selenium
 
PhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examplesPhpSpec 2.0 ilustrated by examples
PhpSpec 2.0 ilustrated by examples
 
Os Nixon
Os NixonOs Nixon
Os Nixon
 
TDD with PhpSpec
TDD with PhpSpecTDD with PhpSpec
TDD with PhpSpec
 
Oracle APEX Performance
Oracle APEX PerformanceOracle APEX Performance
Oracle APEX Performance
 
CodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPCodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHP
 
Introduccion a Jasmin
Introduccion a JasminIntroduccion a Jasmin
Introduccion a Jasmin
 
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
Dip Your Toes in the Sea of Security (ConFoo YVR 2017)
 
Roboconf DSL Advanced Software Engineering
Roboconf DSL Advanced Software EngineeringRoboconf DSL Advanced Software Engineering
Roboconf DSL Advanced Software Engineering
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
 
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
 
Best ways to use the ShareASale API
Best ways to use the ShareASale APIBest ways to use the ShareASale API
Best ways to use the ShareASale API
 
Selenide review and how to start using it in legacy Selenium tests
Selenide review and how to start using it in legacy Selenium testsSelenide review and how to start using it in legacy Selenium tests
Selenide review and how to start using it in legacy Selenium tests
 
TDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for BusinessTDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for Business
 
Developing for Business
Developing for BusinessDeveloping for Business
Developing for Business
 
Building Better Applications with Data::Manager
Building Better Applications with Data::ManagerBuilding Better Applications with Data::Manager
Building Better Applications with Data::Manager
 

Andere mochten auch

Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Codemotion
 
Magento development
Magento developmentMagento development
Magento developmentHuyen Do
 
Yurii Hryhoriev "Php storm tips&tricks"
Yurii Hryhoriev "Php storm tips&tricks"Yurii Hryhoriev "Php storm tips&tricks"
Yurii Hryhoriev "Php storm tips&tricks"Magento Dev
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practicesScott Hurrey
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsAOE
 
eCommerce with Magento
eCommerce with MagentoeCommerce with Magento
eCommerce with MagentoTLLMN
 
A Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to DeploymentA Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to DeploymentJoshua Warren
 
Rock-solid Magento Deployments (and Development)
Rock-solid Magento Deployments (and Development)Rock-solid Magento Deployments (and Development)
Rock-solid Magento Deployments (and Development)AOE
 
Surprising failure factors when implementing eCommerce and Omnichannel eBusiness
Surprising failure factors when implementing eCommerce and Omnichannel eBusinessSurprising failure factors when implementing eCommerce and Omnichannel eBusiness
Surprising failure factors when implementing eCommerce and Omnichannel eBusinessDivante
 
Magento scalability from the trenches (Meet Magento Sweden 2016)
Magento scalability from the trenches (Meet Magento Sweden 2016)Magento scalability from the trenches (Meet Magento Sweden 2016)
Magento scalability from the trenches (Meet Magento Sweden 2016)Divante
 
Omnichannel Customer Experience
Omnichannel Customer ExperienceOmnichannel Customer Experience
Omnichannel Customer ExperienceDivante
 

Andere mochten auch (13)

Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...
 
Magento development
Magento developmentMagento development
Magento development
 
Magento devhub
Magento devhubMagento devhub
Magento devhub
 
Yurii Hryhoriev "Php storm tips&tricks"
Yurii Hryhoriev "Php storm tips&tricks"Yurii Hryhoriev "Php storm tips&tricks"
Yurii Hryhoriev "Php storm tips&tricks"
 
Magento
MagentoMagento
Magento
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
Rock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment WorkflowsRock-solid Magento Development and Deployment Workflows
Rock-solid Magento Development and Deployment Workflows
 
eCommerce with Magento
eCommerce with MagentoeCommerce with Magento
eCommerce with Magento
 
A Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to DeploymentA Successful Magento Project From Design to Deployment
A Successful Magento Project From Design to Deployment
 
Rock-solid Magento Deployments (and Development)
Rock-solid Magento Deployments (and Development)Rock-solid Magento Deployments (and Development)
Rock-solid Magento Deployments (and Development)
 
Surprising failure factors when implementing eCommerce and Omnichannel eBusiness
Surprising failure factors when implementing eCommerce and Omnichannel eBusinessSurprising failure factors when implementing eCommerce and Omnichannel eBusiness
Surprising failure factors when implementing eCommerce and Omnichannel eBusiness
 
Magento scalability from the trenches (Meet Magento Sweden 2016)
Magento scalability from the trenches (Meet Magento Sweden 2016)Magento scalability from the trenches (Meet Magento Sweden 2016)
Magento scalability from the trenches (Meet Magento Sweden 2016)
 
Omnichannel Customer Experience
Omnichannel Customer ExperienceOmnichannel Customer Experience
Omnichannel Customer Experience
 

Ähnlich wie Top 5 magento secure coding best practices Alex Zarichnyi

Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Shinya Ohyanagi
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
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 2012Michelangelo van Dam
 
PHP security audits
PHP security auditsPHP security audits
PHP security auditsDamien Seguy
 
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 tek12Michelangelo van Dam
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And AnishOSSCube
 
Concern of Web Application Security
Concern of Web Application SecurityConcern of Web Application Security
Concern of Web Application SecurityMahmud Ahsan
 
Defensive Coding Crash Course Tutorial
Defensive Coding Crash Course TutorialDefensive Coding Crash Course Tutorial
Defensive Coding Crash Course TutorialMark Niebergall
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastMichelangelo van Dam
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridgeRomans Malinovskis
 
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 101IDERA Software
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Craig Francis
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Damien Seguy
 

Ähnlich wie Top 5 magento secure coding best practices Alex Zarichnyi (20)

Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
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
 
PHP security audits
PHP security auditsPHP security audits
PHP security audits
 
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
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
 
Concern of Web Application Security
Concern of Web Application SecurityConcern of Web Application Security
Concern of Web Application Security
 
Defensive Coding Crash Course Tutorial
Defensive Coding Crash Course TutorialDefensive Coding Crash Course Tutorial
Defensive Coding Crash Course Tutorial
 
Php security3895
Php security3895Php security3895
Php security3895
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Agile data presentation 3 - cambridge
Agile data   presentation 3 - cambridgeAgile data   presentation 3 - cambridge
Agile data presentation 3 - cambridge
 
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
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Postman On Steroids
Postman On SteroidsPostman On Steroids
Postman On Steroids
 
Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)Php Code Audits (PHP UK 2010)
Php Code Audits (PHP UK 2010)
 

Mehr von Magento Dev

DevHub 3 - Composer plus Magento
DevHub 3 - Composer plus MagentoDevHub 3 - Composer plus Magento
DevHub 3 - Composer plus MagentoMagento Dev
 
DevHub 3 - Pricing
DevHub 3 - PricingDevHub 3 - Pricing
DevHub 3 - PricingMagento Dev
 
Magento2 airplane
Magento2 airplaneMagento2 airplane
Magento2 airplaneMagento Dev
 
Imagine recap-devhub
Imagine recap-devhubImagine recap-devhub
Imagine recap-devhubMagento Dev
 
Разработка на стероидах или как я перестал бояться и полюбил свою IDE
Разработка на стероидах или как я перестал бояться и полюбил свою IDEРазработка на стероидах или как я перестал бояться и полюбил свою IDE
Разработка на стероидах или как я перестал бояться и полюбил свою IDEMagento Dev
 
Magento 2 Page Cache
Magento 2 Page CacheMagento 2 Page Cache
Magento 2 Page CacheMagento Dev
 
Data migration into eav model
Data migration into eav modelData migration into eav model
Data migration into eav modelMagento Dev
 
Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueueMagento Dev
 
Choreography of web-services
Choreography of web-servicesChoreography of web-services
Choreography of web-servicesMagento Dev
 
Take more from Jquery
Take more from JqueryTake more from Jquery
Take more from JqueryMagento Dev
 

Mehr von Magento Dev (15)

DevHub 3 - Composer plus Magento
DevHub 3 - Composer plus MagentoDevHub 3 - Composer plus Magento
DevHub 3 - Composer plus Magento
 
DevHub 3 - Pricing
DevHub 3 - PricingDevHub 3 - Pricing
DevHub 3 - Pricing
 
DevHub 3 - CVS
DevHub 3 - CVSDevHub 3 - CVS
DevHub 3 - CVS
 
Magento2 airplane
Magento2 airplaneMagento2 airplane
Magento2 airplane
 
Imagine recap-devhub
Imagine recap-devhubImagine recap-devhub
Imagine recap-devhub
 
Разработка на стероидах или как я перестал бояться и полюбил свою IDE
Разработка на стероидах или как я перестал бояться и полюбил свою IDEРазработка на стероидах или как я перестал бояться и полюбил свою IDE
Разработка на стероидах или как я перестал бояться и полюбил свою IDE
 
Magento 2 Page Cache
Magento 2 Page CacheMagento 2 Page Cache
Magento 2 Page Cache
 
Data migration into eav model
Data migration into eav modelData migration into eav model
Data migration into eav model
 
Php + erlang
Php + erlangPhp + erlang
Php + erlang
 
Tdd php
Tdd phpTdd php
Tdd php
 
Gearman jobqueue
Gearman jobqueueGearman jobqueue
Gearman jobqueue
 
Autotest
AutotestAutotest
Autotest
 
Choreography of web-services
Choreography of web-servicesChoreography of web-services
Choreography of web-services
 
Security in PHP
Security in PHPSecurity in PHP
Security in PHP
 
Take more from Jquery
Take more from JqueryTake more from Jquery
Take more from Jquery
 

Kürzlich hochgeladen

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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 REVIEWERMadyBayot
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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 challengesrafiqahmad00786416
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
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 WorkerThousandEyes
 
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...apidays
 
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 DevelopersWSO2
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
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...apidays
 
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, ...apidays
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
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...Zilliz
 

Kürzlich hochgeladen (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
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
 
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...
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
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...
 
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, ...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
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...
 

Top 5 magento secure coding best practices Alex Zarichnyi

  • 1. Top 5 Magento Secure Coding Best Practices Alex Zarichnyi, Magento ECG
  • 3. Security in Magento • Dedicated team
  • 4. Security in Magento • Dedicated team • External audits
  • 5. Security in Magento • Dedicated team • External audits • Awareness about OWASP Top 10
  • 6. Security in Magento http://magento.com/security • Bug bounty program • Dedicated team • External audits • Awareness about OWASP Top 10 up to $10.000
  • 7. Security in Magento • Built-in security mechanisms • Bug bounty program • Dedicated team • External audits • Awareness about OWASP Top 10
  • 8. Top 5 Secure Coding Practices
  • 9. #1. Validate input as strictly as possible
  • 10. Input Validation Do not trust: • all input parameters • cookie names and values • HTTP header content (X-Forwarded-For)
  • 11. Blacklist vs. Whitelist Validation ‘ 1=1 <script></script> ^d{5}(-d{4})?$ ^(AA|AE|AP|AL|AK|AS|AZ|AR|CA|CO|CT|DE|D C|FM|FL|GA|GU| HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI| MN|MS|MO|MT|NE| NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW |PA|PR|RI|SC|SD|TN| TX|UT|VT|VI|VA|WA|WV|WI|WY)$ Zip Code U.S. State O’Brian <sCrIpT></sCrIpT> Attack patterns What if?
  • 12. Zend_Validate • Alnum values • Credit Carts • Host names • IPs • Custom validators (Mage_Core_Model_Url_Validator) • and many more
  • 13. $email = $this->getRequest()->getParam('email'); if (!empty($email) && Zend_Validate::is($email, 'EmailAddress')) { //continue execution } else { $this->_getSession()->addError($this->__('Invalid email address.')); } Validate email
  • 14. $attributeCode = $this->getRequest()->getParam('attribute_code'); $validator = new Zend_Validate_Regex(array( 'pattern' => '/^[a-z][a-z_0-9]{1,254}$/')); if (!$validato->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 }
  • 15. #2. Use parameterized queries (?, :param1)
  • 16. $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';
  • 17. $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 aaa_test;
  • 18. $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
  • 20. 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(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
  • 21. 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
  • 22. #4. Use CSRF tokens (form keys)
  • 23. <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
  • 25. 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'
  • 26. /** * 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’); }
  • 27. 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
  • 28. Q&A