Skip to content
XSS Write-up Beginner

Cross-Site Scripting in CodeIgniter version 3.1.13

Two reflected cross-site scripting flaws existed in how CodeIgniter rendered error messages: one when a file include failed and one when a malformed SQL query failed in debug mode. An attacker could inject HTML and JavaScript into those error pages, which would then run in a victim's browser.

Antoine Cervoise Follow

Published on synacktiv.com

Vulnerabilities description CodeIgniter CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.1

Antoine Cervoise, Maxime Rinaudo, on synacktiv.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

CodeIgniter is a PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications. Synacktiv discovered two reflected Cross-Site Scripting vulnerabilities in it, both in the way the framework renders error messages:

  1. Error messages generated on failed file includes.
  2. Error messages generated when SQL queries are malformed.

The advisory was published on 2022-11-29 by Antoine Cervoise and Maxime Rinaudo of Synacktiv (5 Boulevard Montmartre, 75002 Paris).

Setup

At the time of writing, versions 3.1.11 and 3.1.13 were proven to be affected. The proof-of-concept URLs point at a local checkout served at http://localhost/bcit-ci-CodeIgniter-b73eb19/, so the tests ran against a local installation of the framework with a controller that passes user input into the vulnerable code paths. No accounts or special roles are involved: the two scenarios are reachable by any user who can send a request to the affected controller.

The relevant configuration knob for the second issue lives in application/config/database.php. By default, debug mode is only enabled outside production:

PHP
'db_debug' => (ENVIRONMENT !== 'production'),

A developer may also force it:

PHP
'db_debug' => TRUE,

Finding it

The two issues share a pattern: the framework takes a value that can be influenced by the user, embeds it in an error message, and returns that message without sanitising it. The first path is the view loader, which includes a file by name. The second is the database layer, which prints the failing SQL statement when debug mode is on. In both cases the error text is rendered back to the browser, so HTML and JavaScript placed in the input are interpreted by the browser rather than displayed as text.

Exploitation

Step 1: XSS in file include error messages

The framework loads a file with the following code:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->view('welcome_message');
    }
}

If the file to load is based on user input, an error is returned when the file does not exist:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        if (isset($_GET['page'])) {
            $this->load->view($_GET['page']);
        }
    }
}

In this scenario any user can inject HTML and JavaScript into the error message:

HTTP
http://localhost/bcit-ci-CodeIgniter-b73eb19/?page=%3Cscript%3Ealert(%27XSS%20by%20Synacktiv%27);%3C/script%3E

In this scenario it is possible to inject HTML and JavaScript into the error message.

The vulnerability can also be triggered using the dedicated library for fetching GET parameters:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $page = $this->input->get('page');
        if (isset($page)) {
            $this->load->view($page);
        }
    }
}

Using the input library does not help: the value still reaches the view loader and then the error message. Configuring the project in production mode does not disable this error message.

Step 2: XSS in SQL error messages

With db_debug enabled, an attacker able to force an SQL error can inject HTML and JavaScript into the error message. The following code sample introduces the vulnerability:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->database();
        if (isset($_GET['id'])) {
            $sql = 'SELECT * FROM toto WHERE id=' . $_GET['id'] . ' LIMIT -1';
            //echo $sql;
            $query = $this->db->query($sql);
            $this->db->error();
        }
        $this->load->view('welcome_message');
    }
}

The id parameter is concatenated directly into the query string.

HTTP
http://localhost/bcit-ci-CodeIgniter-b73eb19/?id=%3Cscript%3Ealert(%27XSS%20by%20Synacktiv%27);%3C/script%3E

Here id decodes to <script>alert('XSS by Synacktiv');</script>, which ends up in the SQL error message and executes in the browser.

Root cause

In both cases the framework builds an error message from user-controlled data and returns it without escaping. The framework builds error messages from user-controlled data and returns them without escaping. The recommendation is to sanitise user inputs within error messages using the xss_clean() function. For the SQL case, the default configuration limits exposure because debug mode is off in production, but a developer who forces 'db_debug' => TRUE re-enables it. For the include case, production mode does not help at all: the error message is still returned.

Impact

