Security/Guides/SQL Queries and 3rd Party Packages

SQL Queries
Connecting your application and database layers can pose security risks. Notably, SQL injection. Below is an outline of the do's and dont's of executing SQL queries in MediaWiki.

Never Correct
MediaWiki developers should never directly execute SQL queries through PHP's database extension functions (such as  or  ). Using the MediaWiki database wrappers helps ensure your queries end up at the correct database (which may or may not be the same as where the wiki itself is stored).

Why? Directly inserting a SQL string in one of these provided functions makes the developer responsible for escaping the SQL string themselves. Otherwise, applications are susceptible to SQL injection attacks.

Usually Correct
Most of the time, developers can use existing wrapper functions like  or   to perform SQL queries. When passing in parameters to these wrapper functions, it is important to use  on raw user data, as it correctly escapes the provided input (such as table name and  /  statements) to help prevent SQL injection.

Correct as of MW >1.35
As of MediaWiki 1.35, developers can use the SelectQueryBuilder class to create SQL  statements. This class allows function chaining so SQL queries are easily readable and don't require specifically formatted input parameters (like  does). The parameters to SelectQueryBuilder wrapper functions such as  should also be escaped via   before being passed in.

Rarely Correct
Rarely, you may need to execute a custom SQL query, one that does not fit within the parameters of the IDatabase wrapper functions or the  in which case you can use. This is useful for queries that are explicitly DBMS-dependent and are unsupported by the query wrappers such as.

3rd Party Packages
Installing 3rd party packages in MediaWiki and other WMF projects can be incredibly useful, but also has the opportunity to introduce security risks.

NPM
MediaWiki and other WMF projects should not use non-WMF NPM packages in production environments (WMF packages being anything in the NPM Wikimedia organization). Installing NPM dependencies for development environments however (e.g. adding packages to your    vs  ) is considered secure. When you install an NPM package you not only install itself, but the tens or hundreds of other dependencies it relies on. At the end of the day, you're introducing untrusted code onto production machines that could do anything from steal ssh keys to access secure files on the hard drive. (See this article by Timo Tijhof for more details on specific risks). One way to mitigate security risks posed from NPM might be by performing security audits, however doing a thorough audit can be cumbersome and requires many of the Security team's time and resources. One such case study in this topic was the usage of the build step...[?]

Composer
MediaWiki and other WMF projects do however, have Composer packages installed in production environments...