No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Debugging, performance and code quality

OpenCart module security: XSS, SQL injection and CSRF in 3.0 and 4.1

OpenCart 3.0 and 4.1 module security: what the core protects and what it doesn't, how to prevent XSS when autoescape is false, SQL injection, CSRF, access to others' data and unsafe file uploads.

11 min read OC 3.0 OC 4.1

OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → module security relies on several core mechanisms, and each has limits. Request escapes GET and POST via htmlspecialchars, the admin checks user_token and the access right for the route, and in 4.1 storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → forms have their own tokens. But Twig works without automatic escaping, raw data from php://input, the API, and the database is escaped by no one, and the module itself must check the right to change data and data ownership. Below we look at where modules most often open up XSS, SQL injection, and CSRF, and how to avoid them in 3.0 and 4.1.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

What does the core protect, and what does it not?

MechanismWhat it doesWhat it does not do
Request (both versions)passes GET, POST, COOKIE, FILES and SERVER through htmlspecialchars(..., ENT_COMPAT, 'UTF-8')does not escape single quotes; does not touch php://input, database data, or API responses
Twig (both versions)renders templatesthe environment is created with 'autoescape' => false, so {{ var }} is output as is
Admin (both versions)startup/login requires a match with user_token, startup/permission checks the access right for the routethe controller itself checks the modify right
Storefront formsin 4.1, login, registration, reviews, returns, and uploads have their own tokens in the session (login_token, register_token, review_token, etc.)in 3.0 there are no such tokens; module forms are not automatically protected in either version
Session cookiein 4.1, set with the SameSite=Strict attribute after installationin 3.0 the attribute is not set

So XSS protection in OpenCart is actually built like this: data is escaped on input, stored in the database already escaped, and output without escaping. As long as data follows the path "form → Request → database → templateA display file: in 2.x it is .tpl, and in 3.0 and 4.1 it is .twig. More in the glossary →", this works. As soon as a module takes data from another source, there is no protection.

How do you prevent XSS?

How XSS works: a diagram

XSS (cross-site scripting) is a situation where a string set by an attacker gets into the page's HTML as markup, not as text. The victim's browser executes it as part of the site. The typical path in an OpenCart module is as follows:

  1. Input. The attacker sends a string with markup, for example <img src=x onerror=alert(1)>. It can get into a comment field, into a JSON request to the module's endpoint, or into data the module receives from an external service.
  2. Bypassing Request. If the data arrived via php://input, the API, or an import, htmlspecialchars did not process it, and the angle brackets remain as they are.
  3. Storage. The module writes the string to the database. This is stored XSS: it fires for everyone who opens the page. If the string is returned immediately in the response without being stored in the database, it is reflected XSS.
  4. Output. The controllerCode that receives a request and prepares data. More in the glossary → passes the value to the template, and Twig with 'autoescape' => false inserts {{ comment }} into HTML unchanged.
  5. Execution. The buyer's or administrator's browser sees the tag and runs the onerror handler on behalf of the site.

The same string at the template output looks different depending on the path:

<!-- пройшов через Request: показується як текст -->
<p>&lt;img src=x onerror=alert(1)&gt;</p>

<!-- прийшов з JSON/API без екранування: виконується -->
<p><img src=x onerror=alert(1)></p>

The most dangerous case is outputting such data in the admin, for example in the module's list of requests. The script runs with the administrator's session: it can see user_token in the addresses on the page and can send requests to the admin on their behalf. Therefore the chain must be broken at at least one step, and it is most reliable to break it during output.

Where unescaped data appears

  • JSON in the request body. json_decode(file_get_contents('php://input')) gives raw strings (see the article about a custom JSON endpoint).
  • Responses from external services: shipping office names, comments from the CRM, payment gateway messages.
  • Import via direct SQL: product names and descriptions from the supplier's price list.
  • Data decoded on purpose. The core does html_entity_decode() for product and category descriptions, because HTML from the administrator is expected there. If a module decodes in the same way a field filled in by the buyer (comment, review), it opens an XSS hole.
  • Attributes in single quotes. ENT_COMPAT does not escape ', so <input value='{{ name }}'> is vulnerable even to data that has passed through Request.
  • JavaScript context. <script>var name = "{{ name }}";</script> breaks on characters that htmlspecialchars does not touch in JS, for example backslashes and line breaks.

Output rules

Because autoescape is disabled, escape explicitly with a Twig filter, depending on the context:

Example: explicit escaping in a module template

{# текст і атрибути в подвійних лапках #}
<span class="city">{{ warehouse.name|e }}</span>
<input type="text" name="comment" value="{{ comment|e('html_attr') }}"/>

{# дані для JavaScript: рядок JSON підготовлено в контролері #}
<script>
  var warehouses = {{ warehouses_json }};
</script>

{# URL з даних користувача: схему http/https перевірено в контролері #}
<a href="{{ link|e('html_attr') }}">...</a>

For the <script> block, the controller prepares the string itself: $data['warehouses_json'] = json_encode($warehouses, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);. The JSON_HEX_* flags convert <, >, quotes, and the ampersand into \u00.. sequences, so the string will not close the </script> tag and will not go beyond the value.

For links built from user data, the url strategy does not fit. It encodes the string via rawurlencode, so it breaks the full address (it encodes : and /) and does not block the javascript: scheme. Use {{ link|e('html_attr') }}, and in the controller check that the URL starts with http:// or https://. Apply the |e('url') filter only to individual query parameters.

Double escaping for data that has already passed through Request looks like &amp;amp; on the page. Therefore the rule is simple: data from core forms, stored through core models, is output as is (this is exactly what the core does). For data from other sources (API, JSON, import), choose one model. You can normalize it when saving via htmlspecialchars(..., ENT_COMPAT, 'UTF-8'), as Request does, and then output it without a filter. Or you can store it raw and escape it with the |e filter on output. Do not combine both approaches for the same field, or you will get double escaping. How a template receives variables is described in the article about Twig in OpenCart.

JSON responses

json_encode() is safe for JSON by itself. But if JavaScript on the page inserts the received values via innerHTML or jQuery .html(), XSS occurs on the client. Insert text via textContent or .text(), and build HTML from escaped values. How the core serves JSON is explained in the article about AJAX in OpenCart.

How do you write SQL without injections?

The DB class in both versions does not provide prepared statements through the public API. The rule is the same for all drivers:

  • cast numbers to their type: (int), (float);
  • wrap strings in quotes and pass them through $this->db->escape();
  • take column names and sort direction only from a whitelist, as the core does with $sort_data;
  • cast the values in IN (...) to int element by element.

Example: search with sorting and LIKE in a module model

$sort_data = ['name', 'date_added', 'status'];

$sort  = in_array($data['sort'] ?? '', $sort_data, true) ? $data['sort'] : 'date_added';
$order = (($data['order'] ?? '') === 'ASC') ? 'ASC' : 'DESC';

$like = addcslashes((string)($data['filter_name'] ?? ''), '%_\\');

$sql = "SELECT * FROM `" . DB_PREFIX . "mymod_item`
        WHERE `name` LIKE '%" . $this->db->escape($like) . "%'
        ORDER BY `" . $sort . "` " . $order . "
        LIMIT " . (int)$start . "," . (int)$limit;

In 4.1 the pdo driver uses prepare() internally, but for module code the rule is the same: (int)/(float) for numbers, escape() for strings, a whitelist for columns. The remaining rules and common mistakes are covered in the article about SQL queries without injections.

How do you protect against CSRF?

Admin

In both versions, any admin route except the login and a few service routes requires user_token in the GET parameters that matches the session. An attacker does not know the token, so they cannot forge an admin request from a third-party site. For how to pass the token in links and AJAX, see the article about user_token. The module has two rules:

  1. Perform all actions that change data (saving, deleting, synchronizing) as POST requests, not GET links. Links with a token end up in browser history and logs.
  2. In every such method, check the modify right. startup/permission checks only access, that is, the right to open the page.

Example: checking the modify right in the save() method (OpenCart 4.1)

public function save(): void {
    $this->load->language('extension/mymod/module/mymod');

    $json = [];

    if (!$this->user->hasPermission('modify', 'extension/mymod/module/mymod')) {
        $json['error']['warning'] = $this->language->get('error_permission');
    }

    if (!$json) {
        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting('module_mymod', $this->request->post);

        $json['success'] = $this->language->get('text_success');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

In 3.0, the route in hasPermission() is written as extension/module/mymod. How groups and rights are organized is described in the article about module access rights.

Storefront

Protect module forms on the storefront (subscription, callback, "notify when in stock", changing data in the account) with a session token modeled on the 4.1 core: generate it when the form is shown, pass it in the address or a hidden field, verify it and delete it when processing.

Example: form token on the storefront (OpenCart 4.1)

// при показі форми
$this->session->data['mymod_token'] = oc_token(32);
$data['action'] = $this->url->link('extension/mymod/module/mymod.send', 'language=' . $this->config->get('config_language') . '&mymod_token=' . $this->session->data['mymod_token']);

// в обробнику send()
$token = (string)($this->request->get['mymod_token'] ?? '');

if (!isset($this->session->data['mymod_token']) || !hash_equals($this->session->data['mymod_token'], $token)) {
    $json['error'] = $this->language->get('error_token');
}

In 3.0 the function is called token(). This matters especially for 3.0, because there are no core form tokens there and no SameSite on the session cookie.

Access to other people's data, files, and secrets

Ownership check

A typical vulnerability in account modules is showing or changing a record by an id from the address without checking whose it is. ?order_id=105 should open an order only when the customer_id of the order matches customer_id in $this->customer->getId(). The core does this in its account/* models, and the module's own models should include customer_id in the WHERE condition. For guest scenarios, use an unpredictable token instead of a sequential id. In 4.1, account pages additionally check customer_token; see the article about the Customer library for details.

File uploads

  • Store files in DIR_UPLOAD (by default system/storage/upload/) under random names. The core does this in tool/upload. Keep the original name in the database. In a standard installation, the storage directory is inside the site root and is protected only by .htaccess, so move it outside the root. On Nginx, .htaccess alone is not enough.
  • Check extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → against a whitelist and check the content type, not only the $_FILES['type'] that the client sets.
  • Never put buyer files in image/ or any other directory where the web server could execute PHP.
  • For paths coming from a request, check realpath(), as tool/image does: the real path must lie inside the allowed directory.

Secrets

  • Do not output API keys, webhook secrets, and passwords into storefront templates or pass them to JavaScript.
  • Do not write them to logs, even debug logs.
  • In the admin settings form, show the secret masked and do not overwrite it with an empty value if the field was not changed.
  • Verify callbacks and endpoints by signature or key via hash_equals().

General measures for protecting the panel itself (passwords, 2FA, renaming the directory) are described in the blog article about OpenCart admin security.

Summary

  • Request escapes input data via htmlspecialchars with ENT_COMPAT, and Twig outputs without escaping. Everything that has not passed through Request (JSON, API, import, decoded fields) should be escaped with the |e filter in the appropriate context.
  • Write attributes in double quotes, and pass data for JS via json_encode with the JSON_HEX_* flags.
  • In SQL: (int) for numbers, escape() for strings, a whitelist for columns and direction.
  • In the admin, actions that change data are done as POST with a modify check. On the storefront, module forms have their own session token.
  • Check the record owner, store uploads in DIR_UPLOAD under random names (the storage directory is outside the site root), and do not expose secrets.

Other materials on debugging, performance, and module code quality are collected in the section "Debug, performance and code quality".

FAQ

Can I enable autoescape in Twig for my module?
The Twig environment is created by the core, so enabling it globally is a core change that will break templates that output HTML. For a module, it's safer to explicitly escape variables with the |e filter in your own templates.
Do I need a captcha if the form already has a token?
A token protects against forged requests from another site, but not against bots that open the form first. For public forms such as a callback request, both measures are useful.
How do I check a module for vulnerabilities before release?
Go through all places where data from a request or API reaches SQL, a template, a file path or an external request, and check each one against the rules above. It also helps to run a PHP static analyzer and try the forms with quotes, tags and very long values.
Is it safe to store HTML from the administrator in module settings?
Yes, the administrator already has full access to the store. But such a field should be available only to users with modify permission for the module, and it must not be filled with customer data.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.