Sanitizing PHPSESSID

nico picture nico · Sep 17, 2010 · Viewed 7.6k times · Source

I'm passing PHPSESSID to a PHP page (via POST) and I was wondering what's the best way of sanitizing the input. Would mysql_real_escape_string suffice? Is there anything special I should take into account when dealing with session IDs (I mean, they can only be letters and numbers right?)?

EDIT: To clarify the question, what I really want to know is: if someone tampers with the POST data, can he send a malicious string as PHPSESSID that would do something nasty when I call session_id($_GET['PHPSESSID'])? I personally cannot think of any, but better safe than sorry...

Thanks

nico

Answer

Pekka picture Pekka · Sep 17, 2010

Good thinking, but as far as I can see, there is no need to sanitize this input. The PHPSESSID will be passed on to session_id().

session_id indeed has some limitations:

Depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus)!

But session_id() should deal with deviations from these rules with an error message. (You may want to catch that error message and terminate the script on error.)

The only real danger that I can see is when you use a custom session handler that e.g. connects to a database. You will have to sanitize the input in that case, e.g. using mysql_real_escape_string(). However, that is something that should take place inside the custom session handler.

It goes without saying that if you use the session ID in some other context - say, as a parameter in a HTML form - you need to take the sanitation measures necessary for that specific output (In that case, htmlspecialchars()).