Introduction

This is a GIF of a man putting on sunglasses and the text on the GIF reads, "Saftey is number one priority."

 

You are working on a new plugin or theme to sell to customers. You think to yourself, let’s just go ahead and process this form or button request. What can go wrong? Nonce so fast.

It’s always fun to develop a new code that provides direct value to the end-user. However, as good software developers, it’s essential that our code is also safe and secure. This will be part one of a multipart series of safe coding practices to consider when writing code, especially as it pertains to user input such as forms and button clicks.

Preface

This is a GIF of a man with a confused look his face and the text on the GIF reads, "What the hell does that mean?"
Before we dive into code, it will help to understand what nonces stand for and what role they fill in safe coding.

Definition

WordPress Codex describes nonces as the following.

A true nonce is a “number used once” to help protect URLs and forms from certain types of misuse, malicious or otherwise. WordPress nonce’s unfortunately aren’t single use, however they are called the same as they serve a much of the same purpose. – WP_Nonces

Role

One of the primary roles of nonces is to protect your websites from cross-site request forgery (CSRF) attacks. You could write a whole novel about CSRF attacks. However, in its simplest form, a CSRF attack can be employed to allow third parties to access sensitive information or resources on your website. For a deeper dive into CSRFs check out the Cross-Site Request Forgery video by Computerphile. (It’s taught by Tom Scott!!!)

Examples of Attacks

  1. Hijacking a bank transfer form. Send money to a bad guy bank account instead of your friend.
  2. Hijacking a purchase request. Additional items are added to your shopping carts, such as buying third-party market items like on eBay or Amazon.
  3. Hijacking a post update request. Malware is embedded into your blog update form. Now your website is infected and your viewers can become infected reading your blog post.
  4. Forces an account delete button. This could be done by a competitor or just people who want to destroy your site’s reputation.
  5. If you can think of something nasty, yes CSRF attacks can probably do it.

The Code

This is a hilarious GIF of a little boy running through a puddle with text saying, "I'm copying and pasting this code now," but then a white dog charges the boy, knocking him face-first into the puddle. The text reads, "Nope! LOL!" The boy gets up and the text reads, "Hmm, what if I copy and paste this code?" The dog charges and knocks the boy down again, and the text reads, "Nope! LOL!"Now that we have all the formalities out of the way let’s dig into some code! Fortunately implementing nonces in WordPress is extremely simple. Breaking it into its two parts you have:

  1. Create a nonce
  2. Validate the nonce

How you implement the two steps to nonces will vary on your project, in our example, we will show you how to incorporate it into a form.

Creating A Nonce

To create a nonce in WordPress, simply call  wp_nonce_field( $action = string, $name = string ); when constructing your form. The $action should be a unique key that you will use to validate the nonce once it has been submitted. $name is the variable name for the nonce when accessed in $_POST after the form has been submitted. To show how simple it is to add to a support formwp_nonce_field( 'support_form', 'support-nonce' ) in this example, the support_form is the action and the support-nonce is how what we will access to test the nonce value once the form is submitted.

Now when the form is displayed, a hidden input field will be added to our form to be sent off when it’s submitted. Since it’s hidden including it in our form won’t change the way it looks or feels.

This is an image of a Support Form with the fields: name, email, phone, notes, and a blue submit button. In this same image, beneath the support form, there is a screenshot of the code with a green arrow pointing at the line of code that includes, "input type = hidden," and "support-nonce."

Validating The Nonce

This is a popular GIF of Ken Jeong from the TV show Community sitting down with his legs up on a desk, while he's wearing a Mexican sombrero and the text reads, "I'll allow it."

Now that we have a nonce being submitted with our form, we now need to add our validation to ensure it’s valid. Where you place your validation code is crucial! Ensure that the validation happens before you access any values of the form, in a way consider the form submission invalid until it’s validated. To verify a nonce, we call wp_verify_nonce( $nonce, $action ). You’ll notice that the attributes are flipped from when we created it ¯\_(ツ)_/¯.

Since submitting a form happens via POST, we can access the nonce value by $_POST[‘support-nonce’].

 

Project: Code in Action

Now that we know how to protect our forms, let’s put that into action! The following video summarizes what we just learned, as well as provides a demonstration taking the code we just learned and integrating it into a real project.

Repo without Nonces: https://github.com/Oceas/wp-security-form

Repo with Nonces: https://github.com/Oceas/wp-security-form/tree/feature/nonce

 

Conclusion

Just two lines of code create and validate. Now, your form inputs are infinitely more secure. But, good coding practices don’t stop here. Over the course of October, I’ll be writing a series of blog posts about safer coding practices including discussions about sanitization and form validation. Subscribe to get notified when these are published.

Comments

Have a comment?

Your email address will not be published. Required fields are marked *

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress