Web form security — the set of tools and practices intended to protect web forms from attacks and abuse — is one of the most critical aspects of overall website security. Web forms allow users to interact with your site and enable a lot of useful functionality. However, once a user can interact with your site to do something useful there is a new attack surface for a hacker to exploit.
To help you get the usability benefits of web forms while limiting the security risks we’ve created this list of best practices for web form security. From WordPress administrators to web developers, if you’re looking to learn about securing web forms you’re in the right place.
Why is web form security important?
Once you add web forms to your site attackers and spammers now have more ways to send data directly to your server in an attempt to compromise it. For example: a hacker might exploit a vulnerable login form with a CSRF attack (more on what that is in the next section!) to gain admin access to your site.
Additionally, web forms often collect payment information, personally identifiable information (PII), protected health information (PHI), or “personal data” (which is a GDPR-related term that is broader than PII). Not only is that type of data valuable to hackers, storing it often comes with specific obligations under regulations like GDPR, HIPAA, and PCI DSS. If you don’t protect your forms, you could be subject to fines or even compromise your ability to collect payments online.
Common web form security threats
How do hackers use web forms to steal data or compromise a site? There’s not just one way, there are many. Some of the most popular attacks and threats against webforms include:
- XSS– Cross site scripting (XSS) attacks occur when a hacker gets a malicious script to run in a user’s browser. While there are many types of XSS attacks, a textbook example of XSS against web forms is an attacker embedding HTML <script> or <img> tags with malicious content in a comment form. Since comments are usually displayed to everyone who views a site, users that load the page after the attack will execute the malicious content the attacker embedded in their comment.
- CSRF– Cross-site request forgery (CSRF) attacks allow a hacker to send requests as a different authenticated user or trick the authenticated user to send a request unwillingly. Many CSRF attacks against web forms generally depend on two things:
- Social engineering to get a victim to click an attacker’s link
- Applications that do not validate the origin of a form submission is legitimate
- If an attacker gets an authenticated victim to click a link that does an HTTP POST to a vulnerable password change form, the attacker can compromise the victim’s account.
- SQLi– SQL injection (SQLi) attacks focus on executing malicious SQL queries. For example, a hacker may gain authenticated access to a site by placing a crafted SQL statement that abuses Boolean Logic into a vulnerable password field in a web form. Let’s take a look at how that might look in practice. Consider a simple and insecure admin login form with a username and password field. If we input superadmin as the username and $uper$trong$ecret as the password, the backend SQL might do something like this before granting us access:
SELECT uid FROM admin_users WHERE name='superadmin' AND password='$uper$trong$ecret’
Then, if there is a matching entry for the user and the password in the database, we get admin access. If the password is wrong, we don’t get access.
But, what if a hacker inputs superadmin as the username and BadPassword‘) OR 1 = 1 — ] as the password? Now that SQL statement looks like this:
SELECT uid FROM admin_users WHERE name='superadmin' AND password='BadPassword' OR 1 = 1 -- ]’
Then, in a vulnerable app, the SQL statement will work if the name is correct and either the password is correct or “1 = 1” which is always true. Now the attacker has successfully logged in as superadmin without knowing the password.
- Form action hijacking– Form action hijacking occurs when attackers compromise a web form and get it to perform an unintended action. The fake Americommerce shopping cart attack is a real-world example of form action hijacking.
- Spam– Even if attackers don’t compromise your forms, spammers can be a real problem, particularly when forms that allow you to post comments are involved. For example, if anyone can submit comments to your forms with no moderation or spam prevention, your comment section can quickly become polluted with malicious links.
Best practices for web form security
You know the threats; now let’s jump into what you can do to protect against them with these web form security best practices.
Apply security updates and patches!
I’m putting this one first because it is one of the most high-impact actions a website administrator can take. Keep your website, plugins, and dependencies up to date and patched. When a security patch is released to address a vulnerability, apply it.
One of the most common reasons a site gets compromised is an unpatched vulnerability being exploited. Don’t make it easy for attackers. Patch the known issues asap. You’ll get a lot of “bang for your buck” from a security perspective if you do.
It’s 2021, and with very few exceptions, you should be encrypting all connections to your website. That means using HTTPS and with SSL certificates. HTTPS is the secure implementation of the HTTP network protocol used for communication between web servers and clients (such as web browsers and mobile apps). It’s considered secure because traffic between servers and clients is encrypted to prevent third parties from reading the data.
Not only does HTTPS encrypt data in transit (which prevents hackers from reading it over the network), it helps validate the integrity and authenticity of the data users see in the browser. This in turn limits the threat of MITM (man-in-the-middle) attacks. A MITM attack is a type of eavesdropping attack where a malicious actor reads and/or modifies traffic between clients and servers. With properly implemented SSL certificates and HTTPS connections a hacker can’t easily read data or present altered data to a client without raising an alert due to an invalid certificate.
Simply put: whenever a user loads a web form and submits data all the traffic should be encrypted end-to-end. That last part about “end-to-end” is why full HTTPS is important.
💡Pro-tip: You can use the Sucuri WAF to redirect all HTTP traffic to HTTPS.
Validate and sanitize user input
Attackers try all sorts of ways to compromise forms. From inputting large amounts of data to trying to inject SQL statements like
SELECT pass FROM users WHERE user_name = 'pepperNeggs' OR 1=1 -- ' '.
That particular SQL statement is an example of a popular method to force an application to return the passwords for all the accounts in the database.
To prevent one of these threats from compromising your website you should set limits on what a user can input into a given field on a form. Specifically, you should validate and sanitize form inputs.
Validation means making sure the data is in the right format. For example, in our screenshot above, we only allow valid email address formats in an email field. Allowing other inputs creates an unnecessary attack surface.
Sanitization means removing, replacing, or escaping potentially dangerous characters. OWASP’s input validation cheat sheet is a great place to get started with input sanitization.
Quantify what data you collect, only collect what you need, and anonymize where possible
From a compliance and risk perspective you should only collect and store data you need. All else equal, the more PII, personal data,, and financial information you capture, the more liability and responsibility you expose yourself to.
Of course, chances are you need some data otherwise you wouldn’t ask users to fill out a form. Quantifying what data you need — for example, email addresses for an email list — and comparing that to what you collect today is a good place to start. From there, you can narrow things down and make sure you only collect what you need.
Additionally, data anonymization — which removes PII from data — can help limit your risk and protect your users. If you’re not familiar with data anonymization, the International Association of Privacy Professionals (IAPP) has a guide to basic data anonymization techniques to help you get started.
Secure file uploads
File uploads fields in forms potentially allow attackers to upload malicious files to your site. They may try to replace a file, load malware, execute a script, or disrupt service with a large file upload.
Here are a few things you can do to keep your uploads secure:
- Restrict allowed file types– By limiting what file types a user can upload (Word documents, PDFs, MP4s, spreadsheets, GIFs, etc.), you can limit the risk of malicious scripts being uploaded to your site.
- Validate files users upload- Of course, hackers are clever. They might rename their malicious.php script to goodtext.txt to get around restrictions on file extensions. File type verification — which actually validates what a file is regardless of extension — or binary analysis of files can help solve this problem.
- Site size limits– What’s the biggest size file a user reasonably needs to upload to your site? Whatever the answer is, don’t let files bigger than that get uploaded.
- Only allow authenticated users to upload files- Whenever practical, only allow authenticated users to load files.
- Change file names after upload– By randomizing file names, you make it harder for hackers to find a potentially malicious file they uploaded or even access files uploaded by other users.
- Isolate uploaded files– Don’t store files users upload in the same directories as other critical files. For example, storing user uploads in your web root folder is a bad idea.
Additionally, you can go a step further and use techniques like content disarm and reconstruction (CDR) to remove embedded threats. CDR is a technology that breaks down files, removes elements that don’t meet predefined standards, and then reconstructs the files with the potential threats removed. For example, if there was a malicious script embedded in a PDF, a CDR tool could remove the script and reconstruct the PDF without it.
Don’t depend on hidden fields for security
Using the HTML <input type=”hidden”> type attribute can be useful for user experience (UX). It hides form data you don’t need the user to fill out. For example, you may want to associate a product ID number with a field. However, <input type=”hidden”> isn’t a security feature, and it should NOT be used to store sensitive data. The reason being is that hidden fields are still visible programmatically and using developer tools in a browser.
However, because hidden fields are often accessed by bots, but almost never by humans, security tools (e.g., honeypots and bot blocking mechanisms) use them to detect malicious behavior.
Use challenge-response systems like reCaptcha
Honestly, I don’t like captchas, and they’re far from a perfect tool. They can be beaten by a variety of available tools and services and make user experience worse.
However, captchas make it harder (not impossible!) for attackers to abuse forms. By using challenge-response systems like Google’s reCaptcha you’re making it a little more time-consuming and expensive for an attacker to submit a form.
The takeaway: challenge-response systems like reCaptcha can slow attackers down. Use them where they make sense, but don’t rely on them as your only line of defense.
Don’t say too much in error messages
When you’re the administrator or developer working on a site, verbose error messages are great. However, when you’re an attacker looking to find vulnerabilities, error messages can help you capture more information.
For example, suppose you have a login form that gives separate “invalid user” and “invalid password” messages. If a hacker gets an “invalid user” response, they know the account isn’t valid, they can move on to the next one. If, instead, your site returned “invalid login information” or “authentication failed”, they can’t infer if the user account is valid.
Disabling developer-related error messages in production is one simple way to limit your risk of exposing too much information. Similarly, be careful with error messages that reveal specific backend information such as libraries used or paths to files.
Protect sensitive forms with authentication
Unless you have a compelling reason to allow anyone to fill out a form (such as a login or account creation form), requiring a user to log in first is a good idea. Authentication adds an additional layer of defense for your forms and an additional layer of difficulty for hackers and spammers.
Secure the email side of your web form workflows
Often, web forms and email go hand-in-hand. For example, as part of a sign-in process, a user may be emailed a link. If any of your web form workflows involve email, you need to secure that aspect as well. Two email security best practices can help here:
- Use double opt-in for email lists – Double opt-in admittedly adds a bit more work for your users and subscribers. After filling out a form, users must then access their email and click a link to validate they’re opting in. Why bother with double opt-in? It cuts down (but doesn’t eliminate) spam and makes it more likely you’re dealing with legitimate users. As a bonus, a user is more likely to be highly interested in your product or service if they’re willing to double opt in.
- Use a secure SMTP server – We’ve already discussed the importance of encryption, and it applies to email as well. If you offload email to a managed service, they should take care of email security for you. However, if you manage your servers, be sure to securely configure your SMTP server.
- Rate limit emails triggered by forms– If a legitimate user is filling out a form, it should only result in one or two emails being sent. If someone is attempting to abuse or exploit your forms, many emails can go out to a single address in a short amount of time. To prevent your forms from being abused in this way, you can use rate-limiting. In simple terms, a rate limit on your emails is a restriction to only send X number of emails to any single address over Y number of minutes.
Think like a hacker
Website security is a constant game of cat-and-mouse and attackers are consistently coming up with creative new ways to compromise sites. That’s why fundamentals like the principle of least privilege and defense-in-depth are so important. The specific threats change over time, and risk models vary from site to site.
A great way to evaluate your own website and web form security is to view it from an attacker’s perspective. If you wanted to hack your own web forms, what would you try? Thinking that way can help you uncover attack surfaces you might not have considered before. If you need a website security team you can count on, we are here to help out!