views:

319

answers:

5

I'm currently using the following code in my cms to check if visitor is logged in as admin so that he can edit the current page:

if($_SESSION['admin']=="1")
{
        echo "<a href="foobar/?update">edit</a>";
}

But I'm worried that the code is unsafe. Can't $_session variables easily be modified by the user?

What would be a safer practice?

+3  A: 

No, that's a good way to do it. The user can't modify the $_SESSION global, unless he has access to your server. Remember to stay away from client-side cookies.

To make it even more safe, a good way is to store the IP-adress and check that it stays the same between every request.

alexn
Thanks! Checking IP sounds good; I reckon you should store the ip directly after session_start(), e.g.:session_start()$_SESSION["visitorIp"] = $_SERVER['REMOTE_ADDR'];Right?
AquinasTub
Checking the IP address is a bad idea actually - there are plenty of organisations with proxies that mean a user can appear to have several IP addresses. This also used to affect all AOL users - not sure if it still does.
Greg
@AquinasTub: Not quite. You aren't checking the visitorIp, just writing it. It should look more like if isset($_SESSION['username']) {/* check user ip */ if ($_SESSION['visitorIp'] != $_SERVER['REMOTE_ADDR']) {session_unset(); header("Location: /login"); exit();} } /* Set user IP */ $_SESSION['visitorIp'] == $_SERVER['REMOTE_ADDR'];
phihag
@Greg: No, it's not if you require proper Cookies AND the ip. It would only be unsafe if you used it as a single authentication factor.
phihag
With IP checking, how would you handle multiple IPs? Doesn't that mean that a user can't stay logged in at multiple computers? Or worse: at the same computer if their ISP gives them different IPs each time?
Dinah
@Dinah: Not if you create a separate session for each ip. I actually implement IP checking authentication (with others) on my PHP system, and I can be logged in from as many computers/IPs as I want. Each system/ip has its own session.
Andrew
I would check to see if the user agent string has changed, and if so, call session_regenerate_id()
alex
A: 

Session variables should be safe enough once your coding is secure.

Also, use the follow instead. Stops mistakes with == Probably should also use true too as it is a lot quicker than string comparisons.

if( "1" === $_SESSION['admin'] )
Ryaner
+1  A: 

$_SESSION variables can not be set by the user. The code is therefore perfectly fine, although you would usually ask your user backend (typically just a table users, sometimes LDAP) about the current user's privileges.

phihag
+3  A: 

The code is OK, you're just showing a link. Just make sure that your UPDATE script is protected as well.

Mario
+1  A: 

I found this presentation about session security

It explains how to avoid:

  • Session fixation.
  • Session hijacking.

Also the slide with more information has some really goods links

Alfred