14

It is important to note that this user input will undergo validation and sanitation using regex (on the server side in PHP) and then will be inserted into a database. Later it would be shown to other users on the same web site (for example: on a forum).

I'm referring to both a case when I know in advance what length I should expect from the user and a case in which I don't, but I can assume that it is not more than 100 characters.

I'm trying to figure out if there is any security advantages for checking user input length.

I know this differs from language to language, I'm using PHP. Information regarding any other language like Java, .NET, Python etc. would be fine.

8
  • Business rules should all be on the business side (server). This allow you to use the same code for the UI, Excel Import, ect… It also takes care if user disable javascript or other things on their client.
    – the_lotus
    Dec 3, 2019 at 17:40
  • 3
    @the_lotus What is the relevance of your comment to this question? This question is about how to perform validation, not where to perform it. Dec 3, 2019 at 17:51
  • @JonBentley I thought they were asking where. As in, should it be validated on the server on top of UI validation. For security, I'm not sure but for proper data model it should.
    – the_lotus
    Dec 3, 2019 at 17:58
  • @the_lotus No, they are asking whether or not there is a security advantage to checking the length of the input. Please take another look at the question. Dec 3, 2019 at 18:22
  • 5
    @MonkeyZeus: A lot of common databases will just truncate data that's too long for a field, it won't provide feedback for PHP to handle. I would argue that if there's a limit, it should be present in all layers; set maximum lengths on the client side to avoid surprises for the user, truncate in PHP (so it doesn't process more than it has to) and set sensible limits on your database. Just take care to avoid the limit going out of sync in different places.
    – Haravikk
    Dec 3, 2019 at 22:21

5 Answers 5

26

As a general rule, you should restrict user input as much as possible, but not more. A field designed to hold the name of towns don't need unrestricted length. But if you cap the length at 25 thinking no names can be longer, you will upset the Welsh.

Shorter input lengths means less space for payloads if you are worried about e.g. SQLi or XSS. It could therefore be seen as defence in depth against these attacks. But if it is your first line of defence, you are in deep trouble... Focus on getting the fundamentals, like prepared statements, right.

Finally, you are right that any restrictions you decide to use must be enforced server side, and not on the client only.

4
  • 13
    "famous for having the longest place name in an English-speaking country" - Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu would like to have a word with you.
    – user253751
    Dec 3, 2019 at 18:29
  • @user253751 fun fact, Wikipedia chops that up into segments when it's used as a title, making double click select less than the full word. Dec 3, 2019 at 21:03
  • 1
    @CJDennis As much as possible but not in a way that restricts your functionality - or such might be what was intended. You typically aim to restrict but stop when it seems to give you trouble in implementing your features or keeping your architecture clean. Dec 4, 2019 at 23:53
  • In the inverse side there are towns named Å in Norway and Denmark. Which would be offended by a minimum length...
    – papirtiger
    Dec 5, 2019 at 8:09
9

It depends on what you want to protect against.

You mentioned that you have a Regular Expression used to validate input. That can be good, but depends ultimately on how your regular expression is formed. If your RegEx looks like this, you'll likely be fine:

