Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 27 ยท Security and quality

Security for Extension Developers

Secure your OpenCart extensions: output escaping, SQL escaping and typed casts, user_token and CSRF, admin permissions, file uploads, secrets and callbacks.

A store handles names, addresses, orders and payments, and an extension runs inside it with full access to all of that. A single missing cast in your SQL or a single unescaped variable in your template can expose a whole shop. Most OpenCart security incidents do not come from the core, which is reviewed by many people, but from third-party extensions written in a hurry. This lesson gives you a checklist to apply to every controller, model and template you write.

You will learn the six places where extensions typically go wrong: output escaping, SQL, request forgery and tokens, admin permissions, file uploads, and secrets and callbacks. The real OpenCart code is read-only here, because OpenCart cannot run on this site. The runnable examples are plain PHP stand-ins using SQLite, so you can attack and repair small versions of the same bugs. Shop-wide security topics are in Shop Security, and the database layer is in Models, the Registry and the Database.

The rule behind everything

Treat all of the following as hostile until proven otherwise: $this->request->get, ->post, ->cookie, ->server and ->files, headers, data coming back from a payment gateway, and even your own database rows if a customer could have written them (product reviews, names, addresses). Validate on input, escape on output, and give every piece of data the type it should have as early as possible.

Output escaping

Cross-site scripting (XSS) happens when user-controlled text reaches HTML unescaped. A customer who names themselves <script>...</script> should see that text, not run it, and an admin who opens the order list must not run it either.

In templates, escape every dynamic value. Do not assume the Twig environment does it for you: OpenCart has configured its Twig instance in a way that differs from a standard Twig setup (look at the options in system/library/template/twig.php of your version), so the safe habit is to be explicit:

TWIG
{# read-only template #}
<p>Hello, {{ firstname|e }}</p>
<a href="{{ link|e('html_attr') }}" title="{{ title|e('html_attr') }}">{{ title|e }}</a>
<script>var name = {{ firstname|json_encode|raw }};</script>

The e filter is safe to add even when automatic escaping is on, because Twig does not escape its output a second time. Choose the strategy for the place where the value lands:

Where the value goes Use
Between tags `
In an attribute value `
In a URL query part `
Inside JavaScript `

The |raw filter turns escaping off. Use it only for markup that you generated and know to be safe, never for something that came from a request or a customer. HTML that the shop owner writes in a rich-text field (such as a product description) is trusted by design, but the same field filled by a customer is not.

In controllers that build JSON or HTML fragments by hand, call htmlspecialchars($value, ENT_QUOTES, 'UTF-8'). The stand-in below shows an attack and the fix:

PHP Stored XSS and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the unsafe output the script tag is real markup, so a browser would run it. In the safe output the same characters appear as &lt;script&gt; and are only text.

SQL: escape, cast, and keep queries in models

OpenCart's database class offers $this->db->query($sql) and $this->db->escape($value). It does not give you a prepared-statement API, so you must make every value safe:

  • Numbers: cast with (int) or (float). This is both the simplest and the strongest protection.
  • Strings: wrap in $this->db->escape() and put the result inside quotes.
  • Never build column names, sort directions or table names from request data. Compare against a fixed allow-list (in_array($sort, ['name', 'price'], true)).
  • Always use DB_PREFIX for table names.
PHP
// read-only model code
$sql = "SELECT * FROM `" . DB_PREFIX . "acme_badge` WHERE `product_id` = '" . (int)$product_id . "'
        AND `label` = '" . $this->db->escape($label) . "'";

$sorts = ['label', 'date_added'];
$sort = in_array($sort, $sorts, true) ? $sort : 'label';
$sql .= " ORDER BY `" . $sort . "`";

Remember the second-order case: a value you escaped when storing is stored raw (without the escape characters), and when you read it back and use it in another query you must escape it again. The following stand-in shows the classic login-bypass injection with SQLite, and then the fixes with typed casts and with a prepared statement. OpenCart code cannot use PDO's prepared statements through its own db class, but the lesson of "values are data, never code" is the same.

PHP SQL injection and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first query leaks a hidden product and the string injection leaks the unpublished one, while the cast and the prepared statement return nothing, because the input is treated as a value. In OpenCart, (int) and $this->db->escape() serve the role of the cast and the placeholder.

CSRF, user_token and admin permissions

Cross-site request forgery makes a logged-in admin's browser send a request they did not intend, for example one that changes your extension's settings. OpenCart's defence in the admin area is the user_token: a random value created at login, put into every admin URL, and checked by the admin's startup code before it runs a controller. Consequences for you:

  • Always build admin links and form actions with &user_token={{ user_token }} (the controller passes $this->session->data['user_token']). Never build a link without it.
  • State changes must use POST, not GET. A GET link such as ...&delete=5 can be triggered by an image tag.
  • On the storefront there is no general token mechanism. For actions that change data (a wishlist, a review, an RMA request), require POST, check the customer is logged in where relevant, and add your own random token stored in the session, then compare with hash_equals.

Being logged in to the admin does not mean being allowed to do something. OpenCart groups admin users into user groups, and each group has two lists, access and modify, naming routes. Your admin controller must check the permission before any change:

PHP
// read-only admin controller code
public function save(): void {
    $this->load->language('extension/acme/module/badge');
    $json = [];

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

    if (!$json) {
        $this->load->model('setting/setting');
        $this->model_setting_setting->editSetting('module_acme_badge', $this->request->post);
        $json['success'] = $this->language->get('text_success');
    }

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

Permissions are assigned in System > Users > User Groups, and your install step must add them for your routes, as shown in Install, Uninstall and Permissions. Forgetting the modify check is one of the most common holes: every admin with only access could change settings by sending the request by hand.

File uploads

An upload is code execution waiting to happen if you accept the wrong file in the wrong place. Rules:

  1. Allow-list the extension and the real content type (use finfo and not the client's header) instead of block-listing .php.
  2. Generate the file name yourself (random, plus the allowed extension). Never trust the original name, or ../ in it.
  3. Store uploads outside the web root or in a folder where PHP execution is disabled, and set a size limit.
  4. Serve downloads through a controller that checks access.

The stand-in validates names and types, and shows the traversal and double-extension tricks being refused:

PHP An upload validator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Only the first one is accepted. The logo.png that is really HTML fails because the detected content does not match the extension.

Secrets and payment callbacks

  • Settings are stored in the setting table as plain text. Do not echo a stored API secret back into the form (show a placeholder and keep the old value if the field is left empty), never write secrets to the error log or to a page, and never ship a default secret in the package.
  • A callback from a payment gateway is an unauthenticated request from the internet. Never mark an order as paid because a URL was visited. Verify the signature with hash_equals on the raw body, check the timestamp, and confirm the amount and order id match. See Building a Payment Extension and Webhooks and Signatures.
  • Do not log full card data or tokens. If you do not need personal data, do not store it (Privacy and Compliance).

A release checklist

Before you release an extension, search it for: every ->request-> read and where the value ends up; every $this->db->query and its casts; every template variable without |e; every admin controller method with a hasPermission check; every upload; every file path built from input; every curl call with timeouts and TLS verification on.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A value from the request is used as a numeric product id in SQL. What is the best protection?

    A cast turns any input, including injected SQL text, into a number, so it cannot change the query.
  2. 2. When is the |raw filter acceptable in a Twig template?

    raw switches escaping off, so it must never be used on request or customer data.
  3. 3. Why must an admin controller that saves settings call hasPermission('modify', ...) even though the user is logged in?

    Access and modify are separate permissions. Without the check, a user who may only view could still send a save request.
  4. 4. Which upload design is safest?

    An allow-list, real content detection and server-chosen names remove the usual tricks such as double extensions and path traversal.
  5. 5. A gateway calls your callback URL with an order id and the word "paid". What must you do before marking the order paid?

    The callback is an anonymous internet request. Only a verified signature proves it came from the gateway.

Summary

  • Escape on output in every template, with |e or the strategy that fits the place; reserve |raw for markup you generated.
  • Cast numbers and escape strings in every SQL statement, never build identifiers from input, and use DB_PREFIX.
  • Use user_token in all admin URLs, POST for changes, and add your own tokens on storefront actions.
  • Check hasPermission('modify', route) in every admin method that changes data, and register permissions on install.
  • Validate uploads by allow-list and real content, name files yourself and store them safely.
  • Keep secrets out of forms, logs and packages, and verify payment callbacks cryptographically.

Next: Testing and Debugging Extensions