[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

PHP Safe to send ID as function argument?

Posted on 2012-08-21
7
Medium Priority
?
369 Views
Last Modified: 2012-08-24
I have a few functions for my PHP website that require an account id, like:

function resendActivation ($email, $id)

It just dawned on me that this might be a security issue, and that maybe I should do:

function resendActivation ($email, $_SESSION['id'])

to ensure that the id is from the current logged in user.

How valid is this concern?

Thanks!
0
Comment
Question by:christamcc
7 Comments
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 38319107
You must validate the session variables always before you process with them. For example,

$s_id =  $_SESSION['id'];

if (isset($s_id))

function resendActivation ($email, $s_id)
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 38319133
Are you using session_start() at the top of your pages so it can work properly?  And where were you getting $id from?
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38319283
The best practice here is to send the Activation with a 1-time activation key.

You create a table in your database

create table Activations
id int
sid char(36)
user_id
date_sent timestamp DEFAULT CURRENT_TIMESTAMP


You creat a record when the activation is sent

SELECT UUID();

Get the value returned and put it in the insert into the above table with the user id. The timestamp will look afteritself.

You send an activation link with the SID in the link and a link back to a page that handles your activation.

When you receive the activation look for a record matching the sid (If you want to put a timelimit on it then check against the create date and the current date to see if the time limit has expired).

If valid then activate user

In either case delete the activation record.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 38319950
Your instincts about external data are spot-on.  Send anything and you risk loss of data or unwanted tampering.  

You might want to send an encoded string that  must be returned along with the clear-text information.  This example pertains to cookies, but it is equally applicable to information sent via email, information in the GET request, etc.  The code creates a message digest from the actual data and a secret seed string.  If the actual data plus the seed string cannot be used to recreate the message digest, the external data has been damaged and must not be used.  Please read it over and post back with any specific questions.

<?php // RAY_cookie_safety.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO ENCODE INFORMATION IN A COOKIE
// TO REDUCE THE RISK OF COOKIE TAMPERING


// A DATA DELIMITER
$dlm = '|';

// YOUR OWN SECRET CODE
$secret_code = 'MY SECRET';

// A DATA STRING THAT WE WANT TO STORE (MIGHT BE A DB KEY)
$cookie_value = 'MARY HAD A LITTLE LAMB';

// ENCODE THE DATA STRING TOGETHER WITH OUR SECRET
$cookie_code = md5($cookie_value . $secret_code);

// CONSTRUCT THE COOKIE STRING WITH THE CLEAR TEXT AND THE CODED STRING
$safe_cookie_value = $cookie_value . $dlm . $cookie_code;

// SET THE COOKIE LIKE "MARY HAD A LITTLE LAMB|cf783c37f18d007d23483b11759ec181"
setcookie('safe_cookie', $safe_cookie_value);



// WHEN STORED, THE COOKIE WILL BE URL-ENCODED SO IT WILL LOOK SOMETHING LIKE THIS ON THE BROWSER
// MARY+HAD+A+LITTLE+LAMB%7Ccf783c37f18d007d23483b11759ec181
// IT WILL BE URL-DECODED BEFORE IT IS PRESENTED TO PHP



// HOW TO TEST THE COOKIE
if (isset($_COOKIE["safe_cookie"]))
{
    // BREAK THE COOKIE VALUE APART AT THE DELIMITER
    $array = explode($dlm, $_COOKIE["safe_cookie"]);

    // ENCODE THE DATA STRING TOGETHER WITH YOUR SECRET
    $cookie_test = md5($array[0] . $secret_code);

    // IF THE MD5 CODES DO NOT MATCH, THE COOKIE IS NO LONGER INTACT
    if ($cookie_test == $array[1])
    {
        echo "<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS INTACT";
    }
    else
    {
        echo "<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS CORRUPT";
    }
}
else
{
    die('COOKIE IS SET - REFRESH THE BROWSER WINDOW NOW');
}




// MUNG THE COOKIE TO DEMONSTRATE WHAT HAPPENS WITH A CORRUPT COOKIE
$_COOKIE["safe_cookie"] = str_replace('MARY', 'FRED', $_COOKIE["safe_cookie"]);

// HOW TO TEST THE COOKIE
if (isset($_COOKIE["safe_cookie"]))
{
    // BREAK THE COOKIE VALUE APART AT THE DELIMITER
    $array = explode($dlm, $_COOKIE["safe_cookie"]);

    // ENCODE THE DATA STRING TOGETHER WITH OUT SECRET
    $cookie_test = md5($array[0] . $secret_code);

    // IF THE MD5 CODES DO NOT MATCH, THE COOKIE IS NO LONGER INTACT
    if ($cookie_test == $array[1])
    {
        echo "<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS INTACT";
    }
    else
    {
        echo"<br/>THE COOKIE {$_COOKIE["safe_cookie"]} IS CORRUPT";
    }
}

Open in new window

HTH, ~Ray
0
 

Author Comment

by:christamcc
ID: 38323563
The activation one was just and example.  I session_start() the page and I include() the function.php in the pages that I need it.  The $id is so far always set from the $_SESSION['id'] originally  (with an isset check), but i had a thought that maybe  someone could somehow call a function from somewhere else and pass a random ID in there.  The Session Id, in my mind, ensured that the call had to come from within my website.  I can't imagine how they would even call my function!  ?  ( ... but I also know that I don't know what I don't yet.)

Thanks Ray, that is an interesting idea.  

(I encode all the important stuff using the md5, like the activation token. )
0
 
LVL 60

Assisted Solution

by:Julian Hansen
Julian Hansen earned 800 total points
ID: 38323800
After re-reading your question I have a nother suggestion.

I have a class called User in my applications which I use to do anything associated with the logged on user.

This user maintains state either in the session or a database with a cookie based identifier.

The id is maintained in the class itself as a private member.

Functions like resendactivation would then be a call to a class member which would use private attributes to get relevant information such as email and id. If the email is not known at the time of the call it can be passed in
Here is a sample class demonstrating the concept
class User
{
  private $id;
  private $email = '';

  function __construct($init)
  {
     // initialise user here
     $this->id = $init['id']; // or however the id is obtained
  }
  
  static function getUser($initialisation_info)
  {
      static $user = null;
      if ($user === null) {
        $user = new User($initialisation_info);
      }

      return $user;
  }
  
  function resendactivation($email = '') 
  {
     $email = ($email == '') ? $this->email : $email;

     do_something_with_email($email, $this->id);
  }
}

$user = User::getUser($stuff);
$user->resendactivation($useremail);

Open in new window

0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1200 total points
ID: 38324267
Maybe I am misunderstanding the scope of your question.  See if these two articles give some ideas that are useful...

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3939-Registration-and-Email-Confirmation-in-PHP.html

...and if not please post back with any questions.  Thanks, ~Ray
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses
Course of the Month18 days, 8 hours left to enroll

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question