An attacker who can get a victim to follow a crafted link, or otherwise cause the victim's browser to request the vulnerable URL, can execute JavaScript in the context of the application. The first variant works regardless of environment, as long as the application passes user input to the view loader. The second requires db_debug to be enabled and a code path where user input reaches a query that can be made to fail. The advisory does not describe any further consequences beyond script execution in the error page.

Fix

Sanitise user inputs within error messages using the xss_clean() function, or apply the patch in the pull request at https://github.com/bcit-ci/CodeIgniter/pull/6113. For the SQL case, configuring the application in production mode disables the error message. The timeline of the disclosure was:

Date Action
2021-06-25 Advisory sent to [redacted], but no MX record exists for this domain.
2021-07 Report on the official Slack about the issue with the MX record.
2021-10-13 Advisory sent to [redacted]
2022-03-11 Agreement between the CodeIgniter security team and Synacktiv to publish a pull request.
2022-03-12 Pull request on the official project.
2022-11-29 Public release.

Variants to test

  • Pass user input into $this->load->view() and request a non-existent view. A positive result is a response whose error message contains your markup unescaped, for example a <script> tag that the browser executes.
  • Do the same through $this->input->get() before the loader call, to check whether the input library changes anything. A positive result is the same unescaped reflection.
  • Look for controllers that concatenate request parameters into SQL and append a clause that guarantees a syntax error, as the sample does with LIMIT -1. With db_debug enabled, a positive result is the failing statement echoed back with your markup intact.
  • Check application/config/database.php for 'db_debug' => TRUE or an environment check that leaves debug on. A positive result is debug output on a reachable environment.
  • A positive result is any error page that reflects your input without encoding.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

What happened, in plain words

CodeIgniter is a piece of software that helps programmers build websites in a language called PHP. Think of it as a ready-made toolbox: instead of writing every part of a website from scratch, a developer picks tools out of the box and assembles them. CodeIgniter is popular because the toolbox is small and simple.

Two security researchers, Antoine Cervoise and Maxime Rinaudo, working for a company called Synacktiv in Paris, found two flaws in CodeIgniter. Both flaws are of the same kind, called reflected Cross-Site Scripting, usually shortened to XSS. The name sounds complicated, so here is the everyday version.

When something goes wrong on a website, the site often shows an error message, for example "the page you asked for does not exist". Normally that message is plain text. But if the website copies something the visitor typed straight into the message without cleaning it first, a visitor can type not just words but also instructions that the browser will obey. A browser treats anything between <script> and </script> as a small program and runs it. So if a visitor can sneak a <script> block into an error message, the browser of whoever views that message will run the visitor's program. That is XSS: the attacker gets their own code running inside someone else's website, in that person's browser.

The word reflected means the malicious input is not stored on the server. It bounces straight back in the response to the same request. The attacker therefore has to get a victim to send that request, typically by tricking them into clicking a prepared link.

The two flaws found are:

  1. An error message shown when CodeIgniter fails to load a file (a "view") that the visitor asked for.
  2. An error message shown when a database query is malformed.

In both cases the visitor's input ends up inside the error message without being cleaned, and the browser runs it.

The advisory was published on 2022-11-29 by Antoine Cervoise and Maxime Rinaudo of Synacktiv (5 Boulevard Montmartre, 75002 Paris).

Setup

At the time of writing, versions 3.1.11 and 3.1.13 were proven to be affected. A version number is just a label the developers give each release, like the edition number of a book; 3.1.13 is a later release than 3.1.11.

The example addresses in the report all start with http://localhost/bcit-ci-CodeIgniter-b73eb19/. The word localhost means "this very computer". The example addresses in the report all start with http://localhost/bcit-ci-CodeIgniter-b73eb19/, meaning a local installation. The long folder name bcit-ci-CodeIgniter-b73eb19 is simply the name of the folder where that copy sits. To follow along, a reader would need the same kind of local installation, with a small test page (called a controller) that passes visitor input into the vulnerable code. The report does not give installation steps.

No accounts or special roles are involved. Anyone who can send a request to the affected page can reach both scenarios. A request is what your browser sends to a server when you open a page or submit a form: a short message asking for something, plus any data you supplied.

The setting that matters for the second flaw lives in a configuration file, application/config/database.php. Configuration files are where a website keeps its settings, much like the settings menu on a phone. By default, a debugging mode for the database is only switched on outside production:

PHP
'db_debug' => (ENVIRONMENT !== 'production'),

