PHP: Sanitize User Input Using Filters & Regex

In this article I share my recent experience implementing the sanitization of user input in a PHP web application using PHP filters and regular expressions.

In this article I share my recent experience implementing the sanitization of user input in a PHP web application using PHP filters and regular expressions.

For background, I was recently troubleshooting a production PHP application and needed to create a form that takes in an ID parameter from the URL and uses it to retrieve a specific record from a table then sends an email using that data.

To keep this as simple as possible, the example below shows how to sanitize user input by not allowing a value based on a PHP filter rule using a regular expression. You’ll need to get comfortable with a little dependency injection as that is how we get our filter options in to PHP at runtime.

If you want to validate that an ID value passed through the URL is exactly two digits, you can use the filter_input() function with a custom regular expression through the FILTER_VALIDATE_REGEXP filter. This approach allows you to specify a pattern that the input must match to be considered valid.

For an ID that consists of exactly two digits (i.e., from 00 to 99), you can use the following code snippet:

$options = array(
    "options" => array(
        // Regular expression for exactly two digits
        "regexp" => "/^\d{2}$/"
    )
);

$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_REGEXP, $options);

if ($id !== false) {
    echo "The ID '$id' is valid.";
} else {
    echo "The ID is not valid. Please provide a two-digit ID.";
}

Here’s a breakdown of how this works:

  • INPUT_GET specifies that the input is expected to come from the query parameters in the URL.
  • 'id' is the name of the parameter you’re trying to validate.
  • FILTER_VALIDATE_REGEXP is the filter used for validating against a regular expression.
  • $options is an associative array that specifies the options for the filter. In this case, it contains a regular expression defined by the regexp key. The expression /^\d{2}$/ ensures that the input consists of exactly two digits:
    • ^ asserts the start of the string.
    • \d{2} matches exactly two digits (\d is a digit, and {2} specifies exactly two occurrences).
    • $ asserts the end of the string.

This code validates that the user input is exactly two digits. If the input meets the criteria, it is considered valid; otherwise, the script returns an error message indicating the input is not valid. This is a straightforward way to enforce specific formats for input values in PHP.

Lastly, the example above focuses on getting a parameter from the URL using the GET HTTP method. If you’re using a form, replace INPUT_GET with INPUT_POST.

I hope this example helps you secure your PHP applications.

~Cyber Abyss

Use Windows Firewall to Block IP Ranges for China, Russia, North & South Korea

Use the steps below to create Windows firewall rules, both incoming and outgoing for Russian, Chinese and South Korean IP ranges. The IP ranges are stored in text files and we’ll use Windows PowerShell to build the firewall rules. The process is pretty pretty simple.

Blocking IP Ranges using PowerShell & Windows Firewall

Use the steps below to create Windows firewall rules, both incoming and outgoing for Russian, Chinese and South Korean IP ranges. The IP ranges are stored in text files and we’ll use Windows PowerShell to build the firewall rules. The process is pretty pretty simple.

Often, I prefer setting Windows Firewall rules using PowerShell so we don’t make a mistake and lock ourselves out of ther server.

First, let’s create a directory for working with PowerShell, our PowerShell Scripts and the IP zone files.

Example: C:\ip-security

Go to this page click on Step 2 link to download your PowerShell scripts zip file.

Extract contents of the the ip-security-package.zip file to your “C:\ip-security” folder.

Your folder should look like this:

PowerShell Security Settings

Before we begin, we need to check the current PowerShell execution policy on your system, you can run the following command in PowerShell:

Get-ExecutionPolicy

This command will display the current execution policy setting. This setting determines the conditions under which PowerShell loads configuration files and runs scripts, providing a key part of your system’s security posture. If you have different execution policies set at different scopes (such as for a particular user, for all users, or for a particular process), you can see all the policies by using:

Get-ExecutionPolicy -List

Step by Step:
Importing the Firewall Blocklists

  1. Open PowerShell from the Command Line as an Administrator so you’ll have the correct rights to make changes to the Windows Firewall
  2. Run this command to make sure PowerShell is in the right mode
Set-ExecutionPolicy Bypass
When you're done...
Set-ExecutionPolicy Restricted 

When you use “Set-ExecutionPolicy Bypass“, you’ll be prompted to type “Y” to approve the change.

Once you’re done, you should set your execution policy back to Restricted or whatever is was before using the same command, just replace the option parameter.

