<p>User equals untrustworthy. Never trust untrustworthy user's input. I get that. However, I am wondering when the best time to sanitize input is. For example, do you blindly store user input and then sanitize it whenever it is accessed/used, or do you sanitize the input immediately and then store this "cleaned" version? Maybe there are also some other approaches I haven't though of in addition to these. I am leaning more towards the first method, because any data that came from user input must still be approached cautiously, where the "cleaned" data might still unknowingly or accidentally be dangerous. Either way, what method do people think is best, and for what reasons?</p>

[{'answer_id': 34901, 'author': 'Craig', 'author_id': 2894, 'author_profile': 'https://Stackoverflow.com/users/2894', 'pm_score': -1, 'selected': False, 'text': '<p>I find that cleaning it immediately has two advantages.  One, you can validate against it and provide feedback to the user.  Two, you do not have to worry about consuming the data in other places.</p>\n'}, {'answer_id': 34902, 'author': 'Daniel Jennings', 'author_id': 3641, 'author_profile': 'https://Stackoverflow.com/users/3641', 'pm_score': 5, 'selected': True, 'text': "<p>I like to sanitize it as early as possible, which means the sanitizing happens when the user tries to enter in invalid data. If there's a TextBox for their age, and they type in anything other that a number, I don't let the keypress for the letter go through.</p>\n\n<p>Then, whatever is reading the data (often a server) I do a sanity check when I read in the data, just to make sure that nothing slips in due to a more determined user (such as hand-editing files, or even modifying packets!)</p>\n\n<p>Edit: Overall, sanitize early and sanitize any time you've lost sight of the data for even a second (e.g. File Save -> File Open)</p>\n"}, {'answer_id': 34903, 'author': 'Sean Chambers', 'author_id': 2993, 'author_profile': 'https://Stackoverflow.com/users/2993', 'pm_score': 0, 'selected': False, 'text': '<p>User input should always be treated as malicious before making it down into lower layers of your application. Always handle sanitizing input as soon as possible and should not for any reason be stored in your database before checking for malicious intent.</p>\n'}, {'answer_id': 34905, 'author': 'mk.', 'author_id': 1797, 'author_profile': 'https://Stackoverflow.com/users/1797', 'pm_score': 1, 'selected': False, 'text': "<p>Clean the data before you store it. Generally you shouldn't be preforming <strong>ANY</strong> SQL actions without first cleaning up input. You don't want to subject yourself to a SQL injection attack.</p>\n\n<p>I sort of follow these basic rules. </p>\n\n<ol>\n<li>Only do modifying SQL actions, such as, INSERT, UPDATE, DELETE through POST. Never GET.</li>\n<li>Escape everything.</li>\n<li>If you are expecting user input to be something make sure you check that it is that something. For example, you are requesting an number, then make sure it is a number. Use validations. </li>\n<li>Use filters. Clean up unwanted characters.</li>\n</ol>\n"}, {'answer_id': 34906, 'author': 'Martin', 'author_id': 770, 'author_profile': 'https://Stackoverflow.com/users/770', 'pm_score': 1, 'selected': False, 'text': '<p>Users are evil!</p>\n\n<p>Well perhaps not always, but my approach is to always sanatize immediately to ensure nothing risky goes anywhere near my backend.</p>\n\n<p>The added benefit is that you can provide feed back to the user if you sanitize at point of input.</p>\n'}, {'answer_id': 34919, 'author': 'BrianH', 'author_id': 1484, 'author_profile': 'https://Stackoverflow.com/users/1484', 'pm_score': 1, 'selected': False, 'text': '<p>Assume all users are malicious.\nSanitize all input as soon as possible.\nFull stop.</p>\n'}, {'answer_id': 34923, 'author': 'Dillie-O', 'author_id': 71, 'author_profile': 'https://Stackoverflow.com/users/71', 'pm_score': 1, 'selected': False, 'text': "<p>I sanitize my data right before I do any processing on it. I may need to take the First and Last name fields and concatenate them into a third field that gets inserted to the database. I'm going to sanitize the input before I even do the concatenation so I don't get any kind of processing or insertion errors. The sooner the better. Even using Javascript on the front end (in a web setup) is ideal because that will occur without any data going to the server to begin with.</p>\n\n<p>The scary part is that you might even want to start sanitizing data coming out of your database as well. The recent surge of ASPRox SQL Injection attacks that have been going around are doubly lethal because it will infect all database tables in a given database. If your database is hosted somewhere where there are multiple accounts being hosted in the same database, your data becomes corrupted because of somebody else's mistake, but now you've joined the ranks of hosting malware to your visitors due to no initial fault of your own.</p>\n\n<p>Sure this makes for a whole lot of work up front, but if the data is critical, then it is a worthy investment.</p>\n"}, {'answer_id': 34984, 'author': 'Peter Stone', 'author_id': 1806, 'author_profile': 'https://Stackoverflow.com/users/1806', 'pm_score': 2, 'selected': False, 'text': "<p>Early is good, definitely before you try to parse it.  Anything you're going to output later, or especially pass to other components (i.e., shell, SQL, etc) must be sanitized.</p>\n\n<p>But don't go overboard - for instance, passwords are hashed before you store them (right?).  Hash functions can accept arbitrary binary data.  And you'll never print out a password (right?).  So don't parse passwords - and don't sanitize them.</p>\n\n<p>Also, make sure that you're doing the sanitizing from a trusted process - JavaScript/anything client-side is worse than useless security/integrity-wise.  (It might provide a better user experience to fail early, though - just do it both places.)</p>\n"}, {'answer_id': 35096, 'author': 'Jon Ericson', 'author_id': 1438, 'author_profile': 'https://Stackoverflow.com/users/1438', 'pm_score': 2, 'selected': False, 'text': '<p>Perl has a taint option which considers all user input "tainted" until it\'s been checked with a regular expression.  Tainted data can be used and passed around, but it taints any data that it comes in contact with until untainted.  For instance, if user input is appended to another string, the new string is also tainted.  Basically, any expression that contains tainted values will output a tainted result.</p>\n\n<p>Tainted data can be thrown around at will (tainting data as it goes), but as soon as it is used by a command that has effect on the outside world, the perl script fails.  So if I use tainted data to create a file, construct a shell command, change working directory, etc, Perl will fail with a security error.  </p>\n\n<p>I\'m not aware of another language that has something like "taint", but using it has been very eye opening.  It\'s amazing how quickly tainted data gets spread around if you don\'t untaint it right away.  Things that natural and normal for a programmer, like setting a variable based on user data or opening a file, seem dangerous and risky with tainting turned on.  So the best strategy for getting things done is to untaint as soon as you get some data from the outside.</p>\n\n<p>And I suspect that\'s the best way in other languages as well: validate user data right away so that bugs and security holes can\'t propagate too far.  Also, it ought to be easier to audit code for security holes if the potential holes are in one place.  And you can never predict which data will be used for what purpose later.</p>\n'}, {'answer_id': 35138, 'author': 'cpm', 'author_id': 3674, 'author_profile': 'https://Stackoverflow.com/users/3674', 'pm_score': 3, 'selected': False, 'text': "<p>The most important thing is to always be consistent in when you escape. Accidental double sanitizing is lame and not sanitizing is dangerous.</p>\n\n<p>For SQL, just make sure your database access library supports bind variables which automatically escapes values. Anyone who manually concatenates user input onto SQL strings should know better.</p>\n\n<p>For HTML, I prefer to escape at the last possible moment. If you destroy user input, you can never get it back, and if they make a mistake they can edit and fix later. If you destroy their original input, it's gone forever.</p>\n"}, {'answer_id': 36088, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 4, 'selected': False, 'text': "<p>It depends on what kind of sanitizing you are doing.  </p>\n\n<p>For protecting against SQL injection, don't do anything to the data itself.  Just use prepared statements, and that way, you don't have to worry about messing with the data that the user entered, and having it negatively affect your logic.  You have to sanitize a little bit, to ensure that numbers are numbers, and dates are dates, since everything is a string as it comes from the request, but don't try to do any checking to do things like block keywords or anything.  </p>\n\n<p>For protecting against XSS attacks, it would probably be easier to fix the data before it's stored.  However, as others mentioned, sometimes it's nice to have a pristine copy of exactly what the user entered, because once you change it, it's lost forever. It's almost too bad there's not a fool proof way to ensure you application only puts out sanitized HTML the way you can ensure you don't get caught by SQL injection by using prepared queries.</p>\n"}, {'answer_id': 3279377, 'author': 'Radu Maris', 'author_id': 207603, 'author_profile': 'https://Stackoverflow.com/users/207603', 'pm_score': 2, 'selected': False, 'text': "<p>My opinion is to sanitize user input as soon as posible client side and server side, i'm doing it like this</p>\n\n<ol>\n<li>(client side), allow the user to\nenter just specific keys in the field.</li>\n<li>(client side), when user goes to the next field using onblur, test the input he entered \nagainst a regexp, and notice the user if something is not good.</li>\n<li>(server side), test the input again,\nif field should be INTEGER check for that (in PHP you can use is_numeric() ),\nif field has a well known format\ncheck it against a regexp, all\nothers ( like text comments ), just\nescape them. If anything is suspicious stop script execution and return a notice to the user that the data he enetered in invalid.</li>\n</ol>\n\n<p>If something realy looks like a posible attack, the script send a mail and a SMS to me, so I can check and maibe prevent it as soon as posible, I just need to check the log where i'm loggin all user inputs, and the steps the script made before accepting the input or rejecting it.</p>\n"}, {'answer_id': 3527727, 'author': 'Epiphany', 'author_id': 425714, 'author_profile': 'https://Stackoverflow.com/users/425714', 'pm_score': 4, 'selected': False, 'text': '<p>I sanitize my user data much like Radu...</p>\n\n<ol>\n<li><p>First client-side using both regex\'s and taking control over allowable characters\n input into given form fields using javascript or jQuery tied to events, such as\n onChange or OnBlur, which removes any disallowed input before it can even be\n submitted. Realize however, that this really only has the effect of letting those\n users in the know, that the data is going to be checked server-side as well. It\'s\n more a warning than any actual protection.</p></li>\n<li><p>Second, and I rarely see this done these days anymore, that the first check being\n done server-side is to check the location of where the form is being submitted from.\n By only allowing form submission from a page that you have designated as a valid\n location, you can kill the script BEFORE you have even read in any data. Granted,\n that in itself is insufficient, as a good hacker with their own server can \'spoof\'\n both the domain and the IP address to make it appear to your script that it is coming\n from a valid form location.</p></li>\n<li><p>Next, and I shouldn\'t even have to say this, but always, and I mean <strong>ALWAYS</strong>, run\n your scripts in taint mode. This forces you to not get lazy, and to be diligent about\n step number 4.</p></li>\n<li><p>Sanitize the user data as soon as possible using well-formed regexes appropriate to\n the data that is expected from any given field on the form. Don\'t take shortcuts like\n the infamous \'<em>magic horn of the unicorn</em>\' to blow through your taint checks...\n or you may as well just turn off taint checking in the first place for all the good\n it will do for your security. That\'s like giving a psychopath a sharp knife, bearing\n your throat, and saying \'You really won\'t hurt me with that will you".</p>\n\n<p>And here is where I differ than most others in this fourth step, as I only sanitize\n the user data that I am going to actually USE in a way that may present a security\n risk, such as any system calls, assignments to other variables, or any writing to\n store data. If I am only using the data input by a user to make a comparison to data\n I have stored on the system myself (therefore knowing that data of my own is safe),\n then I don\'t bother to sanitize the user data, as I am never going to us it a way\n that presents itself as a security problem. For instance, take a username input as\n an example. I use the username input by the user only to check it against a match in\n my database, and if true, after that I use the data from the database to perform\n all other functions I might call for it in the script, knowing it is safe, and never\n use the users data again after that.</p></li>\n<li><p>Last, is to filter out all the attempted auto-submits by robots these days, with a\n \'human authentication\' system, such as Captcha. This is important enough these days\n that I took the time to write my own \'human authentication\' schema that uses photos\n and an input for the \'human\' to enter what they see in the picture. I did this because\n I\'ve found that Captcha type systems really annoy users (you can tell by their\n squinted-up eyes from trying to decipher the distorted letters... usually over and\n over again). This is especially important for scripts that use either SendMail or SMTP\n for email, as these are favorites for your hungry spam-bots.</p></li>\n</ol>\n\n<p>To wrap it up in a nutshell, I\'ll explain it as I do to my wife... your server is like a popular nightclub, and the more bouncers you have, the less trouble you are likely to have\nin the nightclub. I have two bouncers outside the door (client-side validation and human authentication), one bouncer right inside the door (checking for valid form submission location... \'Is that really you on this ID\'), and several more bouncers in\nclose proximity to the door (running taint mode and using good regexes to check the\nuser data).</p>\n\n<p>I know this is an older post, but I felt it important enough for anyone that may read it after my visit here to realize their is no \'<em>magic bullet</em>\' when it comes to security, and it takes all these working in conjuction with one another to make your user-provided data secure. Just using one or two of these methods alone is practically worthless, as their power only exists when they all team together.</p>\n\n<p>Or in summary, as my Mum would often say... \'Better safe than sorry".</p>\n\n<p>UPDATE:</p>\n\n<p>One more thing I am doing these days, is Base64 encoding all my data, and then encrypting the Base64 data that will reside on my SQL Databases. It takes about a third more total bytes to store it this way, but the security benefits outweigh the extra size of the data in my opinion.</p>\n'}, {'answer_id': 18573730, 'author': 'Your Common Sense', 'author_id': 285587, 'author_profile': 'https://Stackoverflow.com/users/285587', 'pm_score': 6, 'selected': False, 'text': '<p>Unfortunately, almost no one of the participants ever clearly understands what are they talking about. Literally. Only <a href="https://stackoverflow.com/a/36088/285587">Kibbee</a> managed to make it straight.</p>\n<p>This topic is all about sanitization. But the truth is, such a thing like wide-termed &quot;general purpose sanitization&quot; everyone is so eager to talk about is <strong>just doesn\'t exist.</strong></p>\n<p>There are <strong>a zillion different mediums</strong>, each require <strong>it\'s own, distinct data formatting.</strong> Moreover - even <strong>single certain medium require different formatting for it\'s parts</strong>. Say, HTML formatting is useless for javascript embedded in HTML page. Or, string formatting is useless for the numbers in SQL query.</p>\n<p>As a matter of fact, such a &quot;sanitization as early as possible&quot;, as suggested in most upvoted answers, is just <strong>impossible</strong>. As one just cannot tell in which certain medium or medium part the data will be used. Say, we are preparing to defend from &quot;sql-injection&quot;, escaping everything that moves. But whoops! - some required fields weren\'t filled and we have to fill out data back into form instead of database... with all the slashes added.</p>\n<p>On the other hand, we diligently escaped all the &quot;user input&quot;... but in the sql query we have no quotes around it, as it is a number or identifier. And no &quot;sanitization&quot; ever helped us.</p>\n<p>On the third hand - okay, we did our best in sanitizing the terrible, untrustworthy and disdained &quot;user input&quot;... but in some inner process we used this very data without any formatting (as we did our best already!) - and whoops! have got second order injection in all its glory.</p>\n<p>So, from the real life usage point of view, the only proper way would be</p>\n<ul>\n<li>formatting, not whatever &quot;sanitization&quot;</li>\n<li>right before use</li>\n<li>according to the certain medium rules</li>\n<li>and even following sub-rules required for this medium\'s different parts.</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/34896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2628/']