Foros del Web » Programando para Internet » PHP »

Sesiones Seguras en PHP

Estas en el tema de Sesiones Seguras en PHP en el foro de PHP en Foros del Web. Tengo un problems con un Script ke encontre el la WEB ke es muy famoso para las Sesiones Seguras, el cual es el siguiente (no ...
  #1 (permalink)  
Antiguo 19/10/2004, 15:31
Avatar de granbosteron  
Fecha de Ingreso: agosto-2004
Mensajes: 164
Antigüedad: 19 años, 8 meses
Puntos: 1
Exclamación Sesiones Seguras en PHP

Tengo un problems con un Script ke encontre el la WEB ke es muy famoso para las Sesiones Seguras, el cual es el siguiente (no se asusten!!!, hay mucho comentado):

<?
function sess_open($sess_path, $session_name){
global $_SEC_SESSION;
$sess_sec=ini_get('session.name')."_sec";

# Apart from the session cookie we set another one, with the same name plus
# '_sec' at the end
# On that cookie, we set a random 32byte string (I'll refer to this string
# as 'key')

if (!isset($_COOKIE[$sess_sec])){
$md5=md5(uniqid(''));
setcookie($sess_sec,$md5,ini_get('session.cookie_l ifetime'),ini_get('session.cookie_path'),ini_get(' session.cookie_domain'));
$_SEC_SESSION['int']['key']=$_COOKIE[$sess_sec]=$md5;
$_SEC_SESSION['data']=serialize(array());
$empty=1;
}else{
$_SEC_SESSION['int']['key']=$md5=$_COOKIE[$sess_sec];
}

# The name of the file that contains the session info,
# starts with 'sec_sess_' and it's followed by the md5 string of the
# session_id concatenated with the previous key.
# This avoids people of reading the ID of the session from the session files
# (to hijack the session)

$_SEC_SESSION['int']['filename']=$filename_sec="$sess_path/sec_sess_".md5(session_id().$md5);
if (isset($empty)){
return 1;
}
if (!file_exists($filename_sec)){
fclose(fopen($filename_sec,'w'));
}
if (!$_SEC_SESSION['int']['fd']=fopen($filename_sec,'r')){
$_SEC_SESSION['data']=serialize(array());
return 0;
}

# The data on that file is dedrypted using the previous key

$data_enc=fread($_SEC_SESSION['int']['fd'],filesize($filename_sec));


fclose($_SEC_SESSION['int']['fd']);
if ($data_enc!=''){
$cipher=MCRYPT_DES;
$data=@mcrypt_ecb($cipher,$_SEC_SESSION['int']['key'],$data_enc,MCRYPT_DECRYPT);
}else{$data='';}
$_SEC_SESSION['data']=$data;
$_SEC_SESSION['int']['hash']=md5($_SEC_SESSION['data']);
return 1;
}
function sess_close(){
return true;
}
function sess_read($key){
return $GLOBALS['_SEC_SESSION']['data'];
}
function sess_write($id,$data){
global $_SEC_SESSION;
$sd=$data;
if ($_SEC_SESSION['int']['hash'] != md5($sd)){
$fd=fopen($_SEC_SESSION['int']['filename'],'w');
$cipher=MCRYPT_DES;
# Here we crypt the data with our key...
$data=@mcrypt_ecb($cipher,$_SEC_SESSION['int']['key'],$sd,MCRYPT_ENCRYPT);
fputs($fd,$data);
fclose($fd);
chmod($_SEC_SESSION['int']['filename'],0600);
}

}
function sess_destroy($key){
return(@unlink($GLOBALS['_SEC_SESSION']['int']['filename']));
}
function sess_gc($maxlifetime){}

session_set_save_handler('sess_open','sess_close', 'sess_read','sess_write','sess_destroy','sess_gc') ;
session_start();
if (!isset($_SESSION['times'])){
$_SESSION['times']=0;
}
$_SESSION['times']++;
print "This session ID is: ".session_id()." but the name of the file that contains the data is ".$_SEC_SESSION['int']['filename']."<br />\n";
print "Btw, this is the ".$_SESSION['times']." you see this page ;) (it works!)<Br />\n";
?>



El Problema es el siguiente.
1. Cuando ingresas la primera vez, me tira un file (ejemplo):



This session ID is: 5028c50a914dc7d7851b8a109b81443f but the name of the file that contains the data is /tmp/sec_sess_f03775b8231a6393dfa134685d0ab78b
Btw, this is the 1 you see this page ;) (it works!)
--------------------------------------------------------------------------------------


2. Y cuando hago refresh me tira unos errores y me cambia el file, y de esta manera las variables que registre la primera vez que entre al sitio, las pierdo. El error es el siguiente:



Warning: fread(): Length parameter must be greater than 0. in /home/www/discountpharmacyusa/demo/index.php on line 116

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/www/discountpharmacyusa/demo/index.php:116) in /home/www/discountpharmacyusa/demo/index.php on line 154

Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/www/discountpharmacyusa/demo/index.php:116) in /home/www/discountpharmacyusa/demo/index.php on line 154

This session ID is: 5028c50a914dc7d7851b8a109b81443f but the name of the file that contains the data is /tmp/sec_sess_ea256c9fa1e2ca28f3aad452df7958a8
Btw, this is the 1 you see this page ;) (it works!)
--------------------------------------------------------------------------------------


3. El error principal es el del fread() y desp. se originan los otros a causa del mismo, ahora no se si fread() tira el error porque no encontro el archivo a leer, o porke no contiene nada entonces al ser filesize<=0 tira el error. Este error lo consegui obviar con la siguiente linea, ke la coloke donde esta el fread() original del script ke esta arriba:



<?
$data_enc=fread($_SEC_SESSION['int']['fd'],(filesize($filename_sec)>0?filesize($filename_sec ):1));
?>
--------------------------------------------------------------------------------------

El error de fread(), con esa linea lo esquiva, pero me sigue cambiando el nombre del FILE original de cuando entras por primera vez al sitio, y de esta manera las variables ke seteo ni bien entro al sitio mio, las pierdo.

Ojo, una vez ke se cambia el FILE, desp, el sitio y el sistema este de "Sesiones Seguras", funciona joya, pero vuelvo a repetir que el FILE no es el mismo ke cuando entre la primera vez.

Se entendio ?? perdon por el gran mensaje.
Saben que puede ser?? me ta volviendo loko, porque se que debe ser una boludez proveniente de mi ignorancia sobre PHP. jeje

Si no conocian el script, espero les sirva.

Agredeceria me den una mano, no entendo mucho de prog. pero si de diseño, cualquier cosa ke pueda ayudarlos, lo hare con placer.

saludos
  #2 (permalink)  
Antiguo 19/10/2004, 15:49
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
Código PHP:
Saben que puede ser?? me ta volviendo lokoporque se que debe ser una boludez proveniente de mi ignorancia sobre PHPjeje 
Realmente no he evaluado el código (ni probado) para ver donde podría estar el error .. Pero como sugerencia te acosejo no liarte con cosas que realmente no sabes como funcionan. Usa sesiones de forma normal propagando el SID en cookies y listo .. Cuando te familirices más con PHP .. tal vez hasta desarrolles tu própio sistema de gestión de sesiones.

Podrías usar también Base de datos (Mysql) para trabajar las sesiones (el "handler" que llaman) en lugar de archivos .. como -por defecto- maneja ya PHP de por sí.

Ejemplos tienes en la documentación oficial de PHP y en sitios como www.phpclasses.org (y en zend.com también había un artículo al respecto .. lee los comentarios de los usuarios de php.net)

http://www.php.net/manual/es/functio...ve-handler.php

Un saludo,
  #3 (permalink)  
Antiguo 19/10/2004, 16:02
Avatar de granbosteron  
Fecha de Ingreso: agosto-2004
Mensajes: 164
Antigüedad: 19 años, 8 meses
Puntos: 1
Gracias Cluster.

