Two-factor Authentication on VIP Go

Two-factor authentication (also known as multi-factor authentication and 2fa) is a method of securing accounts which requires a user to know something (e.g. a password) but also that you possess something (e.g. your mobile device). This method of requiring multiple forms of verification is an easy to way to protect your sites against common account breaches due to leaked or guessed passwords. Two-factor authentication is integrated with all WordPress sites on the VIP Platform and easy to use and enforce.

Enabling Two-Factor Authentication

If you have a WordPress account, to enable Two-factor authentication, just visit Users > Your Profile and enable your preferred authentication methods in the Two-Factor Options section.

Enforcing Two-factor Authentication

Two-factor authentication is required on VIP Go for all administrators and custom roles with the manage_options capability. If you’d like to force two factor authentication for other roles, you can use the wpcom_vip_is_two_factor_forced filter. For example, to enable for all users that can edit posts:

add_action( 'set_current_user', function() { 
    $limited = current_user_can( 'edit_posts' );
    add_filter( 'wpcom_vip_is_two_factor_forced', function() use ( $limited ) {
        return $limited;
    }, PHP_INT_MAX );
} );

Or, to enable for all users on the site:

add_filter( 'wpcom_vip_is_two_factor_forced', '__return_true' );

Disable Two-factor Authentication Enforcement

If you’re using an external auth provider that already enforces two-factor authentication, you can choose disable enforcement for users on the site. You can add this to a file inside your client-mu-plugins folder. (Note that with this snippet, the built-in two factor options will still be available to users).

add_filter( 'wpcom_vip_is_two_factor_forced', '__return_false' );

If you’d like to remove the built-in Two-factor options completely, you can add the following snippet to a file inside your client-mu-plugins folder:

add_filter( 'wpcom_vip_enable_two_factor', '__return_false' );

Resetting Two-Factor Authentication for Locked Out Users

There are two primary methods available for both admin and super admin user roles to disable two-factor authentication for users that are locked out of their account.

Prior to disabling two-factor authentication, we highly recommend confirming that the user has indeed lost access to their account. Since emails can be faked, we recommend confirming with the individual in person or over the phone.

To disable two-factor authentication, you can do either of the following from the Dashboard under Users > Edit > Two-Factor Options:

  • Deselect all available two-factor methods. This will allow the user to login without needing any additional code.
  • Enable the Backup Codes option. Then, you can send a backup code to the user that they can use to login to their account.

Once the user regains access to the account, they can adjust any two-factor settings to prevent losing access moving forward (reset phone number, for example). We also recommend having them print out backup codes to prevent future lockouts.

JavaScript security best practices

The primary vulnerability we need to be careful of in JavaScript is Cross Site Scripting (XSS). In WordPress with PHP, we use escaping functions to avoid that — esc_html(), esc_attr(), esc_url(), etc. Given that, it only seems natural that we would also need to escape HTML in JavaScript.

As it turns out out, however, that’s the wrong way to approach JavaScript security. To avoid XSS, we want to avoid inserting HTML directly into the document and instead, programmatically create DOM nodes and append them to the DOM. This means avoiding .html(), .innerHTML, and other related functions, and instead using .append(), .prepend(), .before(), .after(), and so on.

Here is an example:

jQuery.ajax({
    url: 'http://any-site.com/endpoint.json'
}).done( function( data ) {
    var link = '<a href="' + data.url + '">' + data.title + '</a>';

    jQuery( '#my-div' ).html( link );
});

This approach is dangerous, because we’re trusting that the response from any-site.com includes only safe data – something we can not guarantee, even if the site is our own. Who is to say that data.title doesn’t contain alert( "haxxored");;?

Instead, the correct approach is to create a new DOM node programmatically, then attach it to the DOM:

jQuery.ajax({
    url: 'http://any-site.com/endpoint.json'
}).done( function( data ) {
    var a = jQuery( '<a />' );
    a.attr( 'href', data.url );
    a.text( data.title );

    jQuery( '#my-div' ).append( a );
});

Note: It’s technically faster to insert HTML, because the browser is optimized to parse HTML. The best solution is to minimize insertions of DOM nodes by building larger objects in memory, then insert it into the DOM all at once, when possible.

By passing the data through either jQuery or the browser’s DOM API’s, we ensure the values are properly sanitized and remove the need to inject insecure HTML snippets into the page.

To ensure the security of your application, use the DOM APIs provided by the browser (or jQuery) for all DOM manipulation.

Escaping Dynamic JavaScript Values

When it comes to sending dynamic data from PHP to JavaScript, care must be taken to ensure values are properly escaped. The core function esc_js() helps escape JavaScript for us in DOM attributes, while all other values should be encoded with json_encode().

From the WP Codex on esc_js():

It is intended to be used for inline JS (in a tag attribute, for example onclick=”…”).

If you’re not working with inline JS in HTML event handler attributes, a more suitable function to use is json_encode, which is built-in to PHP.

This approach is incorrect:

var title = '<?php echo esc_js( $title ); ?>';
var content = '<?php echo esc_js( $content ); ?>';
var comment_count = '<?php echo esc_js( $comment_count ); ?>';

Instead, it’s better to use json_encode() (note that json_encode() adds the quotes automatically):

var title = <?php echo wp_json_encode( $title ); ?>;
var content = <?php echo wp_json_encode( $content ); ?>;
var comment_count = <?php echo wp_json_encode( $comment_count ); ?>;

Stripping Tags

It may be tempting to use .html() followed by .text() to strip tags – but this approach is still vulnerable to attack:

// Incorrect
var text = jQuery('<div />').html( some_html_string ).text();
jQuery( '.some-div' ).html( text );

Setting the HTML of an element will always trigger things like src attributes to be executed, which can lead to attacks like this:

// XSS attack waiting to happen
var some_html_string = '<img src="a" onerror="alert('haxxored');" />';

As soon as that string is set as a DOM element’s HTML (even if it’s not currently attached to the DOM!), src will be loaded, will error out, and the code in the onerror handler will be executed…all before .text() is ever called.

The need to strip tags is often indicative of bad practices – remember, always use the appropriate API for DOM manipulation.

// Correct
jQuery( '.some-div' ).text( some_html_string );

Using encodeURIComponent()

When using values as part of a URL, for example when adding parameters to a URL or building a mailto: link the JavaScript variables need to be encoded to be correctly interpreted by the browser. Using encodeURIComponent() will ensure that the characters you use will be properly interpreted by the browser. This also helps prevent some trickery such as adding & which may cause the browser to incorrectly interpret the values you were expecting. You can find more information on this on the OWASP website.

Using DOMPurify

As mentioned above, using jQuery’s .html() function or React’s dangerouslySetInnerHTML() function can open your site to XSS vulnerabilities by treating arbitrary strings as HTML. These functions should be avoided whenever possible. While it’s easy to think content from your own site is “safe,” it can become an attack vector if a user’s account is compromised or if another part of the application is not doing enough validation.

While we recommend that first you try to use structured data and build the HTML inside the JavaScript, that’s not always feasible. If you do need to include HTML strings inside your JavaScript, we recommend using the DOMPurify package to sanitize strings to remove executable elements that could contain attack vectors. This is very similar to how WP_KSES works.

To use DOMPurify you need to include it as such:

/**
 * For Browsers
 */
import DOMPurify from 'dompurify';
// or
const DOMPurify = require('dompurify');

/**
 * For Node.js we need JSDOM's window
 */
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom'); 
const window = (new JSDOM('')).window;
const DOMPurify = createDOMPurify(window);

You can then call it as such:

const clean = DOMPurify.sanitize(dirty);

Here are a few examples taken from the DOMPurify Readme:

DOMPurify.sanitize('<img src=x onerror=alert(1)//>'); // becomes <img src="x">
DOMPurify.sanitize('
abc<iframe/\/src=jAva&amp;Tab;script:alert(3)>def'); // becomes 

abcdef

DOMPurify.sanitize('

<math><mi//xlink:href="data:x,<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3Ealert(4)%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&amp;lt;script&amp;gt;" title="&amp;lt;script&amp;gt;" />">'); // becomes 

<math><mi></mi></math>


DOMPurify.sanitize('
<TABLE>
<tr>
<td>HELLO</tr>

</TABL>'); // becomes 

// =>

<table>
<tbody>
<tr>
<td>HELLO</td>
</tr>
</tbody>

DOMPurify.sanitize('<UL>
<li><A HREF=//google.com>click</UL>
'); // becomes 

<ul>
<li><a href="//google.com">click</a></li>
</ul>
</table>

Other Common XSS Vectors

  • Using eval(). Never do this.
  • Un-whitelisted / un-sanitized data from urls, url fragments, query strings, cookies
  • Including untrusted / unreviewed third-party JS libraries
  • Using outdated / unpatched third-party JS libraries

Helpful Resources

Validating, sanitizing, and escaping

Your code works, but is it safe? When writing your theme and plugin code, you’ll need to be extra cautious of how you handle data coming into WordPress and how it’s presented to the end user. This commonly comes up when building a settings page for your theme, creating and manipulating shortcodes, or saving and rendering extra data associated with a post. There is a distinction between how input and output are managed, and this document will walk you through that.

(If you’re interested in more thoughts on why WordPress.com VIP takes these practices so seriously, read The Importance of Escaping All The Things from June 2014.)

Guiding Principles

  1. Never trust user input.
  2. Escape as late as possible.
  3. Escape everything from untrusted sources (like databases and users), third-parties (like Twitter), etc.
  4. Never assume anything.
  5. Never trust user input.
  6. Sanitation is okay, but validation/rejection is better.
  7. Never trust user input.

“Escaping isn’t only about protecting from bad guys. It’s just making our software durable. Against random bad input, against malicious input, or against bad weather.”
–nb

Validating: Checking User Input

To validate is to ensure the data you’ve requested of the user matches what they’ve submitted. There are several core methods you can use for input validation; usage obviously depends on the type of fields you’d like to validate. Let’s take a look at an example.

Say we have an input area in our form like this:

<input id="my-zipcode" type="text" maxlength="5" name="my-zipcode" />

Just like that, we’ve limited my user to five characters of input, but there’s no limitation on what they can input. They could enter “11221” or “eval(“. If we’re saving to the database, there’s no way we want to give the user unrestricted write access.

This is where validation plays a role. When processing the form, we’ll write code to check each field for its proper data type. If it’s not of the proper data type, we’ll discard it. For instance, to check “my-zipcode” field, we might do something like this:

$safe_zipcode = intval( $_POST['my-zipcode'] );
if ( ! $safe_zipcode )
$safe_zipcode = '';
update_post_meta( $post->ID, 'my_zipcode', $safe_zipcode );

The intval() function casts user input as an integer, and defaults to zero if the input was a non-numeric value. We then check to see if the value ended up as zero. If it did, we’ll save an empty value to the database. Otherwise, we’ll save the properly validated zipcode.

Note that we could go even further and make sure the the zip code is actually a valid one based on ranges and lengths we expect (e.g. 111111111 is not a valid zip code but would be saved fine with the function above).

This style of validation most closely follows WordPress’ whitelist philosophy: only allow the user to input what you’re expecting. Luckily, there’s a number of handy helper functions you can use for most data types.

Sanitizing: Cleaning User Input

Sanitization is a bit more liberal of an approach to accepting user data. We can fall back to using these methods when there’s a range of acceptable input.

For instance, if we had a form field like this:

<input id="title" type="text" name="title" />

We could sanitize the data with the sanitize_text_field() function:

$title = sanitize_text_field( $_POST['title'] );
update_post_meta( $post->ID, 'title', $title );

Behind the scenes, the function does the following:

  • Checks for invalid UTF-8
  • Converts single < characters to entity
  • Strips all tags
  • Remove line breaks, tabs and extra white space
  • Strip octets

The sanitize_*() class of helper functions are super nice for us, as they ensure we’re ending up with safe data and require minimal effort on our part.

In some instances, using wp_kses and it’s related functions might be a good idea as you can easily clean HTML while keeping anything relevant to your needs present.

Escaping: Securing Output

For security on the other end of the spectrum, we have escaping. To escape is to take the data you may already have and help secure it prior to rendering it for the end user. WordPress thankfully has a few helper functions we can use for most of what we’ll commonly need to do:

esc_html() we should use anytime our HTML element encloses a section of data we’re outputting.


<h4><?php echo esc_html( $title ); ?></h4>

esc_url() should be used on all URLs, including those in the ‘src’ and ‘href’ attributes of an HTML element.

<img alt="" src="<?php echo esc_url( $great_user_picture_url ); ?>" />

esc_js() is intended for inline Javascript.

<div onclick='<?php echo esc_js( $value ); ?>' />

esc_attr() can be used on everything else that’s printed into an HTML element’s attribute.

<ul class="<?php echo esc_attr( $stored_class ); ?>">

wp_kses() can be used on everything that is expected to contain HTML.  There are several variants of the main function, each featuring a different list of built-in defaults.  A popular example is wp_kses_post(), which allows all markup normally permitted in posts. You can of course roll your own filter by using wp_kses() directly.

<?php echo wp_kses_post( $partial_html ); echo wp_kses( $another_partial_html , array( 'a' => array(
        'href' => array(),
        'title' => array()
    ),
    'br' => array(),
    'em' => array(),
    'strong' => array(),
);) ?>

As an example, passing an array to wp_kses() containing the member

'a' => array( 'href' , 'title', )

means that only those 2 HTML attributes will be allowed for a tags — all the other ones will be stripped. Referencing a blank array from any given key means that no attributes are allowed for that element and they should all be stripped.

There has historically been a perception that wp_kses() is slow. While it is a bit slower than the other escaping functions, the difference is minimal and does not have as much of an impact as most slow queries or uncached functions would.

It’s important to note that most WordPress functions properly prepare the data for output, and you don’t need to escape again.

<h4><?php the_title(); ?></h4>

rawurlencode() should be used over urlencode() for ensure URLs are correctly encoded. Only legacy systems should use urlencode()`.

<?php echo esc_url( 'http://example.com/a/safe/url?parameter=' . rawurlencode( $stored_class ) ); ?>

Always Escape Late

It’s best to do the output escaping as late as possible, ideally as data is being outputted.

// Okay, but not that great
$url = esc_url( $url );
$text = esc_html( $text );
echo '<a href="'. $url . '">' . $text . '</a>';

// Much better!
echo '<a href="'. esc_url( $url ) . '">' . esc_html( $text ) . '</a>';

This is for a few reasons:

  • It makes our code reviews and deploys happen faster because rather than hunting through many lines of code, we can glance at it and know it’s safe for output.
  • Something could inadvertently change the variable between when it was firstly cast and when it’s outputted, introducing a potential vulnerability.
  • Future changes could refactor the code significantly. We review code under the assumption that everything is being output escaped/cast – if it’s not and some changes go through that make it no longer safe to output, we may incorrectly allow the code through, since we’re assuming it’s being properly handled on output.
  • Late escaping makes it easier for us to do automatic code scanning (saving us time and cutting down on review/deploy times) – something we’ll be doing more of in the future.
  • Escaping/casting on output simply removes any ambiguity and adds clarity (always develop for the maintainer).

Escape on String Creation

It is sometimes not practical to escape late. In a few rare circumstances you cannot pass the output to wp_kses since by definition it would strip the scripts that are being generated.

In situations like this always escape while creating the string and store the value in a variable that is a postfixed with _escaped, _safe or _clean. So instead of $variable do $variable_escaped or $variable_safe.

If a function cannot output internally and late escape, then it must always return “safe” html, that does not rely on them being late escaped. This allows you to do echo my_custom_script_code(); without needing the script tag to be passed through a version of wp_kses that would allow such tags.

Case Studies and FAQs

We know that validating, sanitizing and escaping can be a complex topic; we’ll add some specific case studies and frequently asked questions here as we think they might be helpful.

Q: Doesn’t a function like WP_Query handle sanitizing user input before running a query for me? Why do I need to also sanitize what I send to it?

A: For maximum security, we don’t want to rely on WP_Query to sanitize our data and hope that there are no bugs or unexpected interactions there now or in the future. It’s a good practice to sanitize anything coming from user-land as soon as you begin to interact with it, treating it as potentially malicious right away.

Q: Isn’t WP_KSES_* slow?
A: Even on large strings WP_KSES_* will not add a significant overhead to your pageload. Most of your pageloads should be cached pageloads and the first thing to focus on should be to make sure as many of your end users as possible are getting cached pages. Slow SQL Queries as well as Remote requests are often next on the list. Escaping is often negligible compared to those items.

Zack Tollman wanted to know more about wp_kses functions, so he did a pretty thorough investigation about them here. https://www.tollmanz.com/wp-kses-performance/. He found that wp_kses functions can be 20-40x slower than esc_* functions on PHP 5.6, but the performance hit is much smaller when using HHVM. The post was written before PHP 7 came out, but PHP 7 is likely to have similar performance to HHVM, meaning that wp_kses functions aren’t as much as a performance drain as they used to be, at least on PHP 7 servers. WordPress.com is using PHP 7.

Q: Why do I need to escape these values? It is impossible for them to be unsafe.
A: It is currently impossible for them to be unsafe. But a later code change could easily make it that the variable is modified and therefore can no longer be trusted. Always late escaping whenever possible makes the code much more robust and future proof.

Conclusion

To recap: Follow the whitelist philosophy with data validation, and only allow the user to input data of your expected type. If it’s not the proper type, discard it. When you have a range of data that can be entered, make sure you sanitize it. Escape data as much and as late as possible on output to avoid XSS and malformed HTML.

Take a look through the Data Validation Plugin Handbook page  to see all of the sanitization and escaping functions WordPress has to offer.

ACF 5 and VIP Go

Advanced Custom Fields (ACF) is a popular plugin that many VIP clients choose to use on their sites. However, ACF is not available for clients on the WordPress.com VIP platform, and has not undergone a full, line-by-line review for use on VIP Go. Clients wishing to use ACF on VIP Go accept the security and performance risks of using it. This page outlines some additional steps needed to make ACF more secure and performant, but should not be interpreted as the equivalent of a line-by-line review, or VIP’s approval of the plugin.

Please note that while ACF 5 can be used on most VIP Go sites, ACF 4 is unavailable. If in doubt about whether ACF is allowed for use on your VIP site, please contact us.

When using ACF 5 and ACF 5 Pro, several additional steps are needed in order to make ACF secure, and avoid performance issues:

  • Hide the Admin UI
  • Define fields in PHP
  • Use taxonomies for searchable fields
  • Avoid the_field and escape
  • Secure fields that allow arbitrary output

Hide the ACF Admin UI

The fields UI can be used to add arbitrary fields, including unsafe fields. For example it can allow an admin to display the passwords of users. You can disable the UI using this filter:


add_filter('acf/settings/show_admin', '__return_false');

Define Fields in PHP

In order to make sure that all ACF usage is secure, define the fields in PHP or local json, rather than at runtime. This way they remained versioned and safe. This can be done via the import export menu of a local developer environment to setup the fields available and export them to PHP.

Documentation on how to do this can be found here on the ACF website.

Alternatively, fields can be defined via the local JSON feature as described here, but keep in mind that saving local JSON will not work in production as the filesystem is read only, nor is it desirable as it would bypass the security benefits.

Being Mindful of Taxonomy Term Storage

If an ACF field is going to be queried, filtered, or searched for in a post query, use the taxonomy data checkbox so that the field is stored as a term, not a post meta value. This ensures performance is not impacted by expensive meta queries on the frontend

the_field and Escaping

the_field has no context as to when or where it is called. So how is it to know if it should be using esc_url, esc_attr or wp_kses_post? It doesn’t, which makes it dangerous from a security point of view. Instead, use get_field in combination with an escaping function, e.g.

$url = get_field( 'custom_link' );
echo esc_url( $url );

Flexible content is the exception to this, and should be clearly marked on usage via comments

Fields That Use Arbitrary Output

If the field types that allow arbitrary output are to be used, they must be accounted for in the acf/format_value and equivalent filters such as acf/format_value/type=textarea.

For example:

function vip_make_acf_text_areas_safe( $value, $post_id, $field ) {
	return wp_kses_post( $value );
}

add_filter('acf/format_value/type=textarea', 'vip_make_acf_text_areas_safe', 10, 3);

This way different escaping can be applied via different `$field` values. Alternatively, if all fields of that type use the same escaping, this can be done instead:

add_filter('acf/format_value/type=textarea', 'wp_kses_post', 10, 1);

For more information, see: https://www.advancedcustomfields.com/resources/acf-format_value/

Ready to get started?

Drop us a note.

No matter where you are in the planning process, we’re happy to help, and we’re actual humans here on the other side of the form. 👋 We’re here to discuss your challenges and plans, evaluate your existing resources or a potential partner, or even make some initial recommendations. And, of course, we’re here to help any time you’re in the market for some robust WordPress awesomeness.