I'm just thinking about the best way to go about sanitizing my data to prevent injection attacks. Some people like to sanitize immediately before output, or immediately before insertion to the database... but the problem I see with this is twofold: (1) what if you miss a paramater/variable? (2) what if you're over-sanitizing? Not that it would hurt the output, but there's not much sense sanitizing stuff you already know is safe.

For example, in PHP instead of using $_GET and $_POST couldn't I wrap those with something like:

function get($var) {
return my_sanitizer($_GET[$var]);
}

Or would that not be enough? Where else could malicious code sneak in?

After reading the answers below I realize this question was a bit foolish. It depends on if you're inserting to the database, or outputting HTML. In that case, perhaps it is better to do just before usage. That's okay though, it's easy enough to wrap output methods too...

3 Answers
3

There's more than one kind of sanitization, and more than one kind of injection. For instance, you'll generally want to sanitize or escape HTML and JS sometime before output. But the appropriate choice (e.g., stripping out all HTML, allowing HTML in a whitelist, making the user enter something else, or just escaping it so it shows as text) depends on the application.

As far as database injection, I agree with Nate you should use prepared statements for this (sometimes these use escaping internally, but that's not your concern) instead.

In summary, a homemade catch-all my_sanitizer you run immediately upon getting any data is probably the wrong choice.

Right. My head must not be screwed on right :p I know there are different kinds of injection, but for some reason I was thinking that stripping or replacing <>&" would do the trick in all cases. I guess it depends on what you're doing with that data.
–
MarkOct 15 '09 at 6:02

Personally, I'd always sanitize right before you insert into your database; that said, if you have a SQL based database parameterized SQL and sprocs are the way to go to ensure you aren't injecting anything that will cause harm.