Voy a ver ke onda con los sitios ke me pasaste. Este Script ke les pase es muy bueno, pa los ke saben si lo usan y encuentran el error, avisen.

Hay un artículo sobre este Script, haga click aquí.

Saludos.
  #4 (permalink)  
Antiguo 19/10/2004, 18:52
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
mm bueno .. el artìculo còdigo data del 2002 .. A la fecha PHP ha mejorado bastante en el tema sesiones ..

Podrías leer este documento sobre sesiones y seguridad de estas:
http://www.acros.si/papers/session_fixation.pdf
(la recomendación es del própio php.net)

Un saludo,
  #5 (permalink)  
Antiguo 19/10/2004, 20:36
Avatar de granbosteron  
Fecha de Ingreso: agosto-2004
Mensajes: 164
Antigüedad: 19 años, 8 meses
Puntos: 1
Muy bueno Cluster,

y muchisimas gracias a tus respuestas y tu dedicacion a este FORO que ta muy bueno!!

Voy a empezar por lo basico me parece igualmente.
Sabes donde puede haber buenos scripts con respecto a estas sesiones, para bajarlos e ir estudiandolos mas adelante.

Saludos, nuevamente.
  #6 (permalink)  
Antiguo 19/10/2004, 23:34
Avatar de granbosteron  
Fecha de Ingreso: agosto-2004
Mensajes: 164
Antigüedad: 19 años, 8 meses
Puntos: 1
Uhh!!, la gente ke necesita ke funcione este script, estan emputecidos con ke funcione este sistema de seguridad.

Asi ke sigo buscando el porke del ERROR de mi primer, mensaje.

Alguien seria tan amable de probar este script ??? y ver si encuentran el conflicto que explique en mi primer mensaje. Es copiar y pegar nomas el Script y veran los ke les digo.

Si me ayudan, me dan una gran MANO.... muchas gracias y no me soy Giordano.

Grax
  #7 (permalink)  
Antiguo 22/10/2004, 09:30
Avatar de granbosteron  
Fecha de Ingreso: agosto-2004
Mensajes: 164
Antigüedad: 19 años, 8 meses
Puntos: 1
Script solucionado

Script solucionado

Código PHP:
<?
function sess_open($sess_path$session_name){
    global 
$_SEC_SESSION;
    
$sess_sec=ini_get('session.name')."_sec";

    
# Apart from the session cookie we set another one, with the same name plus
    # '_sec' at the end
    # On that cookie, we set a random 32byte string (I'll refer to this string 
    # as 'key')
    
    
if (!isset($_COOKIE[$sess_sec])){
        
$md5=md5(uniqid(''));
        
setcookie($sess_sec,$md5,ini_get('session.cookie_lifetime'),ini_get('session.cookie_path'),ini_get('session.cookie_domain'));
        
$_SEC_SESSION['int']['key']=$_COOKIE[$sess_sec]=$md5;
        
$_SEC_SESSION['data']=serialize(array());
        
$empty=1;
    }else{
        
$_SEC_SESSION['int']['key']=$md5=$_COOKIE[$sess_sec];
    }

    
# The name of the file that contains the session info,
    # starts with 'sec_sess_' and it's followed by the md5 string of the
    # session_id concatenated with the previous key.
    # This avoids people of reading the ID of the session from the session files 
    # (to hijack the session)
    
    
$_SEC_SESSION['int']['filename']=$filename_sec="$sess_path/sec_sess_".md5(session_id().$md5);
    if (isset(
$empty)){
        return 
1;
    }
    if (!
file_exists($filename_sec)){
        
fclose(fopen($filename_sec,'w'));
    }
    if (!
$_SEC_SESSION['int']['fd']=fopen($filename_sec,'r')){
        
$_SEC_SESSION['data']=serialize(array());
        return 
0;
    }

    
# The data on that file is dedrypted using the previous key
    
    
$data_enc=fread($_SEC_SESSION['int']['fd'],filesize($filename_sec));
    
fclose($_SEC_SESSION['int']['fd']);
    if (
$data_enc!=''){
        
$cipher=MCRYPT_DES;
        
$data=@mcrypt_ecb($cipher,$_SEC_SESSION['int']['key'],$data_enc,MCRYPT_DECRYPT);
    }else{
$data='';}
    
$_SEC_SESSION['data']=$data;
    
$_SEC_SESSION['int']['hash']=md5($_SEC_SESSION['data']);
    return 
1;
}
function 
sess_close(){
    return 
true;
}
function 
sess_read($key){
    return 
$GLOBALS['_SEC_SESSION']['data'];
}
function 
sess_write($id,$data){
    global 
$_SEC_SESSION;
    
$sd=$data;
    if (
$_SEC_SESSION['int']['hash'] != md5($sd)){
        
$fd=fopen($_SEC_SESSION['int']['filename'],'w');
        
$cipher=MCRYPT_DES;
        
# Here we crypt the data with our key...
        
$data=@mcrypt_ecb($cipher,$_SEC_SESSION['int']['key'],$sd,MCRYPT_ENCRYPT);
        
fputs($fd,$data);
        
fclose($fd);
        
chmod($_SEC_SESSION['int']['filename'],0600);
    }

}
function 
sess_destroy($key){
    return(@
unlink($GLOBALS['_SEC_SESSION']['int']['filename']));
}
if(!
session_id()){
    
session_start();
    
session_write_close();
}
function 
sess_gc($maxlifetime){}
session_set_save_handler('sess_open','sess_close','sess_read','sess_write','sess_destroy','sess_gc');
    