Line by line:

  • 'db_debug' is the name of the setting. db is short for database, and debug means "show extra technical detail to help find problems".
  • => means "is set to".
  • (ENVIRONMENT !== 'production') is a small test. ENVIRONMENT is a label saying which stage the site is at. production means the live site that real visitors use. !== means "is not equal to". So the whole expression reads: "debug is on whenever the environment is not production".

A developer may also force it on:

PHP
'db_debug' => TRUE,

Here the setting is simply set to TRUE, meaning always on, whatever the environment. TRUE is a programming word for "yes".

Finding it

The two issues share a pattern: the framework takes a value that can be influenced by the user, embeds it in an error message, and returns that message without sanitising it. Sanitising means cleaning input so that any special characters lose their power, for example turning < into a harmless piece of text instead of the start of a tag.

The first path is the view loader. A view is a page template, a file that holds the HTML of a page. The loader is the part of CodeIgniter that fetches a view by name and includes it in the response. The second path is the database layer, the part that talks to the database. A database is an organised store of information, like a very large, very strict spreadsheet. When a query (a question asked of the database) fails, the database layer can print the failing statement, and that printed text goes back to the browser.

In both cases the error text is rendered back to the browser. Rendered means turned into what you actually see on screen. Because the text is not escaped, HTML and JavaScript placed in the input are interpreted by the browser rather than displayed as text. Escaping is the opposite of interpreting: it tells the browser "show this as characters, do not treat it as instructions".

Exploitation

Step 1: XSS in file include error messages

The framework loads a file with the following code:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->view('welcome_message');
    }
}

Line by line:

  • <?php marks the start of PHP code. Everything after it is instructions for the server, not for the browser.
  • defined('BASEPATH') OR exit('No direct script access allowed'); is a guard. It checks whether a constant called BASEPATH exists. BASEPATH is a marker CodeIgniter sets when it is running properly. If the marker is missing, meaning someone opened this file directly instead of going through the framework, the script stops with the message "No direct script access allowed".
  • class Welcome extends CI_Controller { starts a class called Welcome. A class is a bundle of code with a name. extends CI_Controller means it inherits from CodeIgniter's base controller, so it gets the framework's built-in abilities. A controller is the part of a website that handles an incoming request and decides what to send back.
  • public function index() defines a function called index. A function is a named block of instructions. index is the default action when no specific action is named in the URL.
  • $this->load->view('welcome_message'); asks the framework to load the view named welcome_message. $this means "this controller"; load is the loader tool; view(...) is the instruction to fetch a view by name.
  • The closing braces end the function and the class.

This version is safe because the view name is fixed in the code. The next version is not:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        if (isset($_GET['page'])) {
            $this->load->view($_GET['page']);
        }
    }
}

Line by line, focusing on what changed:

  • if (isset($_GET['page'])) { checks whether the request contains a value called page. $_GET is PHP's built-in way of reading values that were sent in the URL after a question mark. isset(...) means "is this set?".
  • $this->load->view($_GET['page']); now loads whatever view name the visitor supplied, instead of a fixed one.
  • The closing brace ends the if block.

In this scenario, any user can inject HTML and JavaScript into the error message:

HTTP
http://localhost/bcit-ci-CodeIgniter-b73eb19/?page=%3Cscript%3Ealert(%27XSS%20by%20Synacktiv%27);%3C/script%3E

What this URL does, piece by piece:

  • http://localhost/bcit-ci-CodeIgniter-b73eb19/ is the address of the local test site.
  • ? marks the start of the data being sent. Everything after it is a list of name and value pairs.
  • page= is the name of the value, matching $_GET['page'] in the code.
  • %3Cscript%3Ealert(%27XSS%20by%20Synacktiv%27);%3C/script%3E is the value, written in URL encoding. URLs may only contain a limited set of characters, so special characters are written as a percent sign followed by two characters. %3C is <, %3E is >, %27 is a single quote, and %20 is a space. Decoded, the value is <script>alert('XSS by Synacktiv');</script>.

The browser sees the tags, treats them as code, and runs alert('XSS by Synacktiv'), which pops up a small dialog box with that text. A harmless alert is the standard way to prove that script execution is possible; a real attacker would put something more useful to them in place of the alert.

The vulnerability can also be triggered using the dedicated library for fetching GET parameters:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $page = $this->input->get('page');
        if (isset($page)) {
            $this->load->view($page);
        }
    }
}

