Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 30 ยท Quality and Security

Security in Modules

Secure your PrestaShop modules: pSQL and casting for SQL, sanitizing input, CSRF tokens, output escaping in Smarty and Twig, safe uploads and access checks, with vulnerable-versus-safe demos.

A PrestaShop module runs inside a shop that holds customer addresses, order history and the keys to a payment gateway. A single careless line in a module can let a stranger read the customer table or run code on the server. Modules are also the most common source of vulnerabilities in PrestaShop stores, because the core is reviewed by many people while a small module is often written once and forgotten.

In this lesson you will learn the habits that prevent the most common problems: escaping SQL, treating all input as hostile, protecting forms with tokens, escaping output, handling file uploads, and checking who is allowed to do what. Each topic starts with real PrestaShop code (read-only) and then runs a vulnerable-versus-safe demonstration in plain PHP with SQLite, so you can see the attack and the fix. For the shop-wide view of security, read Shop Security.

The demos use small stand-in functions. They show the principle, not PrestaShop's exact implementation, and the stand-ins are not replacements for the real helpers.

Never trust input

Everything that comes from the browser is input: $_GET, $_POST, cookies, headers, uploaded files and even the values of hidden fields. In PrestaShop code you normally read request values with Tools::getValue('name') and test for a submitted form with Tools::isSubmit('submitName'). Tools::getValue() reads from POST first and then GET. It helps with some byte-level problems, such as null bytes, but it does not make the value safe for SQL or for HTML. Think of it as "get the raw value" and decide the right treatment for the place you will use it.

Convert the value to the type you expect at once:

PHP
$productId = (int) Tools::getValue('id_product');
$quantity  = max(1, (int) Tools::getValue('quantity'));
$email     = Tools::getValue('email');

if (!Validate::isEmail($email)) {
    $this->errors[] = $this->trans('Invalid email address.', [], 'Modules.Mymodule.Shop');
}

The Validate class has many checks (isEmail, isUnsignedInt, isName, isCleanHtml and more). Use an allow-list for anything with a few valid choices, such as a sort column or a status.

SQL: pSQL, casting and bqSQL

PrestaShop's database layer is the Db class. When you build a query by hand, every dynamic value must be handled in one of three ways:

  • Integers and floats: cast them, (int) $id and (float) $price.
  • Strings: wrap them in pSQL(), which escapes quotes and other special characters for the database connection. By default it also removes HTML tags; pass true as the second argument only for fields that are meant to hold HTML.
  • Identifiers (table or column names that you take from a variable): wrap them in bqSQL(), which escapes and adds backticks, or better, check them against a fixed list.
PHP
$sql = 'SELECT id_badge, title
        FROM `' . _DB_PREFIX_ . 'mymodule_badge`
        WHERE id_shop = ' . (int) $this->context->shop->id . '
          AND code = \'' . pSQL(Tools::getValue('code')) . '\'';

$rows = Db::getInstance()->executeS($sql);

_DB_PREFIX_ is the table prefix and is a constant of the shop, so it is safe. For inserts and updates, Db::insert() and Db::update() take an array of column values and escape the values for you, so prefer them over hand-written statements (you still choose the table and column names, so keep those fixed). For queries with many parts, DbQuery builds a statement and still expects you to escape values yourself. Newer code in the Symfony back office uses Doctrine, where you pass values as bound parameters.

Never concatenate raw input, and never trust a number you have not cast. The demo below runs a vulnerable lookup and a safe one against SQLite. In the real shop the safe version would use pSQL; the stand-in uses a prepared statement, which is the equivalent idea at the driver level.

PHP Vulnerable versus safe SQL

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.

CSRF: protect every state-changing request

A cross-site request forgery happens when another website makes the visitor's browser send a request to your shop, for example a hidden form that posts to your "delete wishlist" controller. The browser attaches the visitor's cookies, so the shop thinks the user did it. The defense is a secret token that the attacker's page cannot know, included in each form or ajax call and verified on the server.

In a front controller, PrestaShop provides Tools::getToken(). Pass false to get a token tied to the current customer or session. Put it into the form, and compare it when handling the request:

PHP
// When building the page
$this->context->smarty->assign('token', Tools::getToken(false));

// In the controller that handles the POST
if (Tools::getValue('token') !== Tools::getToken(false)) {
    $this->errors[] = $this->trans('Invalid token.', [], 'Modules.Mymodule.Shop');
    return;
}

Also use POST (not GET) for actions that change data: links can be triggered by images and prefetching. In a module's configuration page, HelperForm is given a token created with Tools::getAdminTokenLite('AdminModules'), and the Symfony back office adds a _token to its routes and uses Symfony's form CSRF protection. When you add your own forms or ajax calls to those pages, keep the token that the framework gives you. The idea is explained in Module Front Controllers.

The demo issues a token that is bound to a session and an action, then checks a good request, a forged one and a token taken from another action.

PHP A CSRF token bound to session and action

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.

Escape output for its context

Cross-site scripting (XSS) happens when text typed by a user is printed into a page as HTML. A product review that contains a script tag, shown without escaping, runs in every visitor's browser, including an administrator's. Escape at the moment of output, and match the escaping to the place: HTML text, an HTML attribute, JavaScript or a URL.

In Smarty front-office templates, modern PrestaShop escapes variables automatically, which is why trusted HTML in themes is marked with nofilter:

SMARTY
<h3>{$title}</h3>
<div class="description">{$product.description nofilter}</div>

Treat nofilter as dangerous: use it only on HTML that comes from the shop owner or from your own code, never on text typed by customers or sent by an API. Variables that go into JavaScript need the JavaScript-aware escaper (|escape:'javascript'), and a safer approach is to put the data in a data- attribute or encode it with json_encode. In PHP, Tools::safeOutput($string) returns an HTML-safe string. In Twig templates in the back office, auto-escaping is on and the raw filter turns it off, so the same warning applies to |raw.

Escaping on output, not on input, keeps the stored data accurate and lets you use it in other contexts (an email, a CSV). The demo compares an unescaped page fragment with an escaped one.

PHP Escaping output

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.

File uploads

An upload handler is a doorway for attackers. The classic attack uploads a PHP file with a harmless-looking name and then requests it, so the server executes it. Defend in layers:

  1. Limit the size, and accept only the types you need.
  2. Check the extension against an allow-list. Do not rely on the Content-Type sent by the browser, which the uploader controls.
  3. Check the actual file content. For images, ImageManager::validateUpload($_FILES['image'], $maxBytes) in PrestaShop returns an error message, or false when the file looks acceptable.
  4. Generate your own file name. Never use the original name to build the path.
  5. Store files in a folder where PHP execution is disabled, or outside the web root, and serve private files through a controller that checks access.
PHP
$file = $_FILES['badge_image'] ?? null;
if ($file && !empty($file['tmp_name'])) {
    $error = ImageManager::validateUpload($file, 1024 * 1024);
    if ($error) {
        $this->errors[] = $error;
    } else {
        $name = bin2hex(random_bytes(8)) . '.png';
        move_uploaded_file($file['tmp_name'], _PS_MODULE_DIR_ . 'mymodule/uploads/' . $name);
    }
}

The stand-in validator checks size, an extension allow-list and the first bytes of the file (its "magic number"), then produces a safe name.

PHP A defensive upload check

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.

Who is allowed to do this?

Authentication answers who the user is; authorization answers what that user may do. Check both, on the server, in every controller.

  • Front office: if the data belongs to a customer, check $this->context->customer->isLogged() and that the record's owner id equals the current customer id. Skipping the second check lets one customer read another's order by changing an id in the URL (an insecure direct object reference).
  • Back office, legacy: module configuration pages are protected by the permissions of the module manager. Make sure custom ajax endpoints in the back office check the employee and a token.
  • Back office, Symfony: protect controller actions with the @AdminSecurity annotation (checking the read, update, create or delete permission of a tab). Routes without it can be reachable by any logged-in employee. See The Symfony Back Office.

Also guard direct access to your PHP files. Every module file begins with if (!defined('_PS_VERSION_')) { exit; }, and every folder gets an index.php that redirects, so a visitor cannot list the directory's contents. Do not leave debug output, var_dump calls or test scripts in the released module, and never log passwords, tokens or card data.

Keep a secret out of version control and out of public module folders. API keys belong in Configuration, entered through the module's configuration page. If a key was ever committed to a public repository, treat it as stolen and rotate it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You need an integer id from the request to use in SQL. What is the safest way?

    A cast guarantees a number, so nothing can be injected. Tools::getValue() only reads the value; it does not make it safe for SQL.
  2. 2. Why can a column name in an ORDER BY clause not be protected by a bound parameter?

    A placeholder is a value slot. For identifiers, accept only names from a fixed list (or use bqSQL on a known name).
  3. 3. What does a CSRF token prevent?

    A secret per-session token cannot be known by an attacker's page, so a forged cross-site request fails the check.
  4. 4. When is it acceptable to print a Smarty variable with nofilter?

    nofilter disables escaping, so it is only safe for trusted HTML. Customer-supplied text must stay escaped.
  5. 5. A customer opens /order-detail?id=1042 and changes the id to 1043. What check prevents seeing someone else's order?

    Authorization must be checked on the server for each record. Hidden links or request methods do not stop a user from sending a different id.

Summary

  • Treat every request value as hostile: cast numbers, validate with Validate, and use allow-lists for choices.
  • In SQL, cast numbers, wrap strings in pSQL(), use bqSQL() or an allow-list for identifiers, and prefer Db::insert()/Db::update() or bound parameters.
  • Protect state-changing requests with POST and a token, such as Tools::getToken(false), and keep the tokens that back-office pages give you.
  • Escape on output for the right context; treat nofilter and |raw as dangerous.
  • Validate uploads by size, extension and content, rename them, and store them where PHP cannot run.
  • Check ownership and permissions on the server for every record and every action.

Next: Performance and Caching