Sujets
- Qu’est-ce que la sécurité ?
- Thèmes relatifs à la sécurité
- Vulnérabilités sur votre ordinateur
- Vulnérabilités dans WordPress
- Vulnérabilités du Serveur Web
- Vulnérabilités du réseau
- Mots de passes
- FTP
- File Permissions
- Database Security
- Securing wp-admin
- Securing wp-includes
- Securing wp-config.php
- Disable File Editing
- Plugins
- Security through obscurity
- Data Backups
- Logging
- Monitoring
- Resources
- See Also
La sécurité de WordPress est pris très au sérieux, mais comme pour tout autre système, des problèmes de sécurité potentiels peuvent survenir si certaines précautions de base ne sont pas prises. Cet article passe en revue certaines formes courantes de vulnérabilités, et les choses que vous pouvez faire pour aider à garder votre installation de WordPress sécurisée.
Cet article n’est pas la solution miracle à vos problèmes de sécurité. Si vous avez des préoccupations ou des doutes spécifiques en matière de sécurité, vous devriez en discuter avec des personnes dont vous pensez qu’elles ont une connaissance suffisante de la sécurité informatique et de WordPress.
Qu’est-ce que la sécurité ?
Fondamentalement, la sécurité n’est pas une question de systèmes parfaitement sécurisés. Une telle chose pourrait bien être peu pratique, ou impossible à trouver et/ou à maintenir. Mais la sécurité, c’est la réduction et non l’élimination des risques. Il s’agit d’utiliser tous les contrôles appropriés à votre disposition, dans la limite du raisonnable, qui vous permettent d’améliorer votre posture générale, réduisant ainsi les chances de devenir une cible et de vous faire pirater par la suite.
Hébergeurs de sites internet
Souvent, un bon point de départ en matière de sécurité des sites web est votre environnement d’hébergement. Aujourd’hui, plusieurs options s’offrent à vous, et bien que les hôtes offrent une certaine sécurité, il est important de comprendre où s’arrête leur responsabilité et où commence la vôtre. Voici un bon article qui explique la dynamique complexe entre l’hébergeur web et la sécurité de votre site web. Un serveur sécurisé protège la confidentialité, l’intégrité et la disponibilité des ressources sous le contrôle de l’administrateur du serveur.
Les qualités d’un hébergeur de confiance peuvent inclure :
- Examiner vos préoccupations en matière de sécurité et des fonctionnalités et processus de sécurité qu’offrent les hébergements.
- Fournit les versions stables les plus récentes de tous les logiciels sur le serveur.
- Fournit des méthodes fiables de sauvegarde et de récupération.
Déterminez la sécurité dont vous avez besoin sur votre serveur en déterminant les logiciels et les données qui doivent être sécurisés. Le reste de ce guide vous aidera dans cette tâche.
Applications du site web
Il est facile de regarder les hébergeurs de sites web et de leur confier la responsabilité de la sécurité, mais le propriétaire du site web est également responsable de la sécurité. Les hébergeurs sont souvent responsables de l’infrastructure sur laquelle votre site web se trouve, ils ne sont pas responsables de l’application que vous choisissez d’installer.
Pour comprendre où et pourquoi c’est important, vous devez comprendre comment les sites web sont piratés, cela est rarement attribué à l’infrastructure, mais le plus souvent à l’application elle-même (c’est-à-dire l’environnement dont vous êtes responsable).
Thèmes relatifs à la sécurité
Gardez à l’esprit quelques idées générales tout en considérant la sécurité pour chaque aspect de votre système :
Limiter les accès
Faire des choix intelligents qui réduisent les points d’entrée possibles pour une personne malveillante.
Confinement
Votre système doit être configuré de manière à minimiser les dommages qui peuvent être causés en cas de compromission.
Préparation et connaissances
Conserver des sauvegardes et être au courant de l’état de votre installation WordPress à intervalles réguliers. Avoir un plan de sauvegarde et de récupération de votre installation en cas de catastrophe peut vous aider à vous remettre en ligne plus rapidement en cas de problème.
Sources de confiance
Ne pas utiliser d’extensions/thèmes provenant de sources non fiables. Limitez-vous au dépôt de WordPress.org ou à des sociétés bien connues. Essayer d’obtenir des extensions/thèmes de l’extérieur peut entraîner des problèmes.
Vulnérabilités sur votre ordinateur
Assurez-vous que les ordinateurs que vous utilisez sont exempts de logiciels espions, de logiciels malveillants et d’infections virales. Aucune sécurité dans WordPress ou sur votre serveur web ne fera la moindre différence s’il y a un keylogger sur votre ordinateur.
Gardez toujours à jour votre système d’exploitation et les logiciels qu’il contient, en particulier votre navigateur web, pour vous protéger des failles de sécurité. Si vous naviguez sur des sites non fiables, nous vous recommandons également d’utiliser des outils tels que le no-script (ou la désactivation de javascript/flash/java) dans votre navigateur.
Vulnérabilités dans WordPress
Comme de nombreux logiciels modernes, WordPress est régulièrement mis à jour pour répondre aux nouveaux problèmes de sécurité qui peuvent survenir. L’amélioration de la sécurité des logiciels est toujours une préoccupation constante, et à cette fin vous devriez toujours vous tenir à jour avec la dernière version de WordPress. Les anciennes versions de WordPress ne sont pas maintenues avec les mises à jour de sécurité.
Mettre à jour WordPress
Article principal : Updating WordPress.
La dernière version de WordPress est toujours disponible sur le site principal de WordPress à l’adresse https://wordpress.org. Les communiqués officiels ne sont pas disponibles sur d’autres sites — ne jamais télécharger ou installer WordPress à partir d’un site autre que https://wordpress.org.
Depuis la version 3.7, WordPress dispose de fonctionnalités de mise à jour automatique. Utilisez cette fonctionnalité pour faciliter le processus de mise à jour. Vous pouvez également utiliser le tableau de bord de WordPress pour vous tenir informé des mises à jour. Lisez l’entrée dans le tableau de bord ou le blog des développeurs WordPress pour déterminer les mesures à prendre pour mettre à jour et rester en sécurité.
Si une vulnérabilité est découverte dans WordPress et qu’une nouvelle version est publiée pour remédier au problème, les informations nécessaires pour exploiter la vulnérabilité sont presque certainement dans le domaine public. Cela rend les anciennes versions plus vulnérables aux attaques, et c’est l’une des raisons principales pour lesquelles vous devriez toujours garder WordPress à jour.
Si vous êtes un⋅e administrateur⋅trice chargé⋅ée de plusieurs installations de WordPress, pensez à utiliser Subversion pour faciliter la gestion.
Signaler des problèmes de sécurité
Si vous pensez avoir trouvé une faille de sécurité dans WordPress, vous pouvez nous aider en signalant le problème. Consultez la Foire aux questions sur la sécurité pour savoir comment signaler un problème de sécurité.
Si vous pensez avoir trouvé un bogue, signalez-le. Voir Soumission de bogues pour savoir comment faire. Vous avez peut-être découvert une vulnérabilité, ou un bogue qui peut en entraîner une.
Vulnérabilités du Serveur Web
The web server running WordPress, and the software on it, can have vulnerabilities. Therefore, make sure you are running secure, stable versions of your web server and the software on it, or make sure you are using a trusted host that takes care of these things for you.
Le serveur Web exécutant WordPress et le logiciel qui s’y trouve peuvent présenter des vulnérabilités. Par conséquent, assurez-vous d’exécuter des versions sécurisées et stables de votre serveur Web et du logiciel qui s’y trouve, ou assurez-vous d’utiliser un hébergeur de confiance qui s’occupe de ces choses pour vous.
If you’re on a shared server (one that hosts other websites besides your own) and a website on the same server is compromised, your website can potentially be compromised too even if you follow everything in this guide. Be sure to ask your web host what security precautions they take.
Si vous êtes sur un serveur mutualisé (qui héberge d’autres sites Web que le vôtre) et qu’un site Web sur le même serveur est compromis, votre site Web peut potentiellement l’être également même si vous suivez tout ce qui est indiqué dans ce guide. Assurez-vous de demander à votre hébergeur quelles précautions de sécurité il prend.
Vulnérabilités du réseau
The network on both ends — the WordPress server side and the client network side — should be trusted. That means updating firewall rules on your home router and being careful about what networks you work from. An Internet cafe where you are sending passwords over an unencrypted connection, wireless or otherwise, is not a trusted network.
Le réseau aux deux extrémités – côté serveur WordPress et côté réseau client – doit être fiable. Cela signifie mettre à jour les règles du pare-feu sur votre routeur domestique et faire attention aux réseaux à partir desquels vous travaillez. Un cybercafé où vous envoyez des mots de passe via une connexion non chiffrée, sans fil ou autre, n’est pas un réseau de confiance.
Your web host should be making sure that their network is not compromised by attackers, and you should do the same. Network vulnerabilities can allow passwords and other sensitive information to be intercepted.
Votre hébergeur doit s’assurer que son réseau n’est pas compromis par des attaquants, et vous devez faire de même. Les vulnérabilités du réseau peuvent permettre l’interception de mots de passe et d’autres informations sensibles.
Mots de passes
Many potential vulnerabilities can be avoided with good security habits. A strong password is an important aspect of this.
De nombreuses vulnérabilités potentielles peuvent être évitées avec de bonnes habitudes de sécurité. Un mot de passe fort est un aspect important de celui-ci.
The goal with your password is to make it hard for other people to guess and hard for a brute force attack to succeed. Many automatic password generators are available that can be used to create secure passwords.
Le but de votre mot de passe est de rendre difficile pour les autres de deviner celui-ci et de rendre difficile une attaque par force brute de réussir. De nombreux générateurs de mots de passe automatiques sont disponibles et peuvent être utilisés pour créer des mots de passe sécurisés.
WordPress also features a password strength meter which is shown when changing your password in WordPress. Use this when changing your password to ensure its strength is adequate.
Things to avoid when choosing a password:
- Any permutation of your own real name, username, company name, or name of your website.
- A word from a dictionary, in any language.
- A short password.
- Any numeric-only or alphabetic-only password (a mixture of both is best).
A strong password is necessary not just to protect your blog content. A hacker who gains access to your administrator account is able to install malicious scripts that can potentially compromise your entire server.
In addition to using a strong password, it’s a good idea to enable two-step authentication as an additional security measure.
FTP
When connecting to your server you should use SFTP encryption if your web host provides it. If you are unsure if your web host provides SFTP or not, just ask them.
Using SFTP is the same as FTP, except your password and other data is encrypted as it is transmitted between your computer and your website. This means your password is never sent in the clear and cannot be intercepted by an attacker.
File Permissions
Some neat features of WordPress come from allowing various files to be writable by the web server. However, allowing write access to your files is potentially dangerous, particularly in a shared hosting environment.
It is best to lock down your file permissions as much as possible and to loosen those restrictions on the occasions that you need to allow write access, or to create specific folders with less restrictions for the purpose of doing things like uploading files.
Here is one possible permission scheme.
All files should be owned by your user account, and should be writable by you. Any file that needs write access from WordPress should be writable by the web server, if your hosting set up requires it, that may mean those files need to be group-owned by the user account used by the web server process.
/
The root WordPress directory: all files should be writable only by your user account, except .htaccess
if you want WordPress to automatically generate rewrite rules for you.
/wp-admin/
The WordPress administration area: all files should be writable only by your user account.
/wp-includes/
The bulk of WordPress application logic: all files should be writable only by your user account.
/wp-content/
User-supplied content: intended to be writable by your user account and the web server process.
Within /wp-content/
you will find:
/wp-content/themes/
Theme files. If you want to use the built-in theme editor, all files need to be writable by the web server process. If you do not want to use the built-in theme editor, all files can be writable only by your user account.
/wp-content/plugins/
Plugin files: all files should be writable only by your user account.
Other directories that may be present with /wp-content/
should be documented by whichever plugin or theme requires them. Permissions may vary.
Changing file permissions
If you have shell access to your server, you can change file permissions recursively with the following command:
For Directories:
find /path/to/your/wordpress/install/ -type d -exec chmod 755 {} \;
For Files:
find /path/to/your/wordpress/install/ -type f -exec chmod 644 {} \;
Regarding Automatic Updates
When you tell WordPress to perform an automatic update, all file operations are performed as the user that owns the files, not as the web server’s user. All files are set to 0644 and all directories are set to 0755, and writable by only the user and readable by everyone else, including the web server.
Database Security
If you run multiple blogs on the same server, it is wise to consider keeping them in separate databases each managed by a different user. This is best accomplished when performing the initial WordPress installation. This is a containment strategy: if an intruder successfully cracks one WordPress installation, this makes it that much harder to alter your other blogs.
If you administer MySQL yourself, ensure that you understand your MySQL configuration and that unneeded features (such as accepting remote TCP connections) are disabled. See Secure MySQL Database Design for a nice introduction.
Restricting Database User Privileges
For normal WordPress operations, such as posting blog posts, uploading media files, posting comments, creating new WordPress users and installing WordPress plugins, the MySQL database user only needs data read and data write privileges to the MySQL database; SELECT, INSERT, UPDATE and DELETE.
Therefore any other database structure and administration privileges, such as DROP, ALTER and GRANT can be revoked. By revoking such privileges you are also improving the containment policies.
Note: Some plugins, themes and major WordPress updates might require to make database structural changes, such as add new tables or change the schema. In such case, before installing the plugin or updating a software, you will need to temporarily allow the database user the required privileges.
WARNING: Attempting updates without having these privileges can cause problems when database schema changes occur. Thus, it is NOT recommended to revoke these privileges. If you do feel the need to do this for security reasons, then please make sure that you have a solid backup plan in place first, with regular whole database backups which you have tested are valid and that can be easily restored. A failed database upgrade can usually be solved by restoring the database back to an old version, granting the proper permissions, and then letting WordPress try the database update again. Restoring the database will return it back to that old version and the WordPress administration screens will then detect the old version and allow you to run the necessary SQL commands on it. Most WordPress upgrades do not change the schema, but some do. Only major point upgrades (3.7 to 3.8, for example) will alter the schema. Minor upgrades (3.8 to 3.8.1) will generally not. Nevertheless, keep a regular backup.
Securing wp-admin
Adding server-side password protection (such as BasicAuth) to /wp-admin/
adds a second layer of protection around your blog’s admin area, the login screen, and your files. This forces an attacker or bot to attack this second layer of protection instead of your actual admin files. Many WordPress attacks are carried out autonomously by malicious software bots.
Simply securing the wp-admin/
directory might also break some WordPress functionality, such as the AJAX handler at wp-admin/admin-ajax.php
. See the Resources section for more documentation on how to password protect your wp-admin/
directory properly.
The most common attacks against a WordPress blog usually fall into two categories.
- Sending specially-crafted HTTP requests to your server with specific exploit payloads for specific vulnerabilities. These include old/outdated plugins and software.
- Attempting to gain access to your blog by using « brute-force » password guessing.
The ultimate implementation of this « second layer » password protection is to require an HTTPS SSL encrypted connection for administration, so that all communication and sensitive data is encrypted. See Administration Over SSL.
Securing wp-includes
A second layer of protection can be added where scripts are generally not intended to be accessed by any user. One way to do that is to block those scripts using mod_rewrite in the .htaccess file. Note: to ensure the code below is not overwritten by WordPress, place it outside the # BEGIN WordPress
and # END WordPress
tags in the .htaccess file. WordPress can overwrite anything between these tags.
# Block the include-only files. <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^wp-admin/includes/ - [F,L] RewriteRule !^wp-includes/ - [S=3] RewriteRule ^wp-includes/[^/]+\.php$ - [F,L] RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L] RewriteRule ^wp-includes/theme-compat/ - [F,L] </IfModule> # BEGIN WordPress
Note that this won’t work well on Multisite, as RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
would prevent the ms-files.php file from generating images. Omitting that line will allow the code to work, but offers less security.
Securing wp-config.php
You can move the wp-config.php
file to the directory above your WordPress install. This means for a site installed in the root of your webspace, you can store wp-config.php
outside the web-root folder.
Note: Some people assert that moving wp-config.php has minimal security benefits and, if not done carefully, may actually introduce serious vulnerabilities. Others disagree.
Note that wp-config.php
can be stored ONE directory level above the WordPress (where wp-includes resides) installation. Also, make sure that only you (and the web server) can read this file (it generally means a 400 or 440 permission).
If you use a server with .htaccess, you can put this in that file (at the very top) to deny access to anyone surfing for it:
<files wp-config.php> order allow,deny deny from all </files>
Disable File Editing
The WordPress Dashboard by default allows administrators to edit PHP files, such as plugin and theme files. This is often the first tool an attacker will use if able to login, since it allows code execution. WordPress has a constant to disable editing from Dashboard. Placing this line in wp-config.php is equivalent to removing the ‘edit_themes’, ‘edit_plugins’ and ‘edit_files’ capabilities of all users:
define('DISALLOW_FILE_EDIT', true);
This will not prevent an attacker from uploading malicious files to your site, but might stop some attacks.
Plugins
First of all, make sure your plugins are always updated. Also, if you are not using a specific plugin, delete it from the system.
Firewall
There are many plugins and services that can act as a firewall for your website. Some of them work by modifying your .htaccess
file and restricting some access at the Apache level, before it is processed by WordPress. A good example is iThemes Security or All in One WP Security. Some firewall plugins act at the WordPress level, like WordFence and Shield, and try to filter attacks as WordPress is loading, but before it is fully processed.
Besides plugins, you can also install a WAF (web firewall) at your web server to filter content before it is processed by WordPress. The most popular open source WAF is ModSecurity.
A website firewall can also be added as intermediary between the traffic from the internet and your hosting server. These services all function as reverse proxies, in which they accept the initial requests and reroute them to your server, stripping it of all malicious requests. They accomplish this by modifying your DNS records, via an A record or full DNS swap, allowing all traffic to pass through the new network first. This causes all traffic to be filtered by the firewall before reaching your site. A few companies offer such service, like CloudFlare, Sucuri and Incapsula.
Additionally, these third parties service providers function as Content Distribution Network (CDNs) by default, introducing performance optimization and global reach.
Plugins that need write access
If a plugin wants write access to your WordPress files and directories, please read the code to make sure it is legit or check with someone you trust. Possible places to check are the Support Forums and IRC Channel.
Code execution plugins
As we said, part of the goal of hardening WordPress is containing the damage done if there is a successful attack. Plugins which allow arbitrary PHP or other code to execute from entries in a database effectively magnify the possibility of damage in the event of a successful attack.
A way to avoid using such a plugin is to use custom page templates that call the function. Part of the security this affords is active only when you disallow file editing within WordPress.
Security through obscurity
Security through obscurity is generally an unsound primary strategy. However, there are areas in WordPress where obscuring information might help with security:
- Rename the administrative account: When creating an administrative account, avoid easily guessed terms such as
admin
orwebmaster
as usernames because they are typically subject to attacks first. On an existing WordPress install you may rename the existing account in the MySQL command-line client with a command likeUPDATE wp_users SET user_login = 'newuser' WHERE user_login = 'admin';
, or by using a MySQL frontend like phpMyAdmin. - Change the table_prefix: Many published WordPress-specific SQL-injection attacks make the assumption that the table_prefix is
wp_
, the default. Changing this can block at least some SQL injection attacks.
Data Backups
Back up your data regularly, including your MySQL databases. See the main article: Backing Up Your Database.
Data integrity is critical for trusted backups. Encrypting the backup, keeping an independent record of MD5 hashes for each backup file, and/or placing backups on read-only media increases your confidence that your data has not been tampered with.
A sound backup strategy could include keeping a set of regularly-timed snapshots of your entire WordPress installation (including WordPress core files and your database) in a trusted location. Imagine a site that makes weekly snapshots. Such a strategy means that if a site is compromised on May 1st but the compromise is not detected until May 12th, the site owner will have pre-compromise backups that can help in rebuilding the site and possibly even post-compromise backups which will aid in determining how the site was compromised.
Logging
Logs are your best friend when it comes to understanding what is happening with your website, especially if you’re trying to perform forensics. Contrary to popular beliefs, logs allow you to see what was done and by who and when. Unfortunately the logs will not tell you who, username, logged in, but it will allow you to identify the IP and time and more importantly, the actions the attacker might have taken. You will be able to see any of these attacks via the logs – Cross Site Scripting (XSS), Remote File Inclusion (RFI), Local File Inclusion (LFI) and Directory Traversal attempts. You will also be able to see brute force attempts. There are various examples and tutorials available to help guide you through the process of parsing and analyzing your raw logs.
If you get more comfortable with your logs you’ll be able to see things like, when the theme and plugin editors are being used, when someone updates your widgets and when posts and pages are added. All key elements when doing forensic work on your web server. The are a few WordPress Security plugins that assist you with this as well, like the Sucuri Auditing tool or the Audit Trail plugin.
There are two key open-source solutions you’ll want on your web server from a security perspective, this is a layered approach to security.
OSSEC can run on any NIX distribution and will also run on Windows. When configured correctly its very powerful. The idea is correlate and aggregate all the logs. You have to be sure to configure it to capture all access_logs and error_logs and if you have multiple websites on the server account for that. You’ll also want to be sure to filter out the noise. By default you’ll see a lot of noise and you’ll want to configure it to be really effective.
Monitoring
Sometimes prevention is not enough and you may still be hacked. That’s why intrusion detection/monitoring is very important. It will allow you to react faster, find out what happened and recover your site.
Monitoring your logs
If you are on a dedicated or virtual private server, in which you have the luxury of root access, you have the ability easily configure things so that you can see what’s going on. OSSEC easily facilitates this and here is a little write up that might help you out OSSEC for Website Security – Part I.
Monitoring your files for changes
When an attack happens, it always leave traces. Either on the logs or on the file system (new files, modified files, etc). If you are using OSSEC for example, it will monitor your files and alert you when they change.
Goals
The goals of file system tracking include:
- Monitor changed and added files
- Log changes and additions
- Ability to revert granular changes
- Automated alerts
General approaches
Administrators can monitor file system via general technologies such as:
- System utilities
- Revision control
- OS/kernel level monitoring
Specific tools
Options for file system monitoring include:
- diff – build clean test copy of your site and compare against production
- Git – source code management
- inotify and incron – OS kernel level file monitoring service that can run commands on filesystem events
- Watcher – Python inotify library
- OSSEC – Open Source Host-based Intrusion Detection System that performs log analysis, file integrity checking, policy monitoring, rootkit detection, real-time alerting and active response.
Considerations
When configuring a file based monitoring strategy, there are many considerations, including the following.
Run the monitoring script/service as root
This would make it hard for attackers to disable or modify your file system monitoring solution.
Disable monitoring during scheduled maintenance/upgrades
This would prevent unnecessary notifications when you are performing regular maintenance on the site.
Monitor only executable filetypes
It may be reasonably safe to monitor only executable file types, such as .php files, etc.. Filtering out non-executable files may reduce unnecessary log entries and alerts.
Use strict file system permissions
Read about securing file permissions and ownership. In general, avoid allowing execute and write permissions to the extent possible.
Monitoring your web server externally
If the attacker tries to deface your site or add malware, you can also detect these changes by using a web-based integrity monitor solution. This comes in many forms today, use your favorite search engine and look for Web Malware Detection and Remediation and you’ll likely get a long list of service providers.
Resources
- How to Improve WordPress Security (Infographic)
- Security Plugins
- WordPress Security Cutting Through the BS
- e-Book: Locking Down WordPress
- wpsecure.net has a few guides on how to lock down WordPress.
- A Beginners Guide to Hardening WordPress
- Brad Williams: Lock it Up (Video)
- 21 Ways to Secure Your WordPress Site
- Official docs on how to password protect directories with an .htaccess file
- Simple tutorial on how to password protect the WordPress admin area and fix the 404 error
- AskApache Password Protection plugin for wp-admin/ and other directories Caution: Installing the AskApache Password Protection plugin may lock you out of your WordPress Admin panel. See the comments under the author’s plugin home page to read other users’ experiences with this plugin.