* Read more below on PowerShell Security and Execution Policy Options

Troubleshooting the PowerShell Script

I noticed in a copy I was using today that the PowerShell script was not using the the file input name from the command line argument. Instead, I had to edit a line of code where the input file name is set. See my example below.

param ($InputFile = "southkorea.zone.txt", $RuleName, $ProfileType = "any", $InterfaceType = "any", [Switch] $DeleteOnly)

PowerShell Command Examples

Open PowerShell as an Admin then run these commands.

Set the working directory to the folder where we saved our IP lists and PowerShell script.

cd C:\ip-security\

Make sure you've set the IP import file name in the script. 
To run the PowerShell script, you'll have to enter the command with a .\ in front of the file name.

.\Import-Firewall-Blocklist.ps1

PowerShell Execution Policy Bypass

The PowerShell command Set-ExecutionPolicy Bypass is used in Windows to modify the execution policy setting of the PowerShell scripting environment. PowerShell’s execution policy is a safety feature that controls the conditions under which PowerShell loads configuration files and runs scripts. This feature helps prevent the execution of potentially harmful scripts.

Here’s a breakdown of the command:

  • Set-ExecutionPolicy: This is the cmdlet used to change the PowerShell execution policy.
  • Bypass: This is one of the policy levels that can be set. When you set the execution policy to ‘Bypass’, PowerShell does not block any scripts from running and does not warn the user before running scripts. This means all scripts, including those downloaded from the internet, can run without any restrictions or warnings.

This setting is useful in scenarios where you need to run scripts that are blocked under the default policy, or when operating in a highly controlled environment where the risk from script execution is already managed. However, setting the policy to ‘Bypass’ can be risky, as it exposes the system to potentially harmful scripts. Therefore, it should be used cautiously and typically only in well-understood environments or scenarios where the risks are acceptable.

This will list the execution policies for all scopes, helping you understand the policy context more comprehensively.

If your Set-ExecutionPolicy is currently set to Bypass and you want to enhance security, you should consider setting it to a more restrictive level. Here are some common options, listed from most to least restrictive:

  1. Restricted: This is the default setting on Windows client computers. In this mode, PowerShell does not run any scripts. This is the most secure setting, as it completely prevents script execution.
  2. AllSigned: This policy allows scripts to run only if they are signed by a trusted publisher. This means you can still run scripts, but it adds a layer of security by ensuring that the scripts are verified and not tampered with.
  3. RemoteSigned: This setting requires that all scripts and configuration files downloaded from the Internet are signed by a trusted publisher. However, scripts that are written on the local computer do not need to be signed. This is a good balance between usability and security, preventing potentially harmful scripts from the internet from being executed unknowingly.
  4. Default: The default execution policy set by PowerShell. For Windows clients, it is typically Restricted, and for Windows servers, it is usually RemoteSigned.

To change the execution policy, use the Set-ExecutionPolicy cmdlet followed by the policy level you choose. For example, to set the policy to AllSigned, you would use the command Set-ExecutionPolicy AllSigned. Remember that changing the execution policy can impact how PowerShell scripts run on your system, so ensure that the policy you choose aligns with your security needs and operational requirements. Also, this command might require administrator privileges to execute.

Firewall Types and Functions

A firewall is a network security device that monitors and filters incoming and outgoing network traffic based on an organization’s previously established security policies. At its most basic, a firewall is essentially the barrier that sits between a private internal network and the public Internet. The main purpose of a firewall is to prevent unauthorized access to or from private networks.

Firewalls can be either hardware or software-based. They work by blocking or permitting network traffic based on a set of security rules. Their primary objective is to control the incoming and outgoing network traffic by analyzing the data packets and determining whether they should be allowed through or not, based on the applied rule set.

A key function of a firewall is to protect the network from various types of attacks and intrusions that could occur from traffic coming in from the Internet. Firewalls are a fundamental part of any network security strategy because they provide a first line of defense against a range of cyber threats.

Other Web Server Security Options

Security on the internet is hard and ever changing. Running your own server for your hobby or side hustle can be done but can be very frustrating and overwhelming at times.

If you’re interested in securing your web server, I have more tips in another article, 3 inexpensive ways to protect your web server from a brute force attack.

I hope this story helps someone else on their IT Journey.

~ Cyber Abyss