Secure Ninja Forms in Wordpress
Tags: wordpressplugins, virtru, encryption, wordpress
Published: 2020-01-30 18:28:07

---
title: Secure Ninja Forms in Wordpress
published: true
date: 2020-01-29 22:25:19 UTC
tags: wordpress-plugins,virtru,encryption,wordpress
canonical_url: 
---

Secure WordPress Ninja Form Submissions using the Virtru SDK

![](https://cdn-images-1.medium.com/max/1024/0*5hyVNHSCji0o6sre)<figcaption>Photo by <a href="https://unsplash.com/@webaroo?utm_source=medium&amp;utm_medium=referral">Webaroo.com.au</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption>

Welcome back to the Virtru Technology Blog! Today I will be sharing an idea that came from our digital marketer, Osman Sheikh ([Twitter](https://twitter.com/Osmanify)| [Medium](https://medium.com/@osmnshkh)). For our 2nd Annual [Virtru Hackathon](https://www.virtru.com/blog/virtru-hackathon-2019/.), he suggested using the [Virtru Developer Platform](https://developer.virtru.com) to encrypt content on Ninja Forms, a popular WordPress plugin. In his own words:

> As a digital marketer for Virtru, I have a love-hate relationship with [Wordpress](https://wordpress.com/). I have fond memories of building my first website on Wordpress.com, then moving to a self-hosted version after I managed to convince my parents that this whole internet thing wasn’t a fad. Since then I’ve built everything from personal websites to blogs to eCommerce sites for employers. I’ve also built plugins to enhance WordPress functionality.

> The reason I love Wordpress is the same reason I hate it. It’s an easy-to-use platform where marketers and developers alike can build simple websites in no time at all. It’s simplicity also means that plugins are required for any advanced functionality. While Wordpress is pretty secure out of the box, plugins can be created and published by anyone rendering your site and the data you collect insecure. Additionally, plugin overload can result in a bloated, slow and insecure site.

> We should build a simple solution in JavaScript that encrypts data collected by Ninja Form’s Wordpress plugin before it is exposed to insecure plugins or multi-tenant servers.

**Protect Form Data at Creation**

One of the most common WordPress attack vectors is form plugins. Most of them leave you exposed because they all have the same level of access, resulting in open season on the data collected by your site and its forms. Healthcare companies or nonprofits (with minimal IT resources) that want to collect customer data online without risking data loss, compliance violations, or site performance are limited in their options today.

The goal of this project is to extend the [Ninja Forms](https://ninjaforms.com/) extension using the [Virtru JavaScript SDK](https://docs.developer.virtru.com/js/latest/) to encrypt the form data. The data should be encrypted client-side and the submitter should be the owner. This ensures the data is never exposed server-side to insecure plugins or [multi-tenant servers](https://ninjaforms.com/docs/ninja-forms-secure/).

## Quick Links
  * [Requirements](#Requirements)
  * [Features](#Features)
  * [Installation](#Installation)
  * [End-User Experience](#End-User)
  * [Admin Management](#Admin)
  * [Authentication and Authorization](#Authentication)
  * [Code](#Code)
  * [Conclusion](#Conclusion)

### Requirements <a name="Requirements"></a>

- The latest version of [WordPress](https://wordpress.com)
- [Ninja Forms Plugin](https://ninjaforms.com/docs/add-on-manager/)
- [Virtru Ninja Forms Plugin Extension](https://github.com/virtru/wordpress-ninjaforms-secure)
- Email assigned to “WordPress Site Administrator”

### Features <a name="Features"></a>

#### User Features

- Virtru Encrypted Form submissions
- Site admin added to encryption policies
- Virtru Policy Manage Page

#### Admin Features

- Admin Authentication
- View Virtru Encrypted Data
- View Virtru Encryption Policy
- View Encryption Policy Admin
- Encrypted Export

### Installation <a name="Installation"></a>
<p><a href="https://virtruprivacy.wistia.com/medias/td2j6qwufy?wvideo=td2j6qwufy"><img src="https://embedwistia-a.akamaihd.net/deliveries/4969251828b71c47f7c4d496e6736d4480ab4ef9.jpg?image_play_button_size=2x&amp;image_crop_resized=960x540&amp;image_play_button=1&amp;image_play_button_color=54bbffe0" width="400" height="252.5" style="width: 400px; height: 252.5px;"></a></p>
#### Install

- Log in to WordPress as the Admin
- Install and Activate Ninja Forms
- Install and Activate Virtru for Ninja Forms

#### Secure Form

- Create a Ninja Form
- Add Ninja Form to a Post

### End-User Experience <a name="End-User"></a>
<p><a href="https://virtruprivacy.wistia.com/medias/h4h9il9a29?wvideo=h4h9il9a29"><img src="https://embedwistia-a.akamaihd.net/deliveries/f51ed4e4553cb2e976c961d0c585a9249c8fdd65.jpg?image_play_button_size=2x&amp;image_crop_resized=960x709&amp;image_play_button=1&amp;image_play_button_color=54bbffe0" width="400" height="295" style="width: 400px; height: 295px;"></a></p>
#### Form Usage

The user experience of Virtru + Ninja Forms is unchanged until the user clicks the submit button. When the user clicks submit, the data is caught by the Virtru extension. Virtru requires the data owner (form submitter) to authenticate the first time a user submits data. Once the data is encrypted, it is passed back to Ninja Forms for final processing and storage. The data is never left unencrypted on a server. When the submission is complete, the user is notified and offered a link to the policy management area.

#### Policy Management

The Policy Management area of the Virtru extension allows a user to:

- Add Users to a policy
- Remove Users from a policy
- Revoke policy

### Admin Management <a name="Admin"></a>
<p><a href="https://virtruprivacy.wistia.com/medias/kicr4oo9js?wvideo=kicr4oo9js"><img src="https://embedwistia-a.akamaihd.net/deliveries/b9aeeb110d477e03a89dbf8e1cfabcc06d2a874c.jpg?image_play_button_size=2x&amp;image_crop_resized=960x540&amp;image_play_button=1&amp;image_play_button_color=54bbffe0" width="400" height="300" style="width: 400px; height: 300px;"></a></p>
#### Authenticate

- Navigate to the _NF Virtru Plugin_ tab
- Follow steps to activate
- The admin can view Virtru Encrypted submitted data

#### View Submissions

- Navigate to the Ninja Forms Tab
- Navigate to the Submissions Area
- Select the appropriate form
- Click Edit on the appropriate record
- Click Decrypt to view the unencrypted submissions

### Authentication and Authorization <a name="Authentication"></a>

#### Why Authenticate?

The Virtru encryption policy controls who has access to the keys and policy ownership requires authentication. All policies are owned by the policy creator, the submitter. This means the submitter alone has access to add and remove people from the policy. To be active in the Virtru system, a user must be authenticated to ensure they are who they say they are.

#### Who Owns the Data?

For this implementation, the form submitter owns the data. This means that the submitter can always revoke their data via the policy management page. The data owner can also add and remove people from the policy.

#### Who Can Access the Data?

To ensure the data submitted can be used by the site, the site “Administration Email Address” is added to the security policy. The Administration Email Address is the email address located under **_Settings -> General._** The Administration Email Address can only view the data and cannot modify the policy. In the extension’s current state, the exported data stays encrypted. The only time the Site Admin can view the unencrypted data is from the record edit area of Ninja Forms.

#### Who Accessed the Data?

The [Virtru Audit Log](https://developer.virtru.com/docs/architecture#section-audit-access-over-time) tracks all access and modifications to the Virtru Policy giving the data owner complete visibility. This information enables the data owner to take action by adding or removing users and revoking access to the policy.

### To the Code <a name="Code"></a>

#### Form Submission Hook

To encrypt the form data, we must intercept the request prior to Ninja Forms storing the form data.

```
$.ajaxSetup({
        beforeSend: ajaxBeforeSend
});
```

Once caught, the settings object is inspected for:

- nf\_ajax\_submit
- isEncrypted: false

If the settings match, then the data object is encrypted and passed back to Ninja Forms for storage. The encryption flow operates as follows:

1. Authenticate against Virtru
2. Create Virtru client
3. Create encrypt options
4. Encrypt

### Authentication

I decided to leverage the Virtru Auth Widget to ensure authentication against the Virtru SaaS worked as expected and with minimal effort. Using the Virtru Auth Widget was as easy as adding a couple of lines.

```
wp\_enqueue\_script(‘auth-widget’, ‘https://sdk.virtru.com/js/latest/auth-widget/index.js', array(), false, true);
```

Now, we can use the Auth widget. We need to create an element in the DOM where we will mount the widget.

```
<div id=”[UNIQUE\_ID]”></div>
```

And then run code for the widget mounting

```
Virtru.AuthWidget(‘[UNIQUE\_ID]’, {OPTIONS});
```

In the second parameter, we can pass the options object. We pass in the _afterAuth_ method. This method will be triggered after the user successfully authenticates with Virtru.

#### Decrypt Form Data

When an admin opens a submission we can detect encrypted parts by the custom span we added during encryption. We use a similar flow for encryption:

1. Authenticate against Virtru
2. Create Virtru client
3. Create decrypt options
4. Decrypt

Ninja Forms plugin initializes Backbone during the work. So we can use Backbone listeners to detect rendering forms view.

```
jQuery(document).ready(($) => {
    const nfRadio = Backbone.Radio;
    const radioChannel = nfRadio.channel( 'file\_upload' );
    const uploadController = Marionette.Object.extend({
        initialize: function () {
            this.listenTo(radioChannel, 'render:view',
                this.updateFileUpload);
        },
        updateFileUpload: function (view) {
            const $file = $( view.el ).find( '.nf-element' );
            $file.fileupload({
                submit: function(e, data) {
                    if (!data.isEncrypted) {
                        e.preventDefault();
                        [MOUNT\_ENCRYPT\_APP]
                    }
                }
            });
        }
    });
    new uploadController();
});
```

#### Encrypt Form Data

Encryption looks very similar to decryption except that we return an HTML file. Why HTML? It’s simple to share across different platforms and easy for anyone to open in the [Virtru Secure Reader](https://secure.virtru.com/secure-reader).

```
const encryptedBuffer = await encryptedData.toBuffer();
const blobFile = new Blob([encryptedBuffer], {type: ‘text/html’});
const File = new File([blobFile], `${file.name}.tdf.html`, {type: “text/html”});
```

### Manage Policy

To make this extension useful for users and admins alike, we created a policy management page for both parties. We used React to build the policy management page. It includes the following functionality:

1. Encrypting data
2. Decrypting data
3. Adding/removing users
4. Downloading files
5. Revoking policy
6. Audit log

```
const policy = await client.fetchPolicy(policyId);
const updatedPolicy = policy.builder()
    .addUsersWithAccess(recipientEmail)
    .build();
await client.updatePolicy(newPolicy);
await client.revokePolicy(policyId);
```

### Conclusion <a name="Conclusion"></a>

Integrations always look easy from the outside, until you dig in. Starting with a fantastic Extension, Ninja Forms was the way to go. Leveraging their great documentation and large active community made the integration as painless as possible. The encryption portion was super easy as the widgets and encrypt/decrypt calls are very straight forward. By using this Virtru [project](https://github.com/virtru/wordpress-ninjaforms-secure), WordPress Administrators can secure their client’s most sensitive data with confidence.

* * *