With the Drupalgeddon2 "trauma" still “haunting” us all — both Drupal developers and Drupal end-users — we've convinced ourselves that prevention is, indeed, (way) better than recovery. And, after we've put together, here on this blog, a basic security checklist for Drupal websites and revealed to you the 10 post-hack “emergency” steps to take, we've decided to dig a bit deeper. To answer a legitimate question: “What are some good ways to write secure Drupal code?”

For, in vain you:
 

  • build a “shield” of the best Drupal security modules and plugins around your website
  • enforce a rigid workplace security policy 
     

… if you leave its code vulnerable to various types of cyber attacks, right?

  • But how do I know how unsecured code looks like, to begin with?
  • What are the site configuration gotchas that I should pay attention to?
  • What are the most common vulnerabilities that I risk exposing my Drupal site to?
  • And how can I test it for security issues that might be lurking in its code?

But most of all: What top secure coding practices should I and my Drupal development team follow?

Now, let's get you some answers:
 

1. SQL Injection Vulnerabilities: How You Can Fix & Prevent Them 

SQL injections sure make one of the most “banal”, nonetheless dreadful types of attacks. Once such vulnerabilities are exploited, the attacker gets access to sensitive data on your Drupal site.
 

1.1. Prevent SQL Injection Attacks Using The Database Abstraction Layer

In other words: the proper use of a database layer makes the best shield against any SQL injection exploit attempts.

Now, let's talk... code.

For instance, linking together data right into the SQL queries does not stand for a secure coding practice:

db_query('SELECT foo FROM {table} t WHERE t.name = '. $_GET['user']);

In this case here, this is how you write secure Drupal code:

db_query("SELECT foo FROM {table} t WHERE t.name = :name", [':name' => $_GET['user']]);

Notice the usage of the proper argument substitution with db_query. The database abstraction layer uses a whole range of named placeholders and works on top of the PHP PDO.

Now, as for a scenario requesting a variable number of arguments, you can use either db_select() or an array of arguments:

$users = ['joe', 'poe', $_GET['user']];
db_query("SELECT t.s FROM {table} t WHERE t.field IN (:users)",  [':users' => $users]);
$users = ['joe', 'poe', $_GET['user']];
$result = db_select('table', 't')
  ->fields('t', ['s'])
  ->condition('t.field', $users, 'IN')
  ->execute();

1.2. Have You Detected an SQL Injection Vulnerability? Here's How You Can Fix It

There are some key Drupal security best practices to follow for addressing SQL injection issues:
 

  • always stick to the well-known Drupal database API
  • always filter the parameters that you get (be twice as vigilant and cautious about those who can type anything on your Drupal site)
  • always use placeholders: db_query with :placeholder
  • always check the queries in the code: db_like()
     

Tip: remember to follow these coding practices for addressing and preventing SQL injections on your contrib modules, as well.
 

2. How to Protect Your Drupal Site Against Cross-Site Scripting (XSS) Attacks

We could easily say that XSS attacks “rival” SQL injection attacks in “popularity”:

Drupal's highly vulnerable to cross-site scripting.

All it takes is some wrong settings — input, comment, full HTML — as you configure your website, to make it vulnerable to this type of attacks:

They make a convenient gateway into your website for remote attackers to use to inject HTML or arbitrary web.
 

2.1. Check Functions to Rely on for Sanitizing the User Input (in Drupal 7)

Securing your Drupal 7 site against cross-site scripting attacks always starts with:

Identifying the very “source” of that submitted data/text.

Now, if the “culprit” is a user-submitted piece of content, depending on its type you have several check functions at hand to use for sanitizing it:
 

  • check_url
  • check_plain (for plain text)
  • filter_xss (when dealing with pure HTML)
  • filter_xss_admin (if it's an admin user that entered the “trouble-making” text)
  • check_markup
     

Note: always remember never to enter the user input as-is into HTML!

Tip: a good way to write secure Drupal code is to use t() with % or @ placeholders for putting together translatable, safe strings.
 

2.3. Cross-Site Scripting In Drupal 8: Twig & 3 Useful Sanitization Methods

In Drupal 8, handling cross-site scripting attacks gets significantly easier.

Here's why:
 

  • you have TWIG, with its autoescaping and “sanitize all” HTML mechanism!!!
  • no SQL queries
  • no access to Drupal APIs
     

Now, besides Twig, you have 3 more sanitizing methods at hand for fixing cross-site scripting issues in Drupal 8:
 

  1. HTML: :escape(), for plain text
  2. Xss: :filterAdmin(), for admin-submitted content
  3. Xss: :filter(), where HTML can be used
     

2.4. Testing Your Code Against XSS

In order to check whether certain user inputs are vulnerable, all you need to do is:
 

  • take the “suspicious” user input as a field, as an input HTML
  • enter them both (or just one of them) in your test
     

Note: feel free to user Behat or another framework of choice to automate the whole process.

2 clear signs that you've detected an XSS vulnerability are:
 

  1. you get this pop up alert: <script>altert ('xss') </script>
  2. or this error message close to the IMG tag: img src="a" onerror="alert ('title')"
     

3. Use Twig Templates: They Sanitize All Output...  Automatically 

Did you know that a lot of the Drupal security issues on your website occur precisely because you've skipped sanitizing the user-submitted content before displaying it?

And someone's neglect quickly turns into another one's opportunity...

By skipping to clean up that text beforehand, you lend the attacker a “helping hand” with exploiting your own Drupal site.

Now, getting back to why using Twig templates is one of the best ways to write secure Drupal code:
 

  • they sanitize the user input and output (all HTML, basically) by default; you can write your custom code without worrying about it risking to break up your website
  • you won't run the risk of having safe markup escaped


In short: securing your Drupal 8 website is also about having all HTML outputted from Twig templates.
 

4. How to Write Secure Drupal Code for Finding & Fixing Access Bypass Issues

One of Drupal's strongest “selling points” is precisely its granular permission system. Its whole infrastructure of user roles with different levels of permissions assigned to them.

Furthermore, there are all kinds of access controls that you can “juggle with”:
 

  • Node access system
  • field access
  • Views access control
  • Entity access
     

In short: you're free to empower users to access different sections/carry out different operations on your Drupal site.
 

4.1. How You Can Check for Access Bypass Issues

How do you know whether there are access bypass flaws on your website, that could be easily exploited?

It's easy:
 

  • you simply visit some nid/node and other URL on your site 
  • and just run your Behat automated tests
     

4.2. And How You Can Fix the Identified Access Bypass Issues

Do keep in mind that there are quite a few access callbacks to consider:
 

  • entity_access
  • user_access for  permissions
  • Squery – addTag ('node_access')
  • Menu definitions (make sure you set those correctly)
  • node_access

All you need to do is write automated tests to address any detected problems related to access bypass.
 

5. 3 Ways Deal With Cross-Site Request Forgery (CSRF) in Drupal 

What does it take to write secure Drupal code? 

Writing it... strategically, so that it should prevent any possible cross-site request forgery attack...

Now, here are 3 ways to safeguard it from such exploits:
 

  1. sending and properly validating the token
  2. using Form API
  3. using the built-in csrf_token in Drupal 8
     

In conclusion: a trio of good practices keeps the CSRF attacks away...
 

6. 7 Best Contrib Security Modules to Back Up Your Coding With

Now, after we've gone through some of the best ways to write secure Drupal code, let's see which are the most reliable contrib security modules to strengthen your site's shield with:

 

  1. Hacked!      
  2. Permission report  
  3. Encrypt      
  4. Composer Security Checker        
  5. Security Review          
  6. Paranoia      
  7. Text Formats Report
     

The END! This is how your solid Drupal security “battle plan” could look like. It includes:
 

  • some of the most frequent types of attacks and security issues to pay attention to
  • most effective preventive measures
  • vulnerability detecting methods
  • post-attack emergency actions and sanitization mechanisms
     

What ways to write secure Drupal code would you have added or removed from this list?

Recommended Stories

How to Create and Manage a Content Workflow in Drupal 8: Either a Standard or a Custom One
"A Drupal 8 initiative to improve Drupal's content workflow", this is how Dries Buytaert first defined the… (Read more)
Adriana Cacoveanu / Nov 14 '2018
AI vs Machine Learning: Is AI Different from Machine Learning? Or Are They the Same Thing?
AI, AR, VR, ML, DL... AR vs Machine Learning: is there a difference between these 2 technologies? Which one(s)?… (Read more)
Adriana Cacoveanu / Nov 12 '2018
Predictive UX in Drupal: Can We Create Anticipated User Experiences in Drupal 8?  
What do you get when you put together: Drupal 8 + AI + UX? Drupal8's content management features and integration… (Read more)
Silviu Serdaru / Nov 8 '2018