Securing your WordPress website is an aspect you can’t ignore unless you want to expose your customers’ data and online safety. What’s more, compliance maintenance regarding relevant standards and regulations should be a priority, too. In fact, security monitoring and compliance often go hand in hand, with equal importance.
Implementing both of these can be a challenge, though, especially when you have lots of sites to manage. However, with the Kinsta API’s multitude of endpoints, you have programmatic access to our secure site hosting, which you can further automate and work with.
For this post, we’ll explore how you can leverage the Kinsta API to strengthen your WordPress security and how you can potentially go further than what the MyKinsta dashboard provides.
We’ll also cover your site’s ongoing data compliance strategy. Once we explore the capabilities of the Kinsta API, you’ll get a practical walkthrough of how to integrate security monitoring and compliance into your WordPress workflow.
Understanding continuous security monitoring and compliance
Your website has immense value to certain groups. Malicious users don’t see your products and services—they see data and opportunities to gain. In 2022, SiteLock found that the average site suffered around 100 attacks every day.
As such, monitoring your security on a continuous basis while also checking your level of compliance is vital. Malicious intent is dynamic, which means you need to assess, track, and address your security provisions on an ever-evolving basis. For example, the OWASP Top 10 monitors which types of malicious attacks are the most popular, and this list changes at every survey.
There are plenty of other reasons why you’d want to implement continuous security monitoring, too:
- You can be proactive when it comes to identifying and responding to potential threats.
- Regular monitoring means your site security remains strong and focused on protection.
- You’re able to ensure consistent and up-to-date compliance with typical industry standards and data protection guidelines.
- At a core level, you can reduce the risk of ‘leaking’ data from your site and eroding your reputation.
For WordPress websites, your monitoring and compliance strategy has even greater importance and challenges:
- WordPress offers inherent security, but the platform has a target on its back, thanks to its market share.
- Of course, there’s the complexity of the theme and plugin ecosystems to also monitor.
- If you run multiple sites, you need to ensure a consistent and reliable monitoring strategy is in place.
- Integrating security monitoring seamlessly into existing development workflows
The good news is that you can easily integrate security monitoring into your existing workflow and combine it with WordPress update notifications. Even better, you can control this through the Kinsta API.
A brief primer on the Kinsta API
For Kinsta customers, the API represents the best way to automate and leverage many aspects of your hosting server. We offer plenty of endpoints for all sorts of tasks. For instance, you can manage sites, users, and dependencies such as site themes and plugins. In addition, you can fetch logs and access the same application metrics from the MyKinsta dashboard:
Of course, integrating the Kinsta API into your WordPress workflow will be a breeze, given our big focus on WordPress hosting. You’ll find out how to do this later on. We offer a proactive and programmatic way to handle your security monitoring for key WordPress facets. This includes site updates, logging, and much more.
Much of this dovetails with what you should focus on when it comes to WordPress security. Let’s look at this next.
WordPress’ typical practices for security and compliance
At its core, WordPress is a strong and secure platform, thanks to its mature codebase and stringent reliance on secure practices. For the content management system (CMS) itself, you have official ways to report vulnerabilities:
In fact, there’s a way for end users to report themes, too – a prominent button on the repository page:
It’s clear that WordPress is hot on security, and there are a few key areas of focus for the core codebase:
- Regular updates. WordPress releases regular updates for its core software, which includes patches to address security and performance issues. There are automated ways to update your core, themes, and plugins from the WordPress dashboard
- Strong access controls. WordPress comes with a full-featured set of user roles that let you apply defined access controls to different users. There’s also a built-in password strength tool and controls for making and managing comments.
- Ensuring hosting security. There are many references to secure hosting throughout WordPress’ documentation. The expectation is that your host should offer the same duty of care to your security as its core team does to the CMS.
To help with monitoring some of these facets, you can use the Site Health screen within your WordPress dashboard:
When it comes to compliance, WordPress offers a default privacy policy template for each install. The core platform also encourages the use of vulnerability disclosure forms. Building on top of all of this with the Kinsta API offers a robust security provision—and we’ll show you how next.
How to implement security monitoring with the Kinsta API
If you want to achieve a setup that involves continuous security monitoring, a programmatic approach will arguably be the best approach. The Kinsta API offers lots of different endpoints to help along the way, although it’s not the only approach (more of which later).
Let’s walk you through a typical approach to security monitoring using the API. We’ll start by fetching your API keys and then move on to the other areas.
1. Obtain your API credentials
Without your API keys, you can’t access any aspect of your sites. To generate a new API key, head over to the MyKinsta dashboard and to the Company settings > API Keys screen. If this is your first time here, the screen will likely be blank:
Here, click the Create API Key button and fill in the fields to set an expiry date and name for your key:
Once you click the Generate button, you’ll be able to copy your API key. Remember, you won’t see this again, so make sure you keep it safe and secure:
With your fresh API key in hand, you can begin to explore connecting to the Kinsta API.
2. Explore the available endpoints within the Kinsta API
We recommend you keep the API documentation on hand as you navigate the available endpoints. Not all of them will be suitable for security monitoring, but there are some you’ll lean on more than others:
sites
. Use this when you need to fetch a list of sites associated with a company. You can return basic information, such as its name, ID, and status.backups
. You can make and restore backups for any of your sites usingGET
andPOST
requests. This will form one part of your disaster recovery and security incident responses.logs
. This endpoint can be used for simple error and access logs. It will be one of your go-to endpoints for monitoring and debugging purposes.
We’ll introduce more endpoints in the next section, where you’ll use them to build out your process.
3. Validate your connection and fetch a list of sites
Before you touch a line of code, it’s a good idea to plan ahead in order to solidify your goals. Look at what endpoints are available, combine that with what you want your security monitoring process to look like, and then try and match everything up.
For instance, you may want a regular way to check for outdated WordPress core, themes, and plugins. The sites
endpoint is the way to do this. However, you won’t simply access one endpoint or make one request at a time. This is where the Kinsta API’s flexibility can shine.
Here’s a quick Python script to authenticate access to the API and fetch a site. First, we set some core variables. Note that you’d typically not include your API key and company ID within your code. In this case, we do so for brevity and clarity.
Once we set the variables, we can set authentication headers and then look to validate access. With three short functions, we can validate the token, return a list of sites, and fetch a specific site:
import requests
import os
# Define the API key and company ID within the script
api_token = 'API_KEY'
company_id = 'COMPANY_ID'
# Set the base URL for the Kinsta API
base_url="https://api.kinsta.com/v2"
# Set the headers for authentication
headers = {
'Authorization': f'Bearer {api_token}'
}
def validate_token():
"""Checks and authenticates an API token."""
url = f'{base_url}/validate'
response = requests.get(url, headers=headers)
if response.status_code == 200:
print('API token is valid')
else:
print('API token is invalid')
exit(1)
def get_sites():
"""Fetches a list of sites based on the Company ID."""
url = f'{base_url}/sites?company={company_id}'
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
company_data = data.get('company', {})
sites = company_data.get('sites', [])
return sites
else:
print(f'Failed to fetch sites. Status code: {response.status_code}')
return None
def get_single_site(site_id):
"""Takes a URL template and response, checks the status code, and returns JSON data if present."""
url = f'{base_url}/sites/{site_id}'
response = requests.get(url, headers=headers)
if response.status_code == 200:
site = response.json()
return site
else:
print(f'Failed to fetch site. Status code: {response.status_code}')
return None
A main
function will call each of these other processes, using some logic to send the site information into a set of environment variables:
def main():
validate_token()
sites = get_sites()
if sites:
print(f'Number of sites: {len(sites)}')
if len(sites) > 0:
for site in sites:
print(f'Site ID: {site["id"]}')
print(f'Site Name: {site["name"]}')
print(f'Site Display Name: {site["display_name"]}')
print(f'Site Status: {site["status"]}')
print('Site Labels:', site["site_labels"])
print('---')
# Store site details in environment variables
os.environ[f'SITE_ID_{site["name"]}'] = site["id"]
os.environ[f'SITE_NAME_{site["name"]}'] = site["name"]
os.environ[f'SITE_DISPLAY_NAME_{site["name"]}'] = site["display_name"]
os.environ[f'SITE_STATUS_{site["name"]}'] = site["status"]
os.environ[f'SITE_LABELS_{site["name"]}'] = str(site["site_labels"])
print('Site details stored in environment variables.')
else:
print('No sites found')
else:
print('Failed to fetch sites')
With access to your sites complete, you can look to bring in other endpoints for specific use cases.
4. Begin to combine endpoints to create continuous security monitoring
There are many different ways to use the Kinsta API endpoints for continuous and automated monitoring. Fetching your error logs at regular intervals is an excellent way to be proactive about your site’s security.
We can start with the same authentication and site fetching process from the previous step. Once you have the site you need, a short function can access the API and return the error logs:
def get_error_logs():
"""Fetches error logs up to 1,000 lines."""
url = f'{base_url}/sites/environments/{company_id}/logs?file_name=error&lines=1000'
response = requests.get(url, headers=headers)
if response.status_code == 200:
logs = response.json()
return logs
else:
print(f'Failed to fetch error logs. Status code: {response.status_code}')
return None
If you want to automate this, you should be able to find a package or library to help. For example, Python has the schedule
package, which will run a task at fixed intervals. To implement this, we can create another function that prints logs, then call it using schedule
in main
:
def fetch_and_print_logs():
"""Checks for error logs, and if present, prints them to screen."""
logs = get_error_logs()
if logs:
print('Error Logs:')
for log in logs:
print(log)
print('---')
# Schedule the log fetching task to run once a day at a specific time
schedule.every().day.at('09:00').do(fetch_and_print_logs)
#main.py
…
while True:
schedule.run_pending()
time.sleep(1)
Of course, you can extrapolate here to work with any endpoint you wish, such as backups
, for example. With some work, you could also build a complete system to automate and continuously block IP addresses for your site – you have plenty of scope!
Using the Kinsta API in conjunction with other WordPress plugins
Kinsta’s hosting builds security into the MyKinsta dashboard and its deeper architecture. Because of this, users won’t be able to install most security plugins. To enable the same level of functionality, you’d typically use Kinsta’s tools, such as its IP blocking.
While the Kinsta API offers a ‘bare metal’ way to provide touchpoints for security monitoring and automation, there is the opportunity to dovetail this with some select plugins. For instance, while we don’t let you enable its traffic logging (as it causes high IOPS), the rest of the Wordfence plugin can be of value.
In fact, Wordfence offers a couple of its own endpoints for IP approval and importing settings. The latter could be of interest if you want to replicate known ‘good’ settings across many different sites. However, the Wordfence CLI offers much more scope for combining with our API.
Using both together is beyond the scope of this post, but it’s conceivable to spawn a child process using Node.js to run Python scripts for just one example.
This means you can have a programmatic way to run and automate Wordfence’s functionality alongside Kinsta’s. The Sucuri Security plugin also has a simple API that lets you conduct a site scan.
You can (of course) use plugins in a more straightforward way. For example, WP Activity Log expands upon Kinsta’s logging functionality. It lets you record almost every action that happens on your site, including for third-party plugins.
If you want to integrate the Kinsta API with the plugins on your site, you usually need API access to the plugin. Not all plugins offer this, though, so you might have some restrictions on your favorite plugins.
Maintaining compliance standards with WordPress and Kinsta
As a company that showcases its controls, subprocesses, and compliance, Kinsta knows plenty about the work involved. When it comes to compliance standards, we meet those for SOC 2 Type 2, the GDPR, and the CCPA.
In order to improve user trust, your site should also meet these standards. The GDPR was the first to affect almost every site. This European Union (EU) regulation sets guidelines for how you collect, process, and store personal data. The CCPA is another piece of legislation in a similar vein. For WordPress sites, the built-in privacy policy page and data export tools can help, along with implementing cookie notices.
If you work in finance, health, or similar other sectors, you’ll have other acts, standards, guidelines, and directives to follow:
- The Health Insurance Portability and Accountability Act (HIPAA) sets standards for protecting sensitive patient health information. WordPress’s access controls and user authentication functionality can help here, along with implementing SSL encryption for your sites.
- The Payment Card Industry Data Security Standard (PCI-DSS) is a set of security standards for sites that handle card transactions. WordPress eCommerce sites must follow the PCI-DSS requirements. As with HIPAA, encrypted connections for your site are important. Also, using Two-Factor Authentication (2FA), firewalls, and third-party payment gateways will help you comply.
Kinsta’s infrastructure can be a solid bedrock for your whole compliance strategy, and the Kinsta API can slot in alongside that of WordPress, too. You might even want to look into facets such as file integrity monitoring using third-party tools, services, and plugins.
Optimal tips for using the Kinsta API and WordPress for security and compliance
To finish the post, we’ll give you a few general-purpose tips for using the Kinsta API alongside WordPress. When it comes to your site’s security and compliance, it’s important to maximize the effectiveness of both, as you’ll get the greatest benefit.
A straightforward approach is using the ’authentication’ endpoint to check that your API key is valid:
const resp = await fetch(
`https://api.kinsta.com/v2/validate`,
{
method: 'GET',
headers: {
Authorization: 'Bearer '
}
}
);
const data = await resp.text();
console.log(data);
In addition, you will want to always keep your API credentials confidential, especially if you store your code in a remote Git repo. The strongest practice is to store those keys outside of the webroot and use one of the following methods:
- Environment variables should be a primary consideration, and we’d recommend this approach.
- Wrappers if you use PHP.
- Git commands to restrict access to repos and files and to obfuscate sensitive information. For instance,
git crypt
,git-remote-gcrypt
, orgit secret
.
However, aside from protecting your API keys, there are many other things you can do to make using the Kinsta API and WordPress together more secure:
- Implementing proper error handling and logging can help you identify and troubleshoot issues, boosting the reliability and stability of your security monitoring.
- Use the principle of least privilege when assigning user roles and permissions. In short, grant users only the minimum level of access they need to carry out tasks. Also, review these permissions on a regular basis.
Above all, stay in touch with current security practices and employ the strongest ones. Also, read up about recent vulnerabilities and the software patches that combat them for your themes and plugins. With a regular updating procedure, combined with automating your security monitoring and compliance with the Kinsta API, you’ll have a resilient setup in place.
Summary
At Kinsta, we pride ourselves on providing you with a strong, stable, and secure hosting server. However, you also need to work to monitor your site’s security. Continuous security monitoring for all your WordPress sites is essential.
With the Kinsta API, you have many programmatic ways to support your goals, such as accessing logs, managing an IP block list, and more. Some WordPress plugins that offer API access allow you to automate much more than your server. Automating those security and compliance tasks lets you work on other business-critical areas, safe in the knowledge that your site and its users are safe.
What do you need from your continuous security monitoring that Kinsta can provide? Let us know in the comments section below!