{\"name\":\"(.+?)\",\ ?\"age\":(\d+?)}

If your RegEx looks like this on the other hand...

({.+})

Just saying you use Regular Expressions isn't enough to make any claims about how secure those might be against various attacks such as SQL Injection or Cross-Site Scripting.

What length-validation does protect against is some forms of Denial-of-Service attacks. For example, a HTTP POST request can be several megabytes in size. If you just copy what you receive into a database, then an attacker can quickly fill your database with garbage and affect your availability.

13
  • 4
    @rami300 Yes, it does. If you know that legitimate input can at max be 100 characters, then that's a good thing to do. If you just assume 100 characters is enough, e.g. for names, then it's not good, as some names can be way over 100 characters.
    – user163495
    Dec 3, 2019 at 8:00
  • 8
    If your regex looks like the first one, someone will want to figuratively murder you because their JSON library insists on sorting the keys alphabetically.
    – user253751
    Dec 3, 2019 at 15:01
  • 6
    @Damon That's not a healthy QA attitude. Some people have long names. Some have really long names. Deal with it. Or are those few extra bytes in your database a problem?
    – Jenessa
    Dec 3, 2019 at 22:54
  • 7
    Obligatory "Falsehoods Programmers Believe About Names" link.
    – CJ Dennis
    Dec 3, 2019 at 23:36
  • 6
    @Damon I know a person who has a single letter last name. That's their legal name. As a result, they can't use several of the electric utility companies because they can't open an account there. Somebody, somewhere decided that a legal and valid name didn't deserve to be used. In few years time perhaps you get a non-jerk who has a really long name trying to use your system. But they won't because, apparently, they don't deserve this based on a name they might not have even chosen themselves.
    – VLAZ
    Dec 4, 2019 at 8:49
1

Any validation on the client side of the web app can be easily bypassed and should not be relied on from a security perspective.

Browser developer tools includes very good Html/JavaScript debuggers that allows the client side code to be executed step-by-step, have attributes and scripts modified to bypass security checks and validations.

Even mediocre hackers knows how to exploit that. From a security perspective is necessary to recheck the validations on the server side.

In my apps, I do most of the front-end on the server side. I submit most of the forms using a IFRAME or XmlHttpClient that returns the validation messages or the URL of the confirmation page. This is far easier to develop and very responsive for most forms. Even then, I code a lot of client side JavaScript, but only when makes more impact to the performance or user experience. It is a 80/20 kind of strategy.

3
  • 3
    The question is not about client-side validation - it clearly says server-side in the title.
    – Brilliand
    Dec 3, 2019 at 20:33
  • 1
    @Brilliand In fairness, the question is vague about where the initial validation via regex is being done. It could very well do done on the client side, based on how the question is phrased. Dec 4, 2019 at 17:16
  • I agree that any client-side validation can be easily bypassed but as I stated on the title of the question that i'm referring to server-side PHP validation. I know also edited the body of the question to make it more clear. thanks.
    – rami300
    Dec 5, 2019 at 6:18
1

As a security measure? No.

Attacks via user input occur when a user is able to input commands, usually in the form of database queries, into variables you haven't escaped properly. While truncated input might inadvertently prevent an attack, it isn't truly solving the problem.

In terms of security you should validate all user input, and check that the input is only used in a protected fashion, some of the cases are:

  1. If the value is to be output in HTML, you will want to ensure it either has no HTML tags in it (strip_tags) or only the ones you allow (either use a library, or DOMDocument for this).
  2. If the value is to be used in a calculation, make sure it's a valid number. Easiest way is to cast as (int)$foo or (float)$foo but your needs may vary.
  3. If the value is to be stored in a database, make sure you don't build your query in an unsafe way. Best way to keep queries safe is to use prepared statements, PDO is good for this. Otherwise you need to make sure you escape user input before building your query.

If you tell a user to only enter letters and numbers for a value, then you should only accept letters and numbers on your server. You can add the same condition on the client side, to prevent surprises for your users (giving them an error before sending a form), but the server is where you actually protect yourself, as client-side validation is informative, it's not protective (it's easily bypassed).

On that basis, if you can only store a limited number of characters in a field, you may as well report it to the user if a field is too long.

Let's say you want an e-mail address no more than 128 characters long, you could handle this at all levels like so:

Database (Model)

CREATE TABLE Emails `email` VARCHAR(128) NOT NULL

PHP (Controller)

$email = $_POST['email'];
if ((strlen($email) > 128) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Produce error that input was invalid
    die('ERROR: Invalid e-mail');
}

// Input is valid, store in database (e.g- with PDO)
$stmt = $pdo->prepare('INSERT INTO Emails (email) VALUES (?)');
$stmt->execute([$email]);

HTML (View)

<input name="email" type="email" maxlength="128" placeholder="E-mail" />

This gives you a good mixture of storage efficiency, correctness, safety and feedback to the user; if they have a browser that supports HTML5 they will get early errors if they try to send an invalid value, but we check on the server anyway for safety (non-HTML5 compliant browser, or malicious user).

0
1

You should always ensure you understand what user input you expect and make sure the actual input is as close to what you expect as possible.

Data that is longer than expected can lead to many types of security problems:

  • DOS attacks / resource over-use: 1 GB wasted for a dummy name in a database, or CPU power wasted to regex-validate a 1GB name that shouldn't be longer than 100 characters
  • buffer/data field/ integer overflows
  • business logic exploits: someone implemented some business logic that assumes certain input of a certain lengths and data of larger lengths break it in an exploitable way

A regular expression check is good and potentially more strict than the length check on its own. If it includes the length check implicitly that already covers a lot of the potential problems. Some however remain: Your regex could still be attacked itself, e.g. by using more CPU than necessary to validate input, or by targeting bugs in the regex engine. Regex are also complicated, there is always a chance you or someone who later modifies it, breaks the expression and suddenly it isn't checking the length correctly anymore. An explicit light-weight length check can protect against that. Whether that's worth it, always depends on how secure you want to be and how much effort adding the check is (to maintain) etc.

Making sure user input is as close to what you expect it to be always has security impacts, but also increases implementation/maintenance effort. Humans make mistakes and don't consider all edge cases, so fewer edge cases means more practical security. Whether such checks are necessary in your concrete scenario always depends on what other security measures you have in place, what is the expected attack scenario, what are you guarding, how critical a break-in is etc. pp.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .