How to prevent magento create order with such a potentially harmful or malformed billing address

By | August 8, 2024
Spread the love

The placeholder {{var this.getTemp%00lateFilter().filter(firstname)}} in Magento indicates an attempted injection attack or a misconfiguration. To prevent Magento from creating orders with such a potentially harmful or malformed billing address, you can implement several security measures:

1. Input Validation and Sanitization:

  • Validate User Input: Ensure that all user inputs, including billing addresses, are validated. This means only allowing expected characters (e.g., alphanumeric, spaces, commas) in the billing address fields.
  • Sanitize Inputs: Remove or escape any potentially dangerous characters or sequences from the user input before processing it.

2. Template and Variable Injection Prevention:

  • Disable Direct Template Processing: If user inputs are processed as templates or variables, disable this feature unless absolutely necessary. This can prevent malicious inputs from being executed as code.
  • Escape Variables in Templates: If using variables within templates, make sure they are properly escaped to prevent execution of unexpected or harmful code.

3. Server-Side Validation:

  • Backend Checks: Implement additional server-side validation to ensure that no harmful content is being passed through the system. This acts as a second layer of defense even if front-end validation fails.
  • Custom Validation Rules: Write custom validation rules in Magento to check for specific patterns that should not be allowed in billing addresses.

4. Magento Configuration:

  • Turn On Security Patches: Ensure that all Magento security patches are up to date. These patches often include fixes for known vulnerabilities that could be exploited in this way.
  • Configure Safe Input Filters: Configure Magento to use input filters that prevent potentially dangerous content from being processed or stored.

To prevent orders with specific conditions in Magento 2, such as preventing an order from being created when the billing address contains a particular pattern or string, you typically need to work within Magento’s module system. Specifically, you would modify or create an Observer or Plugin that hooks into the order creation process.

Create an Observer to Prevent Order Creation:

You’ll need to observe the sales_model_service_quote_submit_before event, which is triggered before the order is submitted.

  • Event Configuration (events.xml):

    <?xml version="1.0"?>
    <config xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
        <event name="sales_model_service_quote_submit_before">
            <observer name="yourmodule_prevent_order" instance="YourVendor\YourModule\Observer\PreventOrderCreation" />
        </event>
    </config>

    Create the Observer:

    In YourVendor/YourModule/Observer/PreventOrderCreation.php, you would create the observer that checks the billing address before allowing the order to be created.

    <?php
    
    namespace YourVendor\YourModule\Observer;
    
    use Magento\Framework\Event\ObserverInterface;
    use Magento\Framework\Event\Observer;
    use Magento\Framework\Exception\LocalizedException;
    
    class PreventOrderCreation implements ObserverInterface
    {
        public function execute(Observer $observer)
        {
            $quote = $observer->getEvent()->getQuote();
            $billingAddress = $quote->getBillingAddress();
            $firstname = $billingAddress->getFirstname();
    
            // Check for the specific pattern in the billing first name (as an example)
            if (strpos($firstname, '{{var this.getTemp%00lateFilter().filter(firstname)}}') !== false) {
                throw new LocalizedException(__('Order creation is prevented due to invalid billing information.'));
            }
        }
    }

    In this example, the code checks the firstname in the billing address, and if it contains the suspicious pattern, it throws a LocalizedException, which will prevent the order from being created and display the error message to the user.

See full example to handle Billing / Shipping Address

 

<?php

namespace Techgroup\Addon\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

class QuoteSubmitBefore implements ObserverInterface
{
    /**
     * {{var this.getTemp%00lateFilter().filter(firstname)}}
     * {@inheritDoc}
     * @see \Magento\Framework\Event\ObserverInterface::execute()
     */
    public function execute(Observer $observer)
    {
        $quote           = $observer->getEvent()->getQuote();
        $billingAddress  = $quote->getBillingAddress();
        $shippingAddress = $quote->getShippingAddress();
        
        if($billingAddress)
        {
            $billingAddressArr = $billingAddress->getData();
            unset($billingAddressArr['extension_attributes']);
            
            $error = $this->formDataValidation($billingAddressArr);
            if($error){
                throw new \Exception($error);
            }
        }
        
        if($shippingAddress)
        {
            $shippingAddressArr = $shippingAddress->getData();
            unset($shippingAddressArr['extension_attributes']);
            
            $error = $this->formDataValidation($shippingAddressArr);
            if($error){
                throw new \Exception($error);
            }
        }
    }
    
    /**
     * validate data
     *
     * @param array $data
     * @return string
     */
    public function formDataValidation($data)
    {
        if(!$data || !is_array($data)){
            return false;
        }
        
        $error = "";
        foreach($data as $item => $value){
            if(!is_string($value)){
                continue;
            }
            
            if(!in_array($item, ['firstname', 'lastname', 'city', 'street', 'region', 'telephone', 'company', 'postcode', 'region_id'])){
                continue;
            }
            
            if($value && preg_match("/[\[^\'£$%^&*()}{@:\!'~?><>;@\|\\\=\+\¬\`\]]/", $value))
            {
                $error .= $item.", ";
            }
        }
        
        if($error){
            $error = substr('Please use only letters (a-z or A-Z), numbers (0-9), spaces and "- _ # , ." in fields '.$error, 0, -2);
        }
        
        return $error;
    }
}