session_start();
if (!isset(
$_SESSION['times'])){
    
$_SESSION['times']=0;
}
$_SESSION['times']++;
print 
"This session ID is: ".session_id()." but the name of the file that contains the data is ".$_SEC_SESSION['int']['filename']."<br />\n";
print 
"Btw, this is the ".$_SESSION['times']." you see this page ;) (it works!)<Br />\n";
?>
Espero les sirva, dejen comentarios

Última edición por granbosteron; 22/10/2004 a las 12:26
  #8 (permalink)  
Antiguo 06/06/2008, 10:25
 
Fecha de Ingreso: junio-2008
Mensajes: 1
Antigüedad: 15 años, 10 meses
Puntos: 0
Respuesta: Sesiones Seguras en PHP

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\sesion\x.php:6) in C:\xampp\htdocs\sesion\x.php on line 80

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\sesion\x.php:6) in C:\xampp\htdocs\sesion\x.php on line 80

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\sesion\x.php:6) in C:\xampp\htdocs\sesion\x.php on line 18

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\sesion\x.php:6) in C:\xampp\htdocs\sesion\x.php on line 85

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampp\htdocs\sesion\x.php:6) in C:\xampp\htdocs\sesion\x.php on line 85
This session ID is: ae82ae853ebb44b1f8f4a5e236de5ab0 but the name of the file that contains the data is C:\xampp\tmp/sec_sess_0afd3304eb38deb6ed2803a2c84b2c33
Btw, this is the 1 you see this page ;) (it works!)



me marca ese error porque sera???? help`meeeee
  #9 (permalink)  
Antiguo 06/06/2008, 10:30
Avatar de pateketrueke
Modernizr
 
Fecha de Ingreso: abril-2008
Ubicación: Mexihco-Tenochtitlan
Mensajes: 26.399
Antigüedad: 16 años
Puntos: 2534
Respuesta: Sesiones Seguras en PHP

debes identificar las lineas del error... ponlas si lo consideras necesario

también, se debe a un error... común, velo aquí (FAQ's del foro)

¿Por qué me sale "Warning: Cannot modify header information - headers already sent by (output started at [1]:[2]) in [3] on line [4]
__________________
Y U NO RTFM? щ(ºдºщ)

No atiendo por MP nada que no sea personal.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 15:48.