podverse-rn icon indicating copy to clipboard operation
podverse-rn copied to clipboard

searching-for-podcasts: field: Don’t Sanitize; Do Escape

Open jwmh opened this issue 2 years ago • 1 comments

A detailed overview here, which I think might(?) help with various search-field issues I saw in the (closed) bug reports.

i.e., many birds, one stone

https://benhoyt.com/writings/dont-sanitize-do-escape/

When a boy named Robert'); DROP TABLE users; comes along, NaiveSite’s entire user database is deleted. Oops!

Incidentally, the mother in the xkcd comic says, “I hope you’ve learned to sanitize your database inputs.” … which is somewhat confusing, but I’ll give Randall the benefit of the doubt and assume he meant “escape your database parameters”.

In short, it’s no good to strip out “dangerous characters”, because some characters are dangerous in some contexts and perfectly safe in others.

Escape your output instead

The only code that knows what characters are dangerous is the code that’s outputting in a given context.

So the better approach is to store whatever name the user enters verbatim, and then have the template system HTML-escape when outputting HTML, or properly escape JSON when outputting JSON and JavaScript.

And of course use your SQL engine’s parameterized query features so it properly escapes variables when building SQL:

$stmt = $db->prepare('SELECT * FROM users WHERE name = ?');

$stmt->bind_param('s', $name);

This is sometimes called “contextual escaping”. If you happen to use Go’s html/template package, you get automatic contextual escaping for HTML, CSS, and JavaScript. Most other templating systems at least give you automatic HTML escaping, for example React, Jinja2, and Rails templates.

source: https://benhoyt.com/writings/dont-sanitize-do-escape/

jwmh avatar Jun 21 '23 12:06 jwmh

Hi @jwmh thanks for this insight. I left a related reply to your other comment https://github.com/podverse/podverse-api/pull/526

What you're saying sounds valid and helpful. It's just out of my depths as primarily as front-end and mobile app developer. I'm overwhelmed with my day job and Podverse, and I just don't see myself being able to complete this on my own. Hopefully our open source community will grow some day and more people with other specialities will contribute.

mitchdowney avatar Jun 24 '23 21:06 mitchdowney