Line by line:

  • $page = $this->input->get('page'); reads the page value using CodeIgniter's own input library instead of PHP's $_GET, and stores it in a variable called $page. A variable is a named box that holds a value. The input library is the framework's recommended way of reading request data.
  • if (isset($page)) { checks that the variable actually holds something.
  • $this->load->view($page); passes that value to the view loader, exactly as before.

Using the input library does not help: the value still reaches the view loader and then the error message. Configuring the project in production mode does not disable this error message either. That last point matters: normally, switching a site to production mode hides technical errors from visitors, but here the message is still returned.

Step 2: XSS in SQL error messages

With db_debug enabled, an attacker able to force an SQL error can inject HTML and JavaScript into the error message. SQL is the language used to talk to databases. The following code sample introduces the vulnerability:

PHP
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->database();
        if (isset($_GET['id'])) {
            $sql = 'SELECT * FROM toto WHERE id=' . $_GET['id'] . ' LIMIT -1';
            //echo $sql;
            $query = $this->db->query($sql);
            $this->db->error();
        }
        $this->load->view('welcome_message');
    }
}

Line by line:

  • $this->load->database(); connects the site to its database, like opening a connection to the spreadsheet.
  • if (isset($_GET['id'])) { checks whether the request contains a value called id.
  • $sql = 'SELECT * FROM toto WHERE id=' . $_GET['id'] . ' LIMIT -1'; builds a database question as text. SELECT * FROM toto means "give me every column from a table called toto". WHERE id= narrows it to rows with a given id. The dot . in PHP glues pieces of text together, so the visitor's id value is inserted straight into the middle of the question. LIMIT -1 is part of the query text.
  • //echo $sql; is a commented-out line. The // means the rest of the line is ignored by PHP; it was probably used during testing to print the query.
  • $query = $this->db->query($sql); sends the built question to the database and stores the result.
  • $this->db->error(); asks the database layer for its error information.
  • $this->load->view('welcome_message'); then loads the normal page.

The id parameter is concatenated directly into the query string. The trailing LIMIT -1 makes the statement malformed, so the query fails and the framework renders the error, including the attacker-controlled text:

HTTP
http://localhost/bcit-ci-CodeIgniter-b73eb19/?id=%3Cscript%3Ealert(%27XSS%20by%20Synacktiv%27);%3C/script%3E

This URL is the same idea as before, with id as the name. In this scenario, it is possible to inject HTML and JavaScript into the error message.

Root cause

In both cases the framework builds an error message from user-controlled data and returns it without escaping. The view loader takes the requested view name and echoes it back when the include fails; the database layer echoes the failing SQL statement when db_debug is on. Echoing means printing text into the response. The recommendation is to sanitise user inputs within error messages using the xss_clean() function. A helper is a small ready-made function you can call; xss_clean() is meant to strip dangerous markup from a value.

For the SQL case, the default configuration limits exposure because debug mode is off in production, but a developer who forces 'db_debug' => TRUE re-enables it. For the include case, production mode does not help at all: the error message is still returned.

Impact

An attacker who can get a victim to follow a crafted link, or otherwise cause the victim's browser to request the vulnerable URL, can execute JavaScript in the context of the application. In the context of the application means the script runs as if it came from the site itself, so the browser trusts it the way it trusts the site's own pages. The first variant works regardless of environment, as long as the application passes user input to the view loader. The second requires db_debug to be enabled and a code path where user input reaches a query that can be made to fail. The advisory does not describe any further consequences beyond script execution in the error page.

Fix

Sanitise user inputs within error messages using the xss_clean() function, or apply the patch in the pull request at https://github.com/bcit-ci/CodeIgniter/pull/6113. A patch is a small change to the code that repairs the flaw, and a pull request is a proposed change submitted to a project so its maintainers can review and merge it. For the SQL case, configuring the application in production mode disables the error message.

The timeline of the disclosure was:

Date Action
2021-06-25 Advisory sent to [redacted], but no MX record exists for this domain.
2021-07 Report on the official Slack about the issue with the MX record.
2021-10-13 Advisory sent to [redacted]
2022-03-11 Agreement between the CodeIgniter security team and Synacktiv to publish a pull request.
2022-03-12 Pull request on the official project.
2022-11-29 Public release.

An advisory is the formal notice researchers send to the makers of a product describing a flaw. An MX record is a piece of the internet's address book that tells email servers where to deliver mail for a domain; without one, mail to that address cannot be delivered. Slack is a chat service teams use to talk to each other.

Variants to test

If you are reviewing a CodeIgniter application, these are the checks to try. Each one is a way of asking the same question: does user input come back in an error page without being cleaned?

  • Pass user input into $this->load->view() and request a non-existent view. A positive result is a response whose error message contains your markup unescaped, for example a <script> tag that the browser executes.
  • Do the same through $this->input->get() before the loader call, to check whether the input library changes anything. A positive result is the same unescaped reflection.
  • Look for controllers that concatenate request parameters into SQL and append a clause that guarantees a syntax error, as the sample does with LIMIT -1. With db_debug enabled, a positive result is the failing statement echoed back with your markup intact.
  • Check application/config/database.php for 'db_debug' => TRUE or an environment check that leaves debug on. A positive result is debug output on a reachable environment.
  • A positive result is any error page that reflects your input without encoding.

A payload is the piece of input an attacker sends to trigger the flaw, here the script tag. Routing is the part of a framework that decides which controller handles a given URL. Validation is the checking of submitted data, for example whether a form field was filled in correctly.

Glossary

  • Advisory: the formal notice researchers send to the makers of a product describing a flaw.
  • BASEPATH: a marker constant CodeIgniter sets when it is running properly; its absence means a file was opened directly.
  • Class: a named bundle of code that groups related functions and data.
  • Configuration file: a file holding a website's settings, like a settings menu.
  • Controller: the part of a website that handles an incoming request and decides what to send back.
  • Cross-Site Scripting (XSS): a flaw where an attacker gets their own code to run inside someone else's website, in that person's browser.
  • Database: an organised store of information, like a very large, very strict spreadsheet.
  • Database layer: the part of a framework that talks to the database.
  • db_debug: the CodeIgniter setting that controls whether database errors are shown in detail.
  • Debug mode: a mode that shows extra technical detail to help find problems.
  • Echo: to print text into the response sent to the browser.
  • ENVIRONMENT: a label saying which stage a site is at, such as development or production.
  • Escaping: turning special characters into plain text so the browser shows them instead of acting on them.
  • Function: a named block of instructions that can be called by name.
  • Helper: a small ready-made function provided by a framework.
  • HTML: the language that describes the structure of a web page.
  • In the context of the application: running as if the script came from the site itself, so the browser trusts it like the site's own pages.
  • JavaScript: the programming language browsers run to make pages interactive.
  • localhost: the name for "this very computer", used when testing on your own machine.
  • MX record: a piece of the internet's address book telling email servers where to deliver mail for a domain.
  • Patch: a small change to code that repairs a flaw.
  • Payload: the piece of input an attacker sends to trigger a flaw.
  • PHP: the programming language CodeIgniter is written in and that runs on the server.
  • Production: the live site that real visitors use.
  • Pull request: a proposed change submitted to a project so its maintainers can review and merge it.
  • Reflected: a flaw where the malicious input bounces straight back in the response rather than being stored on the server.
  • Rendered: turned into what you actually see on screen.
  • Request: the message your browser sends to a server asking for something, plus any data you supplied.
  • Routing: the part of a framework that decides which controller handles a given URL.
  • Sanitising: cleaning input so special characters lose their power.
  • Slack: a chat service teams use to talk to each other.
  • SQL: the language used to talk to databases.
  • TRUE: a programming word for "yes".
  • URL encoding: writing special characters in a URL as a percent sign followed by two characters, such as %3C for <.
  • Validation: the checking of submitted data, for example whether a form field was filled in correctly.
  • Variable: a named box that holds a value.
  • Version number: a label developers give each release, like an edition number.
  • View: a page template, a file that holds the HTML of a page.
  • View loader: the part of CodeIgniter that fetches a view by name and includes it in the response.
  • xss_clean(): a CodeIgniter helper meant to strip dangerous markup from a value.

More from CodeIgniter

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site scripting (XSS)

The lesson behind this report.

Script an attacker supplies runs in another user's browser, on the target's origin, with that user's session.